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
refactor(web): split api.ts, add withEnv wrapper, type responses.ts (#328)
Generb13918e77c00
diff --git a/src/web/src/app/api/agent-links/[id]/route.test.ts b/src/web/src/app/api/agent-links/[id]/route.test.tsindex bd9a23604..159045b57 100644--- a/src/web/src/app/api/agent-links/[id]/route.test.ts+++ b/src/web/src/app/api/agent-links/[id]/route.test.ts@@ -32,7 +32,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: (handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });},}));diff --git a/src/web/src/app/api/agent-links/[id]/route.ts b/src/web/src/app/api/agent-links/[id]/route.tsindex 454755f8c..18c724102 100644--- a/src/web/src/app/api/agent-links/[id]/route.ts+++ b/src/web/src/app/api/agent-links/[id]/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, UpdateAgentLinkRequestSchema } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const PATCH = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("agent link id is required", 400);@@ -43,8 +41,7 @@ export const DELETE = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("agent link id is required", 400);diff --git a/src/web/src/app/api/agent-links/route.test.ts b/src/web/src/app/api/agent-links/route.test.tsindex 87e804a61..a99696b33 100644--- a/src/web/src/app/api/agent-links/route.test.ts+++ b/src/web/src/app/api/agent-links/route.test.ts@@ -59,7 +59,7 @@ vi.mock("@/lib/agent-visibility", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: (handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });},}));diff --git a/src/web/src/app/api/agent-links/route.ts b/src/web/src/app/api/agent-links/route.tsindex d79fdd4dc..81e74d712 100644--- a/src/web/src/app/api/agent-links/route.ts+++ b/src/web/src/app/api/agent-links/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import {queries,CreateAgentLinkRequestSchema,@@ -18,8 +17,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const url = new URL(req.url);const limit = Math.min(Number(url.searchParams.get("limit")) || 200, 500);@@ -43,8 +41,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const [body, err] = await parseBody(req, CreateAgentLinkRequestSchema);if (err) return err;@@ -84,8 +81,7 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const agentId = new URL(req.url).searchParams.get("agentId");if (!agentId) {diff --git a/src/web/src/app/api/agents/[id]/access/[userId]/route.test.ts b/src/web/src/app/api/agents/[id]/access/[userId]/route.test.tsindex ffaf2c045..ac12efb9a 100644--- a/src/web/src/app/api/agents/[id]/access/[userId]/route.test.ts+++ b/src/web/src/app/api/agents/[id]/access/[userId]/route.test.ts@@ -34,7 +34,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/[id]/access/[userId]/route.ts b/src/web/src/app/api/agents/[id]/access/[userId]/route.tsindex 84ccfe697..69d7c145f 100644--- a/src/web/src/app/api/agents/[id]/access/[userId]/route.ts+++ b/src/web/src/app/api/agents/[id]/access/[userId]/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;const { id: agentId, userId: targetUserId } = ctx.params!;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const ag = await queries.agent.getAgent(db, agentId, ws.workspaceId);if (!ag) return writeError("agent not found", 404);if (ag.ownerId !== ctx.userId) return writeError("agent owner access required", 403);diff --git a/src/web/src/app/api/agents/[id]/access/route.test.ts b/src/web/src/app/api/agents/[id]/access/route.test.tsindex e2fd287a2..2adfba0d7 100644--- a/src/web/src/app/api/agents/[id]/access/route.test.ts+++ b/src/web/src/app/api/agents/[id]/access/route.test.ts@@ -34,7 +34,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/[id]/access/route.ts b/src/web/src/app/api/agents/[id]/access/route.tsindex d11362420..4fd976d52 100644--- a/src/web/src/app/api/agents/[id]/access/route.ts+++ b/src/web/src/app/api/agents/[id]/access/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, GrantAgentAccessRequestSchema, type Database } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -18,8 +17,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;const { id } = ctx.params!;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const check = await requireAgentOwner(db, id, ws.workspaceId, ctx.userId);if (check.error) return check.error;const accessList = await queries.agentAccess.listAgentAccess(db, id, ws.workspaceId);@@ -34,8 +32,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const { id } = ctx.params!;const [body, err] = await parseBody(req, GrantAgentAccessRequestSchema);if (err) return err;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const check = await requireAgentOwner(db, id, ws.workspaceId, ctx.userId);if (check.error) return check.error;const access = await queries.agentAccess.grantAgentAccess(db, { agentId: id, workspaceId: ws.workspaceId, userId: body.user_id });diff --git a/src/web/src/app/api/agents/[id]/active-tasks/route.test.ts b/src/web/src/app/api/agents/[id]/active-tasks/route.test.tsindex c69af453f..43a0f2231 100644--- a/src/web/src/app/api/agents/[id]/active-tasks/route.test.ts+++ b/src/web/src/app/api/agents/[id]/active-tasks/route.test.ts@@ -29,7 +29,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/[id]/active-tasks/route.ts b/src/web/src/app/api/agents/[id]/active-tasks/route.tsindex cb3f4153b..482522710 100644--- a/src/web/src/app/api/agents/[id]/active-tasks/route.ts+++ b/src/web/src/app/api/agents/[id]/active-tasks/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { createDb, queries } from "@alook/shared";import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";@@ -8,8 +7,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = createDb((env as Env).DB);+ const db = createDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("agent id is required", 400);diff --git a/src/web/src/app/api/agents/[id]/activity/route.test.ts b/src/web/src/app/api/agents/[id]/activity/route.test.tsindex a02d3ef6e..5f89351bf 100644--- a/src/web/src/app/api/agents/[id]/activity/route.test.ts+++ b/src/web/src/app/api/agents/[id]/activity/route.test.ts@@ -28,7 +28,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/[id]/activity/route.ts b/src/web/src/app/api/agents/[id]/activity/route.tsindex d4412f38f..b39c1770a 100644--- a/src/web/src/app/api/agents/[id]/activity/route.ts+++ b/src/web/src/app/api/agents/[id]/activity/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { createDb, queries } from "@alook/shared";import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";@@ -9,8 +8,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = createDb((env as Env).DB);+ const db = createDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("agent id is required", 400);diff --git a/src/web/src/app/api/agents/[id]/chat-init/route.test.ts b/src/web/src/app/api/agents/[id]/chat-init/route.test.tsindex 805d0e3e3..0ce14a2b5 100644--- a/src/web/src/app/api/agents/[id]/chat-init/route.test.ts+++ b/src/web/src/app/api/agents/[id]/chat-init/route.test.ts@@ -61,7 +61,7 @@ vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params =ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/[id]/chat-init/route.ts b/src/web/src/app/api/agents/[id]/chat-init/route.tsindex 7fee48554..4416bf6f8 100644--- a/src/web/src/app/api/agents/[id]/chat-init/route.ts+++ b/src/web/src/app/api/agents/[id]/chat-init/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -18,8 +17,7 @@ export const POST = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/agents/[id]/conversation/route.test.ts b/src/web/src/app/api/agents/[id]/conversation/route.test.tsindex 16979b8d3..1498335e3 100644--- a/src/web/src/app/api/agents/[id]/conversation/route.test.ts+++ b/src/web/src/app/api/agents/[id]/conversation/route.test.ts@@ -25,7 +25,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/[id]/conversation/route.ts b/src/web/src/app/api/agents/[id]/conversation/route.tsindex d5bd09092..d0d6062d0 100644--- a/src/web/src/app/api/agents/[id]/conversation/route.ts+++ b/src/web/src/app/api/agents/[id]/conversation/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const POST = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/agents/[id]/conversations/route.test.ts b/src/web/src/app/api/agents/[id]/conversations/route.test.tsindex bc1c43a94..7dab91503 100644--- a/src/web/src/app/api/agents/[id]/conversations/route.test.ts+++ b/src/web/src/app/api/agents/[id]/conversations/route.test.ts@@ -24,7 +24,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/[id]/conversations/route.ts b/src/web/src/app/api/agents/[id]/conversations/route.tsindex 14c4bb242..88d1e7d2a 100644--- a/src/web/src/app/api/agents/[id]/conversations/route.ts+++ b/src/web/src/app/api/agents/[id]/conversations/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.tsindex 5d3068b02..6a589c566 100644--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.ts+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.ts@@ -33,7 +33,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: { DB: {}, ENCRYPTION_KEY: "test-key", EMAIL_WORKER: { fetch: mockEmailWorkerFetch } }, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.tsindex 247ee1ea8..0850ee6e5 100644--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, UpdateEmailAccountSchema, DEV_EMAIL_WORKER_URL } from "@alook/shared"import { getDb } from "@/lib/db"import { encrypt } from "@alook/shared/crypto"@@ -43,8 +42,7 @@ export const PATCH = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx)if (ws instanceof Response) return ws- const { env } = getCloudflareContext()- const cfEnv = env as Env+ const cfEnv = ctx.envconst db = getDb(cfEnv.DB)const agentId = ctx.params?.id@@ -97,8 +95,7 @@ export const DELETE = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx)if (ws instanceof Response) return ws- const { env } = getCloudflareContext()- const cfEnv = env as Env+ const cfEnv = ctx.envconst db = getDb(cfEnv.DB)const agentId = ctx.params?.iddiff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.tsindex 2ac5757a7..97ee7797c 100644--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.ts+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.ts@@ -25,7 +25,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: { DB: {}, EMAIL_WORKER: { fetch: mockEmailWorkerFetch } }, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.tsindex 80163f6fe..713a74919 100644--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.ts+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, DEV_EMAIL_WORKER_URL } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"@@ -9,8 +8,7 @@ export const POST = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx)if (ws instanceof Response) return ws- const { env } = getCloudflareContext()- const cfEnv = env as Env+ const cfEnv = ctx.envconst db = getDb(cfEnv.DB)const agentId = ctx.params?.iddiff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.tsindex 09729545c..13f3b25dd 100644--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.ts+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.ts@@ -25,7 +25,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/[id]/email-accounts/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/route.test.tsindex 79cded18b..d3ece9075 100644--- a/src/web/src/app/api/agents/[id]/email-accounts/route.test.ts+++ b/src/web/src/app/api/agents/[id]/email-accounts/route.test.ts@@ -31,7 +31,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: { DB: {}, ENCRYPTION_KEY: "test-key", EMAIL_WORKER: { fetch: mockEmailWorkerFetch } }, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/[id]/email-accounts/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/route.tsindex a323d491a..88f1fe2eb 100644--- a/src/web/src/app/api/agents/[id]/email-accounts/route.ts+++ b/src/web/src/app/api/agents/[id]/email-accounts/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, CreateEmailAccountSchema, DEV_EMAIL_WORKER_URL } from "@alook/shared"import { getDb } from "@/lib/db"import { encrypt } from "@alook/shared/crypto"@@ -35,8 +34,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx)if (ws instanceof Response) return ws- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const agentId = ctx.params?.idif (!agentId) return writeError("agent id is required", 400)@@ -52,8 +50,7 @@ export const POST = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx)if (ws instanceof Response) return ws- const { env } = getCloudflareContext()- const cfEnv = env as Env+ const cfEnv = ctx.envconst db = getDb(cfEnv.DB)const agentId = ctx.params?.iddiff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.tsindex 95d625aab..0e7f57c34 100644--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.ts+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.ts@@ -26,7 +26,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.tsindex 89c83a340..6b7e2428e 100644--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.ts+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server"-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, MeetingStatus } from "@alook/shared"import { withAuth } from "@/lib/middleware/auth"import { withWorkspaceMember } from "@/lib/middleware/workspace"@@ -11,8 +10,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx)if (ws instanceof Response) return ws- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const agentId = ctx.params?.idif (!agentId) return writeError("agent id is required", 400)diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.tsindex b5ea8a0a6..78c9e6f3f 100644--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.ts+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.ts@@ -25,7 +25,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.tsindex ffc40a9b9..24ca1395b 100644--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.ts+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server"-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { withAuth } from "@/lib/middleware/auth"import { withWorkspaceMember } from "@/lib/middleware/workspace"@@ -11,8 +10,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx)if (ws instanceof Response) return ws- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const agentId = ctx.params?.idif (!agentId) return writeError("agent id is required", 400)@@ -37,8 +35,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx)if (ws instanceof Response) return ws- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const agentId = ctx.params?.idif (!agentId) return writeError("agent id is required", 400)diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.tsindex 1a8c99637..dc7d4e509 100644--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.ts+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.ts@@ -26,7 +26,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.tsindex 7c6df26aa..d6cf91d95 100644--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.ts+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server"-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, MeetingStatus } from "@alook/shared"import { withAuth } from "@/lib/middleware/auth"import { withWorkspaceMember } from "@/lib/middleware/workspace"@@ -11,8 +10,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx)if (ws instanceof Response) return ws- const { env } = getCloudflareContext()- const cfEnv = env as Env+ const cfEnv = ctx.envconst db = getDb(cfEnv.DB)const agentId = ctx.params?.iddiff --git a/src/web/src/app/api/agents/[id]/meetings/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/route.test.tsindex 9f2dbce72..eb6f1e683 100644--- a/src/web/src/app/api/agents/[id]/meetings/route.test.ts+++ b/src/web/src/app/api/agents/[id]/meetings/route.test.ts@@ -31,7 +31,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/[id]/meetings/route.ts b/src/web/src/app/api/agents/[id]/meetings/route.tsindex b4cf42fb8..e49f3fc57 100644--- a/src/web/src/app/api/agents/[id]/meetings/route.ts+++ b/src/web/src/app/api/agents/[id]/meetings/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server"-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, MeetingStatus } from "@alook/shared"import { withAuth } from "@/lib/middleware/auth"import { withWorkspaceMember } from "@/lib/middleware/workspace"@@ -14,8 +13,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx)if (ws instanceof Response) return ws- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const agentId = ctx.params?.idif (!agentId) return writeError("agent id is required", 400)@@ -36,8 +34,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx)if (ws instanceof Response) return ws- const { env } = getCloudflareContext()- const cfEnv = env as Env+ const cfEnv = ctx.envconst db = getDb(cfEnv.DB)const agentId = ctx.params?.iddiff --git a/src/web/src/app/api/agents/[id]/pin/route.test.ts b/src/web/src/app/api/agents/[id]/pin/route.test.tsindex ebbba6180..6af6294da 100644--- a/src/web/src/app/api/agents/[id]/pin/route.test.ts+++ b/src/web/src/app/api/agents/[id]/pin/route.test.ts@@ -29,7 +29,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/[id]/pin/route.ts b/src/web/src/app/api/agents/[id]/pin/route.tsindex e521fc210..370804fdb 100644--- a/src/web/src/app/api/agents/[id]/pin/route.ts+++ b/src/web/src/app/api/agents/[id]/pin/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;const { id } = ctx.params!;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const agent = await queries.agent.getAgent(db, id, ws.workspaceId, ctx.userId);if (!agent) return writeError("agent not found", 404);const pin = await queries.agentPin.pinAgent(db, { agentId: id, workspaceId: ws.workspaceId, userId: ctx.userId });@@ -24,8 +22,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;const { id } = ctx.params!;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);await queries.agentPin.unpinAgent(db, id, ws.workspaceId, ctx.userId);invalidate(cacheKeys.pins(ws.workspaceId, ctx.userId)).catch(() => {});return new Response(null, { status: 204 });diff --git a/src/web/src/app/api/agents/[id]/route.test.ts b/src/web/src/app/api/agents/[id]/route.test.tsindex 6bcbadba9..f4b4cc751 100644--- a/src/web/src/app/api/agents/[id]/route.test.ts+++ b/src/web/src/app/api/agents/[id]/route.test.ts@@ -32,7 +32,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/[id]/route.ts b/src/web/src/app/api/agents/[id]/route.tsindex 8765b5f91..2211a5d1c 100644--- a/src/web/src/app/api/agents/[id]/route.ts+++ b/src/web/src/app/api/agents/[id]/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, UpdateAgentRequestSchema } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {@@ -31,8 +29,7 @@ export const PATCH = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {@@ -86,8 +83,7 @@ export const DELETE = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/agents/[id]/skills/route.test.ts b/src/web/src/app/api/agents/[id]/skills/route.test.tsindex bc6a6ebb6..725ed7935 100644--- a/src/web/src/app/api/agents/[id]/skills/route.test.ts+++ b/src/web/src/app/api/agents/[id]/skills/route.test.ts@@ -23,7 +23,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/[id]/skills/route.ts b/src/web/src/app/api/agents/[id]/skills/route.tsindex c6de9984c..c11cd276e 100644--- a/src/web/src/app/api/agents/[id]/skills/route.ts+++ b/src/web/src/app/api/agents/[id]/skills/route.ts@@ -1,13 +1,11 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { withAuth } from "@/lib/middleware/auth";import { writeJSON, writeError } from "@/lib/middleware/helpers";import { getDb } from "@/lib/db";export const GET = withAuth(async (req: NextRequest, ctx) => {- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const agentId = ctx.params?.id;if (!agentId) return writeError("agent id required", 400);diff --git a/src/web/src/app/api/agents/[id]/threads/route.ts b/src/web/src/app/api/agents/[id]/threads/route.tsindex 27bbc69c0..5731850c1 100644--- a/src/web/src/app/api/agents/[id]/threads/route.ts+++ b/src/web/src/app/api/agents/[id]/threads/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -9,8 +8,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const agentId = ctx.params?.id;if (!agentId) {diff --git a/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.test.ts b/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.test.tsindex ecb7eeff8..22e432abc 100644--- a/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.test.ts+++ b/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.test.ts@@ -22,7 +22,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.ts b/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.tsindex 780dbc775..3388ae9e7 100644--- a/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.ts+++ b/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"@@ -9,8 +8,7 @@ export const DELETE = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const agentId = ctx.params?.id;const whitelistId = ctx.params?.whitelistId;diff --git a/src/web/src/app/api/agents/[id]/whitelist/route.test.ts b/src/web/src/app/api/agents/[id]/whitelist/route.test.tsindex aa96182ac..ecd2ef2a7 100644--- a/src/web/src/app/api/agents/[id]/whitelist/route.test.ts+++ b/src/web/src/app/api/agents/[id]/whitelist/route.test.ts@@ -43,7 +43,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/[id]/whitelist/route.ts b/src/web/src/app/api/agents/[id]/whitelist/route.tsindex 6b9d3046d..0396c0a07 100644--- a/src/web/src/app/api/agents/[id]/whitelist/route.ts+++ b/src/web/src/app/api/agents/[id]/whitelist/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, AddWhitelistRequestSchema, TASK_TYPES } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"@@ -11,8 +10,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const agentId = ctx.params?.id;if (!agentId) return writeError("agent id is required", 400);@@ -34,8 +32,7 @@ export const POST = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const agentId = ctx.params?.id;if (!agentId) return writeError("agent id is required", 400);diff --git a/src/web/src/app/api/agents/[id]/workspace/browse/route.test.ts b/src/web/src/app/api/agents/[id]/workspace/browse/route.test.tsindex eb6c8b744..62dd1a3af 100644--- a/src/web/src/app/api/agents/[id]/workspace/browse/route.test.ts+++ b/src/web/src/app/api/agents/[id]/workspace/browse/route.test.ts@@ -25,7 +25,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/[id]/workspace/browse/route.ts b/src/web/src/app/api/agents/[id]/workspace/browse/route.tsindex f120d870f..22e244c88 100644--- a/src/web/src/app/api/agents/[id]/workspace/browse/route.ts+++ b/src/web/src/app/api/agents/[id]/workspace/browse/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, WorkspaceFileBrowseRequestSchema } from "@alook/shared";import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";@@ -12,8 +11,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const agentId = ctx.params?.id;if (!agentId) return writeError("agent id required", 400);@@ -31,7 +29,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {path: body.path,});- const kv = (env as Env).CACHE_KV ?? null;+ const kv = ctx.env.CACHE_KV ?? null;if (kv) {kv.put(cacheKeys.hasPendingFileRequest(ws.workspaceId), "1", { expirationTtl: 60 }).catch(() => {});}diff --git a/src/web/src/app/api/agents/active-task-counts/route.test.ts b/src/web/src/app/api/agents/active-task-counts/route.test.tsindex 3b414ce3c..585c70a2f 100644--- a/src/web/src/app/api/agents/active-task-counts/route.test.ts+++ b/src/web/src/app/api/agents/active-task-counts/route.test.ts@@ -48,7 +48,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/active-task-counts/route.ts b/src/web/src/app/api/agents/active-task-counts/route.tsindex cf1b1b553..94ec3e206 100644--- a/src/web/src/app/api/agents/active-task-counts/route.ts+++ b/src/web/src/app/api/agents/active-task-counts/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const [allAgents, allAccess] = await Promise.all([queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId),diff --git a/src/web/src/app/api/agents/active-tasks/route.test.ts b/src/web/src/app/api/agents/active-tasks/route.test.tsindex 790e31eb7..0ef515548 100644--- a/src/web/src/app/api/agents/active-tasks/route.test.ts+++ b/src/web/src/app/api/agents/active-tasks/route.test.ts@@ -22,7 +22,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/active-tasks/route.ts b/src/web/src/app/api/agents/active-tasks/route.tsindex 98b8d2d60..7466e97e0 100644--- a/src/web/src/app/api/agents/active-tasks/route.ts+++ b/src/web/src/app/api/agents/active-tasks/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const [allAgents, allAccess] = await Promise.all([queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId),diff --git a/src/web/src/app/api/agents/pins/reorder/route.test.ts b/src/web/src/app/api/agents/pins/reorder/route.test.tsindex b8eb815a4..f942e0c58 100644--- a/src/web/src/app/api/agents/pins/reorder/route.test.ts+++ b/src/web/src/app/api/agents/pins/reorder/route.test.ts@@ -23,7 +23,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/pins/reorder/route.ts b/src/web/src/app/api/agents/pins/reorder/route.tsindex 2ea1fa657..419cb8115 100644--- a/src/web/src/app/api/agents/pins/reorder/route.ts+++ b/src/web/src/app/api/agents/pins/reorder/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -23,8 +22,7 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {return writeError("ordered_agent_ids must be a non-empty array of strings", 400);}- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const existingPins = await queries.agentPin.listPins(db, ws.workspaceId, ctx.userId);const pinnedIds = new Set(existingPins.map((p) => p.agentId));diff --git a/src/web/src/app/api/agents/pins/route.test.ts b/src/web/src/app/api/agents/pins/route.test.tsindex 85054cfdc..77e467b3f 100644--- a/src/web/src/app/api/agents/pins/route.test.ts+++ b/src/web/src/app/api/agents/pins/route.test.ts@@ -28,7 +28,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/pins/route.ts b/src/web/src/app/api/agents/pins/route.tsindex 39ae2fc11..c4b76bbb2 100644--- a/src/web/src/app/api/agents/pins/route.ts+++ b/src/web/src/app/api/agents/pins/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ import { cached, cacheKeys } from "@/lib/cache";export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const data = await cached(cacheKeys.pins(ws.workspaceId, ctx.userId), 30, async () => {const [pins, sidebarOrder] = await Promise.all([queries.agentPin.listPins(db, ws.workspaceId, ctx.userId),diff --git a/src/web/src/app/api/agents/recruit/route.test.ts b/src/web/src/app/api/agents/recruit/route.test.tsindex a0762803e..ad68a4197 100644--- a/src/web/src/app/api/agents/recruit/route.test.ts+++ b/src/web/src/app/api/agents/recruit/route.test.ts@@ -42,7 +42,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/recruit/route.ts b/src/web/src/app/api/agents/recruit/route.tsindex 83c882f8f..f354c203e 100644--- a/src/web/src/app/api/agents/recruit/route.ts+++ b/src/web/src/app/api/agents/recruit/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, RecruitAgentRequestSchema, isValidHandle, isOnline, buildMimeMessage, extractThreadId, buildEmailMapKey, DEV_WEB_URL, toAlookAddress } from "@alook/shared";import { nanoid } from "nanoid";import { uniqueNamesGenerator, names } from "unique-names-generator";@@ -39,8 +38,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const agentId = req.nextUrl.searchParams.get("agentId");if (!agentId) {@@ -117,7 +115,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {if (isOnline(runtime.machineLastSeenAt) && callingAgent.emailHandle) {try {- const cfEnv = env as Env;+ const cfEnv = ctx.env;const fromAddress = toAlookAddress(callingAgent.emailHandle);const toAddress = toAlookAddress(handle);const subject = "Welcome aboard";diff --git a/src/web/src/app/api/agents/route.test.ts b/src/web/src/app/api/agents/route.test.tsindex 22a425fed..1379bb9b9 100644--- a/src/web/src/app/api/agents/route.test.ts+++ b/src/web/src/app/api/agents/route.test.ts@@ -37,7 +37,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/agents/route.ts b/src/web/src/app/api/agents/route.tsindex aff6d9526..3aca07f36 100644--- a/src/web/src/app/api/agents/route.ts+++ b/src/web/src/app/api/agents/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, isValidHandle, isOnline, CreateAgentRequestSchema, TASK_TYPES } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -14,8 +13,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const [allAgents, allAccess] = await Promise.all([queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId),@@ -29,8 +27,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const [body, valErr] = await parseBody(req, CreateAgentRequestSchema);if (valErr) return valErr;diff --git a/src/web/src/app/api/agents/sidebar/reorder/route.test.ts b/src/web/src/app/api/agents/sidebar/reorder/route.test.tsindex cf90c470a..1ef4c5516 100644--- a/src/web/src/app/api/agents/sidebar/reorder/route.test.ts+++ b/src/web/src/app/api/agents/sidebar/reorder/route.test.ts@@ -23,7 +23,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/agents/sidebar/reorder/route.ts b/src/web/src/app/api/agents/sidebar/reorder/route.tsindex 8aaf97921..c957efc65 100644--- a/src/web/src/app/api/agents/sidebar/reorder/route.ts+++ b/src/web/src/app/api/agents/sidebar/reorder/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -23,8 +22,7 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {return writeError("ordered_agent_ids must be a non-empty array of strings", 400);}- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const [agents, existingPins] = await Promise.all([queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId),diff --git a/src/web/src/app/api/artifacts/[id]/content/route.test.ts b/src/web/src/app/api/artifacts/[id]/content/route.test.tsindex b87015206..6e8d1bce5 100644--- a/src/web/src/app/api/artifacts/[id]/content/route.test.ts+++ b/src/web/src/app/api/artifacts/[id]/content/route.test.ts@@ -30,7 +30,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: (handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });+ return handler(req, { env: { DB: {}, EMAIL_BUCKET: { get: (...a: unknown[]) => mockBucketGet(...a) } }, userId: "u1", email: "[email protected]", workspaceId: "w1", params });},}));diff --git a/src/web/src/app/api/artifacts/[id]/content/route.ts b/src/web/src/app/api/artifacts/[id]/content/route.tsindex a8665bcb0..707619897 100644--- a/src/web/src/app/api/artifacts/[id]/content/route.ts+++ b/src/web/src/app/api/artifacts/[id]/content/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -21,9 +20,8 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {if (ws instanceof Response) return ws;const id = ctx.params?.id as string;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);- const bucket = (env as Env).EMAIL_BUCKET;+ const db = getDb(ctx.env.DB);+ const bucket = ctx.env.EMAIL_BUCKET;const row = await queries.artifact.getArtifact(db, id, ws.workspaceId);if (!row) {diff --git a/src/web/src/app/api/artifacts/[id]/route.test.ts b/src/web/src/app/api/artifacts/[id]/route.test.tsindex 9c433eb0c..56bba33ca 100644--- a/src/web/src/app/api/artifacts/[id]/route.test.ts+++ b/src/web/src/app/api/artifacts/[id]/route.test.ts@@ -27,7 +27,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: (handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1", params });},}));diff --git a/src/web/src/app/api/artifacts/[id]/route.ts b/src/web/src/app/api/artifacts/[id]/route.tsindex 8dad5c1e4..34318bc17 100644--- a/src/web/src/app/api/artifacts/[id]/route.ts+++ b/src/web/src/app/api/artifacts/[id]/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {if (ws instanceof Response) return ws;const id = ctx.params?.id as string;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const row = await queries.artifact.getArtifact(db, id, ws.workspaceId);if (!row) {diff --git a/src/web/src/app/api/artifacts/[id]/thumbnail/route.test.ts b/src/web/src/app/api/artifacts/[id]/thumbnail/route.test.tsindex 6765f51af..0ce5c3b49 100644--- a/src/web/src/app/api/artifacts/[id]/thumbnail/route.test.ts+++ b/src/web/src/app/api/artifacts/[id]/thumbnail/route.test.ts@@ -30,7 +30,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: (handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: { DB: {}, EMAIL_BUCKET: { get: (...a: unknown[]) => mockBucketGet(...a) } }, userId: "u1", email: "[email protected]", params });},}));diff --git a/src/web/src/app/api/artifacts/[id]/thumbnail/route.ts b/src/web/src/app/api/artifacts/[id]/thumbnail/route.tsindex e40dfb2ac..a408d5292 100644--- a/src/web/src/app/api/artifacts/[id]/thumbnail/route.ts+++ b/src/web/src/app/api/artifacts/[id]/thumbnail/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -11,9 +10,8 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {if (ws instanceof Response) return ws;const id = ctx.params?.id as string;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);- const bucket = (env as Env).EMAIL_BUCKET;+ const db = getDb(ctx.env.DB);+ const bucket = ctx.env.EMAIL_BUCKET;const row = await queries.artifact.getArtifact(db, id, ws.workspaceId);if (!row) {diff --git a/src/web/src/app/api/artifacts/route.test.ts b/src/web/src/app/api/artifacts/route.test.tsindex 81d14de13..a62a22d3e 100644--- a/src/web/src/app/api/artifacts/route.test.ts+++ b/src/web/src/app/api/artifacts/route.test.ts@@ -24,7 +24,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/artifacts/route.ts b/src/web/src/app/api/artifacts/route.tsindex fdd8b5f5b..be319f072 100644--- a/src/web/src/app/api/artifacts/route.ts+++ b/src/web/src/app/api/artifacts/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -15,8 +14,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {return writeError("conversation_id is required", 400);}- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const conv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);if (!conv || conv.userId !== ctx.userId) {diff --git a/src/web/src/app/api/artifacts/upload/route.test.ts b/src/web/src/app/api/artifacts/upload/route.test.tsindex 357de80ec..cec6e5532 100644--- a/src/web/src/app/api/artifacts/upload/route.test.ts+++ b/src/web/src/app/api/artifacts/upload/route.test.ts@@ -28,7 +28,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: { DB: {}, EMAIL_BUCKET: { put: mockPut } }, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/artifacts/upload/route.ts b/src/web/src/app/api/artifacts/upload/route.tsindex 8d92b185c..a07c1dd10 100644--- a/src/web/src/app/api/artifacts/upload/route.ts+++ b/src/web/src/app/api/artifacts/upload/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db"import { nanoid } from "nanoid";@@ -18,9 +17,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const bucket = (env as Env).EMAIL_BUCKET;- const db = getDb((env as Env).DB);+ const bucket = ctx.env.EMAIL_BUCKET;+ const db = getDb(ctx.env.DB);let formData: FormData;try {diff --git a/src/web/src/app/api/auth/[...all]/route.ts b/src/web/src/app/api/auth/[...all]/route.tsindex e2dca3aac..16aa71ba0 100644--- a/src/web/src/app/api/auth/[...all]/route.ts+++ b/src/web/src/app/api/auth/[...all]/route.ts@@ -1,13 +1,12 @@+import { NextRequest } from "next/server"import { toNextJsHandler } from "better-auth/next-js"import { createAuth } from "@/lib/auth"-import { getCloudflareContext } from "@opennextjs/cloudflare"+import { withEnv } from "@/lib/middleware/env"-export async function GET(request: Request) {- const { env } = getCloudflareContext()- return toNextJsHandler(createAuth(env as Env)).GET(request)-}+export const GET = withEnv(async (req: NextRequest, ctx) => {+ return toNextJsHandler(createAuth(ctx.env)).GET(req)+});-export async function POST(request: Request) {- const { env } = getCloudflareContext()- return toNextJsHandler(createAuth(env as Env)).POST(request)-}+export const POST = withEnv(async (req: NextRequest, ctx) => {+ return toNextJsHandler(createAuth(ctx.env)).POST(req)+});diff --git a/src/web/src/app/api/calendar/[id]/route.test.ts b/src/web/src/app/api/calendar/[id]/route.test.tsindex 2c3732d4e..f83116647 100644--- a/src/web/src/app/api/calendar/[id]/route.test.ts+++ b/src/web/src/app/api/calendar/[id]/route.test.ts@@ -35,7 +35,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: (handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });},}));diff --git a/src/web/src/app/api/calendar/[id]/route.ts b/src/web/src/app/api/calendar/[id]/route.tsindex 74fe551fb..fa24a51af 100644--- a/src/web/src/app/api/calendar/[id]/route.ts+++ b/src/web/src/app/api/calendar/[id]/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import {queries,UpdateCalendarEventRequestSchema,@@ -17,8 +16,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("calendar event id is required", 400);@@ -37,8 +35,7 @@ export const PATCH = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("calendar event id is required", 400);@@ -168,8 +165,7 @@ export const DELETE = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("calendar event id is required", 400);diff --git a/src/web/src/app/api/calendar/route.test.ts b/src/web/src/app/api/calendar/route.test.tsindex 9647425f5..c91b53468 100644--- a/src/web/src/app/api/calendar/route.test.ts+++ b/src/web/src/app/api/calendar/route.test.ts@@ -35,7 +35,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: (handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });},}));diff --git a/src/web/src/app/api/calendar/route.ts b/src/web/src/app/api/calendar/route.tsindex 908c3bef8..4fdba54c2 100644--- a/src/web/src/app/api/calendar/route.ts+++ b/src/web/src/app/api/calendar/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import {queries,CreateCalendarEventRequestSchema,@@ -19,8 +18,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const agentId = req.nextUrl.searchParams.get("agentId") ?? undefined;const from = req.nextUrl.searchParams.get("from") ?? undefined;@@ -132,8 +130,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const [body, err] = await parseBody(req, CreateCalendarEventRequestSchema);if (err) return err;diff --git a/src/web/src/app/api/channels/[id]/route.test.ts b/src/web/src/app/api/channels/[id]/route.test.tsindex a997dd139..fde441e88 100644--- a/src/web/src/app/api/channels/[id]/route.test.ts+++ b/src/web/src/app/api/channels/[id]/route.test.ts@@ -33,7 +33,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/channels/[id]/route.ts b/src/web/src/app/api/channels/[id]/route.tsindex 197ee378f..149685c60 100644--- a/src/web/src/app/api/channels/[id]/route.ts+++ b/src/web/src/app/api/channels/[id]/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, isUniqueConstraintError } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -12,8 +11,7 @@ export const PATCH = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("channel id is required", 400);@@ -54,8 +52,7 @@ export const DELETE = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("channel id is required", 400);diff --git a/src/web/src/app/api/channels/reorder/route.test.ts b/src/web/src/app/api/channels/reorder/route.test.tsindex fd2a0374a..59d3f13d0 100644--- a/src/web/src/app/api/channels/reorder/route.test.ts+++ b/src/web/src/app/api/channels/reorder/route.test.ts@@ -23,7 +23,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/channels/reorder/route.ts b/src/web/src/app/api/channels/reorder/route.tsindex f4f105d1e..f64e62a67 100644--- a/src/web/src/app/api/channels/reorder/route.ts+++ b/src/web/src/app/api/channels/reorder/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -26,8 +25,7 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {return writeError("cannot reorder the default channel", 400);}- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const existing = await queries.channel.listChannels(db, ws.workspaceId);const existingIds = new Set(existing.map((c) => c.id));diff --git a/src/web/src/app/api/channels/route.test.ts b/src/web/src/app/api/channels/route.test.tsindex 3f0780f7c..a7358eda0 100644--- a/src/web/src/app/api/channels/route.test.ts+++ b/src/web/src/app/api/channels/route.test.ts@@ -32,7 +32,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/channels/route.ts b/src/web/src/app/api/channels/route.tsindex 45315202c..a80f904a2 100644--- a/src/web/src/app/api/channels/route.ts+++ b/src/web/src/app/api/channels/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, isUniqueConstraintError } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const channels = await queries.channel.listChannels(db, ws.workspaceId);@@ -39,8 +37,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);let body: { name?: string };try {diff --git a/src/web/src/app/api/config/min-version/route.ts b/src/web/src/app/api/config/min-version/route.tsindex 99b453e63..34b25d7f1 100644--- a/src/web/src/app/api/config/min-version/route.ts+++ b/src/web/src/app/api/config/min-version/route.ts@@ -1,12 +1,10 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { semverGte } from "@alook/shared";import { withAuth } from "@/lib/middleware/auth";import { writeJSON } from "@/lib/middleware/helpers";import { fetchLatestCliVersion } from "@/lib/npm";-export const GET = withAuth(async () => {- const { env } = getCloudflareContext()- const raw = (env as Env).MIN_CLI_VERSION;+export const GET = withAuth(async (_req, ctx) => {+ const raw = ctx.env.MIN_CLI_VERSION;if (!raw) return writeJSON({ min_cli_version: null });const result = await fetchLatestCliVersion();diff --git a/src/web/src/app/api/config/model-options/route.test.ts b/src/web/src/app/api/config/model-options/route.test.tsindex 12a194e65..f4e856b9d 100644--- a/src/web/src/app/api/config/model-options/route.test.ts+++ b/src/web/src/app/api/config/model-options/route.test.ts@@ -9,7 +9,7 @@ vi.mock("@opennextjs/cloudflare", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: mockEnv, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/config/model-options/route.ts b/src/web/src/app/api/config/model-options/route.tsindex 832d5b76c..0ba68e10e 100644--- a/src/web/src/app/api/config/model-options/route.ts+++ b/src/web/src/app/api/config/model-options/route.ts@@ -1,10 +1,8 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { withAuth } from "@/lib/middleware/auth";import { writeJSON } from "@/lib/middleware/helpers";-export const GET = withAuth(async () => {- const { env } = getCloudflareContext()- const raw = (env as Env).RUNTIME_MODEL_OPTIONS;+export const GET = withAuth(async (_req, ctx) => {+ const raw = ctx.env.RUNTIME_MODEL_OPTIONS;if (!raw) return writeJSON({});let parsed: unknown;diff --git a/src/web/src/app/api/conversations/[id]/active-task/route.test.ts b/src/web/src/app/api/conversations/[id]/active-task/route.test.tsindex 61a0df4f8..0f85b98fb 100644--- a/src/web/src/app/api/conversations/[id]/active-task/route.test.ts+++ b/src/web/src/app/api/conversations/[id]/active-task/route.test.ts@@ -47,7 +47,7 @@ vi.mock("@/lib/broadcast", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/conversations/[id]/active-task/route.ts b/src/web/src/app/api/conversations/[id]/active-task/route.tsindex 2994b08f1..f13e818ef 100644--- a/src/web/src/app/api/conversations/[id]/active-task/route.ts+++ b/src/web/src/app/api/conversations/[id]/active-task/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -13,8 +12,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {@@ -38,8 +36,7 @@ export const DELETE = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/conversations/[id]/init/route.test.ts b/src/web/src/app/api/conversations/[id]/init/route.test.tsindex 9f310e9ac..6baf260ca 100644--- a/src/web/src/app/api/conversations/[id]/init/route.test.ts+++ b/src/web/src/app/api/conversations/[id]/init/route.test.ts@@ -48,7 +48,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/conversations/[id]/init/route.ts b/src/web/src/app/api/conversations/[id]/init/route.tsindex 66d7f5655..1d0d500f5 100644--- a/src/web/src/app/api/conversations/[id]/init/route.ts+++ b/src/web/src/app/api/conversations/[id]/init/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -18,8 +17,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/conversations/[id]/messages/route.test.ts b/src/web/src/app/api/conversations/[id]/messages/route.test.tsindex a959e5467..0fa05da88 100644--- a/src/web/src/app/api/conversations/[id]/messages/route.test.ts+++ b/src/web/src/app/api/conversations/[id]/messages/route.test.ts@@ -44,7 +44,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/conversations/[id]/messages/route.ts b/src/web/src/app/api/conversations/[id]/messages/route.tsindex c8b9b0a81..42b0d0667 100644--- a/src/web/src/app/api/conversations/[id]/messages/route.ts+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, TASK_TYPES, CreateMessageRequestSchema, parsePromptMentions, truncateTitle } from "@alook/shared"import { getDb } from "@/lib/db"import { nanoid } from "nanoid";@@ -23,8 +22,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {@@ -57,9 +55,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)- const bucket = (env as Env).EMAIL_BUCKET;+ const db = getDb(ctx.env.DB)+ const bucket = ctx.env.EMAIL_BUCKET;const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/conversations/[id]/route.test.ts b/src/web/src/app/api/conversations/[id]/route.test.tsindex aa38e769b..6e9975a94 100644--- a/src/web/src/app/api/conversations/[id]/route.test.ts+++ b/src/web/src/app/api/conversations/[id]/route.test.ts@@ -30,7 +30,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/conversations/[id]/route.ts b/src/web/src/app/api/conversations/[id]/route.tsindex cc08e421a..eb41ce01c 100644--- a/src/web/src/app/api/conversations/[id]/route.ts+++ b/src/web/src/app/api/conversations/[id]/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {@@ -30,8 +28,7 @@ export const DELETE = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/conversations/[id]/threads/route.ts b/src/web/src/app/api/conversations/[id]/threads/route.tsindex 60ede4ea7..3b3de5237 100644--- a/src/web/src/app/api/conversations/[id]/threads/route.ts+++ b/src/web/src/app/api/conversations/[id]/threads/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, TASK_TYPES, truncateTitle, CreateThreadRequestSchema, isUniqueConstraintError } from "@alook/shared";import { getDb } from "@/lib/db";import { nanoid } from "nanoid";@@ -15,8 +14,7 @@ export const POST = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const conversationId = ctx.params?.id;if (!conversationId) {@@ -207,8 +205,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const conversationId = ctx.params?.id;if (!conversationId) {diff --git a/src/web/src/app/api/conversations/check-fresh/route.test.ts b/src/web/src/app/api/conversations/check-fresh/route.test.tsindex 92a8b5f67..3cebdf24c 100644--- a/src/web/src/app/api/conversations/check-fresh/route.test.ts+++ b/src/web/src/app/api/conversations/check-fresh/route.test.ts@@ -31,7 +31,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/conversations/check-fresh/route.ts b/src/web/src/app/api/conversations/check-fresh/route.tsindex b845b8d84..de634e621 100644--- a/src/web/src/app/api/conversations/check-fresh/route.ts+++ b/src/web/src/app/api/conversations/check-fresh/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -9,8 +8,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const url = new URL(req.url);const conversationId = url.searchParams.get("conversation_id");diff --git a/src/web/src/app/api/conversations/route.test.ts b/src/web/src/app/api/conversations/route.test.tsindex 899ee0e54..57591ed5f 100644--- a/src/web/src/app/api/conversations/route.test.ts+++ b/src/web/src/app/api/conversations/route.test.ts@@ -26,7 +26,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/conversations/route.ts b/src/web/src/app/api/conversations/route.tsindex 2d0f828ae..8be82a92f 100644--- a/src/web/src/app/api/conversations/route.ts+++ b/src/web/src/app/api/conversations/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, CreateConversationRequestSchema } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const channel = new URL(req.url).searchParams.get("channel") || undefined;@@ -29,8 +27,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const [body, valErr] = await parseBody(req, CreateConversationRequestSchema);if (valErr) return valErr;diff --git a/src/web/src/app/api/daemon/conversations/[id]/messages/route.test.ts b/src/web/src/app/api/daemon/conversations/[id]/messages/route.test.tsindex 011d7ff53..f52757b26 100644--- a/src/web/src/app/api/daemon/conversations/[id]/messages/route.test.ts+++ b/src/web/src/app/api/daemon/conversations/[id]/messages/route.test.ts@@ -40,6 +40,7 @@ vi.mock("@/lib/middleware/auth", () => ({const auth = (req.headers?.get?.("Authorization") as string) || "";const isMachine = auth.startsWith("Bearer al_");return handler(req, {+ env: { DB: {} },userId: "u1",email: "[email protected]",workspaceId: isMachine ? "w1" : undefined,diff --git a/src/web/src/app/api/daemon/conversations/[id]/messages/route.ts b/src/web/src/app/api/daemon/conversations/[id]/messages/route.tsindex ec9dddfd6..41677869b 100644--- a/src/web/src/app/api/daemon/conversations/[id]/messages/route.ts+++ b/src/web/src/app/api/daemon/conversations/[id]/messages/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, AgentDmRequestSchema, truncateTitle } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -17,8 +16,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("Forbidden: machine token required", 403);}- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/daemon/deregister/route.test.ts b/src/web/src/app/api/daemon/deregister/route.test.tsindex ea82db8a9..e4e2b0a42 100644--- a/src/web/src/app/api/daemon/deregister/route.test.ts+++ b/src/web/src/app/api/daemon/deregister/route.test.ts@@ -69,8 +69,8 @@ describe("POST /api/daemon/deregister", () => {return POST;}- const daemonAuth = { userId: "u1", email: "[email protected]", workspaceId: "w1" };- const jwtAuth = { userId: "u1", email: "[email protected]" };+ const daemonAuth = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };+ const jwtAuth = { env: {}, userId: "u1", email: "[email protected]" };it("sets machine last_seen_at to null", async () => {const POST = await loadRoute(daemonAuth);diff --git a/src/web/src/app/api/daemon/deregister/route.ts b/src/web/src/app/api/daemon/deregister/route.tsindex 10cdb6db4..db618ca68 100644--- a/src/web/src/app/api/daemon/deregister/route.ts+++ b/src/web/src/app/api/daemon/deregister/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ import { invalidate, cacheKeys } from "@/lib/cache";import { log } from "@/lib/logger";export const POST = withAuth(async (req: NextRequest, ctx) => {- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const [body, err] = await parseBody(req, DeregisterRequestSchema);if (err) return err;diff --git a/src/web/src/app/api/daemon/heartbeat/route.test.ts b/src/web/src/app/api/daemon/heartbeat/route.test.tsindex 1b1c293bd..b242b121b 100644--- a/src/web/src/app/api/daemon/heartbeat/route.test.ts+++ b/src/web/src/app/api/daemon/heartbeat/route.test.ts@@ -30,7 +30,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any) => {- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1" });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" });}),}));@@ -145,7 +145,7 @@ describe("POST /api/daemon/heartbeat", () => {});vi.doMock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any) => {- return handler(req, { userId: "u1", email: "[email protected]" });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]" });}),}));vi.doMock("@/lib/middleware/helpers", async () =>diff --git a/src/web/src/app/api/daemon/heartbeat/route.ts b/src/web/src/app/api/daemon/heartbeat/route.tsindex 9ca606473..bfb5da443 100644--- a/src/web/src/app/api/daemon/heartbeat/route.ts+++ b/src/web/src/app/api/daemon/heartbeat/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, HeartbeatRequestSchema, OFFLINE_THRESHOLD_MS } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -8,7 +7,6 @@ import { broadcastToUser } from "@/lib/broadcast";import { log } from "@/lib/logger";export const POST = withAuth(async (req: NextRequest, ctx) => {- const { env } = getCloudflareContext();const [body, err] = await parseBody(req, HeartbeatRequestSchema);if (err) return err;@@ -17,7 +15,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("Forbidden: machine token required", 403);}- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);let wasOffline = false;try {const existing = await queries.machine.getMachineByDaemon(db, body.daemon_id, ctx.workspaceId!);diff --git a/src/web/src/app/api/daemon/register/route.test.ts b/src/web/src/app/api/daemon/register/route.test.tsindex 42288d082..8f8364e90 100644--- a/src/web/src/app/api/daemon/register/route.test.ts+++ b/src/web/src/app/api/daemon/register/route.test.ts@@ -105,7 +105,7 @@ describe("POST /api/daemon/register", () => {],};- const authCtx = { userId: "u1", email: "[email protected]" };+ const authCtx = { env: {}, userId: "u1", email: "[email protected]" };it("upserts machine + runtimes and returns 200", async () => {const POST = await loadRoute(authCtx);diff --git a/src/web/src/app/api/daemon/register/route.ts b/src/web/src/app/api/daemon/register/route.tsindex 506e5bc5a..7463f98d4 100644--- a/src/web/src/app/api/daemon/register/route.ts+++ b/src/web/src/app/api/daemon/register/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, semverGte } from "@alook/shared"import { getDb, withD1Retry } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ import { invalidate, cacheKeys } from "@/lib/cache";import { log } from "@/lib/logger";export const POST = withAuth(async (req: NextRequest, ctx) => {- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const [body, err] = await parseBody(req, RegisterDaemonRequestSchema);if (err) return err;diff --git a/src/web/src/app/api/daemon/routes.test.ts b/src/web/src/app/api/daemon/routes.test.tsindex cc5e8c4c9..2f36d154e 100644--- a/src/web/src/app/api/daemon/routes.test.ts+++ b/src/web/src/app/api/daemon/routes.test.ts@@ -7,7 +7,7 @@ import { NextRequest } from "next/server";// invalid payloads are rejected before hitting any DB logic.// ----------------------------------------------------------------------------const daemonAuth = { userId: "u1", email: "[email protected]", workspaceId: "w1" };+const daemonAuth = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };function baseMocks() {return {diff --git a/src/web/src/app/api/daemon/skills/sync/route.test.ts b/src/web/src/app/api/daemon/skills/sync/route.test.tsindex 457c94294..be2af107c 100644--- a/src/web/src/app/api/daemon/skills/sync/route.test.ts+++ b/src/web/src/app/api/daemon/skills/sync/route.test.ts@@ -29,7 +29,7 @@ let injectWorkspaceId: string | undefined = "w1";vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: injectWorkspaceId, params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: injectWorkspaceId, params });}),}));diff --git a/src/web/src/app/api/daemon/skills/sync/route.ts b/src/web/src/app/api/daemon/skills/sync/route.tsindex 04d1904ef..2171b9443 100644--- a/src/web/src/app/api/daemon/skills/sync/route.ts+++ b/src/web/src/app/api/daemon/skills/sync/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, SkillSyncRequestSchema } from "@alook/shared";import { withAuth } from "@/lib/middleware/auth";import { parseBody, writeJSON, writeError } from "@/lib/middleware/helpers";@@ -10,8 +9,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("Forbidden: machine token required", 403);}- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const [body, err] = await parseBody(req, SkillSyncRequestSchema);if (err) return err;diff --git a/src/web/src/app/api/daemon/sweep/route.test.ts b/src/web/src/app/api/daemon/sweep/route.test.tsindex 9eaac737a..88a4dcfe4 100644--- a/src/web/src/app/api/daemon/sweep/route.test.ts+++ b/src/web/src/app/api/daemon/sweep/route.test.ts@@ -28,7 +28,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any) => {- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1" });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" });}),}));@@ -84,7 +84,7 @@ describe("POST /api/daemon/sweep", () => {});vi.doMock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any) => {- return handler(req, { userId: "u1", email: "[email protected]" });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]" });}),}));vi.doMock("@/lib/middleware/helpers", async () =>diff --git a/src/web/src/app/api/daemon/sweep/route.ts b/src/web/src/app/api/daemon/sweep/route.tsindex 503355a8e..363e45903 100644--- a/src/web/src/app/api/daemon/sweep/route.ts+++ b/src/web/src/app/api/daemon/sweep/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { SweepRequestSchema } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -9,7 +8,6 @@ import { promoteDueCalendarEventsForWorkspace } from "@/lib/services/calendar";import { log } from "@/lib/logger";export const POST = withAuth(async (req: NextRequest, ctx) => {- const { env } = getCloudflareContext();const { throttled } = await import("@/lib/cache");const [, err] = await parseBody(req, SweepRequestSchema);@@ -19,7 +17,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("Forbidden: machine token required", 403);}- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);try {await sweepStaleState(db, ctx.workspaceId);diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.test.tsindex 8a0640628..082fdde55 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.test.ts@@ -5,7 +5,7 @@ const mockCompleteTask = vi.fn();const mockTaskToResponse = vi.fn();const mockGetConversation = vi.fn();-let mockAuthCtx: Record<string, unknown> = { userId: "u1", email: "[email protected]", workspaceId: "w1" };+let mockAuthCtx: Record<string, unknown> = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: { withSession: () => ({}) } } })),@@ -67,7 +67,7 @@ const makeReq = (taskId: string, body: Record<string, unknown> = {}) =>describe("POST /api/daemon/tasks/[taskId]/complete", () => {beforeEach(() => {vi.clearAllMocks();- mockAuthCtx = { userId: "u1", email: "[email protected]", workspaceId: "w1" };+ mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };});it("returns completed task and broadcasts to conversation owner", async () => {@@ -89,7 +89,7 @@ describe("POST /api/daemon/tasks/[taskId]/complete", () => {});it("returns 403 when workspaceId is missing (session auth)", async () => {- mockAuthCtx = { userId: "u1", email: "[email protected]" };+ mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]" };const res = await POST(makeReq("t1", { output: "done" }), withParams("t1"));const body = await res.json();diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.tsindex 88402d57d..ed1f44bda 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -15,8 +14,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("Forbidden: machine token required", 403);}- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const taskId = ctx.params?.taskId;if (!taskId) {diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.test.tsindex 1dd85bf36..9ed238e81 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.test.ts@@ -5,7 +5,7 @@ const mockFailTask = vi.fn();const mockTaskToResponse = vi.fn();const mockGetConversation = vi.fn();-let mockAuthCtx: Record<string, unknown> = { userId: "u1", email: "[email protected]", workspaceId: "w1" };+let mockAuthCtx: Record<string, unknown> = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: { withSession: () => ({}) } } })),@@ -67,7 +67,7 @@ const makeReq = (taskId: string, body: Record<string, unknown> = {}) =>describe("POST /api/daemon/tasks/[taskId]/fail", () => {beforeEach(() => {vi.clearAllMocks();- mockAuthCtx = { userId: "u1", email: "[email protected]", workspaceId: "w1" };+ mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };});it("returns failed task and broadcasts to conversation owner", async () => {@@ -89,7 +89,7 @@ describe("POST /api/daemon/tasks/[taskId]/fail", () => {});it("returns 403 when workspaceId is missing (session auth)", async () => {- mockAuthCtx = { userId: "u1", email: "[email protected]" };+ mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]" };const res = await POST(makeReq("t1", { error: "boom" }), withParams("t1"));const body = await res.json();diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.tsindex 4f95c1f03..02b5cc25b 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -15,8 +14,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("Forbidden: machine token required", 403);}- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const taskId = ctx.params?.taskId;if (!taskId) {diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.test.tsindex 0304621e9..452fd8d58 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.test.ts@@ -6,7 +6,7 @@ const mockCreateTaskMessage = vi.fn();const mockGetTask = vi.fn();const mockTaskMessageToResponse = vi.fn((m: any) => m);-let mockAuthCtx: Record<string, unknown> = { userId: "u1", email: "[email protected]", workspaceId: "w1" };+let mockAuthCtx: Record<string, unknown> = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: { withSession: () => ({}) } } })),@@ -67,7 +67,7 @@ const withParams = (taskId: string) => ({describe("GET /api/daemon/tasks/[taskId]/messages", () => {beforeEach(() => {vi.clearAllMocks();- mockAuthCtx = { userId: "u1", email: "[email protected]", workspaceId: "w1" };+ mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };});it("returns messages for workspace-scoped task", async () => {@@ -86,7 +86,7 @@ describe("GET /api/daemon/tasks/[taskId]/messages", () => {});it("returns 403 when workspaceId is missing (session auth)", async () => {- mockAuthCtx = { userId: "u1", email: "[email protected]" };+ mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]" };const res = await GET(new NextRequest("http://localhost/api/daemon/tasks/t1/messages"),@@ -103,7 +103,7 @@ describe("GET /api/daemon/tasks/[taskId]/messages", () => {describe("POST /api/daemon/tasks/[taskId]/messages", () => {beforeEach(() => {vi.clearAllMocks();- mockAuthCtx = { userId: "u1", email: "[email protected]", workspaceId: "w1" };+ mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };});it("creates messages for workspace-scoped task", async () => {@@ -129,7 +129,7 @@ describe("POST /api/daemon/tasks/[taskId]/messages", () => {});it("returns 403 when workspaceId is missing (session auth)", async () => {- mockAuthCtx = { userId: "u1", email: "[email protected]" };+ mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]" };const res = await POST(new NextRequest("http://localhost/api/daemon/tasks/t1/messages", {diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.tsindex 33b3f7667..471205b7d 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb, withD1Retry } from "@/lib/db";import type { TaskMessageResponse } from "@alook/shared"@@ -15,8 +14,7 @@ export const GET = withAuth(async (_req, ctx) => {return writeError("Forbidden: machine token required", 403);}- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const taskId = ctx.params?.taskId;if (!taskId) {@@ -32,8 +30,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("Forbidden: machine token required", 403);}- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const taskId = ctx.params?.taskId;if (!taskId) {diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/start/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/start/route.test.tsindex 0eea7650d..33d30046d 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/start/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/start/route.test.ts@@ -5,7 +5,7 @@ const mockStartTask = vi.fn();const mockTaskToResponse = vi.fn();const mockGetConversation = vi.fn();-let mockAuthCtx: Record<string, unknown> = { userId: "u1", email: "[email protected]", workspaceId: "w1" };+let mockAuthCtx: Record<string, unknown> = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -52,7 +52,7 @@ const withParams = (taskId: string) => ({describe("POST /api/daemon/tasks/[taskId]/start", () => {beforeEach(() => {vi.clearAllMocks();- mockAuthCtx = { userId: "u1", email: "[email protected]", workspaceId: "w1" };+ mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };});it("returns started task and broadcasts to conversation owner", async () => {@@ -112,7 +112,7 @@ describe("POST /api/daemon/tasks/[taskId]/start", () => {});it("returns 403 when workspaceId is missing (session auth)", async () => {- mockAuthCtx = { userId: "u1", email: "[email protected]" };+ mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]" };const res = await POST(new NextRequest("http://localhost/api/daemon/tasks/t1/start", {diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/start/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/start/route.tsindex 0c64ecea9..8d1981500 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/start/route.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/start/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -12,8 +11,7 @@ export const POST = withAuth(async (_req, ctx) => {return writeError("Forbidden: machine token required", 403);}- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const taskId = ctx.params?.taskId;if (!taskId) {diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.tsindex af81aa7a2..d15aa2e3e 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.ts@@ -23,7 +23,7 @@ vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params =ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1", params });}),}));vi.mock("@/lib/middleware/helpers", async () => {diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/status/route.tsindex 7e836a529..488bd2e7d 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/status/route.ts@@ -1,12 +1,10 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb, withD1Retry } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";import { writeJSON, writeError } from "@/lib/middleware/helpers";export const GET = withAuth(async (_req, ctx) => {- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)if (!ctx.workspaceId) {return writeError("Forbidden: machine token required", 403);diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.test.tsindex 612b20905..6eff973ea 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.test.ts@@ -29,7 +29,7 @@ let injectWorkspaceId: string | undefined = "w1";vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: injectWorkspaceId, params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: injectWorkspaceId, params });}),}));diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.tsindex b05f14098..b5ec4a5f5 100644--- a/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.ts+++ b/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -14,8 +13,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("Forbidden: machine token required", 403);}- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const taskId = ctx.params?.taskId;if (!taskId) {diff --git a/src/web/src/app/api/daemon/tasks/poll/route.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.test.tsindex a2e0a6dc9..0fe555bf2 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.test.ts@@ -87,7 +87,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1", params });}),}));diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.tsindex 2761def1c..96349810a 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, PollRequestSchema, semverGte, type FileRequestItem, type PollMeetingItem } from "@alook/shared";import { getDb, withD1Retry } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ import { broadcastToUser } from "@/lib/broadcast";import { log } from "@/lib/logger";export const POST = withAuth(async (req: NextRequest, ctx) => {- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const { cached, cacheKeys, throttled } = await import("@/lib/cache");const [body, err] = await parseBody(req, PollRequestSchema);@@ -143,7 +141,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {await throttled(`expire_fr:${ctx.workspaceId}`, 5, async () => {await queries.workspaceFileRequest.expireStale(db, ctx.workspaceId!);});- const kv = (env as Env).CACHE_KV ?? null;+ const kv = ctx.env.CACHE_KV ?? null;const frFlag = kv ? await kv.get(cacheKeys.hasPendingFileRequest(ctx.workspaceId!)) : null;if (frFlag !== "0") {const pending = await queries.workspaceFileRequest.getPendingByWorkspace(db, ctx.workspaceId);diff --git a/src/web/src/app/api/daemon/workspace/report/route.test.ts b/src/web/src/app/api/daemon/workspace/report/route.test.tsindex 97e8d3ca3..a3f251f49 100644--- a/src/web/src/app/api/daemon/workspace/report/route.test.ts+++ b/src/web/src/app/api/daemon/workspace/report/route.test.ts@@ -30,7 +30,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1", params });}),}));diff --git a/src/web/src/app/api/daemon/workspace/report/route.ts b/src/web/src/app/api/daemon/workspace/report/route.tsindex 0f6ac68d7..6e6a60993 100644--- a/src/web/src/app/api/daemon/workspace/report/route.ts+++ b/src/web/src/app/api/daemon/workspace/report/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, WorkspaceFileReportSchema } from "@alook/shared";import { withAuth } from "@/lib/middleware/auth";import { parseBody, writeJSON, writeError } from "@/lib/middleware/helpers";@@ -11,8 +10,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("Forbidden: machine token required", 403);}- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const [body, err] = await parseBody(req, WorkspaceFileReportSchema);if (err) return err;diff --git a/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts b/src/web/src/app/api/email/[id]/attachment/[index]/route.test.tsindex 6af676d8c..1abef0ac2 100644--- a/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts+++ b/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts@@ -27,7 +27,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: { DB: {}, EMAIL_BUCKET: { get: mockBucketGet } }, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/email/[id]/attachment/[index]/route.ts b/src/web/src/app/api/email/[id]/attachment/[index]/route.tsindex fac94b5e2..f5875e21a 100644--- a/src/web/src/app/api/email/[id]/attachment/[index]/route.ts+++ b/src/web/src/app/api/email/[id]/attachment/[index]/route.ts@@ -1,5 +1,4 @@import PostalMime from "postal-mime";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, filterDownloadableAttachments } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("email id is required", 400);@@ -25,7 +23,7 @@ export const GET = withAuth(async (req, ctx) => {const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);if (!agent) return writeError("not found", 404);- const object = await (env as Env).EMAIL_BUCKET.get(email.r2Key);+ const object = await ctx.env.EMAIL_BUCKET.get(email.r2Key);if (!object) return writeError("email content not available", 404);const raw = await object.arrayBuffer();diff --git a/src/web/src/app/api/email/[id]/body/route.test.ts b/src/web/src/app/api/email/[id]/body/route.test.tsindex 115d5f65e..0dc11cb6c 100644--- a/src/web/src/app/api/email/[id]/body/route.test.ts+++ b/src/web/src/app/api/email/[id]/body/route.test.ts@@ -25,7 +25,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: { DB: {}, EMAIL_BUCKET: { get: (...args: unknown[]) => mockR2Get(...args) } }, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/email/[id]/body/route.ts b/src/web/src/app/api/email/[id]/body/route.tsindex 78146f2a8..04522d8d7 100644--- a/src/web/src/app/api/email/[id]/body/route.ts+++ b/src/web/src/app/api/email/[id]/body/route.ts@@ -1,5 +1,4 @@import PostalMime from "postal-mime";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("email id is required", 400);@@ -22,7 +20,7 @@ export const GET = withAuth(async (req, ctx) => {const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);if (!agent) return writeError("not found", 404);- const object = await (env as Env).EMAIL_BUCKET.get(email.r2Key);+ const object = await ctx.env.EMAIL_BUCKET.get(email.r2Key);if (!object) {return new Response("Email body not available", {status: 404,diff --git a/src/web/src/app/api/email/[id]/raw/route.test.ts b/src/web/src/app/api/email/[id]/raw/route.test.tsindex 11ce2e5d8..7ab856e0f 100644--- a/src/web/src/app/api/email/[id]/raw/route.test.ts+++ b/src/web/src/app/api/email/[id]/raw/route.test.ts@@ -31,7 +31,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: { DB: {}, EMAIL_BUCKET: { get: (...args: unknown[]) => mockR2Get(...args) } }, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/email/[id]/raw/route.ts b/src/web/src/app/api/email/[id]/raw/route.tsindex 6a1344ad9..3ee1b93ac 100644--- a/src/web/src/app/api/email/[id]/raw/route.ts+++ b/src/web/src/app/api/email/[id]/raw/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -9,8 +8,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("email id is required", 400);@@ -21,7 +19,7 @@ export const GET = withAuth(async (req, ctx) => {const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);if (!agent) return writeError("not found", 404);- const object = await (env as Env).EMAIL_BUCKET.get(email.r2Key);+ const object = await ctx.env.EMAIL_BUCKET.get(email.r2Key);if (!object) {return writeError("Email raw content not available", 404);}diff --git a/src/web/src/app/api/email/[id]/route.test.ts b/src/web/src/app/api/email/[id]/route.test.tsindex abe0660e6..7046c654e 100644--- a/src/web/src/app/api/email/[id]/route.test.ts+++ b/src/web/src/app/api/email/[id]/route.test.ts@@ -33,7 +33,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/email/[id]/route.ts b/src/web/src/app/api/email/[id]/route.tsindex 5f2f0fcad..46fef706c 100644--- a/src/web/src/app/api/email/[id]/route.ts+++ b/src/web/src/app/api/email/[id]/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, UpdateEmailStatusRequestSchema } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("email id is required", 400);@@ -29,8 +27,7 @@ export const DELETE = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("email id is required", 400);@@ -50,8 +47,7 @@ export const PATCH = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("email id is required", 400);diff --git a/src/web/src/app/api/email/[id]/thread/route.test.ts b/src/web/src/app/api/email/[id]/thread/route.test.tsindex 85c699450..2d0545119 100644--- a/src/web/src/app/api/email/[id]/thread/route.test.ts+++ b/src/web/src/app/api/email/[id]/thread/route.test.ts@@ -25,7 +25,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/email/[id]/thread/route.ts b/src/web/src/app/api/email/[id]/thread/route.tsindex 3f836a327..c7a73a6e4 100644--- a/src/web/src/app/api/email/[id]/thread/route.ts+++ b/src/web/src/app/api/email/[id]/thread/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("email id is required", 400);diff --git a/src/web/src/app/api/email/[id]/trust/route.test.ts b/src/web/src/app/api/email/[id]/trust/route.test.tsindex 5e42de741..3811bf806 100644--- a/src/web/src/app/api/email/[id]/trust/route.test.ts+++ b/src/web/src/app/api/email/[id]/trust/route.test.ts@@ -50,7 +50,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: (handler: Function) =>(req: NextRequest) =>- handler(req, { userId: "u1", email: "[email protected]", params: { id: req.url.split("/email/")[1]?.split("/")[0] } }),+ handler(req, { env: {}, userId: "u1", email: "[email protected]", params: { id: req.url.split("/email/")[1]?.split("/")[0] } }),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/email/[id]/trust/route.ts b/src/web/src/app/api/email/[id]/trust/route.tsindex ee1d7008e..b6384ec1e 100644--- a/src/web/src/app/api/email/[id]/trust/route.ts+++ b/src/web/src/app/api/email/[id]/trust/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"@@ -13,8 +12,7 @@ export const POST = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx)if (ws instanceof Response) return ws- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.idif (!id) return writeError("email id is required", 400)diff --git a/src/web/src/app/api/email/notify/route.ts b/src/web/src/app/api/email/notify/route.tsindex 99b79e2e1..89386f37e 100644--- a/src/web/src/app/api/email/notify/route.ts+++ b/src/web/src/app/api/email/notify/route.ts@@ -1,15 +1,14 @@import { NextRequest } from "next/server"-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, MeetingStatus, EmailNotifyRequestSchema } from "@alook/shared"import { getDb } from "@/lib/db"+import { withEnv } from "@/lib/middleware/env"import { writeJSON, parseBody } from "@/lib/middleware/helpers"import { broadcastToUser } from "@/lib/broadcast"import { invalidate, cacheKeys } from "@/lib/cache"import { dispatchEmailToAgent } from "@/lib/services/email-dispatch"-export async function POST(req: NextRequest) {- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+export const POST = withEnv(async (req: NextRequest, ctx) => {+ const db = getDb(ctx.env.DB)const [body, valErr] = await parseBody(req, EmailNotifyRequestSchema);if (valErr) return valErr;@@ -71,4 +70,4 @@ export async function POST(req: NextRequest) {}return writeJSON({ ok: true, ...(conversationId ? { conversationId } : {}) })-}+});diff --git a/src/web/src/app/api/email/route.test.ts b/src/web/src/app/api/email/route.test.tsindex 65088e65f..56b01aceb 100644--- a/src/web/src/app/api/email/route.test.ts+++ b/src/web/src/app/api/email/route.test.ts@@ -32,7 +32,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/email/route.ts b/src/web/src/app/api/email/route.tsindex 441eddfaa..64a3fa4d7 100644--- a/src/web/src/app/api/email/route.ts+++ b/src/web/src/app/api/email/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, toAlookAddress } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -13,8 +12,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const agentId = req.nextUrl.searchParams.get("agentId");if (!agentId) return writeError("agentId is required", 400);diff --git a/src/web/src/app/api/email/send/route.test.ts b/src/web/src/app/api/email/send/route.test.tsindex 4c683f219..9f7f89105 100644--- a/src/web/src/app/api/email/send/route.test.ts+++ b/src/web/src/app/api/email/send/route.test.ts@@ -77,7 +77,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: { DB: {}, EMAIL_WORKER: { fetch: (...args: unknown[]) => mockEmailWorkerFetch(...args) }, EMAIL_BUCKET: { get: (...args: unknown[]) => mockEmailBucketGet(...args), put: (...args: unknown[]) => mockEmailBucketPut(...args) }, WORKER_SELF_REFERENCE: { fetch: (...args: unknown[]) => mockWorkerSelfRefFetch(...args) } }, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/email/send/route.ts b/src/web/src/app/api/email/send/route.tsindex 6a2d5f3d6..bfe06a4e8 100644--- a/src/web/src/app/api/email/send/route.ts+++ b/src/web/src/app/api/email/send/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, DEV_EMAIL_WORKER_URL, DEV_WEB_URL, SendEmailRequestSchema, parseEmailHandle, toAlookAddress, buildMimeMessage, extractThreadId, buildEmailMapKey } from "@alook/shared";import { nanoid } from "nanoid";import { getDb } from "@/lib/db"@@ -55,8 +54,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const cfEnv = env as Env;+ const cfEnv = ctx.env;const db = getDb(cfEnv.DB);const [body, valErr] = await parseBody(req, SendEmailRequestSchema);diff --git a/src/web/src/app/api/email/upload/route.test.ts b/src/web/src/app/api/email/upload/route.test.tsindex 06d90f567..a4e1662e6 100644--- a/src/web/src/app/api/email/upload/route.test.ts+++ b/src/web/src/app/api/email/upload/route.test.ts@@ -15,7 +15,7 @@ vi.mock("@opennextjs/cloudflare", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: { DB: {}, EMAIL_BUCKET: { put: (...args: unknown[]) => mockR2Put(...args) } }, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/email/upload/route.ts b/src/web/src/app/api/email/upload/route.tsindex 95dd7caae..e72787283 100644--- a/src/web/src/app/api/email/upload/route.ts+++ b/src/web/src/app/api/email/upload/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { nanoid } from "nanoid";import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";@@ -11,8 +10,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const bucket = (env as Env).EMAIL_BUCKET;+ const bucket = ctx.env.EMAIL_BUCKET;let formData: FormData;try {diff --git a/src/web/src/app/api/flags/[messageId]/route.test.ts b/src/web/src/app/api/flags/[messageId]/route.test.tsindex cfe6c91db..38b59ce4d 100644--- a/src/web/src/app/api/flags/[messageId]/route.test.ts+++ b/src/web/src/app/api/flags/[messageId]/route.test.ts@@ -21,7 +21,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/flags/[messageId]/route.ts b/src/web/src/app/api/flags/[messageId]/route.tsindex 4c576165d..0d4130a9d 100644--- a/src/web/src/app/api/flags/[messageId]/route.ts+++ b/src/web/src/app/api/flags/[messageId]/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -14,8 +13,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {return new Response(null, { status: 400 });}- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);await queries.messageFlag.unflagMessage(db, messageId, ctx.userId, ws.workspaceId);return new Response(null, { status: 204 });diff --git a/src/web/src/app/api/flags/count/route.test.ts b/src/web/src/app/api/flags/count/route.test.tsindex 841c1f955..876c14b88 100644--- a/src/web/src/app/api/flags/count/route.test.ts+++ b/src/web/src/app/api/flags/count/route.test.ts@@ -21,7 +21,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/flags/count/route.ts b/src/web/src/app/api/flags/count/route.tsindex ded5199c7..154e892ce 100644--- a/src/web/src/app/api/flags/count/route.ts+++ b/src/web/src/app/api/flags/count/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const count = await queries.messageFlag.getFlaggedCount(db, ctx.userId, ws.workspaceId);diff --git a/src/web/src/app/api/flags/route.test.ts b/src/web/src/app/api/flags/route.test.tsindex a45dfa4aa..469377278 100644--- a/src/web/src/app/api/flags/route.test.ts+++ b/src/web/src/app/api/flags/route.test.ts@@ -27,7 +27,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/flags/route.ts b/src/web/src/app/api/flags/route.tsindex 885df6d5f..d12b33abd 100644--- a/src/web/src/app/api/flags/route.ts+++ b/src/web/src/app/api/flags/route.ts@@ -1,5 +1,4 @@import { NextRequest, NextResponse } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const idsOnly = req.nextUrl.searchParams.get("ids_only") === "true";const conversationId = req.nextUrl.searchParams.get("conversation_id");@@ -46,8 +44,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return NextResponse.json({ error: "messageId is required" }, { status: 400 });}- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const msgWorkspaceId = await queries.messageFlag.getMessageWorkspaceId(db, body.messageId);diff --git a/src/web/src/app/api/inbox/count/route.test.ts b/src/web/src/app/api/inbox/count/route.test.tsindex f28314a7a..323fe2b78 100644--- a/src/web/src/app/api/inbox/count/route.test.ts+++ b/src/web/src/app/api/inbox/count/route.test.ts@@ -21,7 +21,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/inbox/count/route.ts b/src/web/src/app/api/inbox/count/route.tsindex 04e258e66..e39555a34 100644--- a/src/web/src/app/api/inbox/count/route.ts+++ b/src/web/src/app/api/inbox/count/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const VALID_TYPES = ["user_dm_message", "calendar_event", "email_notification"];const typesParam = req.nextUrl.searchParams.get("types");diff --git a/src/web/src/app/api/inbox/read-all/route.test.ts b/src/web/src/app/api/inbox/read-all/route.test.tsindex 4594468fe..2fc70b47c 100644--- a/src/web/src/app/api/inbox/read-all/route.test.ts+++ b/src/web/src/app/api/inbox/read-all/route.test.ts@@ -22,7 +22,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/inbox/read-all/route.ts b/src/web/src/app/api/inbox/read-all/route.tsindex b25cd9d2c..6508708c7 100644--- a/src/web/src/app/api/inbox/read-all/route.ts+++ b/src/web/src/app/api/inbox/read-all/route.ts@@ -1,5 +1,4 @@import { NextRequest, NextResponse } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);await queries.inbox.markAllConversationsRead(db, ctx.userId, ws.workspaceId);invalidateInboxCounts(ctx.userId, ws.workspaceId).catch(() => {});diff --git a/src/web/src/app/api/inbox/read/route.test.ts b/src/web/src/app/api/inbox/read/route.test.tsindex 6eb7a251a..79a0f8ee9 100644--- a/src/web/src/app/api/inbox/read/route.test.ts+++ b/src/web/src/app/api/inbox/read/route.test.ts@@ -26,7 +26,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/inbox/read/route.ts b/src/web/src/app/api/inbox/read/route.tsindex 966b2258a..e30b6507e 100644--- a/src/web/src/app/api/inbox/read/route.ts+++ b/src/web/src/app/api/inbox/read/route.ts@@ -1,5 +1,4 @@import { NextRequest, NextResponse } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -20,8 +19,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return NextResponse.json({ error: "conversationId is required" }, { status: 400 });}- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const conv = await queries.conversation.getConversation(db, body.conversationId, ws.workspaceId);if (!conv || conv.userId !== ctx.userId) {diff --git a/src/web/src/app/api/inbox/route.test.ts b/src/web/src/app/api/inbox/route.test.tsindex 430f4be8d..0f8d880a6 100644--- a/src/web/src/app/api/inbox/route.test.ts+++ b/src/web/src/app/api/inbox/route.test.ts@@ -21,7 +21,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/inbox/route.ts b/src/web/src/app/api/inbox/route.tsindex 967a7a6ef..da053b45a 100644--- a/src/web/src/app/api/inbox/route.ts+++ b/src/web/src/app/api/inbox/route.ts@@ -1,5 +1,4 @@import { NextRequest, NextResponse } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const limitParam = req.nextUrl.searchParams.get("limit");const limit = limitParam ? Math.min(Math.max(parseInt(limitParam, 10) || 30, 1), 100) : 30;diff --git a/src/web/src/app/api/invite/[token]/route.test.ts b/src/web/src/app/api/invite/[token]/route.test.tsindex 24bd76da8..0906aec2c 100644--- a/src/web/src/app/api/invite/[token]/route.test.ts+++ b/src/web/src/app/api/invite/[token]/route.test.ts@@ -32,7 +32,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/invite/[token]/route.ts b/src/web/src/app/api/invite/[token]/route.tsindex aad038854..9850477ff 100644--- a/src/web/src/app/api/invite/[token]/route.ts+++ b/src/web/src/app/api/invite/[token]/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -9,8 +8,7 @@ import { invalidate, cacheKeys } from "@/lib/cache";export const GET = withAuth(async (req: NextRequest, ctx) => {const { token } = ctx.params!;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const invite = await queries.workspaceInvite.getInviteByToken(db, token);if (!invite) return writeError("invite not found", 404);@@ -27,8 +25,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {export const POST = withAuth(async (req: NextRequest, ctx) => {const { token } = ctx.params!;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const invite = await queries.workspaceInvite.getInviteByToken(db, token);if (!invite) return writeError("invite not found", 404);diff --git a/src/web/src/app/api/issues/[id]/comments/route.test.ts b/src/web/src/app/api/issues/[id]/comments/route.test.tsindex f29364c20..b152d8aef 100644--- a/src/web/src/app/api/issues/[id]/comments/route.test.ts+++ b/src/web/src/app/api/issues/[id]/comments/route.test.ts@@ -57,7 +57,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/issues/[id]/comments/route.ts b/src/web/src/app/api/issues/[id]/comments/route.tsindex 11aa5204e..027d6d336 100644--- a/src/web/src/app/api/issues/[id]/comments/route.ts+++ b/src/web/src/app/api/issues/[id]/comments/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import {CreateIssueCommentBodySchema,TASK_TYPES,@@ -18,8 +17,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("issue id is required", 400);@@ -34,8 +32,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("issue id is required", 400);diff --git a/src/web/src/app/api/issues/[id]/route.test.ts b/src/web/src/app/api/issues/[id]/route.test.tsindex e62a7a86c..ec8b04baf 100644--- a/src/web/src/app/api/issues/[id]/route.test.ts+++ b/src/web/src/app/api/issues/[id]/route.test.ts@@ -48,7 +48,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: (handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });},}));diff --git a/src/web/src/app/api/issues/[id]/route.ts b/src/web/src/app/api/issues/[id]/route.tsindex 5d1a12196..0976e8fd8 100644--- a/src/web/src/app/api/issues/[id]/route.ts+++ b/src/web/src/app/api/issues/[id]/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import {CreateIssueCommentBodySchema,UpdateIssueRequestSchema,@@ -21,8 +20,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("issue id is required", 400);@@ -54,8 +52,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("issue id is required", 400);@@ -166,8 +163,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("issue id is required", 400);@@ -200,8 +196,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) return writeError("issue id is required", 400);diff --git a/src/web/src/app/api/issues/route.test.ts b/src/web/src/app/api/issues/route.test.tsindex d4246decd..d342ea719 100644--- a/src/web/src/app/api/issues/route.test.ts+++ b/src/web/src/app/api/issues/route.test.ts@@ -45,7 +45,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: (handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: { DB: {}, EMAIL_BUCKET: { put: (...a: unknown[]) => mockR2Put(...a) } }, userId: "u1", email: "[email protected]", params });},}));diff --git a/src/web/src/app/api/issues/route.ts b/src/web/src/app/api/issues/route.tsindex f1c7876fe..014ca42a9 100644--- a/src/web/src/app/api/issues/route.ts+++ b/src/web/src/app/api/issues/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { CreateIssueRequestSchema, IssueStatusSchema, queries, TASK_TYPES } from "@alook/shared";import { nanoid } from "nanoid";import { getDb } from "@/lib/db";@@ -28,8 +27,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const agentId = req.nextUrl.searchParams.get("agentId") ?? undefined;const status = req.nextUrl.searchParams.get("status") ?? undefined;@@ -64,9 +62,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);- const bucket = (env as Env).EMAIL_BUCKET;+ const db = getDb(ctx.env.DB);+ const bucket = ctx.env.EMAIL_BUCKET;const contentType = req.headers.get("content-type") ?? "";const isMultipart = contentType.includes("multipart/form-data");diff --git a/src/web/src/app/api/machine-tokens/[id]/route.test.ts b/src/web/src/app/api/machine-tokens/[id]/route.test.tsindex 6d68256ec..8e57b935d 100644--- a/src/web/src/app/api/machine-tokens/[id]/route.test.ts+++ b/src/web/src/app/api/machine-tokens/[id]/route.test.ts@@ -23,7 +23,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/machine-tokens/[id]/route.ts b/src/web/src/app/api/machine-tokens/[id]/route.tsindex 2cb590540..5b2662c79 100644--- a/src/web/src/app/api/machine-tokens/[id]/route.ts+++ b/src/web/src/app/api/machine-tokens/[id]/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const DELETE = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/machine-tokens/activate/route.ts b/src/web/src/app/api/machine-tokens/activate/route.tsindex f1ca51f94..bd9a6f4a9 100644--- a/src/web/src/app/api/machine-tokens/activate/route.ts+++ b/src/web/src/app/api/machine-tokens/activate/route.ts@@ -1,7 +1,7 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, ActivateTokenRequestSchema, createLogger } from "@alook/shared";import { getDb } from "@/lib/db"+import { withEnv } from "@/lib/middleware/env";import { writeJSON } from "@/lib/middleware/helpers";import { runtimeToResponse } from "@/lib/api/responses";import { broadcastToUser } from "@/lib/broadcast";@@ -9,7 +9,7 @@ import { invalidate, cacheKeys } from "@/lib/cache";const log = createLogger({ service: "machine-tokens/activate" });-export async function POST(req: NextRequest) {+export const POST = withEnv(async (req: NextRequest, ctx) => {let raw: unknown;try {raw = await req.json();@@ -24,8 +24,7 @@ export async function POST(req: NextRequest) {const { token, hostname, runtimes } = parsed.data;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const mt = await queries.machineToken.getMachineTokenByToken(db, token);if (!mt) {@@ -89,4 +88,4 @@ export async function POST(req: NextRequest) {workspace_id: workspaceId,runtimes: results.map(runtimeToResponse),});-}+});diff --git a/src/web/src/app/api/machine-tokens/route.test.ts b/src/web/src/app/api/machine-tokens/route.test.tsindex 48fef684c..20d078910 100644--- a/src/web/src/app/api/machine-tokens/route.test.ts+++ b/src/web/src/app/api/machine-tokens/route.test.ts@@ -44,7 +44,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/machine-tokens/route.ts b/src/web/src/app/api/machine-tokens/route.tsindex cd501383e..46e10579a 100644--- a/src/web/src/app/api/machine-tokens/route.ts+++ b/src/web/src/app/api/machine-tokens/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { generateMachineToken } from "@/lib/token";@@ -12,16 +11,14 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const tokens = await queries.machineToken.listMachineTokens(db, ctx.userId, ws.workspaceId);return writeJSON(tokens.map(machineTokenToResponse));});export const POST = withAuth(async (req: NextRequest, ctx) => {- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const wsParam = req.nextUrl.searchParams.get("workspace_id");let workspaceId: string | null = null;diff --git a/src/web/src/app/api/machine-tokens/status/route.test.ts b/src/web/src/app/api/machine-tokens/status/route.test.tsindex be8f3a44c..af57998cf 100644--- a/src/web/src/app/api/machine-tokens/status/route.test.ts+++ b/src/web/src/app/api/machine-tokens/status/route.test.ts@@ -18,7 +18,7 @@ vi.mock("@/lib/middleware/helpers", async () =>await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers"));vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => (req: any) => handler(req, { userId: "u1", email: "[email protected]" }),+ withAuth: (handler: any) => (req: any) => handler(req, { env: {}, userId: "u1", email: "[email protected]" }),}));import { GET } from "./route";diff --git a/src/web/src/app/api/machine-tokens/status/route.ts b/src/web/src/app/api/machine-tokens/status/route.tsindex 8904c8cd1..0a0ebba6b 100644--- a/src/web/src/app/api/machine-tokens/status/route.ts+++ b/src/web/src/app/api/machine-tokens/status/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -7,8 +6,7 @@ import { writeJSON } from "@/lib/middleware/helpers";const DAEMON_ONLINE_THRESHOLD_MS = 120_000;export const GET = withAuth(async (_req, ctx) => {- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const token = await queries.machineToken.getLatestTokenForUser(db, ctx.userId);if (!token) {diff --git a/src/web/src/app/api/me/route.test.ts b/src/web/src/app/api/me/route.test.tsindex eb149cef1..ceed84e33 100644--- a/src/web/src/app/api/me/route.test.ts+++ b/src/web/src/app/api/me/route.test.ts@@ -19,7 +19,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/me/route.ts b/src/web/src/app/api/me/route.tsindex 0a00aabd5..5f09d52f1 100644--- a/src/web/src/app/api/me/route.ts+++ b/src/web/src/app/api/me/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -6,8 +5,7 @@ import { writeJSON, writeError } from "@/lib/middleware/helpers";import { userToResponse } from "@/lib/api/responses";export const GET = withAuth(async (_req, ctx) => {- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const user = await queries.user.getUser(db, ctx.userId);if (!user) {diff --git a/src/web/src/app/api/meeting/callback/route.test.ts b/src/web/src/app/api/meeting/callback/route.test.tsindex e2ae7a8ca..fb5f0cad5 100644--- a/src/web/src/app/api/meeting/callback/route.test.ts+++ b/src/web/src/app/api/meeting/callback/route.test.ts@@ -42,7 +42,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });+ return handler(req, { env: { DB: {}, EMAIL_BUCKET: { put: (...args: unknown[]) => mockBucketPut(...args) }, WORKER_SELF_REFERENCE: { fetch: (...args: unknown[]) => mockSelfRefFetch(...args) } }, userId: "u1", email: "[email protected]", workspaceId: "w1", params });}),}));diff --git a/src/web/src/app/api/meeting/callback/route.ts b/src/web/src/app/api/meeting/callback/route.tsindex c29089d30..ad2ce3bf6 100644--- a/src/web/src/app/api/meeting/callback/route.ts+++ b/src/web/src/app/api/meeting/callback/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server"-import { getCloudflareContext } from "@opennextjs/cloudflare"import { nanoid } from "nanoid"import { queries, MeetingStatus, DEV_WEB_URL, buildMimeMessage, toAlookAddress } from "@alook/shared"import { withAuth } from "@/lib/middleware/auth"@@ -8,8 +7,7 @@ import { getDb } from "@/lib/db"import { log } from "@/lib/logger"export const POST = withAuth(async (req: NextRequest, ctx) => {- const { env } = getCloudflareContext()- const cfEnv = env as Env+ const cfEnv = ctx.envconst db = getDb(cfEnv.DB)if (!ctx.workspaceId) {diff --git a/src/web/src/app/api/members/me/route.test.ts b/src/web/src/app/api/members/me/route.test.tsindex b1d56cc0c..6c585c827 100644--- a/src/web/src/app/api/members/me/route.test.ts+++ b/src/web/src/app/api/members/me/route.test.ts@@ -27,7 +27,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1", params });}),}));diff --git a/src/web/src/app/api/members/me/route.ts b/src/web/src/app/api/members/me/route.tsindex 3c24d180f..2cb950bbc 100644--- a/src/web/src/app/api/members/me/route.ts+++ b/src/web/src/app/api/members/me/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, UpdateMemberRequestSchema } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const member = await queries.member.getMemberByUserAndWorkspace(db,@@ -31,8 +29,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {const [body, err] = await parseBody(req, UpdateMemberRequestSchema);if (err) return err;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const updated = await queries.member.updateMemberGlobalInstruction(db,diff --git a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.tsindex 41f7c8c83..fee7cb10e 100644--- a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts+++ b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts@@ -32,7 +32,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.ts b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.tsindex 0f6d9e523..94c38b700 100644--- a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.ts+++ b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const runtimeId = req.nextUrl.pathname.split("/runtimes/")[1]?.split("/")[0];if (!runtimeId) return writeError("runtime id required", 400);diff --git a/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts b/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.tsindex 3195551cb..86e481371 100644--- a/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts+++ b/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts@@ -35,7 +35,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts b/src/web/src/app/api/runtimes/[runtimeId]/update/route.tsindex 750590cdb..f1b7a4184 100644--- a/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts+++ b/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -12,8 +11,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const runtimeId = req.nextUrl.pathname.split("/runtimes/")[1]?.split("/")[0];if (!runtimeId) return writeError("runtime id required", 400);@@ -40,8 +38,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const runtimeId = req.nextUrl.pathname.split("/runtimes/")[1]?.split("/")[0];if (!runtimeId) return writeError("runtime id required", 400);diff --git a/src/web/src/app/api/runtimes/machine/route.test.ts b/src/web/src/app/api/runtimes/machine/route.test.tsindex 401fc3036..a13341433 100644--- a/src/web/src/app/api/runtimes/machine/route.test.ts+++ b/src/web/src/app/api/runtimes/machine/route.test.ts@@ -34,7 +34,7 @@ vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params =ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/runtimes/machine/route.ts b/src/web/src/app/api/runtimes/machine/route.tsindex 28c703a1a..6cc3d4e31 100644--- a/src/web/src/app/api/runtimes/machine/route.ts+++ b/src/web/src/app/api/runtimes/machine/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -13,8 +12,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const daemonId = req.nextUrl.searchParams.get("daemon_id");if (!daemonId) {diff --git a/src/web/src/app/api/runtimes/route.test.ts b/src/web/src/app/api/runtimes/route.test.tsindex 420c586f2..161e8e2c2 100644--- a/src/web/src/app/api/runtimes/route.test.ts+++ b/src/web/src/app/api/runtimes/route.test.ts@@ -22,7 +22,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/runtimes/route.ts b/src/web/src/app/api/runtimes/route.tsindex 906b61463..c88dbeb57 100644--- a/src/web/src/app/api/runtimes/route.ts+++ b/src/web/src/app/api/runtimes/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const runtimes = await queries.runtime.listAgentRuntimes(db, ws.workspaceId, ctx.userId);diff --git a/src/web/src/app/api/studios/check-handles/route.test.ts b/src/web/src/app/api/studios/check-handles/route.test.tsindex 2e0554d61..82b0ae524 100644--- a/src/web/src/app/api/studios/check-handles/route.test.ts+++ b/src/web/src/app/api/studios/check-handles/route.test.ts@@ -26,7 +26,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/studios/check-handles/route.ts b/src/web/src/app/api/studios/check-handles/route.tsindex 25cc01fd5..4a9234946 100644--- a/src/web/src/app/api/studios/check-handles/route.ts+++ b/src/web/src/app/api/studios/check-handles/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, isValidHandle } from "@alook/shared";import { nanoid } from "nanoid";import { uniqueNamesGenerator, names } from "unique-names-generator";@@ -7,7 +6,7 @@ import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";import { writeJSON, writeError } from "@/lib/middleware/helpers";-export const POST = withAuth(async (req: NextRequest) => {+export const POST = withAuth(async (req: NextRequest, ctx) => {let body: { names: string[] };try {body = await req.json() as { names: string[] };@@ -19,8 +18,7 @@ export const POST = withAuth(async (req: NextRequest) => {return writeError("names must be an array of 1-4 strings", 400);}- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);// Generate all candidate handles upfrontconst candidatesPerName: { name: string; candidates: string[] }[] = [];diff --git a/src/web/src/app/api/studios/check-name/route.test.ts b/src/web/src/app/api/studios/check-name/route.test.tsindex c49ca83fa..6734fa04a 100644--- a/src/web/src/app/api/studios/check-name/route.test.ts+++ b/src/web/src/app/api/studios/check-name/route.test.ts@@ -23,7 +23,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/studios/check-name/route.ts b/src/web/src/app/api/studios/check-name/route.tsindex e9608ae51..d94710f14 100644--- a/src/web/src/app/api/studios/check-name/route.ts+++ b/src/web/src/app/api/studios/check-name/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -34,8 +33,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {return writeError("name produces an invalid slug", 400);}- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const existing = await queries.workspace.getWorkspaceBySlug(db, slug);const available = !existing || (currentWorkspaceId !== null && existing.id === currentWorkspaceId);diff --git a/src/web/src/app/api/studios/route.test.ts b/src/web/src/app/api/studios/route.test.tsindex 6f7c35019..c0ff73aa6 100644--- a/src/web/src/app/api/studios/route.test.ts+++ b/src/web/src/app/api/studios/route.test.ts@@ -79,7 +79,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/studios/route.ts b/src/web/src/app/api/studios/route.tsindex 9c67a6892..694c61d3c 100644--- a/src/web/src/app/api/studios/route.ts+++ b/src/web/src/app/api/studios/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, CreateStudioRequestSchema, isValidHandle, isOnline, TASK_TYPES, toAlookAddress } from "@alook/shared";import { nanoid } from "nanoid";import { uniqueNamesGenerator, names } from "unique-names-generator";@@ -48,8 +47,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const [body, valErr] = await parseBody(req, CreateStudioRequestSchema);if (valErr) return valErr;diff --git a/src/web/src/app/api/tasks/[id]/messages/route.test.ts b/src/web/src/app/api/tasks/[id]/messages/route.test.tsindex d0a9bccbc..757198841 100644--- a/src/web/src/app/api/tasks/[id]/messages/route.test.ts+++ b/src/web/src/app/api/tasks/[id]/messages/route.test.ts@@ -48,7 +48,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/tasks/[id]/messages/route.ts b/src/web/src/app/api/tasks/[id]/messages/route.tsindex fe120f99a..02bdbc7ad 100644--- a/src/web/src/app/api/tasks/[id]/messages/route.ts+++ b/src/web/src/app/api/tasks/[id]/messages/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/tasks/[id]/retry/route.test.ts b/src/web/src/app/api/tasks/[id]/retry/route.test.tsindex 3f3a19df2..11be59e16 100644--- a/src/web/src/app/api/tasks/[id]/retry/route.test.ts+++ b/src/web/src/app/api/tasks/[id]/retry/route.test.ts@@ -48,7 +48,7 @@ vi.mock("@/lib/services/task", () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/tasks/[id]/retry/route.ts b/src/web/src/app/api/tasks/[id]/retry/route.tsindex b100661b9..b36916b53 100644--- a/src/web/src/app/api/tasks/[id]/retry/route.ts+++ b/src/web/src/app/api/tasks/[id]/retry/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -13,8 +12,7 @@ export const POST = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/tasks/[id]/route.test.ts b/src/web/src/app/api/tasks/[id]/route.test.tsindex 27504ccbb..2df90b307 100644--- a/src/web/src/app/api/tasks/[id]/route.test.ts+++ b/src/web/src/app/api/tasks/[id]/route.test.ts@@ -42,7 +42,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/tasks/[id]/route.ts b/src/web/src/app/api/tasks/[id]/route.tsindex 9d8b9b22c..c21ddcc65 100644--- a/src/web/src/app/api/tasks/[id]/route.ts+++ b/src/web/src/app/api/tasks/[id]/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -10,8 +9,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {diff --git a/src/web/src/app/api/traces/[traceId]/route.test.ts b/src/web/src/app/api/traces/[traceId]/route.test.tsindex 57b875f93..fcf6d35ff 100644--- a/src/web/src/app/api/traces/[traceId]/route.test.ts+++ b/src/web/src/app/api/traces/[traceId]/route.test.ts@@ -41,7 +41,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/traces/[traceId]/route.ts b/src/web/src/app/api/traces/[traceId]/route.tsindex 59014177b..e766b2107 100644--- a/src/web/src/app/api/traces/[traceId]/route.ts+++ b/src/web/src/app/api/traces/[traceId]/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -12,8 +11,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const traceId = ctx.params?.traceId;if (!traceId || typeof traceId !== "string" || !traceId.startsWith("tr_") || traceId.length > 30) {diff --git a/src/web/src/app/api/traces/route.test.ts b/src/web/src/app/api/traces/route.test.tsindex 8943a4eeb..134198c7e 100644--- a/src/web/src/app/api/traces/route.test.ts+++ b/src/web/src/app/api/traces/route.test.ts@@ -37,7 +37,7 @@ vi.mock("@alook/shared", () => ({vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/traces/route.ts b/src/web/src/app/api/traces/route.tsindex fa87a6d5d..c6b8c8b8c 100644--- a/src/web/src/app/api/traces/route.ts+++ b/src/web/src/app/api/traces/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -12,8 +11,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const statusRaw = req.nextUrl.searchParams.get("status");const status = statusRaw && ["active", "completed", "failed"].includes(statusRaw) ? statusRaw : undefined;diff --git a/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.test.ts b/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.test.tsindex f3329e875..adc581e4e 100644--- a/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.test.ts+++ b/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.test.ts@@ -24,7 +24,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.ts b/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.tsindex 09c1cb364..146e9e34b 100644--- a/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.ts+++ b/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -12,8 +11,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {const { inviteId } = ctx.params!;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const deleted = await queries.workspaceInvite.deleteInvite(db, inviteId, owner.workspaceId);if (!deleted) return writeError("invite not found", 404);diff --git a/src/web/src/app/api/workspaces/[id]/invites/route.test.ts b/src/web/src/app/api/workspaces/[id]/invites/route.test.tsindex c0486c801..8bad642c6 100644--- a/src/web/src/app/api/workspaces/[id]/invites/route.test.ts+++ b/src/web/src/app/api/workspaces/[id]/invites/route.test.ts@@ -26,7 +26,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/workspaces/[id]/invites/route.ts b/src/web/src/app/api/workspaces/[id]/invites/route.tsindex ddf335292..cf2cf288a 100644--- a/src/web/src/app/api/workspaces/[id]/invites/route.ts+++ b/src/web/src/app/api/workspaces/[id]/invites/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const owner = await withWorkspaceOwner(req, ctx);if (owner instanceof Response) return owner;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const invites = await queries.workspaceInvite.listActiveInvites(db, owner.workspaceId);return writeJSON(invites.map(inviteToResponse));@@ -22,8 +20,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const owner = await withWorkspaceOwner(req, ctx);if (owner instanceof Response) return owner;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString();const invite = await queries.workspaceInvite.createInvite(db, {diff --git a/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.test.ts b/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.test.tsindex cb9037696..ceec52c65 100644--- a/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.test.ts+++ b/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.test.ts@@ -26,7 +26,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.ts b/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.tsindex d99f595ad..724422f0a 100644--- a/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.ts+++ b/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -13,8 +12,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {const { memberId } = ctx.params!;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const target = await queries.member.getMember(db, memberId, owner.workspaceId);if (!target) return writeError("member not found", 404);diff --git a/src/web/src/app/api/workspaces/[id]/members/route.test.ts b/src/web/src/app/api/workspaces/[id]/members/route.test.tsindex ba6e56e31..7f00901e4 100644--- a/src/web/src/app/api/workspaces/[id]/members/route.test.ts+++ b/src/web/src/app/api/workspaces/[id]/members/route.test.ts@@ -24,7 +24,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/workspaces/[id]/members/route.ts b/src/web/src/app/api/workspaces/[id]/members/route.tsindex ff026bbed..4c456aad6 100644--- a/src/web/src/app/api/workspaces/[id]/members/route.ts+++ b/src/web/src/app/api/workspaces/[id]/members/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const members = await queries.member.listMembers(db, ws.workspaceId);return writeJSON(members.map(memberToResponse));diff --git a/src/web/src/app/api/workspaces/[id]/onboarded/route.ts b/src/web/src/app/api/workspaces/[id]/onboarded/route.tsindex 311b9daef..fe5d4f526 100644--- a/src/web/src/app/api/workspaces/[id]/onboarded/route.ts+++ b/src/web/src/app/api/workspaces/[id]/onboarded/route.ts@@ -1,13 +1,11 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";import { writeJSON } from "@/lib/middleware/helpers";export const POST = withAuth(async (req: NextRequest, ctx) => {- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const id = req.nextUrl.pathname.split("/").at(-2)!;diff --git a/src/web/src/app/api/workspaces/[id]/overview/route.test.ts b/src/web/src/app/api/workspaces/[id]/overview/route.test.tsindex 8251ff7f6..177276fa0 100644--- a/src/web/src/app/api/workspaces/[id]/overview/route.test.ts+++ b/src/web/src/app/api/workspaces/[id]/overview/route.test.ts@@ -42,7 +42,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));vi.mock("@/lib/middleware/workspace", () => ({diff --git a/src/web/src/app/api/workspaces/[id]/overview/route.ts b/src/web/src/app/api/workspaces/[id]/overview/route.tsindex 2d2141441..49e8d43b6 100644--- a/src/web/src/app/api/workspaces/[id]/overview/route.ts+++ b/src/web/src/app/api/workspaces/[id]/overview/route.ts@@ -1,4 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";@@ -11,8 +10,7 @@ export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;- const { env } = getCloudflareContext();- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const todayStart = new Date();todayStart.setHours(0, 0, 0, 0);diff --git a/src/web/src/app/api/workspaces/[id]/route.test.ts b/src/web/src/app/api/workspaces/[id]/route.test.tsindex df7c2ea38..0f3fed737 100644--- a/src/web/src/app/api/workspaces/[id]/route.test.ts+++ b/src/web/src/app/api/workspaces/[id]/route.test.ts@@ -33,7 +33,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { ...mockAuthCtx, params });+ return handler(req, { env: { DB: {} }, ...mockAuthCtx, params });}),}));diff --git a/src/web/src/app/api/workspaces/[id]/route.ts b/src/web/src/app/api/workspaces/[id]/route.tsindex 85ca608c4..b01ff833a 100644--- a/src/web/src/app/api/workspaces/[id]/route.ts+++ b/src/web/src/app/api/workspaces/[id]/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, UpdateWorkspaceRequestSchema, DeleteWorkspaceRequestSchema, isUniqueConstraintError } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";@@ -8,8 +7,7 @@ import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { workspaceToResponse } from "@/lib/api/responses";export const GET = withAuth(async (_req, ctx) => {- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const id = ctx.params?.id;if (!id) {@@ -33,8 +31,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {if (!body.name && !body.slug) return writeError("at least one of name or slug is required", 400);- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);try {const updated = await queries.workspace.updateWorkspace(db, owner.workspaceId, body);@@ -53,8 +50,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {const [body, err] = await parseBody(req, DeleteWorkspaceRequestSchema);if (err) return err;- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);+ const db = getDb(ctx.env.DB);const ws = await queries.workspace.getWorkspace(db, owner.workspaceId, ctx.userId);if (!ws) return writeError("workspace not found", 404);diff --git a/src/web/src/app/api/workspaces/route.test.ts b/src/web/src/app/api/workspaces/route.test.tsindex 3122fd662..da34de469 100644--- a/src/web/src/app/api/workspaces/route.test.ts+++ b/src/web/src/app/api/workspaces/route.test.ts@@ -31,7 +31,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { userId: "u1", email: "[email protected]", params });+ return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });}),}));diff --git a/src/web/src/app/api/workspaces/route.ts b/src/web/src/app/api/workspaces/route.tsindex 5fd48dcf7..f09c8cee8 100644--- a/src/web/src/app/api/workspaces/route.ts+++ b/src/web/src/app/api/workspaces/route.ts@@ -1,5 +1,4 @@import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries, isUniqueConstraintError, generateWorkspaceSlug, CreateWorkspaceRequestSchema } from "@alook/shared"import { getDb } from "@/lib/db"import { nanoid } from "nanoid"@@ -8,16 +7,14 @@ import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { workspaceToResponse } from "@/lib/api/responses";export const GET = withAuth(async (_req, ctx) => {- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const workspaces = await queries.workspace.listWorkspaces(db, ctx.userId);return writeJSON(workspaces.map(workspaceToResponse));});export const POST = withAuth(async (req: NextRequest, ctx) => {- const { env } = getCloudflareContext()- const db = getDb((env as Env).DB)+ const db = getDb(ctx.env.DB)const [body, valErr] = await parseBody(req, CreateWorkspaceRequestSchema);if (valErr) return valErr;diff --git a/src/web/src/app/api/ws/token/route.ts b/src/web/src/app/api/ws/token/route.tsindex 4f7dc5804..61f43ed71 100644--- a/src/web/src/app/api/ws/token/route.ts+++ b/src/web/src/app/api/ws/token/route.ts@@ -1,14 +1,14 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"+import { NextRequest } from "next/server"import { createAuth } from "@/lib/auth"import { DEV_WS_DO_URL } from "@alook/shared"+import { withEnv } from "@/lib/middleware/env"-export async function GET(request: Request) {- const { env } = getCloudflareContext()- const auth = createAuth(env as Env)- const session = await auth.api.getSession({ headers: request.headers })+export const GET = withEnv(async (req: NextRequest, ctx) => {+ const auth = createAuth(ctx.env)+ const session = await auth.api.getSession({ headers: req.headers })if (!session) return new Response("Unauthorized", { status: 401 })- const wsDoUrl = (env as unknown as Record<string, unknown>).DEV_WS_DO_URL as string | undefined+ const wsDoUrl = (ctx.env as unknown as Record<string, unknown>).DEV_WS_DO_URL as string | undefinedlet wsPort: number | undefinedtry {wsPort = new URL(wsDoUrl || DEV_WS_DO_URL).port ? Number(new URL(wsDoUrl || DEV_WS_DO_URL).port) : undefined@@ -19,4 +19,4 @@ export async function GET(request: Request) {token: session.session.token,...(wsPort && { wsPort }),})-}+});diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsdeleted file mode 100644index 7964a3552..000000000--- a/src/web/src/lib/api.ts+++ /dev/null@@ -1,1251 +0,0 @@-import type {- Agent,- AgentEmailAccount,- AgentLink,- AgentRuntime,- Artifact,- CalendarEvent,- Channel,- Conversation,- CreateIssueRequest,- CreateAgentLinkRequest,- CreateAgentRequest,- CreateCalendarEventRequest,- CreateEmailAccountRequest,- UpdateAgentLinkRequest,- UpdateCalendarEventRequest,- UpdateEmailAccountRequest,- DeleteCalendarEventRequest,- UpdateAgentRequest,- Email,- Issue,- IssueComment,- LoginResponse,- MeetingSession,- Message,- TaskApi,- TaskMessageResponse,- UpdateIssueRequest,- User,- Workspace,-} from "@alook/shared";-import { ApiError } from "@/lib/errors";-import type { PendingFile } from "@/hooks/use-file-attachments";--const API_BASE = "";--const MOCK_NETWORK_ENABLED = process.env.NODE_ENV === "development" && process.env.NEXT_PUBLIC_MOCK_NETWORK === "true";-const MOCK_NETWORK_DELAY_MS = parseInt(process.env.NEXT_PUBLIC_MOCK_NETWORK_DELAY_MS || "300", 10) || 300;-let mockNetworkLogged = false;--function humanizeValidationDetail(detail: string): string {- const [rawField, ...rest] = detail.split(":");- const rawMessage = rest.join(":").trim();- if (!rawMessage) return detail;-- const field = rawField.trim();- const label = field- .trim()- .replace(/[_-]+/g, " ")- .replace(/\b\w/g, (char) => char.toUpperCase());- let message = rawMessage.replace(/^required$/i, "is required");-- const normalizedMessage = message.toLowerCase().replace(/[_-]+/g, " ");- const normalizedField = field.toLowerCase().replace(/[_-]+/g, " ");- if (normalizedField && normalizedMessage.startsWith(`${normalizedField} `)) {- message = message.slice(field.length).trimStart();- }-- return label ? `${label} ${message}` : message;-}--function getReadableErrorMessage(error: string | undefined, details: string[] | undefined) {- if (error === "validation error" && details?.length) {- return humanizeValidationDetail(details[0]);- }- return error;-}--async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {- if (MOCK_NETWORK_ENABLED) {- if (!mockNetworkLogged) {- console.info(`[Mock Network] Enabled — ${MOCK_NETWORK_DELAY_MS}ms delay on all API requests`);- mockNetworkLogged = true;- }- await new Promise((r) => setTimeout(r, MOCK_NETWORK_DELAY_MS));- }-- let res: Response;- try {- res = await fetch(API_BASE + path, {- ...options,- credentials: "include",- headers: {- "Content-Type": "application/json",- ...options?.headers,- },- });- } catch (err) {- if (err instanceof TypeError) {- throw new ApiError("Unable to connect — check your network", 0);- }- throw err;- }-- if (res.status === 401) {- if (typeof window !== "undefined") {- window.location.href = "/sign-in";- }- throw new ApiError("Unauthorized", 401);- }-- if (!res.ok) {- let serverError: string | undefined;- let details: string[] | undefined;- try {- const body = (await res.json()) as { error?: string; details?: string[] };- serverError = body.error;- details = body.details;- } catch {- // non-JSON body (HTML from proxy, empty body, etc.)- }-- if (res.status === 429) {- throw new ApiError("Please wait a moment before trying again", 429);- }-- if (res.status >= 500) {- throw new ApiError(- getReadableErrorMessage(serverError, details) ||- "Something went wrong — please try again",- res.status,- details,- );- }-- throw new ApiError(- getReadableErrorMessage(serverError, details) || "Something went wrong",- res.status,- details,- );- }-- if (res.status === 204) return undefined as T;- return res.json();-}--// Me-export const getMe = () => apiFetch<User>("/api/me");--// Workspaces-export const listWorkspaces = () => apiFetch<Workspace[]>("/api/workspaces");--export const createWorkspace = (name: string, slug?: string) =>- apiFetch<Workspace>("/api/workspaces", {- method: "POST",- body: JSON.stringify({ name, slug: slug || name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "workspace" }),- });--// Helper to build query strings with workspace_id-function wsQuery(workspaceId: string, extra?: Record<string, string>): string {- const params = new URLSearchParams({ workspace_id: workspaceId, ...extra });- return `?${params.toString()}`;-}--// Config-export const fetchModelOptions = () =>- apiFetch<Record<string, string[]>>("/api/config/model-options");--// Agents-export const listAgents = (workspaceId: string) =>- apiFetch<Agent[]>(`/api/agents${wsQuery(workspaceId)}`);--export const createAgent = (req: CreateAgentRequest, workspaceId: string) =>- apiFetch<Agent>(`/api/agents${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify(req),- });--export const getAgent = (id: string, workspaceId: string) =>- apiFetch<Agent>(`/api/agents/${id}${wsQuery(workspaceId)}`);--export const updateAgent = (id: string, req: UpdateAgentRequest, workspaceId: string) =>- apiFetch<Agent>(`/api/agents/${id}${wsQuery(workspaceId)}`, {- method: "PATCH",- body: JSON.stringify(req),- });--export const deleteAgent = (id: string, workspaceId: string) =>- apiFetch<void>(`/api/agents/${id}${wsQuery(workspaceId)}`, { method: "DELETE" });--// Runtimes-export const listRuntimes = (workspaceId: string) =>- apiFetch<AgentRuntime[]>(`/api/runtimes${wsQuery(workspaceId)}`);--export const deleteMachine = (daemonId: string, workspaceId: string) =>- apiFetch<void>(- `/api/runtimes/machine${wsQuery(workspaceId, { daemon_id: daemonId })}`,- { method: "DELETE" }- );--export const triggerRuntimeUpdate = (runtimeId: string, workspaceId: string) =>- apiFetch<{ pending_update_version: string }>(- `/api/runtimes/${runtimeId}/update${wsQuery(workspaceId)}`,- { method: "POST" }- );--export const triggerRuntimeRescan = (runtimeId: string, workspaceId: string) =>- apiFetch<{ pending_rescan: boolean }>(- `/api/runtimes/${runtimeId}/rescan${wsQuery(workspaceId)}`,- { method: "POST" }- );--export const getMinCliVersion = () =>- apiFetch<{ min_cli_version: string | null }>("/api/config/min-version");--export const fetchLatestCliVersion = () =>- apiFetch<{ version: string; package: string }>("/api/cli/latest-version");--// Channels-export const listChannels = (workspaceId: string) =>- apiFetch<Channel[]>(`/api/channels${wsQuery(workspaceId)}`);--export const createChannelApi = (workspaceId: string, name: string) =>- apiFetch<Channel>(`/api/channels${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify({ name }),- });--export const renameChannelApi = (id: string, workspaceId: string, name: string) =>- apiFetch<Channel>(`/api/channels/${id}${wsQuery(workspaceId)}`, {- method: "PATCH",- body: JSON.stringify({ name }),- });--export const deleteChannelApi = (id: string, workspaceId: string) =>- apiFetch<{ ok: boolean }>(`/api/channels/${id}${wsQuery(workspaceId)}`, {- method: "DELETE",- });--export const reorderChannelsApi = (workspaceId: string, orderedChannelIds: string[]) =>- apiFetch<void>(`/api/channels/reorder${wsQuery(workspaceId)}`, {- method: "PUT",- body: JSON.stringify({ ordered_channel_ids: orderedChannelIds }),- });--// Conversations-export const listConversations = (workspaceId: string, channel?: string) =>- apiFetch<Conversation[]>(`/api/conversations${wsQuery(workspaceId, channel ? { channel } : undefined)}`);--export const createConversation = (agentId: string, workspaceId: string, channel?: string) =>- apiFetch<Conversation>(`/api/conversations${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify({ agent_id: agentId, ...(channel ? { channel } : {}) }),- });--export const getConversation = (id: string, workspaceId: string) =>- apiFetch<Conversation>(`/api/conversations/${id}${wsQuery(workspaceId)}`);--export const listAgentConversations = (agentId: string, workspaceId: string, channel?: string) =>- apiFetch<Conversation[]>(`/api/agents/${agentId}/conversations${wsQuery(workspaceId, channel ? { channel } : undefined)}`);--export const getOrCreateAgentConversation = (agentId: string, workspaceId: string, channel?: string) =>- apiFetch<Conversation>(`/api/agents/${agentId}/conversation${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify({ ...(channel ? { channel } : {}) }),- });--export interface PreviousConversation {- id: string;- created_at: string;-}--export interface ChatInitResponse {- conversation: Conversation;- messages: Message[];- artifacts: Artifact[];- active_task: TaskApi | null;- task_messages: TaskMessageResponse[];- has_more_messages: boolean;- has_more_conversations: boolean;- has_more_artifacts: boolean;-}--export const listPreviousConversations = (- agentId: string,- workspaceId: string,- opts: { exclude: string; before: string; channel?: string; limit?: number },-) => {- const extra: Record<string, string> = { exclude: opts.exclude, before: opts.before };- if (opts.channel) extra.channel = opts.channel;- if (opts.limit) extra.limit = String(opts.limit);- return apiFetch<{ conversations: PreviousConversation[]; has_more: boolean }>(- `/api/agents/${agentId}/conversations${wsQuery(workspaceId, extra)}`,- );-};--export const chatInit = (agentId: string, workspaceId: string, channel?: string) =>- apiFetch<ChatInitResponse>(`/api/agents/${agentId}/chat-init${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify({ ...(channel ? { channel } : {}) }),- });--export interface ConversationInitResponse {- conversation: Conversation;- messages: Message[] | null;- has_more_messages: boolean;- has_more_conversations: boolean;- has_more_artifacts: boolean;- artifacts: Artifact[];- flagged_message_ids: string[];- active_task: TaskApi | null;- task_messages: TaskMessageResponse[];- cache_valid: boolean;- message_count: number;- root_message?: Message | null;-}--export const conversationInit = (- conversationId: string,- workspaceId: string,- opts?: { newestMessageId?: string; messageCount?: number },-) => {- const extra: Record<string, string> = {};- if (opts?.newestMessageId) extra.newest_message_id = opts.newestMessageId;- // Omit a 0 count: the server treats the param as a count to compare against,- // and the string "0" is truthy server-side, so sending it forces- // `serverMessageCount === 0` to fail for every non-empty conversation. 0 here- // means "unknown count" — rely on newestMessageId for the freshness compare.- if (opts?.messageCount) extra.message_count = String(opts.messageCount);- return apiFetch<ConversationInitResponse>(- `/api/conversations/${conversationId}/init${wsQuery(workspaceId, extra)}`,- );-};--export interface FreshnessCheckResponse {- conversation_id: string;- newest_message_id: string | null;- message_count: number;-}--export const checkFreshness = (- opts: { conversationId?: string; agentId?: string; channel?: string },- workspaceId: string,-) => {- const extra: Record<string, string> = {};- if (opts.conversationId) extra.conversation_id = opts.conversationId;- if (opts.agentId) extra.agent_id = opts.agentId;- if (opts.channel) extra.channel = opts.channel;- return apiFetch<FreshnessCheckResponse>(- `/api/conversations/check-fresh${wsQuery(workspaceId, extra)}`,- );-};--export const deleteConversation = (id: string, workspaceId: string) =>- apiFetch<void>(`/api/conversations/${id}${wsQuery(workspaceId)}`, { method: "DELETE" });--export const listMessages = (- conversationId: string,- workspaceId: string,- opts?: { limit?: number; before?: string; beforeId?: string }-) => {- const extra: Record<string, string> = {};- if (opts?.limit) extra.limit = String(opts.limit);- if (opts?.before) extra.before = opts.before;- if (opts?.beforeId) extra.before_id = opts.beforeId;- return apiFetch<{ messages: Message[]; has_more: boolean }>(- `/api/conversations/${conversationId}/messages${wsQuery(workspaceId, extra)}`- );-};--export const listMessagesAroundTask = (- conversationId: string,- workspaceId: string,- taskId: string-) =>- apiFetch<Message[]>(- `/api/conversations/${conversationId}/messages${wsQuery(workspaceId, { around_task: taskId })}`- );--export const sendMessage = async (- conversationId: string,- content: string,- workspaceId: string,- files?: PendingFile[],- metadata?: Record<string, unknown>,-): Promise<{ message: Message; task: TaskApi }> => {- if (!files || files.length === 0) {- return apiFetch<{ message: Message; task: TaskApi }>(- `/api/conversations/${conversationId}/messages${wsQuery(workspaceId)}`,- {- method: "POST",- body: JSON.stringify({ content, ...(metadata ? { metadata } : {}) }),- },- );- }-- const fd = new FormData();- fd.append("content", content);- if (metadata) fd.append("metadata", JSON.stringify(metadata));- for (const pf of files) {- fd.append("file", pf.file);- }- for (let i = 0; i < files.length; i++) {- const blob = files[i].thumbnailBlob;- if (blob) fd.append(`thumbnail:${i}`, blob, "thumbnail.jpg");- }-- let res: Response;- try {- res = await fetch(- `/api/conversations/${conversationId}/messages${wsQuery(workspaceId)}`,- { method: "POST", credentials: "include", body: fd },- );- } catch (err) {- if (err instanceof TypeError) {- throw new ApiError("Unable to connect — check your network", 0);- }- throw err;- }-- if (res.status === 401) {- if (typeof window !== "undefined") window.location.href = "/sign-in";- throw new ApiError("Unauthorized", 401);- }-- if (!res.ok) {- let serverError: string | undefined;- let details: string[] | undefined;- try {- const body = (await res.json()) as { error?: string; details?: string[] };- serverError = body.error;- details = body.details;- } catch {- // non-JSON body- }- if (res.status === 429) throw new ApiError("Please wait a moment before trying again", 429);- if (res.status >= 500) throw new ApiError(serverError || "Something went wrong — please try again", res.status, details);- throw new ApiError(serverError || "Something went wrong", res.status, details);- }-- return res.json() as Promise<{ message: Message; task: TaskApi }>;-};--// Active task for conversation (recovery on page refresh)-export const getActiveTask = (conversationId: string, workspaceId: string) =>- apiFetch<TaskApi | undefined>(`/api/conversations/${conversationId}/active-task${wsQuery(workspaceId)}`);--export const cancelActiveTask = (conversationId: string, workspaceId: string) =>- apiFetch<TaskApi>(`/api/conversations/${conversationId}/active-task${wsQuery(workspaceId)}`, {- method: "DELETE",- });--// Machine tokens-export const createMachineToken = (name?: string, workspaceId?: string) =>- apiFetch<{ token: string; id: string; name: string; created_at: string }>(- `/api/machine-tokens${workspaceId ? wsQuery(workspaceId) : ""}`,- {- method: "POST",- body: JSON.stringify({ name: name || "default" }),- }- );--export const getMachineTokenStatus = () =>- apiFetch<{ status: "pending" | "active" | null; token?: string; workspace_id?: string; hostname?: string; daemon_online?: boolean }>(- "/api/machine-tokens/status",- );--// Agent active tasks-export const listAgentActiveTaskCounts = (workspaceId: string) =>- apiFetch<{ counts: Record<string, number> }>(`/api/agents/active-task-counts${wsQuery(workspaceId)}`);--export interface ActiveTask {- id: string;- status: string;- type: string;- created_at: string;-}--export const listAgentActiveTasks = (agentId: string, workspaceId: string) =>- apiFetch<{ tasks: ActiveTask[] }>(`/api/agents/${agentId}/active-tasks${wsQuery(workspaceId)}`);--export interface WorkspaceActiveTask {- id: string;- agent_id: string;- agent: { name: string; avatarUrl: string | null } | null;- prompt: string;- status: string;- type: string;- conversation_id: string;- channel: string;- created_at: string;-}--export const listWorkspaceActiveTasks = (workspaceId: string) =>- apiFetch<{ tasks: WorkspaceActiveTask[] }>(`/api/agents/active-tasks${wsQuery(workspaceId)}`);--// Activity-export interface ActivityTask {- id: string;- conversation_id: string;- type: string;- status: string;- prompt: string;- created_at: string;- started_at: string | null;- completed_at: string | null;- error: string | null;-}--export const listAgentActivity = (- agentId: string,- workspaceId: string,- opts?: { limit?: number; before?: string; beforeId?: string; status?: string; type?: string }-) => {- const extra: Record<string, string> = {};- if (opts?.limit) extra.limit = String(opts.limit);- if (opts?.before) extra.before = opts.before;- if (opts?.beforeId) extra.before_id = opts.beforeId;- if (opts?.status) extra.status = opts.status;- if (opts?.type) extra.type = opts.type;- return apiFetch<{ tasks: ActivityTask[]; has_more: boolean }>(- `/api/agents/${agentId}/activity${wsQuery(workspaceId, extra)}`- );-};--// Tasks (polling)-export const getTask = (id: string, workspaceId: string) =>- apiFetch<TaskApi>(`/api/tasks/${id}${wsQuery(workspaceId)}`);--export const getTaskMessages = (id: string, workspaceId: string, since?: number) =>- apiFetch<TaskMessageResponse[]>(- `/api/tasks/${id}/messages${wsQuery(workspaceId, since ? { since: String(since) } : undefined)}`- );--export const retryTask = (id: string, workspaceId: string) =>- apiFetch<TaskApi>(`/api/tasks/${id}/retry${wsQuery(workspaceId)}`, {- method: "POST",- });--// Emails-export const listEmails = (agentId: string, workspaceId: string, folder?: string, address?: string) =>- apiFetch<Email[]>(`/api/email${wsQuery(workspaceId, { agentId, ...(folder ? { folder } : {}), ...(address ? { address } : {}) })}`);--export const getEmail = (id: string, workspaceId: string) =>- apiFetch<Email>(`/api/email/${id}${wsQuery(workspaceId)}`);--export const getEmailThread = (id: string, workspaceId: string) =>- apiFetch<Email[]>(`/api/email/${id}/thread${wsQuery(workspaceId)}`);--export const getEmailBody = async (id: string, workspaceId: string): Promise<{ content: string; isHtml: boolean }> => {- const params = new URLSearchParams({ workspace_id: workspaceId });- const res = await fetch(`/api/email/${id}/body?${params}`, { credentials: "include" });- if (!res.ok) return { content: "(body not available)", isHtml: false };- const contentType = res.headers.get("Content-Type") ?? "";- const content = await res.text();- return { content, isHtml: contentType.includes("text/html") };-};--export const deleteEmail = (id: string, workspaceId: string) =>- apiFetch<void>(`/api/email/${id}${wsQuery(workspaceId)}`, { method: "DELETE" });--export const updateEmailStatus = (id: string, workspaceId: string, status: string) =>- apiFetch<Email>(`/api/email/${id}${wsQuery(workspaceId)}`, {- method: "PATCH",- body: JSON.stringify({ status }),- });--export const trustEmail = (id: string, workspaceId: string) =>- apiFetch<{ ok: boolean; email: Email; conversationId: string }>(- `/api/email/${id}/trust${wsQuery(workspaceId)}`,- { method: "POST" }- );--export const uploadEmailAttachment = async (- file: File,- workspaceId: string,-): Promise<{ key: string; filename: string; size: number; contentType: string }> => {- const fd = new FormData();- fd.append("file", file);- const res = await fetch(`/api/email/upload${wsQuery(workspaceId)}`, {- method: "POST",- credentials: "include",- body: fd,- });- if (!res.ok) {- const msg = await res.text().catch(() => "Upload failed");- throw new ApiError(msg, res.status);- }- return res.json();-};--export const sendEmail = (- agentId: string,- to: string,- subject: string,- htmlBody: string,- workspaceId: string,- attachments?: { key: string; filename: string; size: number; contentType: string }[],- threading?: { inReplyTo?: string; references?: string },- customAccountId?: string,-) =>- apiFetch<Email>(`/api/email/send${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify({ agentId, to, subject, htmlBody, attachments, ...threading, customAccountId }),- });--// Calendar events-export const listCalendarEvents = (- workspaceId: string,- opts?: { agentId?: string; from?: string; to?: string }-) => {- const extra: Record<string, string> = {};- if (opts?.agentId) extra.agentId = opts.agentId;- if (opts?.from) extra.from = opts.from;- if (opts?.to) extra.to = opts.to;- return apiFetch<CalendarEvent[]>(`/api/calendar${wsQuery(workspaceId, extra)}`);-};--export const getCalendarEvent = (id: string, workspaceId: string) =>- apiFetch<CalendarEvent>(`/api/calendar/${id}${wsQuery(workspaceId)}`);--export const createCalendarEvent = (- req: CreateCalendarEventRequest,- workspaceId: string-) =>- apiFetch<CalendarEvent>(`/api/calendar${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify(req),- });--export const updateCalendarEvent = (- id: string,- patch: UpdateCalendarEventRequest,- workspaceId: string-) =>- apiFetch<CalendarEvent>(`/api/calendar/${id}${wsQuery(workspaceId)}`, {- method: "PATCH",- body: JSON.stringify(patch),- });--export const deleteCalendarEvent = (- id: string,- workspaceId: string,- body?: DeleteCalendarEventRequest-) =>- apiFetch<CalendarEvent>(`/api/calendar/${id}${wsQuery(workspaceId)}`, {- method: "DELETE",- ...(body && body.scope- ? {- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- }- : {}),- });--// Issues-export type IssueListItem = Issue & { thread_agent_ids?: string[] };--export interface IssueDetailResponse {- issue: Issue & { trace_id?: string | null };- messages: Message[];- comments: IssueComment[];- artifacts: Artifact[];-}--export const listIssues = (- workspaceId: string,- opts?: { agentId?: string; status?: string; terminal?: boolean }-) => {- const extra: Record<string, string> = {};- if (opts?.agentId) extra.agentId = opts.agentId;- if (opts?.status) extra.status = opts.status;- if (opts?.terminal !== undefined) extra.terminal = String(opts.terminal);- return apiFetch<IssueListItem[]>(`/api/issues${wsQuery(workspaceId, extra)}`);-};--export const createIssue = async (- workspaceId: string,- req: CreateIssueRequest & { files?: File[] },-): Promise<{ issue: Issue; message?: Message; task?: TaskApi }> => {- if (!req.files || req.files.length === 0) {- return apiFetch<{ issue: Issue; message?: Message; task?: TaskApi }>(`/api/issues${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify({- agent_id: req.agent_id,- title: req.title,- description: req.description,- }),- });- }-- const fd = new FormData();- if (req.agent_id) fd.append("agent_id", req.agent_id);- fd.append("title", req.title);- fd.append("description", req.description ?? "");- for (const file of req.files) {- fd.append("file", file);- }-- let res: Response;- try {- res = await fetch(`/api/issues${wsQuery(workspaceId)}`, {- method: "POST",- credentials: "include",- body: fd,- });- } catch (err) {- if (err instanceof TypeError) {- throw new ApiError("Unable to connect — check your network", 0);- }- throw err;- }-- if (res.status === 401) {- if (typeof window !== "undefined") window.location.href = "/sign-in";- throw new ApiError("Unauthorized", 401);- }-- if (!res.ok) {- let serverError: string | undefined;- let details: string[] | undefined;- try {- const body = (await res.json()) as { error?: string; details?: string[] };- serverError = body.error;- details = body.details;- } catch {- // non-JSON body- }- if (res.status === 429) throw new ApiError("Please wait a moment before trying again", 429);- if (res.status >= 500) throw new ApiError(serverError || "Something went wrong — please try again", res.status, details);- throw new ApiError(serverError || "Something went wrong", res.status, details);- }-- return res.json() as Promise<{ issue: Issue; message?: Message; task?: TaskApi }>;-};--export const getIssue = (workspaceId: string, issueId: string) =>- apiFetch<IssueDetailResponse>(`/api/issues/${issueId}${wsQuery(workspaceId)}`);--export const updateIssue = (workspaceId: string, issueId: string, patch: UpdateIssueRequest) =>- apiFetch<Issue>(`/api/issues/${issueId}${wsQuery(workspaceId)}`, {- method: "PATCH",- body: JSON.stringify(patch),- });--export const commentIssue = (workspaceId: string, issueId: string, content: string) =>- apiFetch<{ message: Message }>(`/api/issues/${issueId}${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify({ content }),- });--export const deleteIssue = (workspaceId: string, issueId: string) =>- apiFetch<void>(`/api/issues/${issueId}${wsQuery(workspaceId)}`, { method: "DELETE" });--// Whitelist-export interface WhitelistEntry {- id: string;- email: string;- created_at: string;-}--export const listWhitelist = (agentId: string, workspaceId: string) =>- apiFetch<WhitelistEntry[]>(`/api/agents/${agentId}/whitelist${wsQuery(workspaceId)}`);--export const addWhitelistEmail = (agentId: string, email: string, workspaceId: string) =>- apiFetch<WhitelistEntry>(`/api/agents/${agentId}/whitelist${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify({ email }),- });--export const removeWhitelistEmail = (agentId: string, whitelistId: string, workspaceId: string) =>- apiFetch<void>(`/api/agents/${agentId}/whitelist/${whitelistId}${wsQuery(workspaceId)}`, {- method: "DELETE",- });--// Agent Links-export const listAgentLinks = (workspaceId: string) =>- apiFetch<AgentLink[]>(`/api/agent-links${wsQuery(workspaceId)}`);--export const createAgentLink = (req: CreateAgentLinkRequest, workspaceId: string) =>- apiFetch<AgentLink>(`/api/agent-links${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify(req),- });--export const updateAgentLink = (id: string, req: UpdateAgentLinkRequest, workspaceId: string) =>- apiFetch<AgentLink>(`/api/agent-links/${id}${wsQuery(workspaceId)}`, {- method: "PATCH",- body: JSON.stringify(req),- });--export const deleteAgentLink = (id: string, workspaceId: string) =>- apiFetch<AgentLink>(`/api/agent-links/${id}${wsQuery(workspaceId)}`, {- method: "DELETE",- });--// Email Accounts-export const listEmailAccounts = (agentId: string, workspaceId: string) =>- apiFetch<AgentEmailAccount[]>(`/api/agents/${agentId}/email-accounts${wsQuery(workspaceId)}`);--export const createEmailAccount = (agentId: string, data: CreateEmailAccountRequest, workspaceId: string) =>- apiFetch<AgentEmailAccount>(`/api/agents/${agentId}/email-accounts${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify(data),- });--export const updateEmailAccount = (agentId: string, accountId: string, data: UpdateEmailAccountRequest, workspaceId: string) =>- apiFetch<AgentEmailAccount>(`/api/agents/${agentId}/email-accounts/${accountId}${wsQuery(workspaceId)}`, {- method: "PATCH",- body: JSON.stringify(data),- });--export const deleteEmailAccount = (agentId: string, accountId: string, workspaceId: string) =>- apiFetch<{ ok: boolean }>(`/api/agents/${agentId}/email-accounts/${accountId}${wsQuery(workspaceId)}`, {- method: "DELETE",- });--export const testEmailConnection = (agentId: string, accountId: string, workspaceId: string) =>- apiFetch<{ imap: string; smtp: string }>(`/api/agents/${agentId}/email-accounts/${accountId}/test${wsQuery(workspaceId)}`, {- method: "POST",- });--export const syncEmailAccount = (agentId: string, accountId: string, workspaceId: string) =>- apiFetch<{ ok: boolean }>(`/api/agents/${agentId}/email-accounts/${accountId}/sync${wsQuery(workspaceId)}`, {- method: "POST",- });--// Members-export const getMemberMe = (workspaceId: string) =>- apiFetch<{ global_instruction: string }>(`/api/members/me${wsQuery(workspaceId)}`);--export const updateMemberMe = (workspaceId: string, globalInstruction: string) =>- apiFetch<{ global_instruction: string }>(`/api/members/me${wsQuery(workspaceId)}`, {- method: "PATCH",- body: JSON.stringify({ global_instruction: globalInstruction }),- });--// Artifacts-export const listArtifacts = (conversationId: string, workspaceId: string) =>- apiFetch<Artifact[]>(`/api/artifacts${wsQuery(workspaceId, { conversation_id: conversationId })}`);--export const getArtifactContent = async (id: string, workspaceId: string): Promise<string> => {- const params = new URLSearchParams({ workspace_id: workspaceId });- const res = await fetch(`/api/artifacts/${id}/content?${params}`, { credentials: "include" });- if (!res.ok) return "(content not available)";- return res.text();-};--// Auth (Better Auth — redirect helpers only, actual auth via Better Auth client)-export const signOut = async () => {- if (typeof window !== "undefined") {- window.location.href = "/sign-in";- }-};--// Legacy compat: verifyCode via Better Auth is handled by auth-client.ts-export const verifyCode = (email: string, code: string) =>- apiFetch<LoginResponse>("/api/auth/sign-in/email", {- method: "POST",- body: JSON.stringify({ email, otp: code }),- });--// --- Workspace management -----export const updateWorkspace = (workspaceId: string, data: { name?: string; slug?: string }) =>- apiFetch<Workspace>(`/api/workspaces/${workspaceId}${wsQuery(workspaceId)}`, { method: "PATCH", body: JSON.stringify(data) });--export const deleteWorkspace = (workspaceId: string, confirmName: string) =>- apiFetch<void>(`/api/workspaces/${workspaceId}${wsQuery(workspaceId)}`, { method: "DELETE", body: JSON.stringify({ confirm_name: confirmName }) });--// --- Members -----export interface MemberEntry {- id: string; user_id: string; role: string; name: string; email: string; image: string | null; created_at: string;-}--export const listMembers = (workspaceId: string) =>- apiFetch<MemberEntry[]>(`/api/workspaces/${workspaceId}/members${wsQuery(workspaceId)}`);--export const removeMember = (workspaceId: string, memberId: string) =>- apiFetch<void>(`/api/workspaces/${workspaceId}/members/${memberId}${wsQuery(workspaceId)}`, { method: "DELETE" });--// --- Invites -----export interface InviteEntry {- id: string; token: string; expires_at: string; created_at: string;-}--export const listInvites = (workspaceId: string) =>- apiFetch<InviteEntry[]>(`/api/workspaces/${workspaceId}/invites${wsQuery(workspaceId)}`);--export const createInvite = (workspaceId: string) =>- apiFetch<InviteEntry>(`/api/workspaces/${workspaceId}/invites${wsQuery(workspaceId)}`, { method: "POST" });--export const revokeInvite = (workspaceId: string, inviteId: string) =>- apiFetch<void>(`/api/workspaces/${workspaceId}/invites/${inviteId}${wsQuery(workspaceId)}`, { method: "DELETE" });--// --- Workspace overview -----export interface OverviewEmailAccount {- id: string;- agent_id: string;- email_address: string;- status: string;- error_message: string;- last_synced_at: string | null;-}--export interface OverviewRecentTask {- id: string;- agent_id: string;- type: string;- status: string;- prompt: string;- created_at: string;- completed_at: string | null;- error: string | null;-}--export interface OverviewCalendarEvent {- id: string;- agent_id: string;- title: string;- description: string | null;- scheduled_at: string;- repeat_interval: string | null;- repeat_stop_at: string | null;- last_triggered_at: string | null;-}--export interface OverviewMember {- id: string;- user_id: string;- role: string;- name: string;- email: string;- image: string | null;- created_at: string;-}--export interface WorkspaceOverview {- email_stats: { inbound: number; outbound: number; unread: number; rejected: number };- email_accounts: OverviewEmailAccount[];- task_stats: { completed: number; failed: number; cancelled: number; queued: number; stale: number };- recent_tasks: OverviewRecentTask[];- conversation_counts: Record<string, number>;- members: OverviewMember[];- pending_invites: number;- calendar_events: OverviewCalendarEvent[];-}--export const getWorkspaceOverview = (workspaceId: string) =>- apiFetch<WorkspaceOverview>(`/api/workspaces/${workspaceId}/overview${wsQuery(workspaceId)}`);--// --- Invite accept -----export interface InviteInfo {- workspace_name: string; workspace_id: string; invited_by: string;-}--export interface InviteAcceptResult {- workspace_id: string; workspace_slug: string;-}--export const getInviteInfo = (token: string) => apiFetch<InviteInfo>(`/api/invite/${token}`);-export const acceptInvite = (token: string) => apiFetch<InviteAcceptResult>(`/api/invite/${token}`, { method: "POST" });--// --- Agent access -----export interface AgentAccessEntry {- id: string; user_id: string; name: string; email: string; created_at: string;-}--export const listAgentAccess = (workspaceId: string, agentId: string) =>- apiFetch<AgentAccessEntry[]>(`/api/agents/${agentId}/access${wsQuery(workspaceId)}`);--export const grantAgentAccess = (workspaceId: string, agentId: string, userId: string) =>- apiFetch<{ id: string; user_id: string }>(`/api/agents/${agentId}/access${wsQuery(workspaceId)}`, { method: "POST", body: JSON.stringify({ user_id: userId }) });--export const revokeAgentAccess = (workspaceId: string, agentId: string, userId: string, removeWhitelist = false) =>- apiFetch<void>(`/api/agents/${agentId}/access/${userId}${wsQuery(workspaceId)}${removeWhitelist ? "&remove_whitelist=true" : ""}`, { method: "DELETE" });--// Agent Pins-export interface AgentPin {- id: string;- agent_id: string;- created_at: string;- position: number;-}--export interface SidebarOrder {- agent_id: string;- position: number;-}--export const listAgentPins = (workspaceId: string) =>- apiFetch<{ pins: AgentPin[]; sidebar_order: SidebarOrder[] }>(`/api/agents/pins${wsQuery(workspaceId)}`);--export const pinAgent = (workspaceId: string, agentId: string) =>- apiFetch<{ pinned: boolean }>(`/api/agents/${agentId}/pin${wsQuery(workspaceId)}`, { method: "POST" });--export const unpinAgent = (workspaceId: string, agentId: string) =>- apiFetch<void>(`/api/agents/${agentId}/pin${wsQuery(workspaceId)}`, { method: "DELETE" });--export const reorderAgentPins = (workspaceId: string, orderedAgentIds: string[]) =>- apiFetch<void>(`/api/agents/pins/reorder${wsQuery(workspaceId)}`, {- method: "PUT",- body: JSON.stringify({ ordered_agent_ids: orderedAgentIds }),- });--export const reorderUnpinnedAgents = (workspaceId: string, orderedAgentIds: string[]) =>- apiFetch<void>(`/api/agents/sidebar/reorder${wsQuery(workspaceId)}`, {- method: "PUT",- body: JSON.stringify({ ordered_agent_ids: orderedAgentIds }),- });--// Workspace file browsing-export const requestWorkspaceBrowse = (- agentId: string,- workspaceId: string,- requestType: "tree" | "read",- path: string,-) =>- apiFetch<{ request_id: string }>(- `/api/agents/${agentId}/workspace/browse${wsQuery(workspaceId)}`,- {- method: "POST",- body: JSON.stringify({ request_type: requestType, path }),- },- );--// Skill browsing-export const getAgentSkills = (agentId: string, workspaceId: string) =>- apiFetch<{ skills: { name: string; description: string; isGlobal?: boolean }[] }>(- `/api/agents/${agentId}/skills${wsQuery(workspaceId)}`,- );--// Meetings-export const listMeetings = (agentId: string, workspaceId: string) =>- apiFetch<MeetingSession[]>(`/api/agents/${agentId}/meetings${wsQuery(workspaceId)}`);--export const getMeeting = (agentId: string, meetingId: string, workspaceId: string) =>- apiFetch<MeetingSession>(`/api/agents/${agentId}/meetings/${meetingId}${wsQuery(workspaceId)}`);--export const createMeeting = (agentId: string, workspaceId: string, data: {- meetingUrl: string;- title?: string;- participants?: string[];-}) =>- apiFetch<MeetingSession>(`/api/agents/${agentId}/meetings${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify(data),- });--export const stopMeeting = (agentId: string, meetingId: string, workspaceId: string) =>- apiFetch<MeetingSession & { transcript?: string }>(`/api/agents/${agentId}/meetings/${meetingId}/stop${wsQuery(workspaceId)}`, {- method: "POST",- });--export const approveMeeting = (agentId: string, meetingId: string, workspaceId: string) =>- apiFetch<MeetingSession>(`/api/agents/${agentId}/meetings/${meetingId}/approve${wsQuery(workspaceId)}`, {- method: "POST",- });--export const deleteMeeting = (agentId: string, meetingId: string, workspaceId: string) =>- apiFetch<void>(`/api/agents/${agentId}/meetings/${meetingId}${wsQuery(workspaceId)}`, {- method: "DELETE",- });--// Inbox-export interface InboxItem {- id: string;- agent_id: string;- title: string;- channel: string;- latest_response: string;- latest_response_at: string;- root_prompt: string | null;- agent_name: string | null;- agent_avatar_url: string | null;- root_task_status: string | null;- root_task_type: string | null;-}--export const listInboxItems = (- workspaceId: string,- opts?: { limit?: number; before?: string; types?: string[] }-) => {- const extra: Record<string, string> = {};- if (opts?.limit) extra.limit = String(opts.limit);- if (opts?.before) extra.before = opts.before;- if (opts?.types?.length) extra.types = opts.types.join(",");- return apiFetch<{ items: InboxItem[]; has_more: boolean }>(- `/api/inbox${wsQuery(workspaceId, extra)}`- );-};--export const getInboxCount = (workspaceId: string, opts?: { types?: string[] }) => {- const extra: Record<string, string> = {};- if (opts?.types?.length) extra.types = opts.types.join(",");- return apiFetch<{ count: number }>(`/api/inbox/count${wsQuery(workspaceId, extra)}`);-};--export const markInboxRead = (conversationId: string, workspaceId: string) =>- apiFetch<void>(`/api/inbox/read${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify({ conversationId }),- });--export const markAllInboxRead = (workspaceId: string) =>- apiFetch<void>(`/api/inbox/read-all${wsQuery(workspaceId)}`, {- method: "POST",- });--// Flags-export interface FlaggedItem {- id: string;- message_id: string;- message_content: string;- message_role: string;- message_created_at: string;- conversation_id: string;- conversation_title: string;- agent_id: string;- agent_name: string | null;- agent_avatar_url: string | null;- flagged_at: string;-}--export const listFlaggedItems = (- workspaceId: string,- opts?: { limit?: number; before?: string }-) => {- const extra: Record<string, string> = {};- if (opts?.limit) extra.limit = String(opts.limit);- if (opts?.before) extra.before = opts.before;- return apiFetch<{ items: FlaggedItem[]; has_more: boolean }>(- `/api/flags${wsQuery(workspaceId, extra)}`- );-};--export const getFlaggedCount = (workspaceId: string) =>- apiFetch<{ count: number }>(`/api/flags/count${wsQuery(workspaceId)}`);--export const flagMessage = (workspaceId: string, messageId: string) =>- apiFetch<{ flagged: boolean }>(`/api/flags${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify({ messageId }),- });--export const unflagMessage = (workspaceId: string, messageId: string) =>- apiFetch<void>(`/api/flags/${messageId}${wsQuery(workspaceId)}`, {- method: "DELETE",- });--export const listFlaggedMessageIds = (workspaceId: string, conversationId: string) =>- apiFetch<{ message_ids: string[] }>(- `/api/flags${wsQuery(workspaceId, { conversation_id: conversationId, ids_only: "true" })}`- );--// Traces-export interface TraceListItem {- trace_id: string;- root_prompt: string;- root_agent_id: string;- root_agent: { name: string; avatarUrl: string | null } | null;- helper_agents: { id: string; name?: string; avatarUrl?: string | null }[];- status: string;- task_count: number;- started_at: string;- completed_at: string | null;- channel: string;-}--export interface TraceTask {- id: string;- agent_id: string;- agent: { name: string; email_handle: string | null; avatarUrl: string | null } | null;- parent_task_id: string | null;- prompt: string;- status: string;- type: string;- conversation_id: string;- created_at: string;- completed_at: string | null;-}--export const listTraces = (- workspaceId: string,- opts?: { status?: string; limit?: number; before?: string; multiAgent?: boolean; agentId?: string; channel?: string }-) => {- const extra: Record<string, string> = {};- if (opts?.limit) extra.limit = String(opts.limit);- if (opts?.before) extra.before = opts.before;- if (opts?.status) extra.status = opts.status;- if (opts?.multiAgent) extra.multiAgent = "true";- if (opts?.agentId) extra.agentId = opts.agentId;- if (opts?.channel) extra.channel = opts.channel;- return apiFetch<{ traces: TraceListItem[]; has_more: boolean }>(- `/api/traces${wsQuery(workspaceId, extra)}`- );-};--export const getTrace = (traceId: string, workspaceId: string) =>- apiFetch<{ trace_id: string; channel: string; tasks: TraceTask[] }>(- `/api/traces/${traceId}${wsQuery(workspaceId)}`- );--// ── Threads ──--export interface ThreadSummary {- thread_id: string;- parent_message_id: string;- thread_title: string;- reply_count: number;- last_reply_at: string | null;- created_at: string;-}--export interface ThreadListItem {- id: string;- parent_message_id: string;- thread_title: string;- reply_count: number;- last_reply_at: string | null;- last_reply_preview: string;- created_at: string;-}--export const createThread = (- conversationId: string,- parentMessageId: string,- content: string,- workspaceId: string,-) =>- apiFetch<{- conversation: Conversation;- message: Message;- task: TaskApi;- }>(`/api/conversations/${conversationId}/threads${wsQuery(workspaceId)}`, {- method: "POST",- body: JSON.stringify({ parent_message_id: parentMessageId, content }),- });--export const getThreadSummaries = (conversationId: string, workspaceId: string) =>- apiFetch<{ thread_summaries: ThreadSummary[] }>(- `/api/conversations/${conversationId}/threads${wsQuery(workspaceId)}`- );--export const listAgentThreads = (- agentId: string,- workspaceId: string,- opts?: { limit?: number; before?: string }-) => {- const extra: Record<string, string> = {};- if (opts?.limit) extra.limit = String(opts.limit);- if (opts?.before) extra.before = opts.before;- return apiFetch<{ threads: ThreadListItem[]; has_more: boolean }>(- `/api/agents/${agentId}/threads${wsQuery(workspaceId, extra)}`- );-};diff --git a/src/web/src/lib/api/agents.ts b/src/web/src/lib/api/agents.tsnew file mode 100644index 000000000..adf2264f1--- /dev/null+++ b/src/web/src/lib/api/agents.ts@@ -0,0 +1,305 @@+import type {+ Agent,+ AgentEmailAccount,+ AgentLink,+ AgentRuntime,+ CreateAgentLinkRequest,+ CreateAgentRequest,+ CreateEmailAccountRequest,+ MeetingSession,+ UpdateAgentLinkRequest,+ UpdateAgentRequest,+ UpdateEmailAccountRequest,+} from "@alook/shared";+import { apiFetch, wsQuery } from "./client";++// Agents+export const listAgents = (workspaceId: string) =>+ apiFetch<Agent[]>(`/api/agents${wsQuery(workspaceId)}`);++export const createAgent = (req: CreateAgentRequest, workspaceId: string) =>+ apiFetch<Agent>(`/api/agents${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify(req),+ });++export const getAgent = (id: string, workspaceId: string) =>+ apiFetch<Agent>(`/api/agents/${id}${wsQuery(workspaceId)}`);++export const updateAgent = (id: string, req: UpdateAgentRequest, workspaceId: string) =>+ apiFetch<Agent>(`/api/agents/${id}${wsQuery(workspaceId)}`, {+ method: "PATCH",+ body: JSON.stringify(req),+ });++export const deleteAgent = (id: string, workspaceId: string) =>+ apiFetch<void>(`/api/agents/${id}${wsQuery(workspaceId)}`, { method: "DELETE" });++// Runtimes+export const listRuntimes = (workspaceId: string) =>+ apiFetch<AgentRuntime[]>(`/api/runtimes${wsQuery(workspaceId)}`);++export const deleteMachine = (daemonId: string, workspaceId: string) =>+ apiFetch<void>(+ `/api/runtimes/machine${wsQuery(workspaceId, { daemon_id: daemonId })}`,+ { method: "DELETE" }+ );++export const triggerRuntimeUpdate = (runtimeId: string, workspaceId: string) =>+ apiFetch<{ pending_update_version: string }>(+ `/api/runtimes/${runtimeId}/update${wsQuery(workspaceId)}`,+ { method: "POST" }+ );++export const triggerRuntimeRescan = (runtimeId: string, workspaceId: string) =>+ apiFetch<{ pending_rescan: boolean }>(+ `/api/runtimes/${runtimeId}/rescan${wsQuery(workspaceId)}`,+ { method: "POST" }+ );++// Agent active tasks+export const listAgentActiveTaskCounts = (workspaceId: string) =>+ apiFetch<{ counts: Record<string, number> }>(`/api/agents/active-task-counts${wsQuery(workspaceId)}`);++export interface ActiveTask {+ id: string;+ status: string;+ type: string;+ created_at: string;+}++export const listAgentActiveTasks = (agentId: string, workspaceId: string) =>+ apiFetch<{ tasks: ActiveTask[] }>(`/api/agents/${agentId}/active-tasks${wsQuery(workspaceId)}`);++export interface WorkspaceActiveTask {+ id: string;+ agent_id: string;+ agent: { name: string; avatarUrl: string | null } | null;+ prompt: string;+ status: string;+ type: string;+ conversation_id: string;+ channel: string;+ created_at: string;+}++export const listWorkspaceActiveTasks = (workspaceId: string) =>+ apiFetch<{ tasks: WorkspaceActiveTask[] }>(`/api/agents/active-tasks${wsQuery(workspaceId)}`);++// Activity+export interface ActivityTask {+ id: string;+ conversation_id: string;+ type: string;+ status: string;+ prompt: string;+ created_at: string;+ started_at: string | null;+ completed_at: string | null;+ error: string | null;+}++export const listAgentActivity = (+ agentId: string,+ workspaceId: string,+ opts?: { limit?: number; before?: string; beforeId?: string; status?: string; type?: string }+) => {+ const extra: Record<string, string> = {};+ if (opts?.limit) extra.limit = String(opts.limit);+ if (opts?.before) extra.before = opts.before;+ if (opts?.beforeId) extra.before_id = opts.beforeId;+ if (opts?.status) extra.status = opts.status;+ if (opts?.type) extra.type = opts.type;+ return apiFetch<{ tasks: ActivityTask[]; has_more: boolean }>(+ `/api/agents/${agentId}/activity${wsQuery(workspaceId, extra)}`+ );+};++// Whitelist+export interface WhitelistEntry {+ id: string;+ email: string;+ created_at: string;+}++export const listWhitelist = (agentId: string, workspaceId: string) =>+ apiFetch<WhitelistEntry[]>(`/api/agents/${agentId}/whitelist${wsQuery(workspaceId)}`);++export const addWhitelistEmail = (agentId: string, email: string, workspaceId: string) =>+ apiFetch<WhitelistEntry>(`/api/agents/${agentId}/whitelist${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify({ email }),+ });++export const removeWhitelistEmail = (agentId: string, whitelistId: string, workspaceId: string) =>+ apiFetch<void>(`/api/agents/${agentId}/whitelist/${whitelistId}${wsQuery(workspaceId)}`, {+ method: "DELETE",+ });++// Agent Links+export const listAgentLinks = (workspaceId: string) =>+ apiFetch<AgentLink[]>(`/api/agent-links${wsQuery(workspaceId)}`);++export const createAgentLink = (req: CreateAgentLinkRequest, workspaceId: string) =>+ apiFetch<AgentLink>(`/api/agent-links${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify(req),+ });++export const updateAgentLink = (id: string, req: UpdateAgentLinkRequest, workspaceId: string) =>+ apiFetch<AgentLink>(`/api/agent-links/${id}${wsQuery(workspaceId)}`, {+ method: "PATCH",+ body: JSON.stringify(req),+ });++export const deleteAgentLink = (id: string, workspaceId: string) =>+ apiFetch<AgentLink>(`/api/agent-links/${id}${wsQuery(workspaceId)}`, {+ method: "DELETE",+ });++// Email Accounts+export const listEmailAccounts = (agentId: string, workspaceId: string) =>+ apiFetch<AgentEmailAccount[]>(`/api/agents/${agentId}/email-accounts${wsQuery(workspaceId)}`);++export const createEmailAccount = (agentId: string, data: CreateEmailAccountRequest, workspaceId: string) =>+ apiFetch<AgentEmailAccount>(`/api/agents/${agentId}/email-accounts${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify(data),+ });++export const updateEmailAccount = (agentId: string, accountId: string, data: UpdateEmailAccountRequest, workspaceId: string) =>+ apiFetch<AgentEmailAccount>(`/api/agents/${agentId}/email-accounts/${accountId}${wsQuery(workspaceId)}`, {+ method: "PATCH",+ body: JSON.stringify(data),+ });++export const deleteEmailAccount = (agentId: string, accountId: string, workspaceId: string) =>+ apiFetch<{ ok: boolean }>(`/api/agents/${agentId}/email-accounts/${accountId}${wsQuery(workspaceId)}`, {+ method: "DELETE",+ });++export const testEmailConnection = (agentId: string, accountId: string, workspaceId: string) =>+ apiFetch<{ imap: string; smtp: string }>(`/api/agents/${agentId}/email-accounts/${accountId}/test${wsQuery(workspaceId)}`, {+ method: "POST",+ });++export const syncEmailAccount = (agentId: string, accountId: string, workspaceId: string) =>+ apiFetch<{ ok: boolean }>(`/api/agents/${agentId}/email-accounts/${accountId}/sync${wsQuery(workspaceId)}`, {+ method: "POST",+ });++// Agent Access+export interface AgentAccessEntry {+ id: string; user_id: string; name: string; email: string; created_at: string;+}++export const listAgentAccess = (workspaceId: string, agentId: string) =>+ apiFetch<AgentAccessEntry[]>(`/api/agents/${agentId}/access${wsQuery(workspaceId)}`);++export const grantAgentAccess = (workspaceId: string, agentId: string, userId: string) =>+ apiFetch<{ id: string; user_id: string }>(`/api/agents/${agentId}/access${wsQuery(workspaceId)}`, { method: "POST", body: JSON.stringify({ user_id: userId }) });++export const revokeAgentAccess = (workspaceId: string, agentId: string, userId: string, removeWhitelist = false) =>+ apiFetch<void>(`/api/agents/${agentId}/access/${userId}${wsQuery(workspaceId)}${removeWhitelist ? "&remove_whitelist=true" : ""}`, { method: "DELETE" });++// Agent Pins+export interface AgentPin {+ id: string;+ agent_id: string;+ created_at: string;+ position: number;+}++export interface SidebarOrder {+ agent_id: string;+ position: number;+}++export const listAgentPins = (workspaceId: string) =>+ apiFetch<{ pins: AgentPin[]; sidebar_order: SidebarOrder[] }>(`/api/agents/pins${wsQuery(workspaceId)}`);++export const pinAgent = (workspaceId: string, agentId: string) =>+ apiFetch<{ pinned: boolean }>(`/api/agents/${agentId}/pin${wsQuery(workspaceId)}`, { method: "POST" });++export const unpinAgent = (workspaceId: string, agentId: string) =>+ apiFetch<void>(`/api/agents/${agentId}/pin${wsQuery(workspaceId)}`, { method: "DELETE" });++export const reorderAgentPins = (workspaceId: string, orderedAgentIds: string[]) =>+ apiFetch<void>(`/api/agents/pins/reorder${wsQuery(workspaceId)}`, {+ method: "PUT",+ body: JSON.stringify({ ordered_agent_ids: orderedAgentIds }),+ });++export const reorderUnpinnedAgents = (workspaceId: string, orderedAgentIds: string[]) =>+ apiFetch<void>(`/api/agents/sidebar/reorder${wsQuery(workspaceId)}`, {+ method: "PUT",+ body: JSON.stringify({ ordered_agent_ids: orderedAgentIds }),+ });++// Workspace file browsing+export const requestWorkspaceBrowse = (+ agentId: string,+ workspaceId: string,+ requestType: "tree" | "read",+ path: string,+) =>+ apiFetch<{ request_id: string }>(+ `/api/agents/${agentId}/workspace/browse${wsQuery(workspaceId)}`,+ {+ method: "POST",+ body: JSON.stringify({ request_type: requestType, path }),+ },+ );++// Skill browsing+export const getAgentSkills = (agentId: string, workspaceId: string) =>+ apiFetch<{ skills: { name: string; description: string; isGlobal?: boolean }[] }>(+ `/api/agents/${agentId}/skills${wsQuery(workspaceId)}`,+ );++// Meetings+export const listMeetings = (agentId: string, workspaceId: string) =>+ apiFetch<MeetingSession[]>(`/api/agents/${agentId}/meetings${wsQuery(workspaceId)}`);++export const getMeeting = (agentId: string, meetingId: string, workspaceId: string) =>+ apiFetch<MeetingSession>(`/api/agents/${agentId}/meetings/${meetingId}${wsQuery(workspaceId)}`);++export const createMeeting = (agentId: string, workspaceId: string, data: {+ meetingUrl: string;+ title?: string;+ participants?: string[];+}) =>+ apiFetch<MeetingSession>(`/api/agents/${agentId}/meetings${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify(data),+ });++export const stopMeeting = (agentId: string, meetingId: string, workspaceId: string) =>+ apiFetch<MeetingSession & { transcript?: string }>(`/api/agents/${agentId}/meetings/${meetingId}/stop${wsQuery(workspaceId)}`, {+ method: "POST",+ });++export const approveMeeting = (agentId: string, meetingId: string, workspaceId: string) =>+ apiFetch<MeetingSession>(`/api/agents/${agentId}/meetings/${meetingId}/approve${wsQuery(workspaceId)}`, {+ method: "POST",+ });++export const deleteMeeting = (agentId: string, meetingId: string, workspaceId: string) =>+ apiFetch<void>(`/api/agents/${agentId}/meetings/${meetingId}${wsQuery(workspaceId)}`, {+ method: "DELETE",+ });++// Machine tokens+export const createMachineToken = (name?: string, workspaceId?: string) =>+ apiFetch<{ token: string; id: string; name: string; created_at: string }>(+ `/api/machine-tokens${workspaceId ? wsQuery(workspaceId) : ""}`,+ {+ method: "POST",+ body: JSON.stringify({ name: name || "default" }),+ }+ );++export const getMachineTokenStatus = () =>+ apiFetch<{ status: "pending" | "active" | null; token?: string; workspace_id?: string; hostname?: string; daemon_online?: boolean }>(+ "/api/machine-tokens/status",+ );diff --git a/src/web/src/lib/api/artifacts.ts b/src/web/src/lib/api/artifacts.tsnew file mode 100644index 000000000..bc5017ba2--- /dev/null+++ b/src/web/src/lib/api/artifacts.ts@@ -0,0 +1,12 @@+import type { Artifact } from "@alook/shared";+import { apiFetch, wsQuery } from "./client";++export const listArtifacts = (conversationId: string, workspaceId: string) =>+ apiFetch<Artifact[]>(`/api/artifacts${wsQuery(workspaceId, { conversation_id: conversationId })}`);++export const getArtifactContent = async (id: string, workspaceId: string): Promise<string> => {+ const params = new URLSearchParams({ workspace_id: workspaceId });+ const res = await fetch(`/api/artifacts/${id}/content?${params}`, { credentials: "include" });+ if (!res.ok) return "(content not available)";+ return res.text();+};diff --git a/src/web/src/lib/api/calendar.ts b/src/web/src/lib/api/calendar.tsnew file mode 100644index 000000000..71130bfb8--- /dev/null+++ b/src/web/src/lib/api/calendar.ts@@ -0,0 +1,55 @@+import type {+ CalendarEvent,+ CreateCalendarEventRequest,+ UpdateCalendarEventRequest,+ DeleteCalendarEventRequest,+} from "@alook/shared";+import { apiFetch, wsQuery } from "./client";++export const listCalendarEvents = (+ workspaceId: string,+ opts?: { agentId?: string; from?: string; to?: string }+) => {+ const extra: Record<string, string> = {};+ if (opts?.agentId) extra.agentId = opts.agentId;+ if (opts?.from) extra.from = opts.from;+ if (opts?.to) extra.to = opts.to;+ return apiFetch<CalendarEvent[]>(`/api/calendar${wsQuery(workspaceId, extra)}`);+};++export const getCalendarEvent = (id: string, workspaceId: string) =>+ apiFetch<CalendarEvent>(`/api/calendar/${id}${wsQuery(workspaceId)}`);++export const createCalendarEvent = (+ req: CreateCalendarEventRequest,+ workspaceId: string+) =>+ apiFetch<CalendarEvent>(`/api/calendar${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify(req),+ });++export const updateCalendarEvent = (+ id: string,+ patch: UpdateCalendarEventRequest,+ workspaceId: string+) =>+ apiFetch<CalendarEvent>(`/api/calendar/${id}${wsQuery(workspaceId)}`, {+ method: "PATCH",+ body: JSON.stringify(patch),+ });++export const deleteCalendarEvent = (+ id: string,+ workspaceId: string,+ body?: DeleteCalendarEventRequest+) =>+ apiFetch<CalendarEvent>(`/api/calendar/${id}${wsQuery(workspaceId)}`, {+ method: "DELETE",+ ...(body && body.scope+ ? {+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ }+ : {}),+ });diff --git a/src/web/src/lib/api/channels.ts b/src/web/src/lib/api/channels.tsnew file mode 100644index 000000000..32e093355--- /dev/null+++ b/src/web/src/lib/api/channels.ts@@ -0,0 +1,28 @@+import type { Channel } from "@alook/shared";+import { apiFetch, wsQuery } from "./client";++export const listChannels = (workspaceId: string) =>+ apiFetch<Channel[]>(`/api/channels${wsQuery(workspaceId)}`);++export const createChannelApi = (workspaceId: string, name: string) =>+ apiFetch<Channel>(`/api/channels${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify({ name }),+ });++export const renameChannelApi = (id: string, workspaceId: string, name: string) =>+ apiFetch<Channel>(`/api/channels/${id}${wsQuery(workspaceId)}`, {+ method: "PATCH",+ body: JSON.stringify({ name }),+ });++export const deleteChannelApi = (id: string, workspaceId: string) =>+ apiFetch<{ ok: boolean }>(`/api/channels/${id}${wsQuery(workspaceId)}`, {+ method: "DELETE",+ });++export const reorderChannelsApi = (workspaceId: string, orderedChannelIds: string[]) =>+ apiFetch<void>(`/api/channels/reorder${wsQuery(workspaceId)}`, {+ method: "PUT",+ body: JSON.stringify({ ordered_channel_ids: orderedChannelIds }),+ });diff --git a/src/web/src/lib/api/client.ts b/src/web/src/lib/api/client.tsnew file mode 100644index 000000000..f251023d4--- /dev/null+++ b/src/web/src/lib/api/client.ts@@ -0,0 +1,108 @@+import { ApiError } from "@/lib/errors";++const API_BASE = "";++const MOCK_NETWORK_ENABLED = process.env.NODE_ENV === "development" && process.env.NEXT_PUBLIC_MOCK_NETWORK === "true";+const MOCK_NETWORK_DELAY_MS = parseInt(process.env.NEXT_PUBLIC_MOCK_NETWORK_DELAY_MS || "300", 10) || 300;+let mockNetworkLogged = false;++function humanizeValidationDetail(detail: string): string {+ const [rawField, ...rest] = detail.split(":");+ const rawMessage = rest.join(":").trim();+ if (!rawMessage) return detail;++ const field = rawField.trim();+ const label = field+ .trim()+ .replace(/[_-]+/g, " ")+ .replace(/\b\w/g, (char) => char.toUpperCase());+ let message = rawMessage.replace(/^required$/i, "is required");++ const normalizedMessage = message.toLowerCase().replace(/[_-]+/g, " ");+ const normalizedField = field.toLowerCase().replace(/[_-]+/g, " ");+ if (normalizedField && normalizedMessage.startsWith(`${normalizedField} `)) {+ message = message.slice(field.length).trimStart();+ }++ return label ? `${label} ${message}` : message;+}++function getReadableErrorMessage(error: string | undefined, details: string[] | undefined) {+ if (error === "validation error" && details?.length) {+ return humanizeValidationDetail(details[0]);+ }+ return error;+}++export async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {+ if (MOCK_NETWORK_ENABLED) {+ if (!mockNetworkLogged) {+ console.info(`[Mock Network] Enabled — ${MOCK_NETWORK_DELAY_MS}ms delay on all API requests`);+ mockNetworkLogged = true;+ }+ await new Promise((r) => setTimeout(r, MOCK_NETWORK_DELAY_MS));+ }++ let res: Response;+ try {+ res = await fetch(API_BASE + path, {+ ...options,+ credentials: "include",+ headers: {+ "Content-Type": "application/json",+ ...options?.headers,+ },+ });+ } catch (err) {+ if (err instanceof TypeError) {+ throw new ApiError("Unable to connect — check your network", 0);+ }+ throw err;+ }++ if (res.status === 401) {+ if (typeof window !== "undefined") {+ window.location.href = "/sign-in";+ }+ throw new ApiError("Unauthorized", 401);+ }++ if (!res.ok) {+ let serverError: string | undefined;+ let details: string[] | undefined;+ try {+ const body = (await res.json()) as { error?: string; details?: string[] };+ serverError = body.error;+ details = body.details;+ } catch {+ // non-JSON body (HTML from proxy, empty body, etc.)+ }++ if (res.status === 429) {+ throw new ApiError("Please wait a moment before trying again", 429);+ }++ if (res.status >= 500) {+ throw new ApiError(+ getReadableErrorMessage(serverError, details) ||+ "Something went wrong — please try again",+ res.status,+ details,+ );+ }++ throw new ApiError(+ getReadableErrorMessage(serverError, details) || "Something went wrong",+ res.status,+ details,+ );+ }++ if (res.status === 204) return undefined as T;+ return res.json();+}++export function wsQuery(workspaceId: string, extra?: Record<string, string>): string {+ const params = new URLSearchParams({ workspace_id: workspaceId, ...extra });+ return `?${params.toString()}`;+}diff --git a/src/web/src/lib/api/config.ts b/src/web/src/lib/api/config.tsnew file mode 100644index 000000000..70d419983--- /dev/null+++ b/src/web/src/lib/api/config.ts@@ -0,0 +1,10 @@+import { apiFetch } from "./client";++export const fetchModelOptions = () =>+ apiFetch<Record<string, string[]>>("/api/config/model-options");++export const getMinCliVersion = () =>+ apiFetch<{ min_cli_version: string | null }>("/api/config/min-version");++export const fetchLatestCliVersion = () =>+ apiFetch<{ version: string; package: string }>("/api/cli/latest-version");diff --git a/src/web/src/lib/api/conversations.ts b/src/web/src/lib/api/conversations.tsnew file mode 100644index 000000000..cf852e51f--- /dev/null+++ b/src/web/src/lib/api/conversations.ts@@ -0,0 +1,265 @@+import type {+ Artifact,+ Conversation,+ Message,+ TaskApi,+ TaskMessageResponse,+} from "@alook/shared";+import { ApiError } from "@/lib/errors";+import type { PendingFile } from "@/hooks/use-file-attachments";+import { apiFetch, wsQuery } from "./client";++export const listConversations = (workspaceId: string, channel?: string) =>+ apiFetch<Conversation[]>(`/api/conversations${wsQuery(workspaceId, channel ? { channel } : undefined)}`);++export const createConversation = (agentId: string, workspaceId: string, channel?: string) =>+ apiFetch<Conversation>(`/api/conversations${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify({ agent_id: agentId, ...(channel ? { channel } : {}) }),+ });++export const getConversation = (id: string, workspaceId: string) =>+ apiFetch<Conversation>(`/api/conversations/${id}${wsQuery(workspaceId)}`);++export const listAgentConversations = (agentId: string, workspaceId: string, channel?: string) =>+ apiFetch<Conversation[]>(`/api/agents/${agentId}/conversations${wsQuery(workspaceId, channel ? { channel } : undefined)}`);++export const getOrCreateAgentConversation = (agentId: string, workspaceId: string, channel?: string) =>+ apiFetch<Conversation>(`/api/agents/${agentId}/conversation${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify({ ...(channel ? { channel } : {}) }),+ });++export interface PreviousConversation {+ id: string;+ created_at: string;+}++export interface ChatInitResponse {+ conversation: Conversation;+ messages: Message[];+ artifacts: Artifact[];+ active_task: TaskApi | null;+ task_messages: TaskMessageResponse[];+ has_more_messages: boolean;+ has_more_conversations: boolean;+ has_more_artifacts: boolean;+}++export const listPreviousConversations = (+ agentId: string,+ workspaceId: string,+ opts: { exclude: string; before: string; channel?: string; limit?: number },+) => {+ const extra: Record<string, string> = { exclude: opts.exclude, before: opts.before };+ if (opts.channel) extra.channel = opts.channel;+ if (opts.limit) extra.limit = String(opts.limit);+ return apiFetch<{ conversations: PreviousConversation[]; has_more: boolean }>(+ `/api/agents/${agentId}/conversations${wsQuery(workspaceId, extra)}`,+ );+};++export const chatInit = (agentId: string, workspaceId: string, channel?: string) =>+ apiFetch<ChatInitResponse>(`/api/agents/${agentId}/chat-init${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify({ ...(channel ? { channel } : {}) }),+ });++export interface ConversationInitResponse {+ conversation: Conversation;+ messages: Message[] | null;+ has_more_messages: boolean;+ has_more_conversations: boolean;+ has_more_artifacts: boolean;+ artifacts: Artifact[];+ flagged_message_ids: string[];+ active_task: TaskApi | null;+ task_messages: TaskMessageResponse[];+ cache_valid: boolean;+ message_count: number;+ root_message?: Message | null;+}++export const conversationInit = (+ conversationId: string,+ workspaceId: string,+ opts?: { newestMessageId?: string; messageCount?: number },+) => {+ const extra: Record<string, string> = {};+ if (opts?.newestMessageId) extra.newest_message_id = opts.newestMessageId;+ if (opts?.messageCount) extra.message_count = String(opts.messageCount);+ return apiFetch<ConversationInitResponse>(+ `/api/conversations/${conversationId}/init${wsQuery(workspaceId, extra)}`,+ );+};++export interface FreshnessCheckResponse {+ conversation_id: string;+ newest_message_id: string | null;+ message_count: number;+}++export const checkFreshness = (+ opts: { conversationId?: string; agentId?: string; channel?: string },+ workspaceId: string,+) => {+ const extra: Record<string, string> = {};+ if (opts.conversationId) extra.conversation_id = opts.conversationId;+ if (opts.agentId) extra.agent_id = opts.agentId;+ if (opts.channel) extra.channel = opts.channel;+ return apiFetch<FreshnessCheckResponse>(+ `/api/conversations/check-fresh${wsQuery(workspaceId, extra)}`,+ );+};++export const deleteConversation = (id: string, workspaceId: string) =>+ apiFetch<void>(`/api/conversations/${id}${wsQuery(workspaceId)}`, { method: "DELETE" });++export const listMessages = (+ conversationId: string,+ workspaceId: string,+ opts?: { limit?: number; before?: string; beforeId?: string }+) => {+ const extra: Record<string, string> = {};+ if (opts?.limit) extra.limit = String(opts.limit);+ if (opts?.before) extra.before = opts.before;+ if (opts?.beforeId) extra.before_id = opts.beforeId;+ return apiFetch<{ messages: Message[]; has_more: boolean }>(+ `/api/conversations/${conversationId}/messages${wsQuery(workspaceId, extra)}`+ );+};++export const listMessagesAroundTask = (+ conversationId: string,+ workspaceId: string,+ taskId: string+) =>+ apiFetch<Message[]>(+ `/api/conversations/${conversationId}/messages${wsQuery(workspaceId, { around_task: taskId })}`+ );++export const sendMessage = async (+ conversationId: string,+ content: string,+ workspaceId: string,+ files?: PendingFile[],+ metadata?: Record<string, unknown>,+): Promise<{ message: Message; task: TaskApi }> => {+ if (!files || files.length === 0) {+ return apiFetch<{ message: Message; task: TaskApi }>(+ `/api/conversations/${conversationId}/messages${wsQuery(workspaceId)}`,+ {+ method: "POST",+ body: JSON.stringify({ content, ...(metadata ? { metadata } : {}) }),+ },+ );+ }++ const fd = new FormData();+ fd.append("content", content);+ if (metadata) fd.append("metadata", JSON.stringify(metadata));+ for (const pf of files) {+ fd.append("file", pf.file);+ }+ for (let i = 0; i < files.length; i++) {+ const blob = files[i].thumbnailBlob;+ if (blob) fd.append(`thumbnail:${i}`, blob, "thumbnail.jpg");+ }++ let res: Response;+ try {+ res = await fetch(+ `/api/conversations/${conversationId}/messages${wsQuery(workspaceId)}`,+ { method: "POST", credentials: "include", body: fd },+ );+ } catch (err) {+ if (err instanceof TypeError) {+ throw new ApiError("Unable to connect — check your network", 0);+ }+ throw err;+ }++ if (res.status === 401) {+ if (typeof window !== "undefined") window.location.href = "/sign-in";+ throw new ApiError("Unauthorized", 401);+ }++ if (!res.ok) {+ let serverError: string | undefined;+ let details: string[] | undefined;+ try {+ const body = (await res.json()) as { error?: string; details?: string[] };+ serverError = body.error;+ details = body.details;+ } catch {+ // non-JSON body+ }+ if (res.status === 429) throw new ApiError("Please wait a moment before trying again", 429);+ if (res.status >= 500) throw new ApiError(serverError || "Something went wrong — please try again", res.status, details);+ throw new ApiError(serverError || "Something went wrong", res.status, details);+ }++ return res.json() as Promise<{ message: Message; task: TaskApi }>;+};++// Active task for conversation+export const getActiveTask = (conversationId: string, workspaceId: string) =>+ apiFetch<TaskApi | undefined>(`/api/conversations/${conversationId}/active-task${wsQuery(workspaceId)}`);++export const cancelActiveTask = (conversationId: string, workspaceId: string) =>+ apiFetch<TaskApi>(`/api/conversations/${conversationId}/active-task${wsQuery(workspaceId)}`, {+ method: "DELETE",+ });++// Threads+export interface ThreadSummary {+ thread_id: string;+ parent_message_id: string;+ thread_title: string;+ reply_count: number;+ last_reply_at: string | null;+ created_at: string;+}++export interface ThreadListItem {+ id: string;+ parent_message_id: string;+ thread_title: string;+ reply_count: number;+ last_reply_at: string | null;+ last_reply_preview: string;+ created_at: string;+}++export const createThread = (+ conversationId: string,+ parentMessageId: string,+ content: string,+ workspaceId: string,+) =>+ apiFetch<{+ conversation: Conversation;+ message: Message;+ task: TaskApi;+ }>(`/api/conversations/${conversationId}/threads${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify({ parent_message_id: parentMessageId, content }),+ });++export const getThreadSummaries = (conversationId: string, workspaceId: string) =>+ apiFetch<{ thread_summaries: ThreadSummary[] }>(+ `/api/conversations/${conversationId}/threads${wsQuery(workspaceId)}`+ );++export const listAgentThreads = (+ agentId: string,+ workspaceId: string,+ opts?: { limit?: number; before?: string }+) => {+ const extra: Record<string, string> = {};+ if (opts?.limit) extra.limit = String(opts.limit);+ if (opts?.before) extra.before = opts.before;+ return apiFetch<{ threads: ThreadListItem[]; has_more: boolean }>(+ `/api/agents/${agentId}/threads${wsQuery(workspaceId, extra)}`+ );+};diff --git a/src/web/src/lib/api/emails.ts b/src/web/src/lib/api/emails.tsnew file mode 100644index 000000000..970954619--- /dev/null+++ b/src/web/src/lib/api/emails.ts@@ -0,0 +1,69 @@+import type { Email } from "@alook/shared";+import { ApiError } from "@/lib/errors";+import { apiFetch, wsQuery } from "./client";++export const listEmails = (agentId: string, workspaceId: string, folder?: string, address?: string) =>+ apiFetch<Email[]>(`/api/email${wsQuery(workspaceId, { agentId, ...(folder ? { folder } : {}), ...(address ? { address } : {}) })}`);++export const getEmail = (id: string, workspaceId: string) =>+ apiFetch<Email>(`/api/email/${id}${wsQuery(workspaceId)}`);++export const getEmailThread = (id: string, workspaceId: string) =>+ apiFetch<Email[]>(`/api/email/${id}/thread${wsQuery(workspaceId)}`);++export const getEmailBody = async (id: string, workspaceId: string): Promise<{ content: string; isHtml: boolean }> => {+ const params = new URLSearchParams({ workspace_id: workspaceId });+ const res = await fetch(`/api/email/${id}/body?${params}`, { credentials: "include" });+ if (!res.ok) return { content: "(body not available)", isHtml: false };+ const contentType = res.headers.get("Content-Type") ?? "";+ const content = await res.text();+ return { content, isHtml: contentType.includes("text/html") };+};++export const deleteEmail = (id: string, workspaceId: string) =>+ apiFetch<void>(`/api/email/${id}${wsQuery(workspaceId)}`, { method: "DELETE" });++export const updateEmailStatus = (id: string, workspaceId: string, status: string) =>+ apiFetch<Email>(`/api/email/${id}${wsQuery(workspaceId)}`, {+ method: "PATCH",+ body: JSON.stringify({ status }),+ });++export const trustEmail = (id: string, workspaceId: string) =>+ apiFetch<{ ok: boolean; email: Email; conversationId: string }>(+ `/api/email/${id}/trust${wsQuery(workspaceId)}`,+ { method: "POST" }+ );++export const uploadEmailAttachment = async (+ file: File,+ workspaceId: string,+): Promise<{ key: string; filename: string; size: number; contentType: string }> => {+ const fd = new FormData();+ fd.append("file", file);+ const res = await fetch(`/api/email/upload${wsQuery(workspaceId)}`, {+ method: "POST",+ credentials: "include",+ body: fd,+ });+ if (!res.ok) {+ const msg = await res.text().catch(() => "Upload failed");+ throw new ApiError(msg, res.status);+ }+ return res.json();+};++export const sendEmail = (+ agentId: string,+ to: string,+ subject: string,+ htmlBody: string,+ workspaceId: string,+ attachments?: { key: string; filename: string; size: number; contentType: string }[],+ threading?: { inReplyTo?: string; references?: string },+ customAccountId?: string,+) =>+ apiFetch<Email>(`/api/email/send${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify({ agentId, to, subject, htmlBody, attachments, ...threading, customAccountId }),+ });diff --git a/src/web/src/lib/api/inbox.ts b/src/web/src/lib/api/inbox.tsnew file mode 100644index 000000000..5f8732c71--- /dev/null+++ b/src/web/src/lib/api/inbox.ts@@ -0,0 +1,92 @@+import { apiFetch, wsQuery } from "./client";++// Inbox+export interface InboxItem {+ id: string;+ agent_id: string;+ title: string;+ channel: string;+ latest_response: string;+ latest_response_at: string;+ root_prompt: string | null;+ agent_name: string | null;+ agent_avatar_url: string | null;+ root_task_status: string | null;+ root_task_type: string | null;+}++export const listInboxItems = (+ workspaceId: string,+ opts?: { limit?: number; before?: string; types?: string[] }+) => {+ const extra: Record<string, string> = {};+ if (opts?.limit) extra.limit = String(opts.limit);+ if (opts?.before) extra.before = opts.before;+ if (opts?.types?.length) extra.types = opts.types.join(",");+ return apiFetch<{ items: InboxItem[]; has_more: boolean }>(+ `/api/inbox${wsQuery(workspaceId, extra)}`+ );+};++export const getInboxCount = (workspaceId: string, opts?: { types?: string[] }) => {+ const extra: Record<string, string> = {};+ if (opts?.types?.length) extra.types = opts.types.join(",");+ return apiFetch<{ count: number }>(`/api/inbox/count${wsQuery(workspaceId, extra)}`);+};++export const markInboxRead = (conversationId: string, workspaceId: string) =>+ apiFetch<void>(`/api/inbox/read${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify({ conversationId }),+ });++export const markAllInboxRead = (workspaceId: string) =>+ apiFetch<void>(`/api/inbox/read-all${wsQuery(workspaceId)}`, {+ method: "POST",+ });++// Flags+export interface FlaggedItem {+ id: string;+ message_id: string;+ message_content: string;+ message_role: string;+ message_created_at: string;+ conversation_id: string;+ conversation_title: string;+ agent_id: string;+ agent_name: string | null;+ agent_avatar_url: string | null;+ flagged_at: string;+}++export const listFlaggedItems = (+ workspaceId: string,+ opts?: { limit?: number; before?: string }+) => {+ const extra: Record<string, string> = {};+ if (opts?.limit) extra.limit = String(opts.limit);+ if (opts?.before) extra.before = opts.before;+ return apiFetch<{ items: FlaggedItem[]; has_more: boolean }>(+ `/api/flags${wsQuery(workspaceId, extra)}`+ );+};++export const getFlaggedCount = (workspaceId: string) =>+ apiFetch<{ count: number }>(`/api/flags/count${wsQuery(workspaceId)}`);++export const flagMessage = (workspaceId: string, messageId: string) =>+ apiFetch<{ flagged: boolean }>(`/api/flags${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify({ messageId }),+ });++export const unflagMessage = (workspaceId: string, messageId: string) =>+ apiFetch<void>(`/api/flags/${messageId}${wsQuery(workspaceId)}`, {+ method: "DELETE",+ });++export const listFlaggedMessageIds = (workspaceId: string, conversationId: string) =>+ apiFetch<{ message_ids: string[] }>(+ `/api/flags${wsQuery(workspaceId, { conversation_id: conversationId, ids_only: "true" })}`+ );diff --git a/src/web/src/lib/api/index.ts b/src/web/src/lib/api/index.tsnew file mode 100644index 000000000..3301bb199--- /dev/null+++ b/src/web/src/lib/api/index.ts@@ -0,0 +1,165 @@+export { apiFetch, wsQuery } from "./client";+export { getMe } from "./me";+export { fetchModelOptions, getMinCliVersion, fetchLatestCliVersion } from "./config";+export {+ listAgents,+ createAgent,+ getAgent,+ updateAgent,+ deleteAgent,+ listRuntimes,+ deleteMachine,+ triggerRuntimeUpdate,+ triggerRuntimeRescan,+ listAgentActiveTaskCounts,+ listAgentActiveTasks,+ listWorkspaceActiveTasks,+ listAgentActivity,+ listWhitelist,+ addWhitelistEmail,+ removeWhitelistEmail,+ listAgentLinks,+ createAgentLink,+ updateAgentLink,+ deleteAgentLink,+ listEmailAccounts,+ createEmailAccount,+ updateEmailAccount,+ deleteEmailAccount,+ testEmailConnection,+ syncEmailAccount,+ listAgentAccess,+ grantAgentAccess,+ revokeAgentAccess,+ listAgentPins,+ pinAgent,+ unpinAgent,+ reorderAgentPins,+ reorderUnpinnedAgents,+ requestWorkspaceBrowse,+ getAgentSkills,+ listMeetings,+ getMeeting,+ createMeeting,+ stopMeeting,+ approveMeeting,+ deleteMeeting,+ createMachineToken,+ getMachineTokenStatus,+} from "./agents";+export type {+ ActiveTask,+ WorkspaceActiveTask,+ ActivityTask,+ WhitelistEntry,+ AgentAccessEntry,+ AgentPin,+ SidebarOrder,+} from "./agents";+export {+ listChannels,+ createChannelApi,+ renameChannelApi,+ deleteChannelApi,+ reorderChannelsApi,+} from "./channels";+export {+ listConversations,+ createConversation,+ getConversation,+ listAgentConversations,+ getOrCreateAgentConversation,+ listPreviousConversations,+ chatInit,+ conversationInit,+ checkFreshness,+ deleteConversation,+ listMessages,+ listMessagesAroundTask,+ sendMessage,+ getActiveTask,+ cancelActiveTask,+ createThread,+ getThreadSummaries,+ listAgentThreads,+} from "./conversations";+export type {+ PreviousConversation,+ ChatInitResponse,+ ConversationInitResponse,+ FreshnessCheckResponse,+ ThreadSummary,+ ThreadListItem,+} from "./conversations";+export {+ listCalendarEvents,+ getCalendarEvent,+ createCalendarEvent,+ updateCalendarEvent,+ deleteCalendarEvent,+} from "./calendar";+export {+ listEmails,+ getEmail,+ getEmailThread,+ getEmailBody,+ deleteEmail,+ updateEmailStatus,+ trustEmail,+ uploadEmailAttachment,+ sendEmail,+} from "./emails";+export { getTask, getTaskMessages, retryTask } from "./tasks";+export {+ listIssues,+ createIssue,+ getIssue,+ updateIssue,+ commentIssue,+ deleteIssue,+} from "./issues";+export type { IssueListItem, IssueDetailResponse } from "./issues";+export {+ listWorkspaces,+ createWorkspace,+ updateWorkspace,+ deleteWorkspace,+ listMembers,+ removeMember,+ getMemberMe,+ updateMemberMe,+ listInvites,+ createInvite,+ revokeInvite,+ getInviteInfo,+ acceptInvite,+ getWorkspaceOverview,+ signOut,+ verifyCode,+} from "./workspaces";+export type {+ MemberEntry,+ InviteEntry,+ InviteInfo,+ InviteAcceptResult,+ OverviewEmailAccount,+ OverviewRecentTask,+ OverviewCalendarEvent,+ OverviewMember,+ WorkspaceOverview,+} from "./workspaces";+export {+ listInboxItems,+ getInboxCount,+ markInboxRead,+ markAllInboxRead,+ listFlaggedItems,+ getFlaggedCount,+ flagMessage,+ unflagMessage,+ listFlaggedMessageIds,+} from "./inbox";+export type { InboxItem, FlaggedItem } from "./inbox";+export { listTraces, getTrace } from "./traces";+export type { TraceListItem, TraceTask } from "./traces";+export { listArtifacts, getArtifactContent } from "./artifacts";diff --git a/src/web/src/lib/api/issues.ts b/src/web/src/lib/api/issues.tsnew file mode 100644index 000000000..32ccd9264--- /dev/null+++ b/src/web/src/lib/api/issues.ts@@ -0,0 +1,110 @@+import type {+ Artifact,+ Conversation,+ Issue,+ IssueComment,+ Message,+ CreateIssueRequest,+ TaskApi,+ UpdateIssueRequest,+} from "@alook/shared";+import { ApiError } from "@/lib/errors";+import { apiFetch, wsQuery } from "./client";++export type IssueListItem = Issue & { thread_agent_ids?: string[] };++export interface IssueDetailResponse {+ issue: Issue & { trace_id?: string | null };+ messages: Message[];+ comments: IssueComment[];+ artifacts: Artifact[];+}++export const listIssues = (+ workspaceId: string,+ opts?: { agentId?: string; status?: string; terminal?: boolean }+) => {+ const extra: Record<string, string> = {};+ if (opts?.agentId) extra.agentId = opts.agentId;+ if (opts?.status) extra.status = opts.status;+ if (opts?.terminal !== undefined) extra.terminal = String(opts.terminal);+ return apiFetch<IssueListItem[]>(`/api/issues${wsQuery(workspaceId, extra)}`);+};++export const createIssue = async (+ workspaceId: string,+ req: CreateIssueRequest & { files?: File[] },+): Promise<{ issue: Issue; message?: Message; task?: TaskApi }> => {+ if (!req.files || req.files.length === 0) {+ return apiFetch<{ issue: Issue; message?: Message; task?: TaskApi }>(`/api/issues${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify({+ agent_id: req.agent_id,+ title: req.title,+ description: req.description,+ }),+ });+ }++ const fd = new FormData();+ if (req.agent_id) fd.append("agent_id", req.agent_id);+ fd.append("title", req.title);+ fd.append("description", req.description ?? "");+ for (const file of req.files) {+ fd.append("file", file);+ }++ let res: Response;+ try {+ res = await fetch(`/api/issues${wsQuery(workspaceId)}`, {+ method: "POST",+ credentials: "include",+ body: fd,+ });+ } catch (err) {+ if (err instanceof TypeError) {+ throw new ApiError("Unable to connect — check your network", 0);+ }+ throw err;+ }++ if (res.status === 401) {+ if (typeof window !== "undefined") window.location.href = "/sign-in";+ throw new ApiError("Unauthorized", 401);+ }++ if (!res.ok) {+ let serverError: string | undefined;+ let details: string[] | undefined;+ try {+ const body = (await res.json()) as { error?: string; details?: string[] };+ serverError = body.error;+ details = body.details;+ } catch {+ // non-JSON body+ }+ if (res.status === 429) throw new ApiError("Please wait a moment before trying again", 429);+ if (res.status >= 500) throw new ApiError(serverError || "Something went wrong — please try again", res.status, details);+ throw new ApiError(serverError || "Something went wrong", res.status, details);+ }++ return res.json() as Promise<{ issue: Issue; message?: Message; task?: TaskApi }>;+};++export const getIssue = (workspaceId: string, issueId: string) =>+ apiFetch<IssueDetailResponse>(`/api/issues/${issueId}${wsQuery(workspaceId)}`);++export const updateIssue = (workspaceId: string, issueId: string, patch: UpdateIssueRequest) =>+ apiFetch<Issue>(`/api/issues/${issueId}${wsQuery(workspaceId)}`, {+ method: "PATCH",+ body: JSON.stringify(patch),+ });++export const commentIssue = (workspaceId: string, issueId: string, content: string) =>+ apiFetch<{ message: Message }>(`/api/issues/${issueId}${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify({ content }),+ });++export const deleteIssue = (workspaceId: string, issueId: string) =>+ apiFetch<void>(`/api/issues/${issueId}${wsQuery(workspaceId)}`, { method: "DELETE" });diff --git a/src/web/src/lib/api/me.ts b/src/web/src/lib/api/me.tsnew file mode 100644index 000000000..12b0ca772--- /dev/null+++ b/src/web/src/lib/api/me.ts@@ -0,0 +1,4 @@+import type { User } from "@alook/shared";+import { apiFetch } from "./client";++export const getMe = () => apiFetch<User>("/api/me");diff --git a/src/web/src/lib/api/responses.test.ts b/src/web/src/lib/api/responses.test.tsindex 0158c10db..e3c6726c1 100644--- a/src/web/src/lib/api/responses.test.ts+++ b/src/web/src/lib/api/responses.test.ts@@ -294,7 +294,7 @@ describe("machineTokenToResponse", () => {describe("UserResponse shape", () => {it("has expected keys: id, name, email, avatar_url, created_at, updated_at", () => {- const res = userToResponse({ id: "u1", name: "A", email: "[email protected]", avatarUrl: "https://img.png", ...baseFields() });+ const res = userToResponse({ id: "u1", name: "A", email: "[email protected]", image: "https://img.png", ...baseFields() });expect(Object.keys(res).sort()).toEqual(["avatar_url", "created_at", "email", "id", "name", "updated_at"]);@@ -431,7 +431,7 @@ describe("AgentRuntimeResponse shape", () => {describe("all response mappers strip milliseconds from timestamps", () => {it("userToResponse strips milliseconds", () => {- const res = userToResponse({ id: "u1", name: "A", email: "[email protected]", avatarUrl: null, ...baseFields() });+ const res = userToResponse({ id: "u1", name: "A", email: "[email protected]", image: null, ...baseFields() });expect(res.created_at).toBe(tsFormatted);expect(res.updated_at).toBe(tsFormatted);});diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.tsindex fdf2d1d53..3c3f8d608 100644--- a/src/web/src/lib/api/responses.ts+++ b/src/web/src/lib/api/responses.ts@@ -2,22 +2,36 @@ import {formatTimestamp,formatTimestampNullable,} from "@/lib/middleware/helpers";-import { TaskApiBaseSchema, isOnline, TASK_TYPES } from "@alook/shared";+import { TaskApiBaseSchema, isOnline, TASK_TYPES, schema, type Message } from "@alook/shared";-/* eslint-disable @typescript-eslint/no-explicit-any */+type UserRow = typeof schema.user.$inferSelect;+type WorkspaceRow = typeof schema.workspace.$inferSelect;+type AgentRow = typeof schema.agent.$inferSelect;+type EmailRow = typeof schema.emails.$inferSelect;+type ConversationRow = typeof schema.conversation.$inferSelect;+type ChannelRow = typeof schema.channel.$inferSelect;+type MessageRow = typeof schema.message.$inferSelect;+type TaskMessageRow = typeof schema.taskMessage.$inferSelect;+type AgentRuntimeRow = typeof schema.agentRuntime.$inferSelect;+type MachineTokenRow = typeof schema.machineToken.$inferSelect;+type MeetingSessionRow = typeof schema.meetingSession.$inferSelect;+type AgentLinkRow = typeof schema.agentLink.$inferSelect;+type CalendarEventRow = typeof schema.calendarEvent.$inferSelect;+type IssueRow = typeof schema.issue.$inferSelect;+type AgentTaskQueueRow = typeof schema.agentTaskQueue.$inferSelect;-export function userToResponse(u: any) {+export function userToResponse(u: UserRow) {return {id: u.id,name: u.name,email: u.email,- avatar_url: u.avatarUrl ?? null,+ avatar_url: u.image ?? null,created_at: formatTimestamp(u.createdAt),updated_at: formatTimestamp(u.updatedAt),};}-export function workspaceToResponse(w: any) {+export function workspaceToResponse(w: WorkspaceRow) {return {id: w.id,name: w.name,@@ -28,7 +42,7 @@ export function workspaceToResponse(w: any) {};}-export function agentToResponse(a: any) {+export function agentToResponse(a: AgentRow) {let rc = a.runtimeConfig;if (!rc) rc = {};return {@@ -51,7 +65,7 @@ export function agentToResponse(a: any) {};}-export function emailToResponse(e: any) {+export function emailToResponse(e: EmailRow) {return {id: e.id,agent_id: e.agentId,@@ -116,8 +130,8 @@ export function taskToResponse(t: {});}-export function conversationToResponse(c: any) {- const resp: any = {+export function conversationToResponse(c: Partial<ConversationRow> & Pick<ConversationRow, "id" | "agentId" | "title" | "createdAt"> & { messageCount?: number }) {+ const resp: Record<string, unknown> = {id: c.id,agent_id: c.agentId,title: c.title,@@ -135,7 +149,7 @@ export function conversationToResponse(c: any) {return resp;}-export function channelToResponse(c: any) {+export function channelToResponse(c: ChannelRow) {return {id: c.id,workspace_id: c.workspaceId,@@ -145,24 +159,24 @@ export function channelToResponse(c: any) {};}-export function messageToResponse(m: any) {- const resp: any = {+export function messageToResponse(m: MessageRow): Message {+ const resp: Message = {id: m.id,conversation_id: m.conversationId,- role: m.role,+ role: m.role as Message["role"],content: m.content,task_id: m.taskId || null,attachment_ids: m.attachmentIds ? JSON.parse(m.attachmentIds) : null,metadata: m.metadata ? JSON.parse(m.metadata) : null,created_at: formatTimestamp(m.createdAt),};- if (m.status && m.status !== "active") {- resp.status = m.status;+ if (m.status === "active") {+ resp.status = "active";}return resp;}-export function taskMessageToResponse(m: any) {+export function taskMessageToResponse(m: Pick<TaskMessageRow, "id" | "seq" | "type" | "content" | "output">) {return {id: m.id,seq: m.seq,@@ -172,7 +186,7 @@ export function taskMessageToResponse(m: any) {};}-export function runtimeToResponse(rt: any) {+export function runtimeToResponse(rt: AgentRuntimeRow & { machineLastSeenAt?: Date | string | null; pendingUpdateVersion?: string | null; pendingRescan?: boolean | number | null }) {let metadata = rt.metadata;if (!metadata) metadata = {};const machineLastSeenAt = rt.machineLastSeenAt ?? null;@@ -196,7 +210,7 @@ export function runtimeToResponse(rt: any) {};}-export function machineTokenToResponse(mt: any) {+export function machineTokenToResponse(mt: Pick<MachineTokenRow, "id" | "name" | "status" | "lastUsedAt" | "createdAt">) {return {id: mt.id,name: mt.name,@@ -206,7 +220,7 @@ export function machineTokenToResponse(mt: any) {};}-export function meetingToResponse(m: any) {+export function meetingToResponse(m: MeetingSessionRow) {return {id: m.id,agent_id: m.agentId,@@ -229,7 +243,7 @@ export function meetingToResponse(m: any) {};}-export function agentLinkToResponse(row: any) {+export function agentLinkToResponse(row: AgentLinkRow) {return {id: row.id,workspace_id: row.workspaceId,@@ -241,7 +255,7 @@ export function agentLinkToResponse(row: any) {};}-export function calendarEventToResponse(e: any) {+export function calendarEventToResponse(e: CalendarEventRow & { occurrenceAt?: string | null; collapsedCount?: number | null }) {const scheduled = formatTimestamp(e.scheduledAt);const occurrence = e.occurrenceAt ? formatTimestamp(e.occurrenceAt) : scheduled;return {@@ -261,7 +275,7 @@ export function calendarEventToResponse(e: any) {};}-export function issueToResponse(row: any) {+export function issueToResponse(row: IssueRow) {return {id: row.id,workspace_id: row.workspaceId,diff --git a/src/web/src/lib/api/tasks.ts b/src/web/src/lib/api/tasks.tsnew file mode 100644index 000000000..791ab6012--- /dev/null+++ b/src/web/src/lib/api/tasks.ts@@ -0,0 +1,15 @@+import type { TaskApi, TaskMessageResponse } from "@alook/shared";+import { apiFetch, wsQuery } from "./client";++export const getTask = (id: string, workspaceId: string) =>+ apiFetch<TaskApi>(`/api/tasks/${id}${wsQuery(workspaceId)}`);++export const getTaskMessages = (id: string, workspaceId: string, since?: number) =>+ apiFetch<TaskMessageResponse[]>(+ `/api/tasks/${id}/messages${wsQuery(workspaceId, since ? { since: String(since) } : undefined)}`+ );++export const retryTask = (id: string, workspaceId: string) =>+ apiFetch<TaskApi>(`/api/tasks/${id}/retry${wsQuery(workspaceId)}`, {+ method: "POST",+ });diff --git a/src/web/src/lib/api/traces.ts b/src/web/src/lib/api/traces.tsnew file mode 100644index 000000000..8631f38b1--- /dev/null+++ b/src/web/src/lib/api/traces.ts@@ -0,0 +1,48 @@+import { apiFetch, wsQuery } from "./client";++export interface TraceListItem {+ trace_id: string;+ root_prompt: string;+ root_agent_id: string;+ root_agent: { name: string; avatarUrl: string | null } | null;+ helper_agents: { id: string; name?: string; avatarUrl?: string | null }[];+ status: string;+ task_count: number;+ started_at: string;+ completed_at: string | null;+ channel: string;+}++export interface TraceTask {+ id: string;+ agent_id: string;+ agent: { name: string; email_handle: string | null; avatarUrl: string | null } | null;+ parent_task_id: string | null;+ prompt: string;+ status: string;+ type: string;+ conversation_id: string;+ created_at: string;+ completed_at: string | null;+}++export const listTraces = (+ workspaceId: string,+ opts?: { status?: string; limit?: number; before?: string; multiAgent?: boolean; agentId?: string; channel?: string }+) => {+ const extra: Record<string, string> = {};+ if (opts?.limit) extra.limit = String(opts.limit);+ if (opts?.before) extra.before = opts.before;+ if (opts?.status) extra.status = opts.status;+ if (opts?.multiAgent) extra.multiAgent = "true";+ if (opts?.agentId) extra.agentId = opts.agentId;+ if (opts?.channel) extra.channel = opts.channel;+ return apiFetch<{ traces: TraceListItem[]; has_more: boolean }>(+ `/api/traces${wsQuery(workspaceId, extra)}`+ );+};++export const getTrace = (traceId: string, workspaceId: string) =>+ apiFetch<{ trace_id: string; channel: string; tasks: TraceTask[] }>(+ `/api/traces/${traceId}${wsQuery(workspaceId)}`+ );diff --git a/src/web/src/lib/api/workspaces.ts b/src/web/src/lib/api/workspaces.tsnew file mode 100644index 000000000..1d38e88a2--- /dev/null+++ b/src/web/src/lib/api/workspaces.ts@@ -0,0 +1,131 @@+import type { LoginResponse, Workspace } from "@alook/shared";+import { apiFetch, wsQuery } from "./client";++export const listWorkspaces = () => apiFetch<Workspace[]>("/api/workspaces");++export const createWorkspace = (name: string, slug?: string) =>+ apiFetch<Workspace>("/api/workspaces", {+ method: "POST",+ body: JSON.stringify({ name, slug: slug || name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "workspace" }),+ });++export const updateWorkspace = (workspaceId: string, data: { name?: string; slug?: string }) =>+ apiFetch<Workspace>(`/api/workspaces/${workspaceId}${wsQuery(workspaceId)}`, { method: "PATCH", body: JSON.stringify(data) });++export const deleteWorkspace = (workspaceId: string, confirmName: string) =>+ apiFetch<void>(`/api/workspaces/${workspaceId}${wsQuery(workspaceId)}`, { method: "DELETE", body: JSON.stringify({ confirm_name: confirmName }) });++// Members+export interface MemberEntry {+ id: string; user_id: string; role: string; name: string; email: string; image: string | null; created_at: string;+}++export const listMembers = (workspaceId: string) =>+ apiFetch<MemberEntry[]>(`/api/workspaces/${workspaceId}/members${wsQuery(workspaceId)}`);++export const removeMember = (workspaceId: string, memberId: string) =>+ apiFetch<void>(`/api/workspaces/${workspaceId}/members/${memberId}${wsQuery(workspaceId)}`, { method: "DELETE" });++export const getMemberMe = (workspaceId: string) =>+ apiFetch<{ global_instruction: string }>(`/api/members/me${wsQuery(workspaceId)}`);++export const updateMemberMe = (workspaceId: string, globalInstruction: string) =>+ apiFetch<{ global_instruction: string }>(`/api/members/me${wsQuery(workspaceId)}`, {+ method: "PATCH",+ body: JSON.stringify({ global_instruction: globalInstruction }),+ });++// Invites+export interface InviteEntry {+ id: string; token: string; expires_at: string; created_at: string;+}++export const listInvites = (workspaceId: string) =>+ apiFetch<InviteEntry[]>(`/api/workspaces/${workspaceId}/invites${wsQuery(workspaceId)}`);++export const createInvite = (workspaceId: string) =>+ apiFetch<InviteEntry>(`/api/workspaces/${workspaceId}/invites${wsQuery(workspaceId)}`, { method: "POST" });++export const revokeInvite = (workspaceId: string, inviteId: string) =>+ apiFetch<void>(`/api/workspaces/${workspaceId}/invites/${inviteId}${wsQuery(workspaceId)}`, { method: "DELETE" });++// Invite accept+export interface InviteInfo {+ workspace_name: string; workspace_id: string; invited_by: string;+}++export interface InviteAcceptResult {+ workspace_id: string; workspace_slug: string;+}++export const getInviteInfo = (token: string) => apiFetch<InviteInfo>(`/api/invite/${token}`);+export const acceptInvite = (token: string) => apiFetch<InviteAcceptResult>(`/api/invite/${token}`, { method: "POST" });++// Overview+export interface OverviewEmailAccount {+ id: string;+ agent_id: string;+ email_address: string;+ status: string;+ error_message: string;+ last_synced_at: string | null;+}++export interface OverviewRecentTask {+ id: string;+ agent_id: string;+ type: string;+ status: string;+ prompt: string;+ created_at: string;+ completed_at: string | null;+ error: string | null;+}++export interface OverviewCalendarEvent {+ id: string;+ agent_id: string;+ title: string;+ description: string | null;+ scheduled_at: string;+ repeat_interval: string | null;+ repeat_stop_at: string | null;+ last_triggered_at: string | null;+}++export interface OverviewMember {+ id: string;+ user_id: string;+ role: string;+ name: string;+ email: string;+ image: string | null;+ created_at: string;+}++export interface WorkspaceOverview {+ email_stats: { inbound: number; outbound: number; unread: number; rejected: number };+ email_accounts: OverviewEmailAccount[];+ task_stats: { completed: number; failed: number; cancelled: number; queued: number; stale: number };+ recent_tasks: OverviewRecentTask[];+ conversation_counts: Record<string, number>;+ members: OverviewMember[];+ pending_invites: number;+ calendar_events: OverviewCalendarEvent[];+}++export const getWorkspaceOverview = (workspaceId: string) =>+ apiFetch<WorkspaceOverview>(`/api/workspaces/${workspaceId}/overview${wsQuery(workspaceId)}`);++// Auth+export const signOut = async () => {+ if (typeof window !== "undefined") {+ window.location.href = "/sign-in";+ }+};++export const verifyCode = (email: string, code: string) =>+ apiFetch<LoginResponse>("/api/auth/sign-in/email", {+ method: "POST",+ body: JSON.stringify({ email, otp: code }),+ });diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.tsindex 6643c2138..81602ad8b 100644--- a/src/web/src/lib/middleware/auth.ts+++ b/src/web/src/lib/middleware/auth.ts@@ -6,6 +6,7 @@ import { createAuth } from "@/lib/auth"import { cached, cacheKeys, bindCacheKV, throttled } from "@/lib/cache"export interface AuthContext {+ env: EnvuserId: stringemail: stringworkspaceId?: string@@ -51,6 +52,7 @@ export function withAuth(handler: AuthenticatedHandler) {() => queries.machineToken.updateMachineTokenLastUsed(db, mt.id),).catch(() => {});const authCtx: AuthContext = {+ env: cloudflareEnv,userId: mt.userId,email: mt.userEmail,workspaceId: mt.workspaceId ?? undefined,@@ -88,6 +90,7 @@ export function withAuth(handler: AuthenticatedHandler) {}const authCtx: AuthContext = {+ env: cloudflareEnv,userId: sessionResult.response.user.id,email: sessionResult.response.user.email,}diff --git a/src/web/src/lib/middleware/env.ts b/src/web/src/lib/middleware/env.tsnew file mode 100644index 000000000..4db6ffce0--- /dev/null+++ b/src/web/src/lib/middleware/env.ts@@ -0,0 +1,29 @@+import { NextRequest, NextResponse } from "next/server"+import { getCloudflareContext } from "@opennextjs/cloudflare"++interface EnvContext {+ env: Env+ params?: Record<string, string | string[]>+}++export type EnvHandler = (+ req: NextRequest,+ ctx: EnvContext+) => Promise<NextResponse | Response>++export function withEnv(handler: EnvHandler) {+ return async (+ req: NextRequest,+ context?: { params?: Promise<Record<string, string | string[]>> | Record<string, string | string[]> }+ ) => {+ const resolvedParams = context?.params+ ? context.params instanceof Promise+ ? await context.params+ : context.params+ : undefined++ const { env } = await getCloudflareContext({ async: true })++ return handler(req, { env: env as Env, params: resolvedParams })+ }+}