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): delete /agent tree + daemon cutover to /api/community (phase 5b)
Simone08b9e64b3948
diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex 7c7e33e01..bba7e248b 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -185,8 +185,59 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {return { path: req.destPath, filename, contentType, size: size || buf.byteLength };}+ // --- Folded verbs: real REST paths, not flat `/api/<verb>` ---------------+ // listServers and joinServer FOLDED onto the human routes (GET /servers,+ // POST /invites/<token>/join). The unified route returns a SUPERSET; the lean+ // contract projection (Fork C — Aigneis condition 1) happens HERE, at the+ // single proxy response boundary, NOT per CLI command. These hit+ // `/api/community/...` directly; `rewriteAgentPath` is idempotent so the path+ // passes through unprefixed. Mirrors the existing callUpload/callDownload+ // custom-path pattern.++ /** Project a superset server row down to the lean `Server` ({id,name}). */+ function projectServer(row: { id: string; name: string }): Server {+ return { id: row.id, name: row.name };+ }++ async function callListServers(): Promise<{ servers: Server[] }> {+ const res = await fetchImpl(`${base}/api/community/servers`, {+ method: "GET",+ headers: { authorization: `Bearer ${config.voucher}` },+ });+ const body = await parseJsonResponse<{ servers: Array<{ id: string; name: string }> }>(+ res,+ "listServers",+ );+ // Superset in → lean out: drop icon/ownerId/etc., emit only {id,name}.+ return { servers: body.servers.map(projectServer) };+ }++ async function callJoinServer(req: { agentId: AgentId; invite: string }): Promise<{ server: Server }> {+ // The invite token is a ROUTE PARAM on the folded route (POST+ // /invites/<token>/join), not a body field. Body is empty; identity rides+ // the voucher as everywhere else.+ const res = await fetchImpl(+ `${base}/api/community/invites/${encodeURIComponent(req.invite)}/join`,+ {+ method: "POST",+ headers: {+ "content-type": "application/json",+ authorization: `Bearer ${config.voucher}`,+ },+ body: "{}",+ },+ );+ const body = await parseJsonResponse<{ server?: { id: string; name: string } }>(res, "joinServer");+ // Superset {member,serverId,server} in → lean {server:{id,name}} out.+ if (!body.server) {+ throw new Error("joinServer: upstream response missing server");+ }+ return { server: projectServer(body.server) };+ }+return {- listServers: (r: { agentId: AgentId }) => call<{ servers: Server[] }>("listServers", r),+ listServers: (_r: { agentId: AgentId }) => callListServers(),+ joinServer: callJoinServer,listChannels: (r: ListChannelsRequest) => call<{ groups: ChannelGroup[] }>("listChannels", r),channelMember: (r: { agentId?: AgentId; channel: ChannelRef }) =>call<ChannelMemberResult>("channelMember", r),@@ -197,7 +248,6 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {read: (r: ReadRequest) => call<Page<Message>>("read", r),resolve: (r: ResolveRequest) => call<{ message: Message }>("resolve", r),listMembers: (r: { agentId: AgentId; server: string }) => call<{ members: ServerMember[] }>("listMembers", r),- joinServer: (r: { agentId: AgentId; invite: string }) => call<{ server: Server }>("joinServer", r),attachmentUpload: callUpload,attachmentDownload: callDownload,reactAdd: (r: { channel: ChannelRef; seq: Seq; emoji: string }) =>diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.tsindex 1d9b99561..24100e564 100644--- a/src/daemon/src/credentials/credentialProxy.test.ts+++ b/src/daemon/src/credentials/credentialProxy.test.ts@@ -49,14 +49,14 @@ async function post(url: string, voucher: string, path: string) {describe("DEFAULT_CAPABILITY_RESOLVER", () => {it("maps /api/reactAdd to the `send` capability (a read-only voucher must not react)", () => {expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/reactAdd")).toBe("send");- expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/agent/reactAdd")).toBe("send");+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/reactAdd")).toBe("send");});it("maps friendRequest / listFriends to the `friend` capability, both pre- and post-rewrite", () => {expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/friendRequest")).toBe("friend");expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/listFriends")).toBe("friend");- expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/agent/friendRequest")).toBe("friend");- expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/agent/listFriends")).toBe("friend");+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/friendRequest")).toBe("friend");+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/listFriends")).toBe("friend");});});@@ -186,21 +186,26 @@ describe("startCredentialProxy (zero-trust end to end)", () => {expect(upstream.seen.length).toBe(0);});- it("rewrites /api/* to /api/community/agent/* (design §9)", async () => {+ it("rewrites flat /api/* verbs to /api/community/* (plans/22 §9); is idempotent for already-namespaced paths", async () => {const upstream = await startUpstream();upstreamClose = upstream.close;const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });proxy = await startCredentialProxy(broker);- const reg = broker.mint("agent-1", "l", ["send", "read"], REAL_KEY);+ const reg = broker.mint("agent-1", "l", ["send", "read", "server"], REAL_KEY);await post(proxy.url, reg.voucher, "/api/send");- expect(upstream.seen.at(-1)!.path).toBe("/api/community/agent/send");+ expect(upstream.seen.at(-1)!.path).toBe("/api/community/send");await post(proxy.url, reg.voucher, "/api/inboxPull?max=10");- expect(upstream.seen.at(-1)!.path).toBe("/api/community/agent/inboxPull?max=10");+ expect(upstream.seen.at(-1)!.path).toBe("/api/community/inboxPull?max=10");await post(proxy.url, reg.voucher, "/api");- expect(upstream.seen.at(-1)!.path).toBe("/api/community/agent");+ expect(upstream.seen.at(-1)!.path).toBe("/api/community");++ // Idempotent: a folded verb's real REST path (already under /api/community/)+ // passes through unprefixed — NOT doubled into /api/community/community/...+ await post(proxy.url, reg.voucher, "/api/community/servers");+ expect(upstream.seen.at(-1)!.path).toBe("/api/community/servers");});it("leaves non-/api paths untouched", async () => {diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.tsindex 54ca806a6..0ab4b7986 100644--- a/src/daemon/src/credentials/credentialProxy.ts+++ b/src/daemon/src/credentials/credentialProxy.ts@@ -481,15 +481,25 @@ function joinPath(basePath: string, reqUrl: string): string {/*** Rewrite the CLI's bare `/api/*` ops (`/api/send`, `/api/inboxPull`, …) onto- * the real server surface at `/api/community/agent/*` (design §9). This is a- * brand-new API — no prior contract to preserve back-compat for — so the- * rewrite is unconditional for anything under `/api/`; every other path- * passes through untouched.+ * the real unified-actor server surface at `/api/community/*` (plans/22 §9 — the+ * `/api/community/agent/*` tree was deleted; every bot verb now lives flat under+ * `/api/community/`). This is a bot-only API — no back-compat to preserve — so+ * the rewrite is unconditional for anything under `/api/`.+ *+ * IDEMPOTENT: a path already under `/api/community/` passes through untouched.+ * The two FOLDED verbs (listServers → GET `/api/community/servers`, joinServer →+ * POST `/api/community/invites/<token>/join`) are addressed with their real REST+ * paths client-side in `proxyServerApi` (mirroring `callUpload`/`callDownload`);+ * this guard lets those flow through without being double-prefixed into a+ * non-existent `/api/community/community/...`.*/function rewriteAgentPath(reqUrl: string): string {const url = new URL(reqUrl, "http://placeholder");+ if (url.pathname.startsWith("/api/community/")) {+ return url.pathname + url.search;+ }if (url.pathname === "/api" || url.pathname.startsWith("/api/")) {- url.pathname = `/api/community/agent${url.pathname.slice("/api".length)}`;+ url.pathname = `/api/community${url.pathname.slice("/api".length)}`;}return url.pathname + url.search;}diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex 3436ec627..38873fc3a 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -523,13 +523,16 @@ describe("deriveAuditLogSubcommand", () => {expect(deriveAuditLogSubcommand("/api/reactAdd")).toBe("reactAdd");});- it("maps the rewritten /api/community/agent/* pathnames identically", () => {+ it("maps the rewritten /api/community/* pathnames identically", () => {// The proxy's rewriteAgentPath fires AFTER onProxyRequest, so the sighting- // may carry either shape depending on how the CLI called in. Both must- // derive to the same subcommand string.+ // may carry either shape depending on how the CLI called in. Both the flat+ // client path and the post-rewrite /api/community/* path must derive to the+ // same subcommand string. (The legacy /api/community/agent/* form is still+ // normalized too, for any in-flight path.)+ expect(deriveAuditLogSubcommand("/api/community/send")).toBe("send");+ expect(deriveAuditLogSubcommand("/api/community/inboxPull")).toBe("inboxPull");+ expect(deriveAuditLogSubcommand("/api/community/reactAdd")).toBe("reactAdd");expect(deriveAuditLogSubcommand("/api/community/agent/send")).toBe("send");- expect(deriveAuditLogSubcommand("/api/community/agent/inboxPull")).toBe("inboxPull");- expect(deriveAuditLogSubcommand("/api/community/agent/reactAdd")).toBe("reactAdd");});it("returns null for `ack` (dropped — paired with inboxPull, no user intent)", () => {diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex 973249d6e..f11805e0e 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -57,7 +57,12 @@ const WARMUP_CEILING_MS = 30_000;* future.*/export function deriveAuditLogSubcommand(pathname: string): string | null {- const stripped = pathname.replace(/^\/api\/community\/agent\//, "/api/");+ // Normalize both the pre-rewrite client path (`/api/<verb>`) and the+ // post-rewrite upstream path (`/api/community/<verb>`, plans/22 §9 — the old+ // `/api/community/agent/` tree is gone) down to `/api/<verb>` before slicing.+ const stripped = pathname+ .replace(/^\/api\/community\/agent\//, "/api/")+ .replace(/^\/api\/community\//, "/api/");if (!stripped.startsWith("/api/")) return null;const sub = stripped.slice("/api/".length).split("/")[0]?.split("?")[0] ?? "";if (!sub) return null;diff --git a/src/web/src/app/api/community/agent/ack/route.ts b/src/web/src/app/api/community/agent/ack/route.tsdeleted file mode 100644index bed6c061c..000000000--- a/src/web/src/app/api/community/agent/ack/route.ts+++ /dev/null@@ -1,93 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, withD1Retry, CommunityAgentAckRequestSchema } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-import { resolveTargetForMember } from "@/lib/community/resolve-ref"-import { isDmTarget } from "@/lib/community/message-handler"-import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"--/**- * POST /api/community/agent/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`.- *- * 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 = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- 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, ctx.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, ctx.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, ctx.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, ctx.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/agent/attachmentDownload/route.ts b/src/web/src/app/api/community/agent/attachmentDownload/route.tsdeleted file mode 100644index 406abdc38..000000000--- a/src/web/src/app/api/community/agent/attachmentDownload/route.ts+++ /dev/null@@ -1,109 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, createLogger, CommunityAgentAttachmentDownloadRequestSchema } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-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/agent/attachmentDownload- *- * 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 = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- 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 !== ctx.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, ctx.botUserId)- if (!gate.ok) return NextResponse.json({ error: "attachment not found" }, { status: 404 })- } else {- const gate = await requireChannelMember(db, message.channelId, ctx.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: ctx.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/agent/attachmentUpload/route.ts b/src/web/src/app/api/community/agent/attachmentUpload/route.tsdeleted file mode 100644index f6892cb97..000000000--- a/src/web/src/app/api/community/agent/attachmentUpload/route.ts+++ /dev/null@@ -1,99 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, createLogger } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-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/agent/attachmentUpload?target=<ref>- *- * Body: multipart/form-data with a single `file` field.- * Response: `{ id, filename, contentType, size }` — no url, no r2 key.- *- * Auth is `withAgentRunnerAuth` (`crk_` bearer via the credential-proxy swap).- * `target` is resolved through `resolveTargetForMember` so the bot's- * membership + write-permission gate is identical to `send`.- */-export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- // 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, ctx.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, ctx.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, ctx.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: ctx.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: ctx.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: ctx.botUserId,- r2Key: r2KeyToCleanUp,- cleanupErr: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),- })- }- }- log.error("attachment_route_failure", {- route: "attachmentUpload",- botUserId: ctx.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/agent/channelMember/route.ts b/src/web/src/app/api/community/agent/channelMember/route.tsdeleted file mode 100644index 067f2665c..000000000--- a/src/web/src/app/api/community/agent/channelMember/route.ts+++ /dev/null@@ -1,129 +0,0 @@-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 { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"-import { requireChannelAccess } from "@/lib/community/permissions"--/**- * POST /api/community/agent/channelMember — `alook channel member --channel <ref>`.- * Returns the followed members of a channel/thread.- *- * 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 = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- 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, ctx.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, ctx.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/agent/friendRequest/route.ts b/src/web/src/app/api/community/agent/friendRequest/route.tsdeleted file mode 100644index 81e8bffb0..000000000--- a/src/web/src/app/api/community/agent/friendRequest/route.ts+++ /dev/null@@ -1,132 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import {- queries,- CommunityAgentFriendRequestSchema,- parseNameAndTag,- isBlocked,-} from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-import { requireNotBlocked } from "@/lib/community/permissions"-import { broadcastToUserSafe } from "@/lib/community/fanout"-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"--/**- * POST /api/community/agent/friendRequest — agent-initiated friend request.- * Body `{ username: "name#0042" }`. Identity is the bearer voucher (bot). All- * bot-origin requests are owner-gated except sibling-bot targets (same owner),- * which auto-accept. See plans/agent-friendship-approval-gate.md §Route 1.- */-export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- 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 === ctx.botUserId) {- return NextResponse.json({ error: "cannot friend yourself" }, { status: 400 })- }- if (target.id === ctx.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 === ctx.ownerUserId) {- const block = await requireNotBlocked(db, ctx.botUserId, target.id)- if (!block.ok) return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })-- const result = await queries.communityFriendship.ensureSiblingBotFriendship(db, {- botA: ctx.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, ctx.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: ctx.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: ctx.botUserId,- action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUESTED,- targetType: "user",- targetId: target.id,- changes: JSON.stringify({ requesterBotId: ctx.botUserId, addresseeId: target.id }),- })- for (const supersededId of result.supersededIds) {- logAudit(db, {- serverId: null,- actorId: ctx.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, ctx.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/agent/inboxPull/route.ts b/src/web/src/app/api/community/agent/inboxPull/route.tsdeleted file mode 100644index 90c999389..000000000--- a/src/web/src/app/api/community/agent/inboxPull/route.ts+++ /dev/null@@ -1,77 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, withD1Retry, CommunityAgentInboxPullRequestSchema } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"--const MAX_PULL = 200--/**- * POST /api/community/agent/inboxPull — plan §7.- *- * 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 = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- 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, ctx.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,- ctx.botUserId,- attachmentsByMessageId,- ),- { route: "community/agent/inboxPull:hydrate" },- )- return NextResponse.json({ messages, hasMore })-})diff --git a/src/web/src/app/api/community/agent/inboxSnapshot/route.ts b/src/web/src/app/api/community/agent/inboxSnapshot/route.tsdeleted file mode 100644index 338fd4df5..000000000--- a/src/web/src/app/api/community/agent/inboxSnapshot/route.ts+++ /dev/null@@ -1,21 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"--/**- * POST /api/community/agent/inboxSnapshot — plan §7. Body `{}`.- * Non-consuming bodiless summary of pending unread, bucketed per channel/DM.- */-export const POST = withAgentRunnerAuth(async (_req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)-- const snapshot = await queries.communityAgentInbox.getInboxSnapshotForAgent(db, ctx.botUserId)- const rows = await queries.communityAgentInbox.toInboxRows(db, snapshot, ctx.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/agent/joinServer/route.ts b/src/web/src/app/api/community/agent/joinServer/route.tsdeleted file mode 100644index 2764861f5..000000000--- a/src/web/src/app/api/community/agent/joinServer/route.ts+++ /dev/null@@ -1,102 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, ROLES, WS_EVENTS, isUniqueConstraintError, CommunityAgentJoinServerRequestSchema } from "@alook/shared"-import type { CommunityMemberJoin } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-import { fanOutToServerMembers, broadcastToUserSafe } from "@/lib/community/fanout"-import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"--/**- * POST /api/community/agent/joinServer — `alook server join --invite <link>`.- * Body `{ invite }` (bare token — the CLI extracts it client-side). Enforces- * an owner-only check: the invite must have been created by THIS bot's- * owner, so an owner can safely tell their bot to join any invite the owner- * pastes without the bot reasoning about who sent it.- *- * `invite.createdBy === null` (the original creator's account no longer- * exists) is treated as the generic "Invalid or expired invite" case, NOT an- * owner mismatch — checked before the real-mismatch branch (see plan's- * "Nullable createdBy" design note). Both rejection branches run BEFORE- * `useInvite`, so a foreign/dead-creator invite is never consumed by a- * rejected attempt.- */-export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- 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 = CommunityAgentJoinServerRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })- }-- const invite = await queries.communityInvite.getInviteByToken(db, parsed.data.invite)- if (!invite) {- return NextResponse.json({ error: "Invalid or expired invite" }, { status: 400 })- }- if (invite.createdBy === null) {- return NextResponse.json({ error: "Invalid or expired invite" }, { status: 400 })- }- if (invite.createdBy !== ctx.ownerUserId) {- return NextResponse.json(- {- error: "This invite was not created by your owner — refusing to join.",- hint: "Ask your owner to send an invite link they created themselves.",- },- { status: 403 },- )- }-- let result: Awaited<ReturnType<typeof queries.communityInvite.useInvite>>- try {- result = await queries.communityInvite.useInvite(db, parsed.data.invite, ctx.botUserId)- } catch (err: unknown) {- if (isUniqueConstraintError(err)) {- return NextResponse.json({ error: "Already a member" }, { status: 400 })- }- throw err- }- if (!result) {- return NextResponse.json({ error: "Invalid or expired invite" }, { status: 400 })- }-- logAudit(db, {- serverId: result.invite.serverId,- actorId: ctx.botUserId,- action: COMMUNITY_AUDIT_ACTIONS.BOT_JOINED_VIA_INVITE,- targetType: "invite",- targetId: result.invite.id,- })-- const memberEvent: CommunityMemberJoin = {- type: WS_EVENTS.MEMBER_JOIN,- serverId: result.invite.serverId,- member: {- id: result.member.id,- userId: result.member.userId,- name: result.member.userName ?? "",- discriminator: result.member.discriminator ?? undefined,- avatar: result.member.userImage ?? undefined,- role: result.member.role ?? ROLES.MEMBER,- joinedAt: result.member.joinedAt,- },- }-- fanOutToServerMembers(result.invite.serverId, memberEvent, { excludeUserId: ctx.botUserId })-- // The bot's OWNER isn't necessarily a member of the server the bot just- // joined, so `fanOutToServerMembers` (scoped to existing members) will- // never reach them. Send the same event directly to the owner so their- // bot-list / server-rail reflects the join without a hard refresh. If- // the owner IS also a member, `patchCacheJoin` in- // `use-server-members.ts` dedupes by userId (`total` bump is a no-op on- // re-delivery), so double-delivery is safe.- broadcastToUserSafe(ctx.ownerUserId, memberEvent)-- const server = await queries.communityServer.getServer(db, result.invite.serverId)- return NextResponse.json({ server: { id: server!.id, name: server!.name } })-})diff --git a/src/web/src/app/api/community/agent/listChannels/route.ts b/src/web/src/app/api/community/agent/listChannels/route.tsdeleted file mode 100644index 914a4cb72..000000000--- a/src/web/src/app/api/community/agent/listChannels/route.ts+++ /dev/null@@ -1,120 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, CommunityAgentListChannelsRequestSchema, formatRef } from "@alook/shared"-import type {- CommunityCliChannelGroup as ChannelGroup,- ChannelListItem,-} from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"--/**- * POST /api/community/agent/listChannels — `alook channel list`. Body- * `{ server? }` — `server` accepts either the server's id or its display- * name (resolved via `resolveServerByNameForMember`, same helper- * `listMembers` uses), or omit to list across every server the bot is in.- * Top-level channels only (`listChannelsForMember` filters- * `parentChannelId IS NULL`, mirroring `listServerChannels`) — same- * visibility rule a human sees: private-category channels appear only when the- * bot is an admin, the channel's creator, or an added member.- *- * Response is `{ groups: [{ category, channels: [{ref, name, type, visibility}] }] }`- * (plan §Design). Channels are bucketed by their `categoryId` — uncategorized- * (`categoryId === null`) is emitted first (Discord-style), then categories- * ordered by `position` (stable-sort by id on ties). Empty groups are dropped- * so the private-category group never leaks its name to a viewer with no- * access. `visibility` is derived from the row's category (`private = 1` →- * `"private"`, else `"public"`) — the same rule `isChannelPrivate` uses.- *- * When `server` is omitted, groups from every server the bot is in are- * concatenated into one flat `groups` array (no wire-shape branch — the CLI- * layer refuses to call without `--server`, so agents never hit this).- */-export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)-- 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 = CommunityAgentListChannelsRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })- }-- let servers: Array<{ id: string; name: string }>- if (parsed.data.server) {- servers = await queries.communityServer.resolveServerByNameForMember(db, ctx.botUserId, parsed.data.server)- if (servers.length === 0) {- return NextResponse.json({ error: `server not found: ${parsed.data.server}` }, { status: 404 })- }- if (servers.length > 1) {- const candidates = servers.map((s) => `${s.id} ("${s.name}")`).join(", ")- return NextResponse.json(- { error: `ambiguous server name "${parsed.data.server}" — matches ${servers.length} servers: ${candidates}` },- { status: 400 },- )- }- } else {- servers = await queries.communityServer.listUserServers(db, ctx.botUserId)- }-- // Fan out per-server DB work in parallel — for a bot in N servers this- // stays flat instead of paying N× the RTT that a sequential per-server- // loop would.- const perServer = await Promise.all(- servers.map(async (server) => {- const [rows, categories] = await Promise.all([- queries.communityChannel.listChannelsForMember(db, server.id, ctx.botUserId),- queries.communityCategory.listCategoriesByServer(db, server.id),- ])-- const categoryById = new Map<string, { id: string; name: string; position: number | null; private: number | null }>()- for (const c of categories) categoryById.set(c.id, c)-- const uncategorized: ChannelListItem[] = []- const byCategory = new Map<string, ChannelListItem[]>()-- // rows come from `listChannelsForMember` already ordered by- // `communityChannel.position asc`; bucket into groups preserving that- // per-bucket order.- for (const c of rows) {- const cat = c.categoryId ? categoryById.get(c.categoryId) : null- const isPrivate = !!(cat && (cat.private ?? 0) === 1)- const item: ChannelListItem = {- ref: formatRef({ server: server.name, channel: c.name }),- name: c.name,- type: c.type,- visibility: isPrivate ? "private" : "public",- }- if (!c.categoryId || !cat) {- uncategorized.push(item)- } else {- const bucket = byCategory.get(c.categoryId) ?? []- bucket.push(item)- byCategory.set(c.categoryId, bucket)- }- }-- const serverGroups: ChannelGroup[] = []- if (uncategorized.length > 0) {- serverGroups.push({ category: null, channels: uncategorized })- }- for (const cat of categories) {- const items = byCategory.get(cat.id)- if (!items || items.length === 0) continue- serverGroups.push({- category: { name: cat.name, private: (cat.private ?? 0) === 1 },- channels: items,- })- }- return serverGroups- }),- )-- const groups: ChannelGroup[] = perServer.flat()-- return NextResponse.json({ groups })-})diff --git a/src/web/src/app/api/community/agent/listFriends/route.ts b/src/web/src/app/api/community/agent/listFriends/route.tsdeleted file mode 100644index fb279bd33..000000000--- a/src/web/src/app/api/community/agent/listFriends/route.ts+++ /dev/null@@ -1,63 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries } from "@alook/shared"-import type { FriendCard } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-import { wsDoFetch } from "@/lib/broadcast"--/**- * POST /api/community/agent/listFriends — the bot's friends + pending, three- * buckets, each entry a profile card. Never emits `isBot`.- * See plans/agent-friendship-approval-gate.md §Route 2.- */-export const POST = withAgentRunnerAuth(async (_req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)-- const buckets = await queries.communityFriendship.listAgentFriends(db, ctx.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: ctx.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/agent/listMembers/route.ts b/src/web/src/app/api/community/agent/listMembers/route.tsdeleted file mode 100644index 3861384e1..000000000--- a/src/web/src/app/api/community/agent/listMembers/route.ts+++ /dev/null@@ -1,51 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, CommunityAgentListMembersRequestSchema, formatHandle } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"--/**- * POST /api/community/agent/listMembers — `alook server member --server <id-or-name>`.- * Body `{ server }`. `server` accepts either the server id or its name (never- * id-only, never name-only) — reuses `resolveServerByNameForMember`'s existing- * id-then-name resolution, scoped to the bot's own membership.- *- * Ambiguous name matches (2+ servers) are NOT surfaced via a separate `hint`- * field — the candidate ids/names are baked directly into the `error` string,- * since there is no structured-hint consumer on the CLI side (see plan's- * "hint stays a plain string" design note).- */-export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- 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 = CommunityAgentListMembersRequestSchema.safeParse(raw)- if (!parsed.success) {- return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })- }-- const servers = await queries.communityServer.resolveServerByNameForMember(db, ctx.botUserId, parsed.data.server)- if (servers.length === 0) {- return NextResponse.json({ error: `server not found: ${parsed.data.server}` }, { status: 404 })- }- if (servers.length > 1) {- const candidates = servers.map((s) => `${s.id} ("${s.name}")`).join(", ")- return NextResponse.json(- { error: `ambiguous server name "${parsed.data.server}" — matches ${servers.length} servers: ${candidates}` },- { status: 400 },- )- }- const serverId = servers[0]!.id-- const rows = await queries.communityMember.listMembers(db, serverId)- const members = rows.map((r) => ({- handle: formatHandle(r.userName ?? "", r.discriminator ?? "0000"),- role: r.role ?? "member",- }))-- return NextResponse.json({ members })-})diff --git a/src/web/src/app/api/community/agent/listServers/route.ts b/src/web/src/app/api/community/agent/listServers/route.tsdeleted file mode 100644index 61431cb47..000000000--- a/src/web/src/app/api/community/agent/listServers/route.ts+++ /dev/null@@ -1,15 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"--/**- * POST /api/community/agent/listServers — plan §7. Body `{}`. Which- * servers/workspaces the bot participates in. Never includes `ownerUserId`.- */-export const POST = withAgentRunnerAuth(async (_req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)- const rows = await queries.communityServer.listUserServers(db, ctx.botUserId)- const servers = rows.map((s) => ({ id: s.id, name: s.name }))- return NextResponse.json({ servers })-})diff --git a/src/web/src/app/api/community/agent/nap/route.ts b/src/web/src/app/api/community/agent/nap/route.tsdeleted file mode 100644index 2eac17a59..000000000--- a/src/web/src/app/api/community/agent/nap/route.ts+++ /dev/null@@ -1,82 +0,0 @@-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 { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-import { pushAgentNapToMachine } from "@/lib/community/bot-push"--/**- * POST /api/community/agent/nap — `alook nap --handoff <file>|--text <s>`.- *- * 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 = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- 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, ctx.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, ctx.machineId, {- agentId: ctx.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.- // Stamp lastRefreshContextAt at the SAME chokepoint (single write point),- // reusing the audit row's own createdAt so the my-bots "last refreshed"- // indicator can never drift from the nap audit event.- const inserted = await queries.communityBotAuditLog.insertBotAuditNap(db, { botId: ctx.botUserId })- if (inserted) {- await queries.communityBot.touchBotRefreshContext(db, ctx.botUserId, inserted.createdAt)- }-- return NextResponse.json({ napped: true })-})diff --git a/src/web/src/app/api/community/agent/reactAdd/route.ts b/src/web/src/app/api/community/agent/reactAdd/route.tsdeleted file mode 100644index 6fb329213..000000000--- a/src/web/src/app/api/community/agent/reactAdd/route.ts+++ /dev/null@@ -1,94 +0,0 @@-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 { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-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/agent/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.- */-export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- 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, ctx.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, ctx.botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- } else {- const gate = await requireChannelMember(db, resolved.channelId, ctx.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: ctx.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: ctx.botUserId,- emoji: body.emoji,- channelId: resolved.channelId,- }-- if (isDmTarget(resolved)) {- await fanOutToDM(resolved.channelId, event, { excludeUserId: ctx.botUserId })- } else {- await fanOutToChannel(resolved.channelId, event, { excludeUserId: ctx.botUserId })- }-- return NextResponse.json({ ok: true })-})diff --git a/src/web/src/app/api/community/agent/read/route.ts b/src/web/src/app/api/community/agent/read/route.tsdeleted file mode 100644index b7a2a7390..000000000--- a/src/web/src/app/api/community/agent/read/route.ts+++ /dev/null@@ -1,56 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, CommunityAgentReadRequestSchema } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-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/agent/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).- */-export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- 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, ctx.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, ctx.botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- } else {- const gate = await requireChannelMember(db, resolved.channelId, ctx.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, ctx.botUserId)-- return NextResponse.json({ items: messages, hasMore, ...(latestSeq !== undefined ? { latestSeq } : {}) })-})diff --git a/src/web/src/app/api/community/agent/resolve/route.ts b/src/web/src/app/api/community/agent/resolve/route.tsdeleted file mode 100644index 3b54cc632..000000000--- a/src/web/src/app/api/community/agent/resolve/route.ts+++ /dev/null@@ -1,72 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, CommunityAgentResolveRequestSchema } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-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/agent/resolve — plan §7. Body `{ channel, seq }` (two- * separate fields, not a combined `"/server/channel#N"` ref string — the- * CLI's own `parseRef` already splits a user-typed ref before calling this).- * `seq === 0` is the legacy pre-migration sentinel, never a real message —- * rejected with 404 (defense-in-depth).- */-export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- 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, ctx.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, ctx.botUserId)- if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })- } else {- const gate = await requireChannelMember(db, resolved.channelId, ctx.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,- ctx.botUserId,- attachments,- )- return NextResponse.json({ message })-})diff --git a/src/web/src/app/api/community/agent/send/route.ts b/src/web/src/app/api/community/agent/send/route.tsdeleted file mode 100644index 67a9da7f0..000000000--- a/src/web/src/app/api/community/agent/send/route.ts+++ /dev/null@@ -1,224 +0,0 @@-import { NextResponse, type NextRequest } from "next/server"-import { queries, withD1Retry, CommunityAgentSendRequestSchema } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-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/agent/send — plan §7.- *- * Single resolve, WITH create flags (`createDmIfMissing`/`createThreadIfMissing:- * true`), rather than the plan's literal read-only-then-mutating double- * resolve. This is intentionally simplified but behaviorally identical: a- * DM/thread row can only be auto-created when it has NEVER had a message- * sent to it, which means that scope's `community_message_seq` counter is- * necessarily absent (`latestSeq === 0`) — i.e. it is IMPOSSIBLE for the- * alignment gate to block a send into a target that doesn't exist yet- * (blocking requires `latestSeq > seen`, and `seen >= 0` always). So- * auto-create can never fire on a request this gate would have blocked- * anyway — a single resolve is safe and avoids a redundant DB round trip.- */-export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {- 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, ctx.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/agent/send:latest-seq" },- ),- withD1Retry(- () => queries.communityReadState.getReadState(db, { userId: ctx.botUserId, ...scopeTarget }),- { route: "community/agent/send:read-state" },- ),- ])- const seen = body.seenUpToSeq ?? readState?.lastReadSeq ?? 0- const hasUnread = await withD1Retry(- () => queries.communityAgentInbox.hasDeliverableUnreadForAgentScope(- db,- ctx.botUserId,- resolved.channelId,- seen,- ),- { route: "community/agent/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, ctx.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, ctx.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: ctx.botUserId,- targetId: attachmentTargetId,- }),- { route: "community/agent/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/agent/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: ctx.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/agent/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,- ctx.botUserId,- orderedAttachments,- )- return NextResponse.json({ state: "sent", message, deduped: result.deduped })-})diff --git a/src/web/src/app/api/community/agent/nap/route.test.ts b/src/web/src/app/api/community/nap/route.test.tssimilarity index 79%rename from src/web/src/app/api/community/agent/nap/route.test.tsrename to src/web/src/app/api/community/nap/route.test.tsindex ffe8090c7..90598fd76 100644--- a/src/web/src/app/api/community/agent/nap/route.test.ts+++ b/src/web/src/app/api/community/nap/route.test.ts@@ -32,17 +32,28 @@ vi.mock("@/lib/community/bot-push", () => ({pushAgentNapToMachine: (...a: unknown[]) => mockPushAgentNapToMachine(...a),}))-// Runner-key auth: the bot acts on ITSELF — botUserId/machineId come from the-// authenticated runner, not the request body.-vi.mock("@/lib/middleware/community-agent-runner-auth", () => ({- withAgentRunnerAuth: (handler: any) => async (req: any) =>- handler(req, { env: { DB: {} }, botUserId: "b1", machineId: "mac_1" }),+// Unified actor: nap is a bot-only verb (moved from /agent/nap to /community/nap,+// plans/22 §9). withCommunityActor injects the resolved actor; the bot acts on+// ITSELF — botUserId/machineId come from the authenticated runner, not the body.+// requireBot is a passthrough for a bot actor (human → 403, covered by the+// community-actor unit test). This test mocks the wrapper directly (as the+// incoming /agent/nap test did) so it stays focused on the nap handler logic.+vi.mock("@/lib/middleware/community-actor", () => ({+ withCommunityActor: (handler: any) => async (req: any) =>+ handler(req, {+ env: { DB: {} },+ actor: { kind: "bot", userId: "b1", ownerUserId: "owner_1", machineId: "mac_1" },+ }),+ requireBot: (actor: any) =>+ actor.kind === "bot"+ ? { ok: true, bot: actor }+ : { ok: false, response: new Response(null, { status: 403 }) },}))import { POST } from "./route"function req(body: unknown = { handoff: "note to future self" }) {- return new NextRequest("http://localhost/api/community/agent/nap", {+ return new NextRequest("http://localhost/api/community/nap", {method: "POST",body: JSON.stringify(body),})@@ -59,7 +70,7 @@ const READY_CTX = {ownerUserId: "owner_1",}-describe("POST /api/community/agent/nap", () => {+describe("POST /api/community/nap", () => {beforeEach(() => {vi.clearAllMocks()})@@ -114,7 +125,8 @@ describe("POST /api/community/agent/nap", () => {// Single-source invariant (mirror of reset-session): lastRefreshContextAt is// stamped exactly once, in lockstep with the nap audit row, reusing that// row's OWN createdAt — so the my-bots "last refreshed" indicator can never- // drift from the nap audit event.+ // drift from the nap audit event. (Ported onto the moved /community/nap route+ // during the rebase — the /agent/nap this feature originally patched is gone.)expect(mockTouchBotRefreshContext).toHaveBeenCalledTimes(1)expect(mockTouchBotRefreshContext).toHaveBeenCalledWith(expect.anything(),diff --git a/src/web/src/app/api/community/nap/route.ts b/src/web/src/app/api/community/nap/route.tsindex 857370cc7..4d606e8e9 100644--- a/src/web/src/app/api/community/nap/route.ts+++ b/src/web/src/app/api/community/nap/route.ts@@ -76,7 +76,15 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {}// Audit on delivery only (mirrors reset/model-switch). No notification.- await queries.communityBotAuditLog.insertBotAuditNap(db, { botId: botUserId })+ // Stamp lastRefreshContextAt at the SAME chokepoint (single write point),+ // reusing the audit row's own createdAt so the my-bots "last refreshed"+ // indicator can never drift from the nap audit event. (Ported from the+ // incoming my-bots refresh feature onto this moved /community/nap route+ // during the rebase — the /agent/nap it originally patched was deleted here.)+ const inserted = await queries.communityBotAuditLog.insertBotAuditNap(db, { botId: botUserId })+ if (inserted) {+ await queries.communityBot.touchBotRefreshContext(db, botUserId, inserted.createdAt)+ }return NextResponse.json({ napped: true })})diff --git a/src/web/src/lib/middleware/community-agent-runner-auth.test.ts b/src/web/src/lib/middleware/community-agent-runner-auth.test.tsdeleted file mode 100644index 3e1f5df21..000000000--- a/src/web/src/lib/middleware/community-agent-runner-auth.test.ts+++ /dev/null@@ -1,177 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest, NextResponse } from "next/server"-import { makeD1Error } from "@alook/shared/db/resilience-testing"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}))--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))--const mockFindActiveAgentRunnerKeyByBearer = vi.fn()-const mockGetUserInternal = vi.fn()-const mockGetBotBinding = vi.fn()-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- communityMachine: {- findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a),- },- user: {- getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),- },- communityBot: {- getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a),- },- },- }-})--import { withAgentRunnerAuth } from "./community-agent-runner-auth"--const handler = vi.fn(async (_req: NextRequest, ctx: any) => NextResponse.json({ ok: true, ctx }))--describe("withAgentRunnerAuth", () => {- beforeEach(() => {- vi.clearAllMocks()- })-- const wrapped = withAgentRunnerAuth(handler)-- it("rejects when Authorization is missing", async () => {- const req = new NextRequest("http://localhost/x")- const res = await wrapped(req)- expect(res.status).toBe(401)- expect(await res.json()).toEqual({ error: "missing or malformed Authorization header" })- })-- it("rejects a non-crk_ bearer without querying the DB", async () => {- const req = new NextRequest("http://localhost/x", { headers: { Authorization: "Bearer sk_something" } })- const res = await wrapped(req)- expect(res.status).toBe(401)- expect(mockFindActiveAgentRunnerKeyByBearer).not.toHaveBeenCalled()- })-- it("rejects a revoked/unknown crk_ key", async () => {- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue(null)- const req = new NextRequest("http://localhost/x", { headers: { Authorization: "Bearer crk_unknown" } })- const res = await wrapped(req)- expect(res.status).toBe(401)- expect(await res.json()).toEqual({ error: "runner key revoked or unknown" })- })-- it("rejects when the bot user is missing, not a bot, or soft-deleted", async () => {- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({- userId: "owner_1",- machineId: "m_1",- agentId: "bot_1",- })- for (const badUser of [null, { isBot: false, deletedAt: null }, { isBot: true, deletedAt: "2026-01-01" }]) {- mockGetUserInternal.mockResolvedValue(badUser)- const req = new NextRequest("http://localhost/x", { headers: { Authorization: "Bearer crk_abc" } })- const res = await wrapped(req)- expect(res.status).toBe(401)- expect(await res.json()).toEqual({ error: "bot not found or inactive" })- }- expect(mockGetBotBinding).not.toHaveBeenCalled()- })-- it("rejects on binding machine mismatch", async () => {- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({- userId: "owner_1",- machineId: "m_1",- agentId: "bot_1",- })- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })- mockGetBotBinding.mockResolvedValue({ machineId: "m_OTHER", runtime: "claude" })- const req = new NextRequest("http://localhost/x", { headers: { Authorization: "Bearer crk_abc" } })- const res = await wrapped(req)- expect(res.status).toBe(401)- expect(await res.json()).toEqual({ error: "bot binding mismatch" })- })-- it("rejects when no binding exists at all", async () => {- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({- userId: "owner_1",- machineId: "m_1",- agentId: "bot_1",- })- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })- mockGetBotBinding.mockResolvedValue(null)- const req = new NextRequest("http://localhost/x", { headers: { Authorization: "Bearer crk_abc" } })- const res = await wrapped(req)- expect(res.status).toBe(401)- })-- it("populates ctx { botUserId, ownerUserId, machineId } on a valid crk_ for a live bot on the right machine", async () => {- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({- userId: "owner_1",- machineId: "m_1",- agentId: "bot_1",- })- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })- mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })- const req = new NextRequest("http://localhost/x", { headers: { Authorization: "Bearer crk_abc" } })- const res = await wrapped(req)- expect(res.status).toBe(200)- const body = (await res.json()) as { ctx: any }- // Field mapping must not be inverted: row.agentId → botUserId, row.userId → ownerUserId.- expect(body.ctx).toMatchObject({- botUserId: "bot_1",- ownerUserId: "owner_1",- machineId: "m_1",- })- })-- it("returns 503 + Retry-After when D1 exhausts retries on the runner-key lookup", async () => {- vi.spyOn(console, "log").mockImplementation(() => {})- mockFindActiveAgentRunnerKeyByBearer.mockRejectedValue(makeD1Error("internal_error"))- const req = new NextRequest("http://localhost/x", { headers: { Authorization: "Bearer crk_abc" } })- const res = await wrapped(req)- expect(res.status).toBe(503)- expect(res.headers.get("Retry-After")).toBe("1")- expect(await res.json()).toEqual({ error: "database temporarily unavailable" })- }, 10_000)-- it("returns 503 when D1 exhausts on the getUserInternal step", async () => {- vi.spyOn(console, "log").mockImplementation(() => {})- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({- userId: "owner_1",- machineId: "m_1",- agentId: "bot_1",- })- mockGetUserInternal.mockRejectedValue(makeD1Error("sqlite_busy"))- const req = new NextRequest("http://localhost/x", { headers: { Authorization: "Bearer crk_abc" } })- const res = await wrapped(req)- expect(res.status).toBe(503)- }, 10_000)-- it("preserves 401 for non-D1 failures — bot deleted, no retry", async () => {- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({- userId: "owner_1",- machineId: "m_1",- agentId: "bot_1",- })- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: "2026-01-01" })- const req = new NextRequest("http://localhost/x", { headers: { Authorization: "Bearer crk_abc" } })- const res = await wrapped(req)- expect(res.status).toBe(401)- expect(mockGetUserInternal).toHaveBeenCalledTimes(1)- })-- it("preserves 401 for binding mismatch — no retry", async () => {- mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({- userId: "owner_1",- machineId: "m_1",- agentId: "bot_1",- })- mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })- mockGetBotBinding.mockResolvedValue({ machineId: "m_OTHER" })- const req = new NextRequest("http://localhost/x", { headers: { Authorization: "Bearer crk_abc" } })- const res = await wrapped(req)- expect(res.status).toBe(401)- expect(mockGetBotBinding).toHaveBeenCalledTimes(1)- })-})diff --git a/src/web/src/lib/middleware/community-agent-runner-auth.ts b/src/web/src/lib/middleware/community-agent-runner-auth.tsindex ee68033c4..5b2157fa5 100644--- a/src/web/src/lib/middleware/community-agent-runner-auth.ts+++ b/src/web/src/lib/middleware/community-agent-runner-auth.ts@@ -1,16 +1,16 @@-import { NextRequest, NextResponse } from "next/server"-import { getCloudflareContext } from "@opennextjs/cloudflare"+import { NextResponse } from "next/server"import { queries, withD1Retry, createLogger } from "@alook/shared"import type { Database } from "@alook/shared"-import { getDb } from "@/lib/db"const log = createLogger({ service: "community-agent-runner-auth" })/*** The bot identity resolved from a `crk_` runner key — the BOT's own user id,- * its OWNER's user id, and the machine it's bound to. Shared by both- * `withAgentRunnerAuth` (the legacy `/agent/*` wrapper) and the unified- * `withCommunityActor` (see community-actor.ts).+ * its OWNER's user id, and the machine it's bound to. Consumed by the unified+ * `withCommunityActor` (see community-actor.ts). The legacy `withAgentRunnerAuth`+ * wrapper and the `/api/community/agent/*` route tree it guarded were deleted in+ * plans/22 §9 phase 5 once every bot verb moved onto the unified actor;+ * `resolveBotActor` is the surviving, shared crk_ validator.*/export interface ResolvedBotActor {botUserId: string@@ -18,20 +18,6 @@ export interface ResolvedBotActor {machineId: string}-interface AgentRunnerAuthContext {- env: Env- /** The BOT's own user id — `row.agentId` from `findActiveAgentRunnerKeyByBearer`. */- botUserId: string- /** The bot's OWNER (the human who ran `mintAgentRunnerKey`) — `row.userId`. */- ownerUserId: string- machineId: string-}--export type AgentRunnerAuthenticatedHandler = (- req: NextRequest,- ctx: AgentRunnerAuthContext & { params?: Record<string, string> }-) => Promise<NextResponse | Response>-const RETRY_OPTS = { route: "community-agent-runner-auth" }function serviceUnavailable(): NextResponse {@@ -135,58 +121,3 @@ export async function resolveBotActor(actor: { botUserId: row.agentId, ownerUserId: row.userId, machineId: row.machineId },}}--/**- * Agent-runner auth middleware for the CLI bridge (`/api/community/agent/*`).- * Requires `Authorization: Bearer crk_…`. Now a thin adapter over the shared- * `resolveBotActor` — behavior is unchanged: a missing/non-`crk_` bearer 401s- * here (this wrapper is bot-only, so `not_bot` maps to the same 401 the old- * inline check returned).- *- * NOTE (migration): this wrapper stays live until the last `/agent/*` route is- * moved onto `withCommunityActor`; then it and the `/agent` tree are deleted- * together. See plans/22-community-unified-actor-route-unify.md §9.- */-export function withAgentRunnerAuth(handler: AgentRunnerAuthenticatedHandler) {- return async (- req: NextRequest,- context?: { params?: Promise<Record<string, string>> | Record<string, string> }- ) => {- const resolvedParams = context?.params- ? context.params instanceof Promise- ? await context.params- : context.params- : undefined-- const authHeader = req.headers.get("Authorization")- // Preserve the old messages: a missing/malformed Bearer vs a non-crk_- // bearer 401'd with distinct copy. `resolveBotActor` collapses both to- // `not_bot`, so re-derive the specific 401 here (bot-only wrapper).- if (!authHeader || !authHeader.startsWith("Bearer ")) {- return NextResponse.json({ error: "missing or malformed Authorization header" }, { status: 401 })- }- if (!authHeader.slice(7).trim().startsWith("crk_")) {- return NextResponse.json({ error: "invalid runner key" }, { status: 401 })- }-- const { env } = await getCloudflareContext({ async: true })- const cloudflareEnv = env as Env- const db = getDb(cloudflareEnv.DB)-- const resolved = await resolveBotActor(db, authHeader)- if (resolved.kind === "error") return resolved.response- // `not_bot` is unreachable here (the crk_ guard above already returned), but- // handle it defensively as the same 401 the guard would have produced.- if (resolved.kind === "not_bot") {- return NextResponse.json({ error: "invalid runner key" }, { status: 401 })- }-- return handler(req, {- env: cloudflareEnv,- botUserId: resolved.actor.botUserId,- ownerUserId: resolved.actor.ownerUserId,- machineId: resolved.actor.machineId,- params: resolvedParams,- })- }-}