Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

8.0 KB
Raw Blame
import { Hono } from 'hono';

import { agentAccountDigestFlush } from './handlers/agentAccountDigestFlush';
import { agentAccountWebhook, agentAccountWebhookBodyLimit } from './handlers/agentAccountWebhook';
import { agentInboxReport } from './handlers/agentInboxReport';
import { botCallback } from './handlers/botCallback';
import { botReplay } from './handlers/botReplay';
import { botWakeFlush } from './handlers/botWakeFlush';
import { channelAdvance, channelCallback, channelWatchReport } from './handlers/channel';
import { deviceToolCompletion } from './handlers/deviceToolCompletion';
import {
  documentAccess,
  documentProjection,
  documentRoomStatus,
  documentSeed,
} from './handlers/documentCollab';
import { execAgent } from './handlers/execAgent';
import { finalizeAbandoned } from './handlers/finalizeAbandoned';
import { gatewayCallback } from './handlers/gatewayCallback';
import { gatewayCron } from './handlers/gatewayCron';
import { gatewayDesiredConnections } from './handlers/gatewayDesiredConnections';
import { gatewayStart } from './handlers/gatewayStart';
import { groupMemberCallback } from './handlers/groupMemberCallback';
import { inboundWebhookReport } from './handlers/inboundWebhookReport';
import { llmRelayChunks, llmRelayPayload } from './handlers/llmRelay';
import { messengerInstall } from './handlers/messengerInstall';
import { messengerOAuthCallback } from './handlers/messengerOAuthCallback';
import { messengerWebhook } from './handlers/messengerWebhook';
import { platformWebhook } from './handlers/platformWebhook';
import { reapOperations } from './handlers/reapOperations';
import { runStep, runStepHealth } from './handlers/runStep';
import { shellExpire } from './handlers/shellExpire';
import { subAgentCallback } from './handlers/subAgentCallback';
import { toolResult } from './handlers/toolResult';
import { bearerSecretAuth } from './middlewares/bearerSecretAuth';
import { deviceGatewayServiceAuth } from './middlewares/deviceGatewayServiceAuth';
import { qstashAuth } from './middlewares/qstashAuth';
import { qstashOrApiKeyAuth } from './middlewares/qstashOrApiKeyAuth';
import { serviceTokenAuth } from './middlewares/serviceTokenAuth';

/**
 * Hono app for `/api/agent/*` endpoints. Mounted via the Next.js optional
 * catch-all at `src/app/(backend)/api/agent/[[...route]]/route.ts`.
 *
 * Routing precedence: existing static `route.ts` files win over the catch-all,
 * so individual paths can migrate one at a time β€” delete the static `route.ts`
 * and add the corresponding handler here.
 */
const app = new Hono().basePath('/api/agent');

// POST /api/agent β€” start a new agent operation (QStash sig OR API key)
app.post('/', qstashOrApiKeyAuth(), execAgent);

// POST /api/agent/run β€” execute a single step (QStash signature)
app.post('/run', qstashAuth(), runStep);
app.get('/run', runStepHealth);

app.post('/channel/advance', qstashAuth(), channelAdvance);
app.post('/channel/watch-report', qstashAuth(), channelWatchReport);
app.post('/webhooks/channel-callback', qstashAuth(), channelCallback);

// POST /api/agent/webhooks/inbox-report β€” a mail-woken run finished: post its answer to the
// owner's direct Channel (QStash)
app.post('/webhooks/inbox-report', qstashAuth(), agentInboxReport);

// POST /api/agent/webhooks/inbound-webhook-report β€” a webhook-woken run finished: post its answer
// to the Channel or Thread the webhook delivers to (QStash)
app.post('/webhooks/inbound-webhook-report', qstashAuth(), inboundWebhookReport);

// POST /api/agent/tool-result β€” gateway-side tool result LPUSH'd to Redis
app.post('/tool-result', serviceTokenAuth(), toolResult);

// POST /api/agent/device-tool-completion β€” device gateway relays the final
// result of a device command that a parked operation is waiting on
app.post('/device-tool-completion', deviceGatewayServiceAuth(), deviceToolCompletion);

// POST /api/agent/shell-expire β€” deadline for a parked shell command (QStash)
app.post('/shell-expire', qstashAuth(), shellExpire);

// LLM relay: the user's device runs one LLM attempt for a device-only model
// provider. Auth is the per-call lease token carried by `llm_execute`.
// GET  /api/agent/llm-relay/:callId/payload β€” request body of the attempt
app.get('/llm-relay/:callId/payload', llmRelayPayload);
// POST /api/agent/llm-relay/:callId/chunks β€” one batch of protocol chunks
app.post('/llm-relay/:callId/chunks', llmRelayChunks);
app.get('/document-access', serviceTokenAuth(), documentAccess);
app.post('/document-projection', serviceTokenAuth(), documentProjection);
app.post('/document-seed', serviceTokenAuth(), documentSeed);
app.get('/document-room-status', serviceTokenAuth(), documentRoomStatus);

// POST /api/agent/finalize-abandoned β€” watchdog reverse-trigger finalize
app.post('/finalize-abandoned', serviceTokenAuth(), finalizeAbandoned);
app.get('/finalize-abandoned', (c) =>
  c.json({
    healthy: true,
    message: 'Agent finalize-abandoned endpoint is running',
    timestamp: new Date().toISOString(),
  }),
);

// GET /api/agent/gateway β€” Vercel cron entry point (Bearer CRON_SECRET)
app.get(
  '/gateway',
  bearerSecretAuth(() => process.env.CRON_SECRET),
  gatewayCron,
);

// GET /api/agent/reap-operations β€” Vercel cron entry point (Bearer CRON_SECRET)
app.get(
  '/reap-operations',
  bearerSecretAuth(() => process.env.CRON_SECRET),
  reapOperations,
);

// POST /api/agent/gateway/start β€” non-Vercel ensureRunning (Bearer KEY_VAULTS_SECRET)
app.post(
  '/gateway/start',
  bearerSecretAuth(() => {
    const activeSecret = process.env.KEY_VAULTS_SECRET;
    return activeSecret?.trim()
      ? [activeSecret, process.env.KEY_VAULTS_FALLBACK_SECRET]
      : undefined;
  }),
  gatewayStart,
);

// POST /api/agent/gateway/callback β€” message gateway state-change callbacks
// (auth is inline so the disabled-feature 204 short-circuits before auth)
app.post('/gateway/callback', gatewayCallback);

// POST /api/agent/gateway/desired-connections β€” a gateway pulls the connect
// payloads it should hold, so it can rebuild itself after a restart.
// (auth is inline for the same reason as the callback above)
app.post('/gateway/desired-connections', gatewayDesiredConnections);

// POST /api/agent/webhooks/bot-callback β€” agent step/completion webhooks (QStash)
app.post('/webhooks/bot-callback', qstashAuth(), botCallback);

// Replay retries carry no completion response and require the queue signature.
app.post('/webhooks/bot-replay', qstashAuth(), botReplay);

// POST /api/agent/webhooks/bot-wake-flush β€” delayed flush of the bot-wake channel scheduler (QStash)
app.post('/webhooks/bot-wake-flush', qstashAuth(), botWakeFlush);

// POST /api/agent/webhooks/subagent-callback β€” sub-agent completion bridge (QStash)
app.post('/webhooks/subagent-callback', qstashAuth(), subAgentCallback);

// POST /api/agent/webhooks/group-member-callback β€” group-action member bridge (QStash)
app.post('/webhooks/group-member-callback', qstashAuth(), groupMemberCallback);

// POST /api/agent/webhooks/:platform[/:appId] β€” Chat SDK bot platform webhooks
app.post('/webhooks/:platform/:appId?', platformWebhook);

// POST /api/agent/accounts/webhooks/:provider β€” inbound mail deliveries
// for the agent's own accounts. Auth is the provider signature, verified inside
// the handler, so the only middleware is a body cap that runs before anything
// is buffered.
app.post('/accounts/webhooks/:provider', agentAccountWebhookBodyLimit, agentAccountWebhook);

// POST /api/agent/accounts/digest-flush β€” delayed run of the mail held for one
// account's digest (QStash)
app.post('/accounts/digest-flush', qstashAuth(), agentAccountDigestFlush);

// GET /api/agent/messenger/:platform/install β€” start per-tenant OAuth install
app.get('/messenger/:platform/install', messengerInstall);

// GET /api/agent/messenger/:platform/oauth/callback β€” OAuth redirect target
app.get('/messenger/:platform/oauth/callback', messengerOAuthCallback);

// POST /api/agent/messenger/webhooks/:platform β€” shared Messenger bot webhook
app.post('/messenger/webhooks/:platform', messengerWebhook);

export default app;