Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

refactor(api): restructure the api into feature modules (part 1) (#138)

Croff4aff469e1ac0
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md
index 1a8ef6db..19ba804a 100644
--- a/apps/api/AGENTS.md
+++ b/apps/api/AGENTS.md
@@ -5,25 +5,43 @@ Rules and invariants for this package below; read the code for the walkthrough.
## Structure
-- Feature-based: one folder per domain = `routes.ts` (controller) + `store.ts`
- (Drizzle service). Cross-cutting code in `shared/`. See `src/` for the current set.
-- `app.ts` assembles and exports the app (`export const app`, no `.listen()`);
- `index.ts` only binds the port. `export type App = typeof app` types the Eden Treaty
- client (web + tests).
-- `routes.ts`: `new Elysia({ name: "<feature>", detail: { tags: ["<Tag>"] } })` —
- routes chained directly on it, input validated with `t`, each route sets
- `detail.summary`.
-- `store.ts`: plain async functions, no Elysia/HTTP types, returns DTOs never rows.
+- Feature-based: one folder per domain under `src/modules/`, three files —
+ `index.ts` (controller), `model.ts` (schemas), `service.ts` (Drizzle). Cross-cutting
+ code in `shared/`. See `src/modules/` for the current set.
+- Features nest one level deeper only where they already call each other:
+ `modules/agents/{core,schedules,skills,tools}`, where `core` holds the agent itself
+ and its runtime. A feature whose links to its neighbours run one way stays flat. A
+ schema several of the nested features share sits in the parent's `model.ts` and is
+ re-exported from each child's (`agentParams`).
+- `src/app.ts` assembles and exports the app (`export const app`, no `.listen()`);
+ `src/index.ts` only binds the port. `export type App = typeof app` types the Eden
+ Treaty client (web + tests).
+- `index.ts`: `new Elysia({ name: "<feature>", detail: { tags: ["<Tag>"] } })` —
+ routes chained directly on it, each route sets `detail.summary`. Handlers only;
+ the schemas they reference come from `model.ts`.
+- `model.ts`: the `t` schemas of the feature's requests and responses. An update body
+ is `t.Partial(<create body>)` where it accepts the same fields.
+- `service.ts`: plain async functions, no Elysia/HTTP types, returns DTOs never rows.
+- The features still sitting in `src/<feature>/` as `routes.ts` + `store.ts` predate
+ this layout. Move one to `src/modules/` when you next change it; do not add a new
+ feature in the old shape.
+- Imports inside a module are relative (`./model`); everything it reaches outside
+ itself goes through the subpath aliases in `apps/api/package.json` — `#shared/*`,
+ `#mcp/*`, `#modules/*`, `#tests/*`. They map to a `.ts` file (`"#shared/*":
+"./src/shared/*.ts"`), which is what makes both `tsc` and Bun resolve them, and they
+ resolve against the api's own `package.json`, so they hold in the Docker image where
+ the process starts from the repo root. A tsconfig `paths` alias would not: there is
+ no tsconfig.json at that root.
## Adding a route
- Chain on the same instance — never reassign to an intermediate `const` (breaks
Elysia type inference and `type App`).
-- Validate all input with `t`. Numeric path ids use `t.Numeric()`; never
- `Number(params.x)` in the handler.
+- Validate all input with `t`, from a schema declared in the feature's `model.ts`.
+ Numeric path ids use `t.Numeric()`; never `Number(params.x)` in the handler.
- Enforce access with a guard in the route options, never an imperative call in the
handler (see Auth and access).
-- Throw `HttpError` for failures; return the store DTO on success; `noContent()` for a
+- Throw `HttpError` for failures; return the service DTO on success; `noContent()` for a
delete with no body; `set.status = 201` on create.
- New feature: `.use()` it in `planner.ts` and register its tag in the swagger
`documentation.tags` list in `app.ts`.
@@ -35,6 +53,12 @@ Rules and invariants for this package below; read the code for the walkthrough.
- Unique violation: wrap the insert in `rethrowDuplicate(err, "<what>")` → 409.
- `onError` also maps `t`-schema rejection → 400, `NOT_FOUND` → 404, anything else →
500 logged with `[planner]`.
+- A route declares the statuses it can fail with by spreading a map from
+ `shared/responses.ts` into its `response`: `accessErrors` (401/403/404) for a
+ guarded read, `commonErrors` (+400) where it also validates input, `errors(...)` for
+ anything else (`{ ...commonErrors, ...errors(409) }`). Listing the codes per route is
+ what puts them in the OpenAPI docs — a `guard({ schema: "standalone", response })`
+ on the feature passes typecheck but drops them from the spec.
## Data invariants
diff --git a/apps/api/package.json b/apps/api/package.json
index ed2c88d2..21107d82 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -3,6 +3,12 @@
"version": "1.0.0",
"private": true,
"type": "module",
+ "imports": {
+ "#shared/*": "./src/shared/*.ts",
+ "#mcp/*": "./src/mcp/*.ts",
+ "#modules/*": "./src/modules/*.ts",
+ "#tests/*": "./src/__tests__/*.ts"
+ },
"scripts": {
"dev": "bun --env-file=../../.env run --watch src/index.ts",
"start": "bun run src/index.ts",
diff --git a/apps/api/src/analytics/routes.ts b/apps/api/src/analytics/routes.ts
deleted file mode 100644
index 0f618edd..00000000
--- a/apps/api/src/analytics/routes.ts
+++ /dev/null
@@ -1,390 +0,0 @@
-import { Elysia, t } from 'elysia';
-import { guards } from '../shared/guards';
-import { mcpTool } from '../mcp/generate';
-import { ErrorResponse } from '../shared/responses';
-import {
- getStats,
- getBreakdown,
- getPulse,
- getThroughput,
- listActivity,
- listAgentRunFeed,
- getAgentRunStats,
- getWebhookStats,
- getAgentWorkload,
- type ActivityCursor,
-} from './store';
-
-// Issue count stats (StatsDto from the store).
-const StatsDto = t.Object({
- open: t.Number(),
- inProgress: t.Number(),
- backlog: t.Number(),
- overdue: t.Number(),
- unassigned: t.Number(),
- closedLast7d: t.Number(),
-});
-
-// One breakdown bucket (BreakdownItem from the store).
-const BreakdownItem = t.Object({
- key: t.String(),
- label: t.String(),
- count: t.Number(),
- color: t.Nullable(t.String()),
-});
-
-// One pulse heatmap cell (PulseBucket from the store).
-const PulseBucket = t.Object({
- label: t.String(),
- count: t.Number(),
-});
-
-// One throughput week (ThroughputWeek from the store).
-const ThroughputWeek = t.Object({
- week: t.String(),
- created: t.Number(),
- closed: t.Number(),
-});
-
-// One activity feed entry (ActivityItem from the store).
-const ActivityItem = t.Object({
- id: t.Number(),
- issueId: t.Number(),
- issueSequence: t.Number(),
- issueTitle: t.String(),
- kind: t.String(),
- actorUserId: t.Nullable(t.String()),
- actorName: t.Nullable(t.String()),
- body: t.Nullable(t.String()),
- action: t.Nullable(t.String()),
- subject: t.Nullable(t.String()),
- fromText: t.Nullable(t.String()),
- toText: t.Nullable(t.String()),
- createdAt: t.String(),
-});
-
-// The keyset cursor for the next activity page (ActivityCursor from the store).
-const ActivityCursorDto = t.Object({
- ts: t.String(),
- id: t.Number(),
-});
-
-// One page of the activity feed (ActivityPage from the store).
-const ActivityPage = t.Object({
- items: t.Array(ActivityItem),
- nextCursor: t.Nullable(ActivityCursorDto),
-});
-
-// One agent run in the project-wide feed (AgentRunFeedItem from the store).
-const AgentRunFeedItem = t.Object({
- id: t.Number(),
- status: t.String(),
- trigger: t.Union([
- t.Literal('mention'),
- t.Literal('delegation'),
- t.Literal('schedule'),
- t.Literal('manual'),
- ]),
- agentId: t.Number(),
- agentName: t.String(),
- issueId: t.Nullable(t.Number()),
- issueSequence: t.Nullable(t.Number()),
- lastError: t.Nullable(t.String()),
- createdAt: t.String(),
-});
-
-// Agent run outcome counts over a window (AgentRunStatsDto from the store).
-const AgentRunStatsDto = t.Object({
- total: t.Number(),
- success: t.Number(),
- failed: t.Number(),
- pending: t.Number(),
-});
-
-// Webhook delivery health (WebhookStatsDto from the store).
-const WebhookStatsDto = t.Object({
- total: t.Number(),
- success: t.Number(),
- failed: t.Number(),
- pending: t.Number(),
- activeWebhooks: t.Number(),
- disabledWebhooks: t.Number(),
-});
-
-// One agent's workload row (AgentWorkloadItem from the store).
-const AgentWorkloadItem = t.Object({
- agentId: t.Number(),
- agentName: t.String(),
- kind: t.String(),
- delegatedOpen: t.Number(),
- runsTotal: t.Number(),
- runsSuccess: t.Number(),
- runsFailed: t.Number(),
-});
-
-// Read-only project analytics that back the dashboard widgets. Every route is
-// under /projects/:projectKey/analytics and gated by the dashboards read
-// permission (the analytics feed the dashboards). All figures come from existing
-// tables; see store.ts.
-export const analyticsRoutes = new Elysia({
- name: 'analytics',
- detail: { tags: ['Analytics'] },
-})
- .use(guards)
- .get(
- '/projects/:projectKey/analytics/stats',
- async ({ project }) => {
- return getStats(project.id);
- },
- {
- permission: ['dashboards', 'read'],
- response: {
- 200: StatsDto,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Get project stats',
- description: 'Issue counts by state (open, in progress, overdue, and more).',
- ...mcpTool('get_project_stats'),
- },
- },
- )
-
- .get(
- '/projects/:projectKey/analytics/breakdown',
- async ({ project, query }) => {
- return getBreakdown(project.id, query.by);
- },
- {
- query: t.Object({
- by: t.Union([
- t.Literal('status'),
- t.Literal('priority'),
- t.Literal('type'),
- t.Literal('assignee'),
- t.Literal('delegate'),
- ]),
- }),
- permission: ['dashboards', 'read'],
- response: {
- 200: t.Array(BreakdownItem),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Get project breakdown',
- description: 'Issue counts grouped by a chosen dimension.',
- ...mcpTool('get_project_breakdown'),
- },
- },
- )
-
- .get(
- '/projects/:projectKey/analytics/pulse',
- async ({ project, query }) => {
- const unit = query.unit ?? 'day';
- // Cap columns so the generated bucket axis stays bounded (hour columns hold
- // 24 cells each, so their cap is lower).
- const maxColumns = unit === 'hour' ? 140 : unit === 'week' ? 130 : 160;
- const columns = query.columns != null ? Math.min(Math.max(query.columns, 1), maxColumns) : 26;
- return getPulse(project.id, unit, columns);
- },
- {
- query: t.Object({
- unit: t.Optional(t.Union([t.Literal('hour'), t.Literal('day'), t.Literal('week')])),
- columns: t.Optional(t.Numeric()),
- }),
- permission: ['dashboards', 'read'],
- response: {
- 200: t.Array(PulseBucket),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Get project pulse',
- description: 'Activity counts over time for a heatmap.',
- ...mcpTool('get_project_pulse'),
- },
- },
- )
-
- .get(
- '/projects/:projectKey/analytics/throughput',
- async ({ project, query }) => {
- const weeks = query.weeks != null ? Math.min(Math.max(query.weeks, 1), 52) : 12;
- return getThroughput(project.id, weeks);
- },
- {
- query: t.Object({ weeks: t.Optional(t.Numeric()) }),
- permission: ['dashboards', 'read'],
- response: {
- 200: t.Array(ThroughputWeek),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Get project throughput',
- description: 'Created versus closed issues over time.',
- ...mcpTool('get_project_throughput'),
- },
- },
- )
-
- .get(
- '/projects/:projectKey/analytics/activity',
- async ({ project, query }) => {
- const limit = query.limit ?? 25;
- let before: ActivityCursor | null = null;
- if (query.cursor) {
- try {
- before = JSON.parse(query.cursor);
- } catch {
- // Ignore a malformed cursor and serve the first page.
- }
- }
- const issueIds =
- query.issueIds != null
- ? query.issueIds
- .split(',')
- .map(Number)
- .filter((n) => Number.isInteger(n))
- : null;
- return listActivity(project.id, {
- before,
- limit,
- actorUserId: query.actorUserId ?? null,
- action: query.action ?? null,
- issueIds,
- });
- },
- {
- query: t.Object({
- limit: t.Optional(t.Numeric()),
- cursor: t.Optional(t.String()),
- actorUserId: t.Optional(t.String()),
- action: t.Optional(t.String()),
- // Comma-separated issue ids the client resolved from the widget's work items
- // filter; absent means no issue-scope restriction.
- issueIds: t.Optional(t.String()),
- }),
- permission: ['dashboards', 'read'],
- response: {
- 200: ActivityPage,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Get project activity',
- description: 'Project-wide feed of issue activity.',
- ...mcpTool('get_project_activity'),
- },
- },
- )
-
- .get(
- '/projects/:projectKey/analytics/agent-runs',
- async ({ project, query }) => {
- const limit = query.limit ?? 20;
- return listAgentRunFeed(project.id, { status: query.status ?? null, limit });
- },
- {
- query: t.Object({
- status: t.Optional(
- t.Union([t.Literal('pending'), t.Literal('success'), t.Literal('failed')]),
- ),
- limit: t.Optional(t.Numeric()),
- }),
- permission: ['dashboards', 'read'],
- response: {
- 200: t.Array(AgentRunFeedItem),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'List agent runs',
- description: 'Project-wide feed of agent runs.',
- ...mcpTool('list_agent_runs'),
- },
- },
- )
-
- .get(
- '/projects/:projectKey/analytics/agent-run-stats',
- async ({ project, query }) => {
- const days = query.days != null ? Math.min(Math.max(query.days, 1), 90) : 30;
- return getAgentRunStats(project.id, days);
- },
- {
- query: t.Object({ days: t.Optional(t.Numeric()) }),
- permission: ['dashboards', 'read'],
- response: {
- 200: AgentRunStatsDto,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Get agent run stats',
- description: 'Agent run outcome counts (success, failed, pending).',
- ...mcpTool('get_agent_run_stats'),
- },
- },
- )
-
- .get(
- '/projects/:projectKey/analytics/webhook-stats',
- async ({ project, query }) => {
- const days = query.days != null ? Math.min(Math.max(query.days, 1), 90) : 30;
- return getWebhookStats(project.id, days);
- },
- {
- query: t.Object({ days: t.Optional(t.Numeric()) }),
- permission: ['dashboards', 'read'],
- response: {
- 200: WebhookStatsDto,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Get webhook stats',
- description: 'Webhook delivery outcomes and active/disabled webhook counts.',
- ...mcpTool('get_webhook_stats'),
- },
- },
- )
-
- .get(
- '/projects/:projectKey/analytics/agent-workload',
- async ({ project }) => {
- return getAgentWorkload(project.id);
- },
- {
- permission: ['dashboards', 'read'],
- response: {
- 200: t.Array(AgentWorkloadItem),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Get agent workload',
- description: 'Per-agent open delegated issues and run outcomes.',
- ...mcpTool('get_agent_workload'),
- },
- },
- );
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index ddbeda42..9c7bc32e 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -12,10 +12,10 @@ import { planner } from './planner';
import { webhookTestRoutes } from './webhook-test/routes';
import { mountMcp } from './mcp/mount';
import { setMcpApp } from './mcp/app-ref';
-import { internalAgentRunRoutes } from './ai-agents/internal-routes';
+import { internalAgentRunRoutes } from './modules/agents/core/internal-routes';
import { internalNotificationRoutes } from './notifications/internal-routes';
import { internalTelegramRoutes } from './telegram/internal-routes';
-import { githubWebhookRoutes } from './github/routes';
+import { githubWebhookRoutes } from './modules/github/webhook';
// The assembled Elysia app, without `.listen()`. `index.ts` imports this and
// binds the port; tests import it and pass it to Eden Treaty to drive routes in
diff --git a/apps/api/src/avatars/routes.ts b/apps/api/src/avatars/routes.ts
deleted file mode 100644
index 05508590..00000000
--- a/apps/api/src/avatars/routes.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { Elysia, t } from 'elysia';
-import { randomUUID } from 'node:crypto';
-import { db, user } from '@repo/db';
-import { eq } from 'drizzle-orm';
-import { noContent } from '../shared/http';
-import { authContext } from '../shared/auth-context';
-import { requireUser } from '../shared/access';
-import { HttpError } from '../shared/lib';
-import { putObject, getObject, deleteObject } from '../shared/s3';
-import { ErrorResponse } from '../shared/responses';
-import { getStorageSettings, MB } from '../settings/storage';
-
-// Avatar images for the signed-in user. The bytes live in the S3-compatible
-// object store (../shared/s3.ts) under `avatars/<uuid>`; the user's `image`
-// column (managed by better-auth) holds the relative serve URL. Only image
-// types are accepted, so the public raw route can render them inline safely.
-// The size limit is an instance setting (see ../settings/storage.ts), read per
-// request so a change in god mode takes effect without a restart.
-
-// Raster image types only. SVG is excluded on purpose: it can carry script and
-// the raw route is public and same-origin, so an inline SVG would be stored XSS.
-const ALLOWED_TYPES = /^image\/(png|jpe?g|gif|webp|avif)$/i;
-
-// The relative URL stored in user.image for one of our avatars. The frontend
-// prefixes it with the API origin when rendering.
-const avatarUrl = (id: string) => `/avatars/${id}/raw`;
-
-// The object key for an avatar id (the uuid used in its URL).
-const avatarKey = (id: string) => `avatars/${id}`;
-
-// Pulls the avatar id out of a stored user.image URL, or null if it is not one
-// of our avatars (an external/OAuth image or empty). Used to delete the previous
-// object when the avatar is replaced or removed.
-function avatarIdFromImage(image: string | null | undefined): string | null {
- if (!image) return null;
- const match = image.match(/\/avatars\/([^/]+)\/raw$/);
- return match ? match[1] : null;
-}
-
-async function deletePreviousAvatar(image: string | null | undefined): Promise<void> {
- const id = avatarIdFromImage(image);
- if (!id) return;
- await deleteObject(avatarKey(id)).catch((err) => {
- console.error(
- `[planner] failed to delete previous avatar ${id}:`,
- err instanceof Error ? err.message : err,
- );
- });
-}
-
-export const avatarRoutes = new Elysia({ name: 'avatars', detail: { tags: ['Avatars'] } })
- .use(authContext)
-
- // Accepts a multipart form with a single "file" image field, stores the bytes,
- // sets the user's image to the new serve URL, and removes the previous avatar
- // object. Returns the new image URL.
- .post(
- '/me/avatar',
- async ({ user: sessionUser, body }) => {
- const current = requireUser(sessionUser);
- const file = body.file;
- if (!(file instanceof File)) throw new HttpError(400, 'No file uploaded (form field "file")');
- if (file.size === 0) throw new HttpError(400, 'Uploaded file is empty');
- const { maxAvatarMb } = await getStorageSettings();
- if (file.size > maxAvatarMb * MB) {
- throw new HttpError(413, `Image exceeds the ${maxAvatarMb} MB limit`);
- }
- const contentType = file.type || '';
- if (!ALLOWED_TYPES.test(contentType)) {
- throw new HttpError(400, 'Avatar must be a PNG, JPEG, GIF, WebP, or AVIF image');
- }
-
- const id = randomUUID();
- const bytes = Buffer.from(await file.arrayBuffer());
- try {
- await putObject(avatarKey(id), bytes, contentType);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- console.error(
- `[planner] avatar PUT failed (key=${avatarKey(id)}, size=${file.size}):`,
- err,
- );
- throw new HttpError(502, `Object store error: ${msg}`);
- }
-
- const url = avatarUrl(id);
- // Point the account at the new object first, then drop the old one (the
- // session user still carries the previous image); a failed cleanup only
- // orphans bytes.
- await db.update(user).set({ image: url }).where(eq(user.id, current.id));
- await deletePreviousAvatar(sessionUser?.image);
-
- return { image: url };
- },
- {
- body: t.Object({ file: t.File() }),
- response: {
- 200: t.Object({ image: t.String() }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 413: ErrorResponse,
- 502: ErrorResponse,
- },
- detail: { summary: "Upload the current user's avatar" },
- },
- )
-
- // Clears the user's avatar and removes the stored object.
- .delete(
- '/me/avatar',
- async ({ user: sessionUser }) => {
- const current = requireUser(sessionUser);
- await db.update(user).set({ image: null }).where(eq(user.id, current.id));
- await deletePreviousAvatar(sessionUser?.image);
- return noContent();
- },
- {
- response: {
- 204: t.Void(),
- 401: ErrorResponse,
- },
- detail: { summary: "Remove the current user's avatar" },
- },
- )
-
- // Public preview URL: unauthenticated so it works in an <img> tag. The id is an
- // unguessable uuid. Only raster image types are stored, and nosniff plus the
- // media allowlist keep the bytes from being interpreted as anything executable.
- .get(
- '/avatars/:id/raw',
- async ({ params }) => {
- let obj;
- try {
- obj = await getObject(avatarKey(params.id));
- } catch (err) {
- throw new HttpError(404, err instanceof Error ? err.message : 'Object not found');
- }
- const ct = /^image\//i.test(obj.contentType) ? obj.contentType : 'application/octet-stream';
- const headers: Record<string, string> = {
- 'Content-Type': ct,
- 'X-Content-Type-Options': 'nosniff',
- 'Cache-Control': 'public, max-age=31536000, immutable',
- };
- if (obj.contentLength != null) headers['Content-Length'] = String(obj.contentLength);
- return new Response(obj.body, { headers });
- },
- {
- params: t.Object({ id: t.String() }),
- // Public route: no 401/403. Returns raw bytes, so no typed 200 body.
- response: { 404: ErrorResponse },
- detail: { summary: "Preview a user's avatar (public, no auth)" },
- },
- );
diff --git a/apps/api/src/columns/routes.ts b/apps/api/src/columns/routes.ts
deleted file mode 100644
index 6bc9a432..00000000
--- a/apps/api/src/columns/routes.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { Elysia, t } from 'elysia';
-import { mcpTool } from '../mcp/generate';
-import { noContent } from '../shared/http';
-import { authContext } from '../shared/auth-context';
-import { guards } from '../shared/guards';
-import { requireUser } from '../shared/access';
-import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
-import { listColumns, createColumn, updateColumn, reorderColumns, deleteColumn } from './store';
-
-const stateType = t.Union([
- t.Literal('backlog'),
- t.Literal('unstarted'),
- t.Literal('started'),
- t.Literal('completed'),
- t.Literal('canceled'),
-]);
-
-const columnParams = t.Object({ projectKey: t.String(), columnId: t.Numeric() });
-
-// A column DTO (ColumnRow from the store).
-const ColumnResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- name: t.String(),
- stateType: t.String(),
- color: t.String(),
- position: t.Number(),
-});
-
-export const columnRoutes = new Elysia({ name: 'columns', detail: { tags: ['Columns'] } })
- .use(authContext)
- .use(guards)
- .post(
- '/projects/:projectKey/columns',
- async ({ project, body, set }) => {
- set.status = 201;
- return createColumn({ projectId: project.id, ...body });
- },
- {
- body: t.Object({
- name: t.String({ minLength: 1 }),
- stateType,
- color: t.Optional(t.String()),
- }),
- permission: ['states', 'create'],
- response: {
- 201: ColumnResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Create a column',
- description:
- 'Create a column (workflow state). stateType is one of ' +
- 'backlog/unstarted/started/completed/canceled.',
- ...mcpTool('create_column'),
- },
- },
- )
-
- // Reorders the project's columns. Body carries the full desired left-to-right
- // order of column ids; the store renumbers positions to match.
- .put(
- '/projects/:projectKey/columns/reorder',
- async ({ project, body }) => {
- await reorderColumns(project.id, body.orderedIds);
- return listColumns(project.id);
- },
- {
- body: t.Object({ orderedIds: t.Array(t.Integer(), { minItems: 1 }) }),
- permission: ['states', 'edit'],
- response: {
- 200: t.Array(ColumnResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Reorder columns',
- description:
- "Reorder a project's columns. orderedIds is the full left-to-right list of " +
- 'column ids. Returns the reordered columns.',
- ...mcpTool('reorder_columns'),
- },
- },
- )
-
- .patch(
- '/projects/:projectKey/columns/:columnId',
- async ({ params, project, body }) => {
- const column = await updateColumn(params.columnId, project.id, body);
- if (!column) throw new HttpError(404, 'Column not found');
- return column;
- },
- {
- body: t.Object({
- name: t.Optional(t.String({ minLength: 1 })),
- stateType: t.Optional(stateType),
- color: t.Optional(t.String()),
- }),
- params: columnParams,
- permission: ['states', 'edit'],
- response: {
- 200: ColumnResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Update a column',
- description: "Update a column's name, stateType, or color.",
- ...mcpTool('update_column'),
- },
- },
- )
-
- // Deletes a column. Body picks what happens to its issues: mode 'move' reassigns
- // them to targetColumnId, mode 'delete' removes them. Backlog columns are
- // rejected by the store layer.
- .delete(
- '/projects/:projectKey/columns/:columnId',
- async ({ params, project, body, user }) => {
- await deleteColumn(params.columnId, project.id, body, requireUser(user).id);
- return noContent();
- },
- {
- body: t.Union([
- t.Object({ mode: t.Literal('move'), targetColumnId: t.Integer() }),
- t.Object({ mode: t.Literal('delete') }),
- ]),
- params: columnParams,
- permission: ['states', 'delete'],
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Delete a column',
- description:
- "Delete a column. Body mode 'move' reassigns its issues to targetColumnId, " +
- "'delete' removes them. Backlog columns cannot be deleted.",
- ...mcpTool('delete_column'),
- },
- },
- );
diff --git a/apps/api/src/custom-fields/routes.ts b/apps/api/src/custom-fields/routes.ts
deleted file mode 100644
index 60c11407..00000000
--- a/apps/api/src/custom-fields/routes.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import { Elysia, t } from 'elysia';
-import { noContent } from '../shared/http';
-import { guards } from '../shared/guards';
-import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
-import { mcpTool } from '../mcp/generate';
-import { listCustomFields, createCustomField, updateCustomField, deleteCustomField } from './store';
-import { getIssueTypeById } from '../issue-types/store';
-
-const fieldType = t.Union([
- t.Literal('text'),
- t.Literal('markdown'),
- t.Literal('url'),
- t.Literal('number'),
- t.Literal('boolean'),
- t.Literal('date'),
- t.Literal('select'),
- t.Literal('multi_select'),
-]);
-
-const fieldParams = t.Object({ projectKey: t.String(), fieldId: t.Numeric() });
-
-// A field option DTO (CustomFieldOptionRow from the store).
-const CustomFieldOptionResponse = t.Object({
- id: t.Number(),
- value: t.String(),
- color: t.String(),
- position: t.Number(),
-});
-
-// A custom field DTO (CustomFieldRow from the store).
-const CustomFieldResponse = t.Object({
- id: t.Number(),
- issueTypeId: t.Nullable(t.Number()),
- name: t.String(),
- fieldType,
- showInBody: t.Boolean(),
- position: t.Number(),
- options: t.Array(CustomFieldOptionResponse),
-});
-
-export const customFieldRoutes = new Elysia({
- name: 'custom-fields',
- detail: { tags: ['Custom Fields'] },
-})
- .use(guards)
- // issueTypeId query param includes that type's own fields alongside the
- // project-wide ones; omitting it returns only the project-wide fields.
- .get(
- '/projects/:projectKey/custom-fields',
- async ({ project, query }) => {
- return listCustomFields(project.id, { issueTypeId: query.issueTypeId });
- },
- {
- params: t.Object({ projectKey: t.String() }),
- query: t.Object({ issueTypeId: t.Optional(t.Numeric()) }),
- permission: ['custom_fields', 'read'],
- response: {
- 200: t.Array(CustomFieldResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: "List a project's custom fields",
- description: "List a project's custom fields.",
- ...mcpTool('list_custom_fields'),
- },
- },
- )
-
- .post(
- '/projects/:projectKey/custom-fields',
- async ({ project, body, set }) => {
- // A type-scoped field must target an issue type of this project.
- if (body.issueTypeId != null) {
- const type = await getIssueTypeById(body.issueTypeId);
- if (!type || type.projectId !== project.id) {
- throw new HttpError(400, 'issueTypeId does not belong to this project');
- }
- }
- set.status = 201;
- return createCustomField({ projectId: project.id, ...body });
- },
- {
- params: t.Object({ projectKey: t.String() }),
- body: t.Object({
- issueTypeId: t.Optional(t.Nullable(t.Integer())),
- name: t.String({ minLength: 1 }),
- fieldType,
- showInBody: t.Optional(t.Boolean()),
- options: t.Optional(t.Array(t.String({ minLength: 1 }))),
- }),
- permission: ['custom_fields', 'create'],
- response: {
- 201: CustomFieldResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Create a custom field',
- description: 'Create a custom field for a project.',
- ...mcpTool('create_custom_field'),
- },
- },
- )
-
- .patch(
- '/projects/:projectKey/custom-fields/:fieldId',
- async ({ project, params, body }) => {
- const field = await updateCustomField(project.id, params.fieldId, body);
- if (!field) throw new HttpError(404, 'Custom field not found');
- return field;
- },
- {
- body: t.Object({
- name: t.Optional(t.String({ minLength: 1 })),
- showInBody: t.Optional(t.Boolean()),
- }),
- params: fieldParams,
- permission: ['custom_fields', 'edit'],
- response: {
- 200: CustomFieldResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Update a custom field',
- description: 'Update a custom field.',
- ...mcpTool('update_custom_field'),
- },
- },
- )
-
- .delete(
- '/projects/:projectKey/custom-fields/:fieldId',
- async ({ project, params }) => {
- const deleted = await deleteCustomField(project.id, params.fieldId);
- if (!deleted) throw new HttpError(404, 'Custom field not found');
- return noContent();
- },
- {
- params: fieldParams,
- permission: ['custom_fields', 'delete'],
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Delete a custom field',
- description: 'Delete a custom field.',
- ...mcpTool('delete_custom_field'),
- },
- },
- );
diff --git a/apps/api/src/god/routes.ts b/apps/api/src/god/routes.ts
index b5ad2800..b60c3ce7 100644
--- a/apps/api/src/god/routes.ts
+++ b/apps/api/src/god/routes.ts
@@ -13,7 +13,7 @@ import {
import { authContext } from '../shared/auth-context';
import { requireGod } from '../shared/access';
import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
+import { accessErrors, commonErrors, errors } from '../shared/responses';
import { noContent } from '../shared/http';
import { deleteProject } from '../projects/store';
import {
@@ -221,7 +221,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
hasEmailProvider: await hasConfiguredEmailProvider(),
}),
{
- response: { 200: AuthSettingsResponse, 401: ErrorResponse, 403: ErrorResponse },
+ response: { 200: AuthSettingsResponse, ...errors(401, 403) },
detail: {
summary: 'Get authentication settings',
description: 'Get the instance registration mode and email-dependent auth options.',
@@ -243,12 +243,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
},
{
body: AuthSettingsBody,
- response: {
- 200: AuthSettingsResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- },
+ response: { 200: AuthSettingsResponse, ...errors(400, 401, 403) },
detail: {
summary: 'Update authentication settings',
description: 'Update the instance registration mode and email-dependent auth options.',
@@ -257,7 +252,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
)
.get('/god/email-settings', () => getEmailSettings(), {
- response: { 200: EmailSettingsResponse, 401: ErrorResponse, 403: ErrorResponse },
+ response: { 200: EmailSettingsResponse, ...errors(401, 403) },
detail: {
summary: 'Get instance email settings',
description: 'Get the mail provider used for authentication email (secrets redacted).',
@@ -266,12 +261,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
.put('/god/email-settings', ({ body }) => setEmailSettings(body), {
body: EmailSettingsBody,
- response: {
- 200: EmailSettingsResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- },
+ response: { 200: EmailSettingsResponse, ...errors(400, 401, 403) },
detail: {
summary: 'Update instance email settings',
description: 'Update the mail provider used for authentication email.',
@@ -282,7 +272,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
'/god/google-settings',
async () => ({ ...(await getGoogleSettings()), redirectUri: GOOGLE_REDIRECT_URI }),
{
- response: { 200: GoogleSettingsResponse, 401: ErrorResponse, 403: ErrorResponse },
+ response: { 200: GoogleSettingsResponse, ...errors(401, 403) },
detail: {
summary: 'Get Google sign-in settings',
description: 'Get the Google OAuth credentials (the client secret redacted).',
@@ -306,12 +296,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
},
{
body: GoogleSettingsBody,
- response: {
- 200: GoogleSettingsResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- },
+ response: { 200: GoogleSettingsResponse, ...errors(400, 401, 403) },
detail: {
summary: 'Update Google sign-in settings',
description: 'Update the Google OAuth credentials and whether Google sign-in is offered.',
@@ -320,7 +305,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
)
.get('/god/storage-settings', () => getStorageSettings(), {
- response: { 200: StorageSettingsSchema, 401: ErrorResponse, 403: ErrorResponse },
+ response: { 200: StorageSettingsSchema, ...errors(401, 403) },
detail: {
summary: 'Get storage limits',
description: 'Get the instance upload limits: file sizes, accepted types, and project quota.',
@@ -329,12 +314,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
.put('/god/storage-settings', ({ body }) => setStorageSettings(body), {
body: StorageSettingsBody,
- response: {
- 200: StorageSettingsSchema,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- },
+ response: { 200: StorageSettingsSchema, ...errors(400, 401, 403) },
detail: {
summary: 'Update storage limits',
description:
@@ -343,7 +323,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
})
.get('/god/hotkey-settings', () => getHotkeySettings(), {
- response: { 200: HotkeyCombosSchema, 401: ErrorResponse, 403: ErrorResponse },
+ response: { 200: HotkeyCombosSchema, ...errors(401, 403) },
detail: {
summary: 'Get instance keyboard shortcuts',
description:
@@ -353,12 +333,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
.put('/god/hotkey-settings', ({ body }) => setHotkeySettings(body), {
body: HotkeyCombosSchema,
- response: {
- 200: HotkeyCombosSchema,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- },
+ response: { 200: HotkeyCombosSchema, ...errors(400, 401, 403) },
detail: {
summary: 'Update instance keyboard shortcuts',
description:
@@ -371,7 +346,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
// sidebar hides the indicator from everyone else. The version alone is readable by
// any signed-in user (/settings/version).
.get('/god/updates', () => getUpdateStatus(), {
- response: { 200: UpdateStatusSchema, 401: ErrorResponse, 403: ErrorResponse },
+ response: { 200: UpdateStatusSchema, ...errors(401, 403) },
detail: {
summary: 'Get the update status',
description:
@@ -380,7 +355,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
})
.post('/god/updates/check', () => getUpdateStatus(), {
- response: { 200: UpdateStatusSchema, 401: ErrorResponse, 403: ErrorResponse },
+ response: { 200: UpdateStatusSchema, ...errors(401, 403) },
detail: {
summary: 'Check for updates now',
description:
@@ -389,7 +364,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
})
.get('/god/telegram-settings', () => getInstanceBotSettings(), {
- response: { 200: TelegramSettingsResponse, 401: ErrorResponse, 403: ErrorResponse },
+ response: { 200: TelegramSettingsResponse, ...errors(401, 403) },
detail: {
summary: 'Get Telegram bot settings',
description: 'Get the instance Telegram bot (the token redacted).',
@@ -416,12 +391,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
},
{
body: TelegramSettingsBody,
- response: {
- 200: TelegramSettingsResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- },
+ response: { 200: TelegramSettingsResponse, ...errors(400, 401, 403) },
detail: {
summary: 'Update Telegram bot settings',
description:
@@ -450,9 +420,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
}),
response: {
200: t.Object({ items: t.Array(InstanceUserResponse), total: t.Number() }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
+ ...errors(400, 401, 403),
},
detail: {
summary: 'List instance users',
@@ -471,12 +439,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
},
{
params: t.Object({ userId: t.String() }),
- response: {
- 200: InstanceUserDetailResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: InstanceUserDetailResponse, ...accessErrors },
detail: {
summary: 'Get an instance user',
description:
@@ -494,12 +457,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
},
{
params: t.Object({ userId: t.String() }),
- response: {
- 200: InstanceUserDetailResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: InstanceUserDetailResponse, ...accessErrors },
detail: {
summary: 'Confirm a user email address',
description:
@@ -544,13 +502,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
// issue, comment and attachment in them goes too.
withProjects: t.Optional(t.Boolean()),
}),
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete a user',
description:
@@ -575,9 +527,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
}),
response: {
200: t.Object({ items: t.Array(InstanceProjectResponse), total: t.Number() }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
+ ...errors(400, 401, 403),
},
detail: {
summary: 'List instance projects',
@@ -596,13 +546,7 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
},
{
params: t.Object({ projectId: t.Numeric() }),
- response: {
- 200: InstanceProjectDetailResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: InstanceProjectDetailResponse, ...commonErrors },
detail: {
summary: 'Get an instance project',
description:
diff --git a/apps/api/src/initiatives/routes.ts b/apps/api/src/initiatives/routes.ts
deleted file mode 100644
index 96159fb3..00000000
--- a/apps/api/src/initiatives/routes.ts
+++ /dev/null
@@ -1,400 +0,0 @@
-import { Elysia, t } from 'elysia';
-import { mcpTool } from '../mcp/generate';
-import { noContent } from '../shared/http';
-import { guards, entityGuard } from '../shared/guards';
-import { authContext } from '../shared/auth-context';
-import { requireUser } from '../shared/access';
-import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
-import {
- listInitiatives,
- listInitiativeOptions,
- initiativeStatusCounts,
- getInitiative,
- getInitiativeProjectId,
- createInitiative,
- updateInitiative,
- deleteInitiative,
-} from './store';
-import { listFeed } from './activity';
-
-const initiativeParams = t.Object({ initiativeId: t.Numeric() });
-
-// The initiative lifecycle enum, validated at the edge so an invalid value is a
-// 400 (not a Postgres CHECK violation → 500). Mirrors the DB check constraint.
-const InitiativeStatus = t.Union([
- t.Literal('proposed'),
- t.Literal('planned'),
- t.Literal('active'),
- t.Literal('completed'),
- t.Literal('canceled'),
-]);
-
-// InitiativeRow from the store. progress is derived issue counts; health is
-// computed on the fly (on_track/at_risk/off_track, or null when there is nothing
-// to judge).
-const InitiativeResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- title: t.String(),
- description: t.String(),
- status: t.String(),
- ownerUserId: t.Nullable(t.String()),
- priority: t.Nullable(t.String()),
- startDate: t.Nullable(t.String()),
- targetDate: t.Nullable(t.String()),
- position: t.Number(),
- createdAt: t.String(),
- updatedAt: t.String(),
- labelIds: t.Array(t.Number()),
- progress: t.Object({ completed: t.Number(), canceled: t.Number(), total: t.Number() }),
- health: t.Nullable(t.String()),
-});
-
-// InitiativeFeedItemRow from activity.ts: one timeline entry, from the initiative
-// itself (source 'initiative') or a linked issue (source 'issue').
-const FeedItemResponse = t.Object({
- id: t.Number(),
- source: t.String(),
- kind: t.String(),
- actorUserId: t.Nullable(t.String()),
- actorName: t.Nullable(t.String()),
- body: t.Nullable(t.String()),
- action: t.Nullable(t.String()),
- subject: t.Nullable(t.String()),
- fromText: t.Nullable(t.String()),
- toText: t.Nullable(t.String()),
- createdAt: t.String(),
- issueId: t.Nullable(t.Number()),
- issueIdentifier: t.Nullable(t.String()),
-});
-
-const FeedPageResponse = t.Object({
- items: t.Array(FeedItemResponse),
- nextCursor: t.Nullable(t.Object({ ts: t.String(), id: t.Number() })),
-});
-
-export const initiativeRoutes = new Elysia({
- name: 'initiatives',
- detail: { tags: ['Initiatives'] },
-})
- .use(authContext)
- .use(guards)
- // Guard for routes that address an initiative by its own id (no :projectKey in
- // the path). Set `initiative: "<action>"` in the route options.
- .macro({
- initiative: entityGuard('initiatives', 'Initiative not found', (p) =>
- getInitiativeProjectId(Number(p.initiativeId)),
- ),
- })
-
- .get(
- '/projects/:projectKey/initiatives',
- async ({ project, query }) => {
- const statuses = query.status
- ? query.status
- .split(',')
- .map((s) => s.trim())
- .filter(Boolean)
- : undefined;
- const page = query.page ?? 1;
- const pageSize = query.pageSize ?? 25;
- const { items, total } = await listInitiatives(project.id, {
- statuses,
- search: query.search,
- sort: query.sort,
- dir: query.dir,
- limit: pageSize,
- offset: (page - 1) * pageSize,
- });
- return { items, total, page, pageSize };
- },
- {
- params: t.Object({ projectKey: t.String() }),
- query: t.Object({
- status: t.Optional(
- t.String({
- description:
- 'Filter by status: a comma-separated subset of proposed,planned,active,completed,canceled. Omit for all.',
- }),
- ),
- search: t.Optional(t.String({ description: 'Case-insensitive match on the title.' })),
- sort: t.Optional(
- t.Union(
- [
- t.Literal('title'),
- t.Literal('priority'),
- t.Literal('targetDate'),
- t.Literal('owner'),
- ],
- { description: 'Sort column. Omit for the manual position order.' },
- ),
- ),
- dir: t.Optional(
- t.Union([t.Literal('asc'), t.Literal('desc')], {
- description: 'Sort direction. Default asc.',
- }),
- ),
- page: t.Optional(t.Numeric({ minimum: 1, description: '1-based page. Default 1.' })),
- pageSize: t.Optional(
- t.Numeric({
- minimum: 1,
- maximum: 100,
- description: 'Items per page (1-100). Default 25.',
- }),
- ),
- }),
- permission: ['initiatives', 'read'],
- response: {
- 200: t.Object({
- items: t.Array(InitiativeResponse),
- total: t.Number(),
- page: t.Number(),
- pageSize: t.Number(),
- }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'List initiatives',
- description: "List a project's initiatives, filtered, sorted and paged.",
- ...mcpTool('list_initiatives'),
- },
- },
- )
-
- // Fills the initiative picker on an issue. Read under work items: linking an issue
- // needs the titles, not the initiative pages the `initiatives` resource gates.
- .get(
- '/projects/:projectKey/initiatives/options',
- async ({ project, query }) => listInitiativeOptions(project.id, query),
- {
- params: t.Object({ projectKey: t.String() }),
- query: t.Object({
- search: t.Optional(t.String({ description: 'Match by title.' })),
- include: t.Optional(
- t.Numeric({
- description: 'Keep this initiative in the list even when it is closed.',
- }),
- ),
- }),
- permission: ['work_items', 'read'],
- response: {
- 200: t.Array(t.Object({ id: t.Number(), title: t.String(), status: t.String() })),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'List initiative options',
- description: 'The initiatives an issue can be linked to: id, title and status.',
- },
- },
- )
-
- .get(
- '/projects/:projectKey/initiatives/counts',
- async ({ project }) => initiativeStatusCounts(project.id),
- {
- params: t.Object({ projectKey: t.String() }),
- permission: ['initiatives', 'read'],
- response: {
- 200: t.Object({
- total: t.Number(),
- proposed: t.Number(),
- planned: t.Number(),
- active: t.Number(),
- completed: t.Number(),
- canceled: t.Number(),
- }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Initiative status counts',
- description: "Per-status initiative counts for a project, for the list's tabs.",
- },
- },
- )
-
- .post(
- '/projects/:projectKey/initiatives',
- async ({ project, body, user, set }) => {
- set.status = 201;
- return createInitiative(project.id, body, requireUser(user).id);
- },
- {
- params: t.Object({ projectKey: t.String() }),
- body: t.Object({
- title: t.String({ minLength: 1, description: 'Initiative title.' }),
- description: t.Optional(t.String({ description: 'Initiative description.' })),
- status: t.Optional(InitiativeStatus),
- ownerUserId: t.Optional(
- t.Nullable(t.String({ description: 'Owner user id (a project member), or null.' })),
- ),
- priority: t.Optional(
- t.Nullable(t.String({ description: 'One of: urgent, high, medium, low. Or null.' })),
- ),
- startDate: t.Optional(
- t.Nullable(t.String({ description: "Start date 'YYYY-MM-DD', or null." })),
- ),
- targetDate: t.Optional(
- t.Nullable(t.String({ description: "Target date 'YYYY-MM-DD', or null." })),
- ),
- labelIds: t.Optional(
- t.Array(t.Integer(), { description: 'Label ids to attach. From get_project.labels.' }),
- ),
- }),
- permission: ['initiatives', 'create'],
- response: {
- 201: InitiativeResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Create an initiative',
- description: 'Create an initiative in a project.',
- ...mcpTool('create_initiative'),
- },
- },
- )
-
- .get(
- '/initiatives/:initiativeId',
- async ({ params }) => {
- const found = await getInitiative(params.initiativeId);
- if (!found) throw new HttpError(404, 'Initiative not found');
- return found;
- },
- {
- params: initiativeParams,
- initiative: 'read',
- response: {
- 200: InitiativeResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Get an initiative',
- description: 'Get an initiative by its numeric id.',
- ...mcpTool('get_initiative'),
- },
- },
- )
-
- .patch(
- '/initiatives/:initiativeId',
- async ({ params, body, user }) => {
- const actorUserId = requireUser(user).id;
- const updated = await updateInitiative(params.initiativeId, body, actorUserId);
- if (!updated) throw new HttpError(404, 'Initiative not found');
- return updated;
- },
- {
- params: initiativeParams,
- body: t.Object({
- title: t.Optional(t.String({ minLength: 1, description: 'New title.' })),
- description: t.Optional(t.String({ description: 'New description.' })),
- status: t.Optional(InitiativeStatus),
- ownerUserId: t.Optional(
- t.Nullable(t.String({ description: 'New owner user id (a project member), or null.' })),
- ),
- priority: t.Optional(
- t.Nullable(t.String({ description: 'One of: urgent, high, medium, low. Or null.' })),
- ),
- startDate: t.Optional(
- t.Nullable(t.String({ description: "Start date 'YYYY-MM-DD', or null." })),
- ),
- targetDate: t.Optional(
- t.Nullable(t.String({ description: "Target date 'YYYY-MM-DD', or null." })),
- ),
- labelIds: t.Optional(
- t.Array(t.Integer(), { description: "Replace the initiative's labels with these ids." }),
- ),
- }),
- initiative: 'edit',
- response: {
- 200: InitiativeResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Update an initiative',
- description: 'Update an initiative by its numeric id.',
- ...mcpTool('update_initiative'),
- },
- },
- )
-
- .delete(
- '/initiatives/:initiativeId',
- async ({ params }) => {
- await deleteInitiative(params.initiativeId);
- return noContent();
- },
- {
- params: initiativeParams,
- initiative: 'delete',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Delete an initiative',
- description: 'Delete an initiative by its numeric id. Irreversible.',
- ...mcpTool('delete_initiative'),
- },
- },
- )
-
- .get(
- '/initiatives/:initiativeId/feed',
- async ({ params, query }) => {
- const limit = query.limit != null ? Number(query.limit) : 25;
- let before = null;
- if (query.cursor) {
- try {
- before = JSON.parse(query.cursor);
- } catch {
- // Ignore a malformed cursor and serve the first page.
- }
- }
- return listFeed(params.initiativeId, { before, limit });
- },
- {
- params: initiativeParams,
- query: t.Object({
- limit: t.Optional(t.String({ description: 'Max items per page (1-100). Default 25.' })),
- cursor: t.Optional(
- t.String({ description: 'nextCursor from the previous page, for paging.' }),
- ),
- }),
- initiative: 'read',
- response: {
- 200: FeedPageResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
- detail: {
- summary: 'Get an initiative feed',
- description: "Get an initiative's activity feed by its numeric id.",
- ...mcpTool('list_initiative_activity'),
- },
- },
- );
diff --git a/apps/api/src/invites/routes.ts b/apps/api/src/invites/routes.ts
index 7056a447..7f38af13 100644
--- a/apps/api/src/invites/routes.ts
+++ b/apps/api/src/invites/routes.ts
@@ -5,7 +5,7 @@ import { authContext } from '../shared/auth-context';
import { guards } from '../shared/guards';
import { requireUser, type AuthUser } from '../shared/access';
import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
+import { accessErrors, commonErrors, errors } from '../shared/responses';
import { getRole } from '../roles/store';
import {
createInvite,
@@ -113,14 +113,7 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
roleId: t.Optional(t.Nullable(t.Integer())),
}),
permission: ['members_invite', 'create'],
- response: {
- 201: InviteRowResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 201: InviteRowResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Create an invite',
description:
@@ -139,12 +132,7 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
{
params: t.Object({ projectKey: t.String() }),
permission: ['members_invite', 'read'],
- response: {
- 200: t.Array(InviteRowResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(InviteRowResponse), ...accessErrors },
detail: { summary: "List a project's invites", ...mcpTool('list_invites') },
},
)
@@ -160,13 +148,7 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
{
params: t.Object({ projectKey: t.String(), inviteId: t.Numeric() }),
permission: ['members_invite', 'delete'],
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete an invite',
description: 'Revoke a project invite.',
@@ -189,12 +171,7 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
},
{
params: tokenParams,
- response: {
- 200: InviteViewResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: InviteViewResponse, ...errors(400, 401, 404) },
detail: {
summary: 'Get an invite',
description: 'Get an invite by its token, with its project and role.',
@@ -213,14 +190,7 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
},
{
params: tokenParams,
- response: {
- 200: AcceptInviteResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 200: AcceptInviteResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Accept an invite',
description: 'Accept an invite (email must match your session).',
@@ -238,14 +208,7 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
},
{
params: tokenParams,
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors, ...errors(409) },
detail: {
summary: 'Reject an invite',
description: 'Reject an invite (email must match your session).',
diff --git a/apps/api/src/issue-types/routes.ts b/apps/api/src/issue-types/routes.ts
index 558df2eb..da46103d 100644
--- a/apps/api/src/issue-types/routes.ts
+++ b/apps/api/src/issue-types/routes.ts
@@ -3,7 +3,7 @@ import { mcpTool } from '../mcp/generate';
import { noContent } from '../shared/http';
import { guards } from '../shared/guards';
import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
+import { commonErrors } from '../shared/responses';
import { createIssueType, updateIssueType, deleteIssueType } from './store';
const typeParams = t.Object({ projectKey: t.String(), typeId: t.Numeric() });
@@ -38,13 +38,7 @@ export const issueTypeRoutes = new Elysia({
isDefault: t.Optional(t.Boolean()),
}),
permission: ['issue_types', 'create'],
- response: {
- 201: IssueTypeResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: IssueTypeResponse, ...commonErrors },
detail: {
summary: 'Create an issue type',
description:
@@ -69,13 +63,7 @@ export const issueTypeRoutes = new Elysia({
}),
params: typeParams,
permission: ['issue_types', 'edit'],
- response: {
- 200: IssueTypeResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: IssueTypeResponse, ...commonErrors },
detail: {
summary: 'Update an issue type',
description: "Update an issue type's name, color, or default flag.",
@@ -93,13 +81,7 @@ export const issueTypeRoutes = new Elysia({
{
params: typeParams,
permission: ['issue_types', 'delete'],
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete an issue type',
description: 'Delete an issue type.',
diff --git a/apps/api/src/issues/activity.ts b/apps/api/src/issues/activity.ts
index db09098d..7878e20c 100644
--- a/apps/api/src/issues/activity.ts
+++ b/apps/api/src/issues/activity.ts
@@ -12,9 +12,9 @@ import {
import { and, desc, eq, gte, inArray, lt, sql } from 'drizzle-orm';
import { HttpError, iso } from '../shared/lib';
import { emitWebhookEvent } from '../webhooks/emit';
-import { parseMentions } from '../ai-agents/mentions';
-import { isAgentUser, listInternalAgentsByUserIds } from '../ai-agents/store';
-import { enqueueAgentRun } from '../ai-agents/run-queue';
+import { parseMentions } from '#modules/agents/core/mentions';
+import { isAgentUser, listInternalAgentsByUserIds } from '#modules/agents/core/service';
+import { enqueueAgentRun } from '#modules/agents/core/run-queue';
import { notifyComment, notifyIssueChange } from '../notifications/store';
// Issue timeline: comments and change-log activity in one table (issue_activity).
diff --git a/apps/api/src/issues/routes.ts b/apps/api/src/issues/routes.ts
index e4a1f0b4..7c1afb4c 100644
--- a/apps/api/src/issues/routes.ts
+++ b/apps/api/src/issues/routes.ts
@@ -7,7 +7,7 @@ import { assertPermission, assertMcpEnabled, requireUser } from '../shared/acces
import { isMcpRequest } from '../shared/mcp-request';
import { getProjectById } from '../projects/store';
import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
+import { accessErrors, commonErrors, errors } from '../shared/responses';
import { deleteObject } from '../shared/s3';
import {
createIssue,
@@ -452,13 +452,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
),
}),
permission: ['work_items', 'create'],
- response: {
- 201: IssueResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: IssueResponse, ...commonErrors },
detail: {
summary: 'Create an issue',
description: 'Create an issue in a project.',
@@ -501,13 +495,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
}),
}),
permission: ['work_items', 'edit'],
- response: {
- 200: t.Object({ updated: t.Number() }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Object({ updated: t.Number() }), ...commonErrors },
detail: { summary: 'Bulk update issues' },
},
)
@@ -526,13 +514,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
add: t.Array(t.Integer(), { minItems: 1, description: 'Label ids to add.' }),
}),
permission: ['work_items', 'edit'],
- response: {
- 200: t.Object({ updated: t.Number() }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Object({ updated: t.Number() }), ...commonErrors },
detail: { summary: 'Bulk add labels to issues' },
},
)
@@ -554,14 +536,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
newParentId: t.Optional(NewParentIdSchema),
}),
permission: ['work_items', 'edit'],
- response: {
- 200: t.Object({ archived: t.Number() }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 200: t.Object({ archived: t.Number() }), ...commonErrors, ...errors(409) },
detail: { summary: 'Bulk archive issues' },
},
)
@@ -589,14 +564,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
newParentId: t.Optional(NewParentIdSchema),
}),
permission: ['work_items', 'delete'],
- response: {
- 200: t.Object({ deleted: t.Number() }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 200: t.Object({ deleted: t.Number() }), ...commonErrors, ...errors(409) },
detail: { summary: 'Bulk delete issues' },
},
)
@@ -624,13 +592,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
limit: t.Optional(t.Numeric({ description: 'Max results (1-500). Default 50.' })),
}),
permission: ['work_items', 'read'],
- response: {
- 200: t.Array(IssueSearchHitResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(IssueSearchHitResponse), ...commonErrors },
detail: {
summary: 'Search issues by text',
description: "Search a project's issues by text.",
@@ -699,13 +661,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
limit: t.Optional(t.Numeric({ description: 'Max results (1-500). Default 50.' })),
}),
permission: ['work_items', 'read'],
- response: {
- 200: t.Array(IssueSearchHitResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(IssueSearchHitResponse), ...commonErrors },
detail: {
summary: 'List issues by filters',
description: "List a project's issues by field filters.",
@@ -730,12 +686,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
{
params: t.Object({ projectKey: t.String() }),
permission: ['work_items', 'read'],
- response: {
- 200: t.Object({ issues: t.Array(BoardIssueResponse) }),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Object({ issues: t.Array(BoardIssueResponse) }), ...accessErrors },
detail: { summary: 'Get board issues' },
},
)
@@ -748,12 +699,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
{
params: t.Object({ projectKey: t.String() }),
permission: ['work_items', 'read'],
- response: {
- 200: t.Array(IssueResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(IssueResponse), ...accessErrors },
detail: { summary: 'List archived issues' },
},
)
@@ -777,13 +723,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
{
params: t.Object({ projectKey: t.String(), sequenceNumber: t.Numeric() }),
permission: ['work_items', 'read'],
- response: {
- 200: IssueWithFieldsResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: IssueWithFieldsResponse, ...commonErrors },
detail: {
summary: 'Get an issue by number',
description:
@@ -818,13 +758,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
},
{
params: issueParams,
- response: {
- 200: IssueWithFieldsResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: IssueWithFieldsResponse, ...commonErrors },
detail: {
summary: 'Get an issue',
description: 'Get an issue by its numeric id.',
@@ -905,13 +839,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
}),
params: issueParams,
workItem: 'edit',
- response: {
- 200: IssueResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: IssueResponse, ...commonErrors },
detail: {
summary: 'Update an issue',
description: 'Update an issue by its numeric id.',
@@ -946,14 +874,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
newParentId: t.Optional(t.Numeric(NewParentIdSchema)),
}),
workItem: 'delete',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors, ...errors(409) },
detail: {
summary: 'Delete an issue',
description:
@@ -990,14 +911,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
}),
),
workItem: 'edit',
- response: {
- 200: IssueResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 200: IssueResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Archive an issue',
description:
@@ -1021,13 +935,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
{
params: issueParams,
workItem: 'edit',
- response: {
- 200: IssueResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: IssueResponse, ...commonErrors },
detail: {
summary: 'Restore an archived issue',
description:
@@ -1059,13 +967,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
}),
params: t.Object({ issueId: t.Numeric(), fieldId: t.Numeric() }),
workItem: 'edit',
- response: {
- 200: t.Object({ ok: t.Boolean() }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Object({ ok: t.Boolean() }), ...commonErrors },
detail: {
summary: 'Set a custom field value',
description: 'Set a custom field value on an issue by its numeric id.',
@@ -1093,14 +995,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
}),
params: issueParams,
workItem: 'edit',
- response: {
- 201: IssueLinkResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 201: IssueLinkResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Link two issues',
description:
@@ -1122,13 +1017,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
{
params: t.Object({ issueId: t.Numeric(), linkId: t.Numeric() }),
workItem: 'edit',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Unlink two issues',
description: "Remove one of an issue's relations by the link id.",
@@ -1143,13 +1032,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
.get('/issues/:issueId/checklists', async ({ params }) => listChecklists(params.issueId), {
params: issueParams,
workItem: 'read',
- response: {
- 200: t.Array(ChecklistResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(ChecklistResponse), ...commonErrors },
detail: {
summary: "List an issue's checklists",
description: 'Every checklist of an issue with its items, both in display order.',
@@ -1166,13 +1049,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
body: t.Object({ title: ChecklistTitleSchema }),
params: issueParams,
workItem: 'edit',
- response: {
- 201: ChecklistResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: ChecklistResponse, ...commonErrors },
detail: {
summary: 'Add a checklist',
description: 'Add a checklist to an issue. It starts empty; add its items separately.',
@@ -1189,13 +1066,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
body: OrderedIdsSchema,
params: issueParams,
workItem: 'edit',
- response: {
- 200: t.Array(ChecklistResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(ChecklistResponse), ...commonErrors },
detail: {
summary: "Reorder an issue's checklists",
description: "Set the display order of an issue's checklists.",
@@ -1211,13 +1082,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
body: t.Object({ title: ChecklistTitleSchema }),
params: checklistParams,
checklist: 'edit',
- response: {
- 200: ChecklistResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ChecklistResponse, ...commonErrors },
detail: { summary: 'Rename a checklist', description: "Change a checklist's title." },
},
)
@@ -1233,13 +1098,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
{
params: checklistParams,
checklist: 'edit',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete a checklist',
description: 'Delete a checklist and every item on it.',
@@ -1257,13 +1116,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
body: t.Object({ content: ChecklistItemContentSchema }),
params: checklistParams,
checklist: 'edit',
- response: {
- 201: ChecklistItemResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: ChecklistItemResponse, ...commonErrors },
detail: {
summary: 'Add a checklist item',
description: 'Append an item to a checklist.',
@@ -1278,13 +1131,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
body: OrderedIdsSchema,
params: checklistParams,
checklist: 'edit',
- response: {
- 200: t.Array(ChecklistItemResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(ChecklistItemResponse), ...commonErrors },
detail: {
summary: 'Reorder checklist items',
description: 'Set the display order of the items within one checklist.',
@@ -1304,13 +1151,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
}),
params: checklistItemParams,
checklistItem: 'edit',
- response: {
- 200: ChecklistItemResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ChecklistItemResponse, ...commonErrors },
detail: {
summary: 'Update a checklist item',
description: "Change a checklist item's text, its checked state, or both.",
@@ -1328,13 +1169,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
{
params: checklistItemParams,
checklistItem: 'edit',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete a checklist item',
description: 'Remove one item from a checklist.',
@@ -1355,13 +1190,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
{
params: issueParams,
workItem: 'read',
- response: {
- 200: t.Array(IssueWatcherResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(IssueWatcherResponse), ...commonErrors },
detail: {
summary: 'Watch an issue',
description: 'Subscribe the current user to an issue and return its watchers.',
@@ -1380,13 +1209,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
{
params: issueParams,
workItem: 'read',
- response: {
- 200: t.Array(IssueWatcherResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(IssueWatcherResponse), ...commonErrors },
detail: {
summary: 'Unwatch an issue',
description: 'Unsubscribe the current user from an issue and return its watchers.',
@@ -1406,13 +1229,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
params: issueParams,
query: feedPageQuery,
workItem: 'read',
- response: {
- 200: FeedPageResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: FeedPageResponse, ...commonErrors },
detail: {
summary: 'Get an issue feed',
description: "Get an issue's activity feed by its numeric id.",
@@ -1431,13 +1248,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
params: issueParams,
query: feedPageQuery,
workItem: 'read',
- response: {
- 200: GroupedFeedPageResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: GroupedFeedPageResponse, ...commonErrors },
detail: {
summary: 'Get an issue feed grouped by status',
description:
@@ -1452,13 +1263,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
.get('/issues/:issueId/timeline', async ({ params }) => listStatusTimeline(params.issueId), {
params: issueParams,
workItem: 'read',
- response: {
- 200: t.Array(TimelineSegmentResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(TimelineSegmentResponse), ...commonErrors },
detail: {
summary: 'Get an issue status timeline',
description: "Get the stretches an issue spent in each status, with each one's duration.",
@@ -1479,13 +1284,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
),
}),
workItem: 'read',
- response: {
- 200: t.Array(FeedItemResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(FeedItemResponse), ...commonErrors },
detail: {
summary: 'Get the activity of one timeline stretch',
description: "Get an issue's activity entries written between two moments, oldest first.",
@@ -1509,13 +1308,7 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
body: t.Object({ body: t.String({ minLength: 1, description: 'Comment text.' }) }),
params: issueParams,
workItem: 'create',
- response: {
- 201: FeedItemResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: FeedItemResponse, ...commonErrors },
detail: {
summary: 'Add a comment',
description: 'Add a comment to an issue by its numeric id.',
diff --git a/apps/api/src/issues/store.ts b/apps/api/src/issues/store.ts
index 751ca7bd..5fed446f 100644
--- a/apps/api/src/issues/store.ts
+++ b/apps/api/src/issues/store.ts
@@ -30,10 +30,10 @@ import {
sql,
type SQL,
} from 'drizzle-orm';
-import type { IssueQuery } from '../ai-agents/issue-query';
+import type { IssueQuery } from '#modules/agents/core/issue-query';
import { iso, num, HttpError } from '../shared/lib';
import type { ProjectRow } from '../projects/store';
-import { getCustomFieldById, type CustomFieldType } from '../custom-fields/store';
+import { getCustomFieldById, type CustomFieldType } from '#modules/custom-fields/service';
import {
recordActivity,
recordActivityEntries,
@@ -45,15 +45,15 @@ import {
type IssueSnapshot,
} from './activity';
import { autoWatchIssue } from './watchers';
-import { mapAttachment, type AttachmentRow } from '../attachments/store';
+import { mapAttachment, type AttachmentRow } from '#modules/attachments/service';
import { notifyIssueChange } from '../notifications/store';
import { emitWebhookEvent } from '../webhooks/emit';
-import { getAssignTriggerAgent, isProjectAgent } from '../ai-agents/store';
-import { deleteThreadsWhere } from '../ai-agents/runtime/memory';
-import { getInitiativeProjectId } from '../initiatives/store';
-import { getCycleRef } from '../cycles/store';
+import { getAssignTriggerAgent, isProjectAgent } from '#modules/agents/core/service';
+import { deleteThreadsWhere } from '#modules/agents/core/runtime/memory';
+import { getInitiativeProjectId } from '#modules/initiatives/service';
+import { getCycleRef } from '#modules/cycles/service';
import { getMembership } from '../members/store';
-import { enqueueAgentRun } from '../ai-agents/run-queue';
+import { enqueueAgentRun } from '#modules/agents/core/run-queue';
import { applySubtaskAutomation } from './automation';
// Data access for issues and their per-issue data: labels, custom field values,
diff --git a/apps/api/src/issues/subtasks.ts b/apps/api/src/issues/subtasks.ts
index 33dbcebc..19d457b2 100644
--- a/apps/api/src/issues/subtasks.ts
+++ b/apps/api/src/issues/subtasks.ts
@@ -3,7 +3,7 @@ import { and, eq, inArray, sql, type SQL } from 'drizzle-orm';
import { alias } from 'drizzle-orm/pg-core';
import { HttpError } from '../shared/lib';
import { archiveIssue, deleteIssue, restoreIssue, updateIssue } from './store';
-import type { AttachmentRow } from '../attachments/store';
+import type { AttachmentRow } from '#modules/attachments/service';
// An issue's subtasks: issues carrying its id in parent_id. The hierarchy is one
// level deep (see assertParent in store.ts), so a subtask has no subtasks of its
diff --git a/apps/api/src/labels/routes.ts b/apps/api/src/labels/routes.ts
index d40e60d4..55ac9987 100644
--- a/apps/api/src/labels/routes.ts
+++ b/apps/api/src/labels/routes.ts
@@ -3,7 +3,7 @@ import { mcpTool } from '../mcp/generate';
import { noContent } from '../shared/http';
import { guards } from '../shared/guards';
import { HttpError, rethrowDuplicate } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
+import { commonErrors, errors } from '../shared/responses';
import {
createLabel,
updateLabel,
@@ -53,14 +53,7 @@ export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labels
groupId: t.Optional(t.Nullable(t.Integer())),
}),
permission: ['labels', 'create'],
- response: {
- 201: LabelResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 201: LabelResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Create a label',
description: 'Create a label. Optional groupId assigns it to a label group.',
@@ -89,14 +82,7 @@ export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labels
}),
params: labelParams,
permission: ['labels', 'edit'],
- response: {
- 200: LabelResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 200: LabelResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Update a label',
description:
@@ -115,13 +101,7 @@ export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labels
{
params: labelParams,
permission: ['labels', 'delete'],
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete a label',
description: 'Delete a label.',
@@ -144,14 +124,7 @@ export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labels
{
body: t.Object({ name: t.String({ minLength: 1 }), color: t.Optional(t.String()) }),
permission: ['labels', 'create'],
- response: {
- 201: LabelGroupResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 201: LabelGroupResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Create a label group',
description: 'Create a label group, a named container for labels.',
@@ -179,14 +152,7 @@ export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labels
}),
params: groupParams,
permission: ['labels', 'edit'],
- response: {
- 200: LabelGroupResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 200: LabelGroupResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Update a label group',
description: "Update a label group's name or color.",
@@ -204,13 +170,7 @@ export const labelRoutes = new Elysia({ name: 'labels', detail: { tags: ['Labels
{
params: groupParams,
permission: ['labels', 'delete'],
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete a label group',
description: 'Delete a label group.',
diff --git a/apps/api/src/members/routes.ts b/apps/api/src/members/routes.ts
index 7bd43eea..b0f1e69a 100644
--- a/apps/api/src/members/routes.ts
+++ b/apps/api/src/members/routes.ts
@@ -5,7 +5,7 @@ import { authContext } from '../shared/auth-context';
import { guards } from '../shared/guards';
import { assertPermission, requireUser } from '../shared/access';
import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
+import { accessErrors, commonErrors } from '../shared/responses';
import {
listMembers,
getMembership,
@@ -45,12 +45,7 @@ export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Memb
{
params: t.Object({ projectKey: t.String() }),
permission: ['members_manage', 'read'],
- response: {
- 200: t.Array(MemberResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(MemberResponse), ...accessErrors },
detail: { summary: 'List project members', ...mcpTool('list_members') },
},
)
@@ -90,13 +85,7 @@ export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Memb
params: memberParams,
body: t.Object({ role: memberRole, roleId: t.Optional(t.Nullable(t.Integer())) }),
projectOwner: true,
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: "Update a member's role",
description:
@@ -128,13 +117,7 @@ export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Memb
params: memberParams,
body: t.Object({ description: t.String({ maxLength: 500 }) }),
projectMember: true,
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: "Set a member's description",
description:
@@ -167,13 +150,7 @@ export const memberRoutes = new Elysia({ name: 'members', detail: { tags: ['Memb
{
params: memberParams,
projectMember: true,
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Remove a member',
description: 'Remove a member from the project, or leave it yourself.',
diff --git a/apps/api/src/actions/__tests__/integration/actions.test.ts b/apps/api/src/modules/actions/__tests__/integration/actions.test.ts
similarity index 98%
rename from apps/api/src/actions/__tests__/integration/actions.test.ts
rename to apps/api/src/modules/actions/__tests__/integration/actions.test.ts
index 82e3485f..a7db9cdd 100644
--- a/apps/api/src/actions/__tests__/integration/actions.test.ts
+++ b/apps/api/src/modules/actions/__tests__/integration/actions.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
async function setupOwnerProject() {
const owner = await signUpTestUser();
diff --git a/apps/api/src/actions/routes.ts b/apps/api/src/modules/actions/index.ts
similarity index 58%
rename from apps/api/src/actions/routes.ts
rename to apps/api/src/modules/actions/index.ts
index d7392e85..b54459f0 100644
--- a/apps/api/src/actions/routes.ts
+++ b/apps/api/src/modules/actions/index.ts
@@ -1,10 +1,18 @@
import { Elysia, t } from 'elysia';
-import { noContent } from '../shared/http';
-import { guards, entityGuard } from '../shared/guards';
-import { authContext } from '../shared/auth-context';
-import { HttpError } from '../shared/lib';
-import { mcpTool } from '../mcp/generate';
-import { ErrorResponse } from '../shared/responses';
+import { noContent } from '#shared/http';
+import { guards, entityGuard } from '#shared/guards';
+import { authContext } from '#shared/auth-context';
+import { HttpError } from '#shared/lib';
+import { mcpTool } from '#mcp/generate';
+import { accessErrors, commonErrors } from '#shared/responses';
+import {
+ ActionResponse,
+ ActionListResponse,
+ actionParams,
+ createActionBody,
+ updateActionBody,
+ reorderActionsBody,
+} from './model';
import {
listActions,
createAction,
@@ -12,22 +20,7 @@ import {
updateAction,
deleteAction,
reorderActions,
-} from './store';
-
-const actionParams = t.Object({ actionId: t.Numeric() });
-
-// An action DTO (ActionRow from the store). condition and effect are jsonb blobs
-// owned by the UI, stored and returned without inspecting their shape.
-const ActionResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- name: t.String(),
- icon: t.String(),
- condition: t.Any(),
- effect: t.Any(),
- position: t.Number(),
- createdAt: t.String(),
-});
+} from './service';
export const actionRoutes = new Elysia({ name: 'actions', detail: { tags: ['Actions'] } })
.use(authContext)
@@ -48,12 +41,7 @@ export const actionRoutes = new Elysia({ name: 'actions', detail: { tags: ['Acti
},
{
permission: ['actions', 'read'],
- response: {
- 200: t.Array(ActionResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ActionListResponse, ...accessErrors },
detail: {
summary: 'List actions',
description: "List a project's actions.",
@@ -72,12 +60,7 @@ export const actionRoutes = new Elysia({ name: 'actions', detail: { tags: ['Acti
},
{
projectMember: true,
- response: {
- 200: t.Array(ActionResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ActionListResponse, ...accessErrors },
detail: {
summary: 'List quick actions',
description: "List a project's actions for the issue quick actions.",
@@ -92,20 +75,9 @@ export const actionRoutes = new Elysia({ name: 'actions', detail: { tags: ['Acti
return createAction({ projectId: project.id, ...body });
},
{
- body: t.Object({
- name: t.String({ minLength: 1 }),
- icon: t.Optional(t.String()),
- condition: t.Optional(t.Any()),
- effect: t.Optional(t.Any()),
- }),
+ body: createActionBody,
permission: ['actions', 'create'],
- response: {
- 201: ActionResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: ActionResponse, ...commonErrors },
detail: {
summary: 'Create an action',
description: 'Create an action in a project.',
@@ -121,15 +93,9 @@ export const actionRoutes = new Elysia({ name: 'actions', detail: { tags: ['Acti
return reorderActions(project.id, body.orderedIds);
},
{
- body: t.Object({ orderedIds: t.Array(t.Integer(), { minItems: 1 }) }),
+ body: reorderActionsBody,
permission: ['actions', 'edit'],
- response: {
- 200: t.Array(ActionResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ActionListResponse, ...commonErrors },
detail: {
summary: 'Reorder actions',
description: "Set the display order of a project's actions.",
@@ -146,21 +112,10 @@ export const actionRoutes = new Elysia({ name: 'actions', detail: { tags: ['Acti
return action;
},
{
- body: t.Object({
- name: t.Optional(t.String({ minLength: 1 })),
- icon: t.Optional(t.String()),
- condition: t.Optional(t.Any()),
- effect: t.Optional(t.Any()),
- }),
+ body: updateActionBody,
params: actionParams,
savedAction: 'edit',
- response: {
- 200: ActionResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ActionResponse, ...commonErrors },
detail: {
summary: 'Update an action',
description: 'Update an existing action.',
@@ -178,13 +133,7 @@ export const actionRoutes = new Elysia({ name: 'actions', detail: { tags: ['Acti
{
params: actionParams,
savedAction: 'delete',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete an action',
description: 'Delete an action. Irreversible.',
diff --git a/apps/api/src/modules/actions/model.ts b/apps/api/src/modules/actions/model.ts
new file mode 100644
index 00000000..b84bfde1
--- /dev/null
+++ b/apps/api/src/modules/actions/model.ts
@@ -0,0 +1,29 @@
+import { t } from 'elysia';
+
+export const ActionResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ name: t.String(),
+ icon: t.String(),
+ condition: t.Any(),
+ effect: t.Any(),
+ position: t.Number(),
+ createdAt: t.String(),
+});
+
+export const ActionListResponse = t.Array(ActionResponse);
+
+export const actionParams = t.Object({ actionId: t.Numeric() });
+
+export const createActionBody = t.Object({
+ name: t.String({ minLength: 1 }),
+ icon: t.Optional(t.String()),
+ condition: t.Optional(t.Any()),
+ effect: t.Optional(t.Any()),
+});
+
+export const updateActionBody = t.Partial(createActionBody);
+
+export const reorderActionsBody = t.Object({
+ orderedIds: t.Array(t.Integer(), { minItems: 1 }),
+});
diff --git a/apps/api/src/actions/store.ts b/apps/api/src/modules/actions/service.ts
similarity index 98%
rename from apps/api/src/actions/store.ts
rename to apps/api/src/modules/actions/service.ts
index 0a9e6749..a2fcd008 100644
--- a/apps/api/src/actions/store.ts
+++ b/apps/api/src/modules/actions/service.ts
@@ -1,6 +1,6 @@
import { db, projectAction } from '@repo/db';
import { and, eq, sql } from 'drizzle-orm';
-import { iso, num } from '../shared/lib';
+import { iso, num } from '#shared/lib';
// Manual actions: saved macros on a project. condition is a filter set deciding
// which issues the action applies to (empty = always); effect is a partial issue
diff --git a/apps/api/src/ai-agents/__tests__/integration/agent-runs.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/agent-runs.test.ts
similarity index 97%
rename from apps/api/src/ai-agents/__tests__/integration/agent-runs.test.ts
rename to apps/api/src/modules/agents/core/__tests__/integration/agent-runs.test.ts
index 1363e808..85893bd0 100644
--- a/apps/api/src/ai-agents/__tests__/integration/agent-runs.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/integration/agent-runs.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
// The run-history endpoint: GET /projects/:key/ai-agents/:agentId/runs lists an agent's
// triggered runs (a mention or a delegation), newest first, keyset-paginated. Runs are
diff --git a/apps/api/src/ai-agents/__tests__/integration/agent-threads.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/agent-threads.test.ts
similarity index 98%
rename from apps/api/src/ai-agents/__tests__/integration/agent-threads.test.ts
rename to apps/api/src/modules/agents/core/__tests__/integration/agent-threads.test.ts
index 295781c4..5d319370 100644
--- a/apps/api/src/ai-agents/__tests__/integration/agent-threads.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/integration/agent-threads.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
import { ensureThread, buildMemory } from '../../runtime/memory';
// The chat-history endpoints:
diff --git a/apps/api/src/ai-agents/__tests__/integration/ai-agents.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts
similarity index 98%
rename from apps/api/src/ai-agents/__tests__/integration/ai-agents.test.ts
rename to apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts
index c18fb7a3..af2605b9 100644
--- a/apps/api/src/ai-agents/__tests__/integration/ai-agents.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-import { untaggedRoutes } from '../../../__tests__/helpers/mcp';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { untaggedRoutes } from '#tests/helpers/mcp';
// AI agents attached to a project. Each agent is backed by a hidden bot user, owns a
// better-auth API key, and is a project member acting under a project role. An
diff --git a/apps/api/src/ai-agents/__tests__/integration/mention-runs.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/mention-runs.test.ts
similarity index 95%
rename from apps/api/src/ai-agents/__tests__/integration/mention-runs.test.ts
rename to apps/api/src/modules/agents/core/__tests__/integration/mention-runs.test.ts
index c37e093a..072d64f3 100644
--- a/apps/api/src/ai-agents/__tests__/integration/mention-runs.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/integration/mention-runs.test.ts
@@ -1,10 +1,10 @@
import { describe, it, expect, beforeEach } from 'bun:test';
import { db, agentRun } from '@repo/db';
import { eq } from 'drizzle-orm';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-import { createComment } from '../../../issues/activity';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { createComment } from '../../../../../issues/activity';
import { claimDueRuns } from '../../run-queue';
// Mentioning an internal agent in a comment queues an agent_run so the agent can
diff --git a/apps/api/src/ai-agents/__tests__/integration/route-tools.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts
similarity index 96%
rename from apps/api/src/ai-agents/__tests__/integration/route-tools.test.ts
rename to apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts
index 6d52886a..7c889bd7 100644
--- a/apps/api/src/ai-agents/__tests__/integration/route-tools.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/integration/route-tools.test.ts
@@ -1,15 +1,15 @@
import { beforeEach, describe, expect, it } from 'bun:test';
import { db, aiAgent, apikey, projectMember } from '@repo/db';
import { eq } from 'drizzle-orm';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-import { getProjectByKey } from '../../../projects/store';
-import { getAgentById, getInternalAgentApiKey } from '../../store';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { getProjectByKey } from '../../../../../projects/store';
+import { getAgentById, getInternalAgentApiKey } from '../../service';
import { buildRouteTools } from '../../runtime/tools/route-tools';
import { AGENT_ACTIONS, ALWAYS_ON_ACTIONS } from '../../runtime/tools/catalog';
-import { routeTools } from '../../../mcp/generate';
-import { getMcpApp } from '../../../mcp/app-ref';
+import { routeTools } from '#mcp/generate';
+import { getMcpApp } from '#mcp/app-ref';
// The tools an internal agent runs with, built from the routes tagged mcpTool() and
// dispatched in process with the agent's own API key. What is asserted here is the
diff --git a/apps/api/src/ai-agents/__tests__/integration/run-queue.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/run-queue.test.ts
similarity index 95%
rename from apps/api/src/ai-agents/__tests__/integration/run-queue.test.ts
rename to apps/api/src/modules/agents/core/__tests__/integration/run-queue.test.ts
index bdf840e9..f0f5ecdb 100644
--- a/apps/api/src/ai-agents/__tests__/integration/run-queue.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/integration/run-queue.test.ts
@@ -1,9 +1,9 @@
import { describe, it, expect, beforeEach } from 'bun:test';
import { db, agentRun } from '@repo/db';
import { eq } from 'drizzle-orm';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
import {
enqueueAgentRun,
claimDueRuns,
diff --git a/apps/api/src/ai-agents/__tests__/integration/thread-cleanup.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/thread-cleanup.test.ts
similarity index 97%
rename from apps/api/src/ai-agents/__tests__/integration/thread-cleanup.test.ts
rename to apps/api/src/modules/agents/core/__tests__/integration/thread-cleanup.test.ts
index 346ebf76..eef1da97 100644
--- a/apps/api/src/ai-agents/__tests__/integration/thread-cleanup.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/integration/thread-cleanup.test.ts
@@ -1,9 +1,9 @@
import { describe, it, expect, beforeEach } from 'bun:test';
import { db } from '@repo/db';
import { sql } from 'drizzle-orm';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
import { ensureThread, buildMemory } from '../../runtime/memory';
// Agent conversation threads live in Mastra's tables, which carry no foreign key of
diff --git a/apps/api/src/ai-agents/__tests__/unit/mentions.test.ts b/apps/api/src/modules/agents/core/__tests__/unit/mentions.test.ts
similarity index 100%
rename from apps/api/src/ai-agents/__tests__/unit/mentions.test.ts
rename to apps/api/src/modules/agents/core/__tests__/unit/mentions.test.ts
diff --git a/apps/api/src/ai-agents/__tests__/unit/thread-ids.test.ts b/apps/api/src/modules/agents/core/__tests__/unit/thread-ids.test.ts
similarity index 100%
rename from apps/api/src/ai-agents/__tests__/unit/thread-ids.test.ts
rename to apps/api/src/modules/agents/core/__tests__/unit/thread-ids.test.ts
diff --git a/apps/api/src/ai-agents/__tests__/unit/tools.test.ts b/apps/api/src/modules/agents/core/__tests__/unit/tools.test.ts
similarity index 100%
rename from apps/api/src/ai-agents/__tests__/unit/tools.test.ts
rename to apps/api/src/modules/agents/core/__tests__/unit/tools.test.ts
diff --git a/apps/api/src/ai-agents/helpers/dates.ts b/apps/api/src/modules/agents/core/helpers/dates.ts
similarity index 100%
rename from apps/api/src/ai-agents/helpers/dates.ts
rename to apps/api/src/modules/agents/core/helpers/dates.ts
diff --git a/apps/api/src/ai-agents/helpers/env.ts b/apps/api/src/modules/agents/core/helpers/env.ts
similarity index 100%
rename from apps/api/src/ai-agents/helpers/env.ts
rename to apps/api/src/modules/agents/core/helpers/env.ts
diff --git a/apps/api/src/ai-agents/helpers/errors.ts b/apps/api/src/modules/agents/core/helpers/errors.ts
similarity index 100%
rename from apps/api/src/ai-agents/helpers/errors.ts
rename to apps/api/src/modules/agents/core/helpers/errors.ts
diff --git a/apps/api/src/ai-agents/routes.ts b/apps/api/src/modules/agents/core/index.ts
similarity index 55%
rename from apps/api/src/ai-agents/routes.ts
rename to apps/api/src/modules/agents/core/index.ts
index 4e312bc5..9555a7d4 100644
--- a/apps/api/src/ai-agents/routes.ts
+++ b/apps/api/src/modules/agents/core/index.ts
@@ -1,11 +1,11 @@
import { Elysia, t } from 'elysia';
-import { noContent } from '../shared/http';
-import { guards } from '../shared/guards';
-import { authContext } from '../shared/auth-context';
-import { requireUser } from '../shared/access';
-import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
-import { mcpTool } from '../mcp/generate';
+import { noContent } from '#shared/http';
+import { guards } from '#shared/guards';
+import { authContext } from '#shared/auth-context';
+import { requireUser } from '#shared/access';
+import { HttpError } from '#shared/lib';
+import { accessErrors, commonErrors, errors } from '#shared/responses';
+import { mcpTool } from '#mcp/generate';
import {
listAgents,
createAgent,
@@ -13,34 +13,31 @@ import {
deleteAgent,
regenerateKey,
getAgentById,
-} from './store';
+} from './service';
+import {
+ AgentRunPageResponse,
+ AiAgentListResponse,
+ AiAgentResponse,
+ ChatMessagesResponse,
+ ChatThreadListResponse,
+ CreateAgentResponse,
+ RegenerateKeyResponse,
+ RunAgentResponse,
+ agentParams,
+ createAgentBody,
+ runBody,
+ runsQuery,
+ threadMessagesQuery,
+ threadParams,
+ updateAgentBody,
+} from './model';
import { runAgent, streamAgent, type RunOpts } from './runtime';
import { peoplePreamble } from './prompt/run-context';
-import type { SessionUser } from '../shared/auth-context';
+import type { SessionUser } from '#shared/auth-context';
import { listAgentRuns } from './run-queue';
import { listChatThreads, getChatThreadMessages, deleteChatThread } from './runtime/memory';
import { isOwnChatThread } from './runtime/thread-ids';
-const agentParams = t.Object({
- projectKey: t.String(),
- agentId: t.Numeric({ description: 'Agent id from list_ai_agents.' }),
-});
-const threadParams = t.Object({
- projectKey: t.String(),
- agentId: t.Numeric(),
- threadId: t.String(),
-});
-
-// Body of the interactive run endpoints. threadId continues a conversation when the
-// agent has memory enabled; omit it to start a new thread (the id used is returned in
-// the response).
-const runBody = t.Object({
- prompt: t.String({ minLength: 1, description: 'Message to send the agent.' }),
- threadId: t.Optional(
- t.String({ description: 'Thread id from an earlier run, to continue that conversation.' }),
- ),
-});
-
// Run options for an interactive chat run (the test chat): the caller owns the memory
// thread and is named to the agent as the requester. A supplied thread id must be one
// issued to this caller for this agent — anyone else's chat, and the threads of the
@@ -59,164 +56,12 @@ function chatRunOpts(user: SessionUser | null, agentId: number, threadId?: strin
};
}
-// A username is a short handle used to address the agent; keep it URL/mention safe.
-const username = t.String({
- minLength: 1,
- maxLength: 64,
- pattern: '^[a-zA-Z0-9._-]+$',
- description: 'Mention handle (letters, digits, . _ -).',
-});
-
-// Internal-agent model configuration, all optional so a config can be filled in
-// over time. Ignored (stored as null/empty) for an external agent.
-const configFields = {
- modelCredentialId: t.Optional(
- t.Nullable(
- t.Number({
- description:
- 'Credential id of the LLM provider, from list_integration_credentials. Required for an ' +
- 'internal agent to run.',
- }),
- ),
- ),
- model: t.Optional(
- t.Nullable(
- t.String({
- description:
- "Model id the provider offers, from list_provider_models, e.g. 'claude-sonnet-5'.",
- }),
- ),
- ),
- instructions: t.Optional(t.Nullable(t.String({ description: 'System prompt for the agent.' }))),
- tools: t.Optional(
- t.Array(t.String(), {
- description:
- 'Built-in action keys from list_ai_agent_tools the agent is granted. Tools on an ' +
- 'integration are granted separately, through set_ai_agent_configured_tools.',
- }),
- ),
- temperature: t.Optional(t.Nullable(t.Number({ description: 'Sampling temperature.' }))),
- maxSteps: t.Optional(t.Nullable(t.Integer({ description: 'Max tool-call steps per run.' }))),
- memoryEnabled: t.Optional(
- t.Boolean({ description: 'Keep conversation memory across a thread.' }),
- ),
- memoryLastMessages: t.Optional(
- t.Nullable(t.Integer({ minimum: 1, description: 'How many recent messages to recall.' })),
- ),
- triggerOnMention: t.Optional(t.Boolean({ description: 'Run when @-mentioned in a comment.' })),
- triggerOnAssign: t.Optional(t.Boolean({ description: 'Run when assigned to an issue.' })),
- roleId: t.Optional(
- t.Nullable(
- t.Integer({
- description:
- 'Role from list_roles the bot acts under, capping what its tools may do; null uses the ' +
- 'default role.',
- }),
- ),
- ),
-};
-
-// An agent DTO (AiAgentRow from the store).
-const AiAgentResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- userId: t.String(),
- name: t.String(),
- username: t.String(),
- kind: t.Union([t.Literal('external'), t.Literal('internal')]),
- modelCredentialId: t.Nullable(t.Number()),
- model: t.Nullable(t.String()),
- instructions: t.Nullable(t.String()),
- tools: t.Array(t.String()),
- temperature: t.Nullable(t.Number()),
- maxSteps: t.Nullable(t.Number()),
- memoryEnabled: t.Boolean(),
- memoryLastMessages: t.Nullable(t.Number()),
- triggerOnMention: t.Boolean(),
- triggerOnAssign: t.Boolean(),
- roleId: t.Nullable(t.Number()),
- createdAt: t.String(),
- apiKeyStart: t.Nullable(t.String()),
- modelProvider: t.Nullable(t.String()),
- actionCount: t.Number(),
- skillCount: t.Number(),
- toolCount: t.Number(),
-});
-
-// createAgent's result: the agent plus its one-time API key secret (null for an
-// internal agent, which has no key).
-const CreateAgentResponse = t.Object({
- agent: AiAgentResponse,
- apiKey: t.Nullable(t.String()),
-});
-
-// The new API key secret returned once by regenerate-key.
-const RegenerateKeyResponse = t.Object({ apiKey: t.String() });
-
-// A run's generated text and the conversation thread id (null when memory is off).
-const RunAgentResponse = t.Object({
- text: t.String(),
- threadId: t.Nullable(t.String()),
-});
-
-// One row of an agent's run history (AgentRunRow from run-queue).
-const AgentRunResponse = t.Object({
- id: t.Number(),
- status: t.String(),
- trigger: t.Union([
- t.Literal('mention'),
- t.Literal('delegation'),
- t.Literal('schedule'),
- t.Literal('manual'),
- ]),
- issueId: t.Nullable(t.Number()),
- issueIdentifier: t.Nullable(t.String()),
- issueTitle: t.Nullable(t.String()),
- prompt: t.String(),
- attempts: t.Number(),
- lastError: t.Nullable(t.String()),
- nextAttemptAt: t.String(),
- createdAt: t.String(),
-});
-
-// One page of an agent's runs (AgentRunPage from run-queue).
-const AgentRunPageResponse = t.Object({
- items: t.Array(AgentRunResponse),
- nextCursor: t.Nullable(t.Number()),
-});
-
-// One chat thread in the caller's history with an agent (ChatThreadSummary).
-const ChatThreadResponse = t.Object({
- id: t.String(),
- title: t.Nullable(t.String()),
- createdAt: t.String(),
- updatedAt: t.String(),
-});
-
-// One page of a chat thread's transcript (ChatMessagePage).
-const ChatMessagesResponse = t.Object({
- items: t.Array(
- t.Object({
- id: t.String(),
- role: t.Union([t.Literal('user'), t.Literal('assistant')]),
- text: t.String(),
- createdAt: t.String(),
- }),
- ),
- nextPage: t.Nullable(t.Number()),
-});
-
export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['AI Agents'] } })
.use(authContext)
.use(guards)
.get('/projects/:projectKey/ai-agents', ({ project }) => listAgents(project.id), {
permission: ['ai_agents', 'read'],
- response: {
- 200: t.Array(AiAgentResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: AiAgentListResponse, ...accessErrors },
detail: {
summary: 'List AI agents',
description: "List a project's AI agents with their config.",
@@ -234,13 +79,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
{
params: agentParams,
permission: ['ai_agents', 'read'],
- response: {
- 200: AiAgentResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: AiAgentResponse, ...commonErrors },
detail: {
summary: 'Get an AI agent',
description: 'Get an AI agent by id with its config.',
@@ -259,23 +98,9 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
return createAgent(project.id, body);
},
{
- body: t.Object({
- name: t.String({ minLength: 1, description: 'Display name.' }),
- username,
- kind: t.Union([t.Literal('external'), t.Literal('internal')], {
- description: "'external' (API key) or 'internal' (in-process, needs a model config).",
- }),
- ...configFields,
- }),
+ body: createAgentBody,
permission: ['ai_agents', 'create'],
- response: {
- 201: CreateAgentResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 201: CreateAgentResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Create an AI agent',
description:
@@ -294,21 +119,10 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
return agent;
},
{
- body: t.Object({
- name: t.Optional(t.String({ minLength: 1 })),
- username: t.Optional(username),
- ...configFields,
- }),
+ body: updateAgentBody,
params: agentParams,
permission: ['ai_agents', 'edit'],
- response: {
- 200: AiAgentResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 200: AiAgentResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Update an AI agent',
description: "Update an AI agent's name, username, or model config.",
@@ -333,13 +147,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
{
params: agentParams,
permission: ['ai_agents', 'edit'],
- response: {
- 200: RegenerateKeyResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: RegenerateKeyResponse, ...commonErrors },
detail: {
summary: 'Regenerate the API key',
description: "Rotate an external agent's API key and return the new secret once.",
@@ -360,18 +168,9 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
},
{
params: agentParams,
- query: t.Object({
- before: t.Optional(t.Numeric()),
- limit: t.Optional(t.Numeric()),
- }),
+ query: runsQuery,
permission: ['ai_agents', 'read'],
- response: {
- 200: AgentRunPageResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: AgentRunPageResponse, ...commonErrors },
detail: {
summary: 'List agent runs',
description: "List an agent's triggered runs.",
@@ -389,13 +188,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
{
params: agentParams,
permission: ['ai_agents', 'delete'],
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete an AI agent',
description: 'Delete an AI agent and its bot user. Irreversible.',
@@ -418,13 +211,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
body: runBody,
params: agentParams,
permission: ['ai_agents', 'read'],
- response: {
- 200: RunAgentResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: RunAgentResponse, ...commonErrors },
detail: {
summary: 'Run an AI agent',
description:
@@ -476,10 +263,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
// The success body is an SSE stream (text/event-stream), returned as a raw
// Response, so it is not a JSON shape the validator can describe.
200: t.Any(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
+ ...commonErrors,
},
detail: {
summary: 'Run an AI agent (stream)',
@@ -501,13 +285,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
{
params: agentParams,
permission: ['ai_agents', 'read'],
- response: {
- 200: t.Array(ChatThreadResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ChatThreadListResponse, ...commonErrors },
detail: { summary: 'List chat threads' },
},
)
@@ -526,15 +304,9 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
},
{
params: threadParams,
- query: t.Object({ page: t.Optional(t.Numeric({ minimum: 0 })) }),
+ query: threadMessagesQuery,
permission: ['ai_agents', 'read'],
- response: {
- 200: ChatMessagesResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ChatMessagesResponse, ...commonErrors },
detail: { summary: 'Get thread messages' },
},
)
@@ -555,13 +327,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
{
params: threadParams,
permission: ['ai_agents', 'read'],
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: { summary: 'Delete a chat thread' },
},
);
diff --git a/apps/api/src/ai-agents/internal-routes.ts b/apps/api/src/modules/agents/core/internal-routes.ts
similarity index 100%
rename from apps/api/src/ai-agents/internal-routes.ts
rename to apps/api/src/modules/agents/core/internal-routes.ts
diff --git a/apps/api/src/ai-agents/issue-query.ts b/apps/api/src/modules/agents/core/issue-query.ts
similarity index 100%
rename from apps/api/src/ai-agents/issue-query.ts
rename to apps/api/src/modules/agents/core/issue-query.ts
diff --git a/apps/api/src/ai-agents/mentions.ts b/apps/api/src/modules/agents/core/mentions.ts
similarity index 100%
rename from apps/api/src/ai-agents/mentions.ts
rename to apps/api/src/modules/agents/core/mentions.ts
diff --git a/apps/api/src/modules/agents/core/model.ts b/apps/api/src/modules/agents/core/model.ts
new file mode 100644
index 00000000..86d76a63
--- /dev/null
+++ b/apps/api/src/modules/agents/core/model.ts
@@ -0,0 +1,192 @@
+import { t } from 'elysia';
+
+export { agentParams } from '../model';
+
+export const threadParams = t.Object({
+ projectKey: t.String(),
+ agentId: t.Numeric(),
+ threadId: t.String(),
+});
+
+// Body of the interactive run endpoints. threadId continues a conversation when the
+// agent has memory enabled; omit it to start a new thread (the id used is returned in
+// the response).
+export const runBody = t.Object({
+ prompt: t.String({ minLength: 1, description: 'Message to send the agent.' }),
+ threadId: t.Optional(
+ t.String({ description: 'Thread id from an earlier run, to continue that conversation.' }),
+ ),
+});
+
+// A username is a short handle used to address the agent; keep it URL/mention safe.
+const username = t.String({
+ minLength: 1,
+ maxLength: 64,
+ pattern: '^[a-zA-Z0-9._-]+$',
+ description: 'Mention handle (letters, digits, . _ -).',
+});
+
+// Internal-agent model configuration, all optional so a config can be filled in
+// over time. Ignored (stored as null/empty) for an external agent.
+const configFields = {
+ modelCredentialId: t.Optional(
+ t.Nullable(
+ t.Number({
+ description:
+ 'Credential id of the LLM provider, from list_integration_credentials. Required for an ' +
+ 'internal agent to run.',
+ }),
+ ),
+ ),
+ model: t.Optional(
+ t.Nullable(
+ t.String({
+ description:
+ "Model id the provider offers, from list_provider_models, e.g. 'claude-sonnet-5'.",
+ }),
+ ),
+ ),
+ instructions: t.Optional(t.Nullable(t.String({ description: 'System prompt for the agent.' }))),
+ tools: t.Optional(
+ t.Array(t.String(), {
+ description:
+ 'Built-in action keys from list_ai_agent_tools the agent is granted. Tools on an ' +
+ 'integration are granted separately, through set_ai_agent_configured_tools.',
+ }),
+ ),
+ temperature: t.Optional(t.Nullable(t.Number({ description: 'Sampling temperature.' }))),
+ maxSteps: t.Optional(t.Nullable(t.Integer({ description: 'Max tool-call steps per run.' }))),
+ memoryEnabled: t.Optional(
+ t.Boolean({ description: 'Keep conversation memory across a thread.' }),
+ ),
+ memoryLastMessages: t.Optional(
+ t.Nullable(t.Integer({ minimum: 1, description: 'How many recent messages to recall.' })),
+ ),
+ triggerOnMention: t.Optional(t.Boolean({ description: 'Run when @-mentioned in a comment.' })),
+ triggerOnAssign: t.Optional(t.Boolean({ description: 'Run when assigned to an issue.' })),
+ roleId: t.Optional(
+ t.Nullable(
+ t.Integer({
+ description:
+ 'Role from list_roles the bot acts under, capping what its tools may do; null uses the ' +
+ 'default role.',
+ }),
+ ),
+ ),
+};
+
+// An agent DTO (AiAgentRow from the service).
+export const AiAgentResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ userId: t.String(),
+ name: t.String(),
+ username: t.String(),
+ kind: t.Union([t.Literal('external'), t.Literal('internal')]),
+ modelCredentialId: t.Nullable(t.Number()),
+ model: t.Nullable(t.String()),
+ instructions: t.Nullable(t.String()),
+ tools: t.Array(t.String()),
+ temperature: t.Nullable(t.Number()),
+ maxSteps: t.Nullable(t.Number()),
+ memoryEnabled: t.Boolean(),
+ memoryLastMessages: t.Nullable(t.Number()),
+ triggerOnMention: t.Boolean(),
+ triggerOnAssign: t.Boolean(),
+ roleId: t.Nullable(t.Number()),
+ createdAt: t.String(),
+ apiKeyStart: t.Nullable(t.String()),
+ modelProvider: t.Nullable(t.String()),
+ actionCount: t.Number(),
+ skillCount: t.Number(),
+ toolCount: t.Number(),
+});
+
+// createAgent's result: the agent plus its one-time API key secret (null for an
+// internal agent, which has no key).
+export const CreateAgentResponse = t.Object({
+ agent: AiAgentResponse,
+ apiKey: t.Nullable(t.String()),
+});
+
+// The new API key secret returned once by regenerate-key.
+export const RegenerateKeyResponse = t.Object({ apiKey: t.String() });
+
+// A run's generated text and the conversation thread id (null when memory is off).
+export const RunAgentResponse = t.Object({
+ text: t.String(),
+ threadId: t.Nullable(t.String()),
+});
+
+// One row of an agent's run history (AgentRunRow from run-queue).
+export const AgentRunResponse = t.Object({
+ id: t.Number(),
+ status: t.String(),
+ trigger: t.Union([
+ t.Literal('mention'),
+ t.Literal('delegation'),
+ t.Literal('schedule'),
+ t.Literal('manual'),
+ ]),
+ issueId: t.Nullable(t.Number()),
+ issueIdentifier: t.Nullable(t.String()),
+ issueTitle: t.Nullable(t.String()),
+ prompt: t.String(),
+ attempts: t.Number(),
+ lastError: t.Nullable(t.String()),
+ nextAttemptAt: t.String(),
+ createdAt: t.String(),
+});
+
+// One page of an agent's runs (AgentRunPage from run-queue).
+export const AgentRunPageResponse = t.Object({
+ items: t.Array(AgentRunResponse),
+ nextCursor: t.Nullable(t.Number()),
+});
+
+// One chat thread in the caller's history with an agent (ChatThreadSummary).
+export const ChatThreadResponse = t.Object({
+ id: t.String(),
+ title: t.Nullable(t.String()),
+ createdAt: t.String(),
+ updatedAt: t.String(),
+});
+
+// One page of a chat thread's transcript (ChatMessagePage).
+export const ChatMessagesResponse = t.Object({
+ items: t.Array(
+ t.Object({
+ id: t.String(),
+ role: t.Union([t.Literal('user'), t.Literal('assistant')]),
+ text: t.String(),
+ createdAt: t.String(),
+ }),
+ ),
+ nextPage: t.Nullable(t.Number()),
+});
+
+export const AiAgentListResponse = t.Array(AiAgentResponse);
+
+export const ChatThreadListResponse = t.Array(ChatThreadResponse);
+
+export const createAgentBody = t.Object({
+ name: t.String({ minLength: 1, description: 'Display name.' }),
+ username,
+ kind: t.Union([t.Literal('external'), t.Literal('internal')], {
+ description: "'external' (API key) or 'internal' (in-process, needs a model config).",
+ }),
+ ...configFields,
+});
+
+export const updateAgentBody = t.Object({
+ name: t.Optional(t.String({ minLength: 1 })),
+ username: t.Optional(username),
+ ...configFields,
+});
+
+export const runsQuery = t.Object({
+ before: t.Optional(t.Numeric()),
+ limit: t.Optional(t.Numeric()),
+});
+
+export const threadMessagesQuery = t.Object({ page: t.Optional(t.Numeric({ minimum: 0 })) });
diff --git a/apps/api/src/ai-agents/prompt/framing.ts b/apps/api/src/modules/agents/core/prompt/framing.ts
similarity index 98%
rename from apps/api/src/ai-agents/prompt/framing.ts
rename to apps/api/src/modules/agents/core/prompt/framing.ts
index 665218c7..0654d19d 100644
--- a/apps/api/src/ai-agents/prompt/framing.ts
+++ b/apps/api/src/modules/agents/core/prompt/framing.ts
@@ -4,7 +4,7 @@ import { renderMentionsPlain, parseMentionedUsers } from '../mentions';
// Frames a triggered internal run into the text an agent receives: the framed user
// prompt (framePrompt) and the system-instruction blocks about the run mode
// (runModePreamble) and the people involved (peopleContext). The interactive test
-// chat does not use this path — it frames its own prompt in routes.ts.
+// chat does not use this path — it frames its own prompt in the controller.
// The fields of a claimed run this module reads. The HTTP body in internal-routes.ts
// is structurally compatible.
diff --git a/apps/api/src/ai-agents/prompt/run-context.ts b/apps/api/src/modules/agents/core/prompt/run-context.ts
similarity index 100%
rename from apps/api/src/ai-agents/prompt/run-context.ts
rename to apps/api/src/modules/agents/core/prompt/run-context.ts
diff --git a/apps/api/src/ai-agents/run-queue.ts b/apps/api/src/modules/agents/core/run-queue.ts
similarity index 99%
rename from apps/api/src/ai-agents/run-queue.ts
rename to apps/api/src/modules/agents/core/run-queue.ts
index cde3756e..aadeed49 100644
--- a/apps/api/src/ai-agents/run-queue.ts
+++ b/apps/api/src/modules/agents/core/run-queue.ts
@@ -1,6 +1,6 @@
import { db, agentRun, issue, project } from '@repo/db';
import { and, desc, eq, lt, sql } from 'drizzle-orm';
-import { iso } from '../shared/lib';
+import { iso } from '#shared/lib';
import { intEnv } from './helpers/env';
import { renderMentionsPlain } from './mentions';
diff --git a/apps/api/src/ai-agents/runtime/index.ts b/apps/api/src/modules/agents/core/runtime/index.ts
similarity index 96%
rename from apps/api/src/ai-agents/runtime/index.ts
rename to apps/api/src/modules/agents/core/runtime/index.ts
index 9c6e06a5..0712789c 100644
--- a/apps/api/src/ai-agents/runtime/index.ts
+++ b/apps/api/src/modules/agents/core/runtime/index.ts
@@ -1,9 +1,9 @@
import { Agent } from '@mastra/core/agent';
-import { getAgentById, getInternalAgentApiKey, type AiAgentRow } from '../store';
-import { getProjectById, type ProjectRow } from '../../projects/store';
-import { getCredentialSecret } from '../../integrations/store';
-import { listAgentSkills } from '../../agent-skills/store';
-import { listAgentToolsForRun } from '../../agent-tools/store';
+import { getAgentById, getInternalAgentApiKey, type AiAgentRow } from '../service';
+import { getProjectById, type ProjectRow } from '../../../../projects/store';
+import { getCredentialSecret } from '../../integrations/service';
+import { listAgentSkills } from '../../skills/service';
+import { listAgentToolsForRun } from '../../tools/service';
import { buildCustomTools } from './tools/custom-tools';
import { buildRouteTools } from './tools/route-tools';
import { buildLocalTools } from './tools/local';
@@ -11,11 +11,11 @@ import { buildSkillTool, skillsPreamble } from './skill-runtime';
import { buildMemory, ensureThread, DEFAULT_LAST_MESSAGES } from './memory';
import { isChatThreadId, newChatThreadId } from './thread-ids';
import { errorMessage } from '../helpers/errors';
-import { HttpError } from '../../shared/lib';
+import { HttpError } from '#shared/lib';
// Runtime execution of internal agents via Mastra. An agent is built on demand
// from its stored configuration (provider/model/instructions) and run against a
-// prompt. It is given the work-item system tools for its project (see tools/agent-tools),
+// prompt. It is given the work-item system tools for its project (see tools/route-tools),
// so it can read and manage that project's issues, comments, labels, custom field
// values, and attachments — acting as its own bot user, plus a read_skill tool for
// any skills enabled on it.
diff --git a/apps/api/src/ai-agents/runtime/memory.ts b/apps/api/src/modules/agents/core/runtime/memory.ts
similarity index 100%
rename from apps/api/src/ai-agents/runtime/memory.ts
rename to apps/api/src/modules/agents/core/runtime/memory.ts
diff --git a/apps/api/src/ai-agents/runtime/skill-runtime.ts b/apps/api/src/modules/agents/core/runtime/skill-runtime.ts
similarity index 98%
rename from apps/api/src/ai-agents/runtime/skill-runtime.ts
rename to apps/api/src/modules/agents/core/runtime/skill-runtime.ts
index 9bc75233..47000dfd 100644
--- a/apps/api/src/ai-agents/runtime/skill-runtime.ts
+++ b/apps/api/src/modules/agents/core/runtime/skill-runtime.ts
@@ -1,6 +1,6 @@
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';
-import { getSkillMarkdown, getSkillRefContent, type SkillRow } from '../../agent-skills/store';
+import { getSkillMarkdown, getSkillRefContent, type SkillRow } from '../../skills/service';
// Wires a project's skills into an internal agent run using progressive disclosure:
// the system prompt lists only each enabled skill's name and description, and a
diff --git a/apps/api/src/ai-agents/runtime/thread-ids.ts b/apps/api/src/modules/agents/core/runtime/thread-ids.ts
similarity index 100%
rename from apps/api/src/ai-agents/runtime/thread-ids.ts
rename to apps/api/src/modules/agents/core/runtime/thread-ids.ts
diff --git a/apps/api/src/ai-agents/runtime/tools/catalog.ts b/apps/api/src/modules/agents/core/runtime/tools/catalog.ts
similarity index 100%
rename from apps/api/src/ai-agents/runtime/tools/catalog.ts
rename to apps/api/src/modules/agents/core/runtime/tools/catalog.ts
diff --git a/apps/api/src/ai-agents/runtime/tools/custom-tools.ts b/apps/api/src/modules/agents/core/runtime/tools/custom-tools.ts
similarity index 100%
rename from apps/api/src/ai-agents/runtime/tools/custom-tools.ts
rename to apps/api/src/modules/agents/core/runtime/tools/custom-tools.ts
diff --git a/apps/api/src/ai-agents/runtime/tools/local.ts b/apps/api/src/modules/agents/core/runtime/tools/local.ts
similarity index 100%
rename from apps/api/src/ai-agents/runtime/tools/local.ts
rename to apps/api/src/modules/agents/core/runtime/tools/local.ts
diff --git a/apps/api/src/ai-agents/runtime/tools/route-tools.ts b/apps/api/src/modules/agents/core/runtime/tools/route-tools.ts
similarity index 96%
rename from apps/api/src/ai-agents/runtime/tools/route-tools.ts
rename to apps/api/src/modules/agents/core/runtime/tools/route-tools.ts
index 6bb5729c..2f693827 100644
--- a/apps/api/src/ai-agents/runtime/tools/route-tools.ts
+++ b/apps/api/src/modules/agents/core/runtime/tools/route-tools.ts
@@ -1,9 +1,9 @@
import { createTool } from '@mastra/core/tools';
import type { z } from 'zod';
-import type { ProjectRow } from '../../../projects/store';
-import { routeTools, type McpInputSchema, type McpRouteTool } from '../../../mcp/generate';
-import { dispatchTool } from '../../../mcp/dispatch';
-import { getMcpApp } from '../../../mcp/app-ref';
+import type { ProjectRow } from '../../../../../projects/store';
+import { routeTools, type McpInputSchema, type McpRouteTool } from '#mcp/generate';
+import { dispatchTool } from '#mcp/dispatch';
+import { getMcpApp } from '#mcp/app-ref';
import { ALWAYS_ON_KEYS, normalizeToolKeys, toolMeta } from './catalog';
// The tools an internal agent uses to work in its project, built from the routes
diff --git a/apps/api/src/ai-agents/store.ts b/apps/api/src/modules/agents/core/service.ts
similarity index 97%
rename from apps/api/src/ai-agents/store.ts
rename to apps/api/src/modules/agents/core/service.ts
index be70286c..34714d3a 100644
--- a/apps/api/src/ai-agents/store.ts
+++ b/apps/api/src/modules/agents/core/service.ts
@@ -10,8 +10,8 @@ import {
} from '@repo/db';
import { and, eq, inArray, sql } from 'drizzle-orm';
import { auth } from '@repo/auth';
-import { iso, HttpError, rethrowDuplicate } from '../shared/lib';
-import { getCredentialById } from '../integrations/store';
+import { iso, HttpError, rethrowDuplicate } from '#shared/lib';
+import { getCredentialById } from '../integrations/service';
import { integrationKind } from '../integrations/catalog';
import { encryptSecret, decryptSecret } from '@repo/crypto';
import { normalizeToolKeys, ALWAYS_ON_ACTIONS } from './runtime/tools/catalog';
@@ -507,3 +507,13 @@ export async function deleteAgent(id: number, projectId: number): Promise<boolea
await db.delete(user).where(eq(user.id, agent.userId));
return true;
}
+
+// True if the agent belongs to the project (guards addressing an agent by id).
+export async function agentInProject(agentId: number, projectId: number): Promise<boolean> {
+ const rows = await db
+ .select({ id: aiAgent.id })
+ .from(aiAgent)
+ .where(and(eq(aiAgent.id, agentId), eq(aiAgent.projectId, projectId)))
+ .limit(1);
+ return rows.length > 0;
+}
diff --git a/apps/api/src/integrations/__tests__/integration/integrations.test.ts b/apps/api/src/modules/agents/integrations/__tests__/integration/integrations.test.ts
similarity index 95%
rename from apps/api/src/integrations/__tests__/integration/integrations.test.ts
rename to apps/api/src/modules/agents/integrations/__tests__/integration/integrations.test.ts
index 4857c236..503fbb09 100644
--- a/apps/api/src/integrations/__tests__/integration/integrations.test.ts
+++ b/apps/api/src/modules/agents/integrations/__tests__/integration/integrations.test.ts
@@ -1,9 +1,9 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-import { addProjectMember } from '../../../__tests__/helpers/members';
-import { untaggedRoutes } from '../../../__tests__/helpers/mcp';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { addProjectMember } from '#tests/helpers/members';
+import { untaggedRoutes } from '#tests/helpers/mcp';
// Integration credentials for a project: one store for LLM provider keys (kind 'llm')
// and tool credentials (kind 'tool'). The secret is stored encrypted and never
diff --git a/apps/api/src/integrations/catalog.ts b/apps/api/src/modules/agents/integrations/catalog.ts
similarity index 100%
rename from apps/api/src/integrations/catalog.ts
rename to apps/api/src/modules/agents/integrations/catalog.ts
diff --git a/apps/api/src/integrations/routes.ts b/apps/api/src/modules/agents/integrations/index.ts
similarity index 58%
rename from apps/api/src/integrations/routes.ts
rename to apps/api/src/modules/agents/integrations/index.ts
index 13323d7d..f3e168f6 100644
--- a/apps/api/src/integrations/routes.ts
+++ b/apps/api/src/modules/agents/integrations/index.ts
@@ -1,60 +1,25 @@
import { Elysia, t } from 'elysia';
-import { noContent } from '../shared/http';
-import { guards } from '../shared/guards';
-import { authContext } from '../shared/auth-context';
-import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
-import { mcpTool } from '../mcp/generate';
+import { noContent } from '#shared/http';
+import { guards } from '#shared/guards';
+import { authContext } from '#shared/auth-context';
+import { HttpError } from '#shared/lib';
+import { accessErrors, commonErrors } from '#shared/responses';
+import { mcpTool } from '#mcp/generate';
import { INTEGRATION_CATALOG, integrationKind } from './catalog';
-import { listModelsForProvider } from './models';
-import { listCredentials, createCredential, updateCredential, deleteCredential } from './store';
-
-const credentialParams = t.Object({ projectKey: t.String(), credentialId: t.Numeric() });
-
-// A stored credential DTO — never carries the secret, only the redacted view.
-const CredentialResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- integrationKey: t.String(),
- label: t.Nullable(t.String()),
- redacted: t.Record(t.String(), t.Any()),
- createdAt: t.String(),
-});
-
-const ConfigFieldResponse = t.Object({
- key: t.String(),
- label: t.String(),
- type: t.String(),
- required: t.Boolean(),
- placeholder: t.Optional(t.String()),
- help: t.Optional(t.String()),
-});
-
-const IntegrationResponse = t.Object({
- key: t.String(),
- label: t.String(),
- kind: t.String(),
- credentialSchema: t.Array(ConfigFieldResponse),
- tools: t.Array(
- t.Object({
- key: t.String(),
- label: t.String(),
- description: t.String(),
- scopes: t.Optional(t.Array(t.String())),
- }),
- ),
-});
-
-const ProviderModelResponse = t.Object({ id: t.String(), name: t.String() });
-
-// A connected integration as a picker option: what it is and what it is called.
-// Carries no credential fields, redacted or otherwise.
-const IntegrationOptionResponse = t.Object({
- id: t.Number(),
- integrationKey: t.String(),
- kind: t.Union([t.Literal('llm'), t.Literal('tool')]),
- label: t.Nullable(t.String()),
-});
+import { listModelsForProvider } from './provider-models';
+import {
+ CredentialListResponse,
+ CredentialResponse,
+ IntegrationCatalogResponse,
+ IntegrationOptionListResponse,
+ ProviderModelListResponse,
+ createCredentialBody,
+ credentialParams,
+ integrationOptionsQuery,
+ providerParams,
+ updateCredentialBody,
+} from './model';
+import { listCredentials, createCredential, updateCredential, deleteCredential } from './service';
// The credential store is gated under the integrations resource; the catalog, the
// provider models and the picker options carry no project secrets and are open to
@@ -72,12 +37,7 @@ export const integrationRoutes = new Elysia({
// project member: the catalog is a constant in this codebase, not project data.
.get('/projects/:projectKey/integrations/catalog', () => INTEGRATION_CATALOG, {
projectMember: true,
- response: {
- 200: t.Array(IntegrationResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: IntegrationCatalogResponse, ...accessErrors },
detail: {
summary: 'List available integrations',
description:
@@ -94,19 +54,9 @@ export const integrationRoutes = new Elysia({
'/projects/:projectKey/integrations/models/:provider',
({ params }) => listModelsForProvider(params.provider),
{
- params: t.Object({
- projectKey: t.String(),
- provider: t.String({
- description: "LLM provider key from list_integrations, e.g. 'anthropic'.",
- }),
- }),
+ params: providerParams,
projectMember: true,
- response: {
- 200: t.Array(ProviderModelResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ProviderModelListResponse, ...accessErrors },
detail: {
summary: "List a provider's models",
description:
@@ -132,22 +82,9 @@ export const integrationRoutes = new Elysia({
});
},
{
- params: t.Object({ projectKey: t.String() }),
- query: t.Object({
- kind: t.Optional(
- t.Union([t.Literal('llm'), t.Literal('tool')], {
- description: 'Only the integrations of this kind.',
- }),
- ),
- }),
+ query: integrationOptionsQuery,
projectMember: true,
- response: {
- 200: t.Array(IntegrationOptionResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: IntegrationOptionListResponse, ...commonErrors },
detail: {
summary: 'List integration options',
description:
@@ -158,12 +95,7 @@ export const integrationRoutes = new Elysia({
.get('/projects/:projectKey/integrations', ({ project }) => listCredentials(project.id), {
permission: ['integrations', 'read'],
- response: {
- 200: t.Array(CredentialResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: CredentialListResponse, ...accessErrors },
detail: {
summary: 'List credentials',
description:
@@ -181,19 +113,9 @@ export const integrationRoutes = new Elysia({
return createCredential(project.id, body);
},
{
- body: t.Object({
- integrationKey: t.String({ minLength: 1 }),
- label: t.Optional(t.Nullable(t.String())),
- credential: t.Record(t.String(), t.Any()),
- }),
+ body: createCredentialBody,
permission: ['integrations', 'create'],
- response: {
- 201: CredentialResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: CredentialResponse, ...commonErrors },
detail: {
summary: 'Add a credential',
description: 'Store a credential for an integration.',
@@ -211,19 +133,10 @@ export const integrationRoutes = new Elysia({
return row;
},
{
- body: t.Object({
- label: t.Optional(t.Nullable(t.String())),
- credential: t.Optional(t.Record(t.String(), t.Any())),
- }),
+ body: updateCredentialBody,
params: credentialParams,
permission: ['integrations', 'edit'],
- response: {
- 200: CredentialResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: CredentialResponse, ...commonErrors },
detail: {
summary: 'Update a credential',
description: "Update a credential's label or secret. The integration is fixed.",
@@ -241,12 +154,7 @@ export const integrationRoutes = new Elysia({
{
params: credentialParams,
permission: ['integrations', 'delete'],
- response: {
- 204: t.Void(),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...accessErrors },
detail: {
summary: 'Delete a credential',
description: 'Delete an integration credential.',
diff --git a/apps/api/src/integrations/llm-providers.ts b/apps/api/src/modules/agents/integrations/llm-providers.ts
similarity index 100%
rename from apps/api/src/integrations/llm-providers.ts
rename to apps/api/src/modules/agents/integrations/llm-providers.ts
diff --git a/apps/api/src/modules/agents/integrations/model.ts b/apps/api/src/modules/agents/integrations/model.ts
new file mode 100644
index 00000000..ea12cffd
--- /dev/null
+++ b/apps/api/src/modules/agents/integrations/model.ts
@@ -0,0 +1,81 @@
+import { t } from 'elysia';
+
+export const credentialParams = t.Object({
+ projectKey: t.String(),
+ credentialId: t.Numeric(),
+});
+
+export const providerParams = t.Object({
+ projectKey: t.String(),
+ provider: t.String({ description: "LLM provider key from list_integrations, e.g. 'anthropic'." }),
+});
+
+export const integrationOptionsQuery = t.Object({
+ kind: t.Optional(
+ t.Union([t.Literal('llm'), t.Literal('tool')], {
+ description: 'Only the integrations of this kind.',
+ }),
+ ),
+});
+
+// A stored credential DTO — never carries the secret, only the redacted view.
+export const CredentialResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ integrationKey: t.String(),
+ label: t.Nullable(t.String()),
+ redacted: t.Record(t.String(), t.Any()),
+ createdAt: t.String(),
+});
+
+export const CredentialListResponse = t.Array(CredentialResponse);
+
+const ConfigFieldResponse = t.Object({
+ key: t.String(),
+ label: t.String(),
+ type: t.String(),
+ required: t.Boolean(),
+ placeholder: t.Optional(t.String()),
+ help: t.Optional(t.String()),
+});
+
+const IntegrationResponse = t.Object({
+ key: t.String(),
+ label: t.String(),
+ kind: t.String(),
+ credentialSchema: t.Array(ConfigFieldResponse),
+ tools: t.Array(
+ t.Object({
+ key: t.String(),
+ label: t.String(),
+ description: t.String(),
+ scopes: t.Optional(t.Array(t.String())),
+ }),
+ ),
+});
+
+export const IntegrationCatalogResponse = t.Array(IntegrationResponse);
+
+export const ProviderModelListResponse = t.Array(t.Object({ id: t.String(), name: t.String() }));
+
+// A connected integration as a picker option: what it is and what it is called.
+// Carries no credential fields, redacted or otherwise.
+const IntegrationOptionResponse = t.Object({
+ id: t.Number(),
+ integrationKey: t.String(),
+ kind: t.Union([t.Literal('llm'), t.Literal('tool')]),
+ label: t.Nullable(t.String()),
+});
+
+export const IntegrationOptionListResponse = t.Array(IntegrationOptionResponse);
+
+export const createCredentialBody = t.Object({
+ integrationKey: t.String({ minLength: 1 }),
+ label: t.Optional(t.Nullable(t.String())),
+ credential: t.Record(t.String(), t.Any()),
+});
+
+export const updateCredentialBody = t.Object({
+ label: t.Optional(t.Nullable(t.String())),
+ credential: t.Optional(t.Record(t.String(), t.Any())),
+});
diff --git a/apps/api/src/integrations/models.ts b/apps/api/src/modules/agents/integrations/provider-models.ts
similarity index 100%
rename from apps/api/src/integrations/models.ts
rename to apps/api/src/modules/agents/integrations/provider-models.ts
diff --git a/apps/api/src/integrations/store.ts b/apps/api/src/modules/agents/integrations/service.ts
similarity index 99%
rename from apps/api/src/integrations/store.ts
rename to apps/api/src/modules/agents/integrations/service.ts
index d7b0187d..9546b1b9 100644
--- a/apps/api/src/integrations/store.ts
+++ b/apps/api/src/modules/agents/integrations/service.ts
@@ -7,7 +7,7 @@ import {
type ToolConfig,
type ConfigField,
} from '@repo/agent-tools';
-import { iso, HttpError } from '../shared/lib';
+import { iso, HttpError } from '#shared/lib';
import { encryptSecret, decryptSecret } from '@repo/crypto';
import { credentialSchemaFor } from './catalog';
diff --git a/apps/api/src/modules/agents/model.ts b/apps/api/src/modules/agents/model.ts
new file mode 100644
index 00000000..89ec20ed
--- /dev/null
+++ b/apps/api/src/modules/agents/model.ts
@@ -0,0 +1,7 @@
+import { t } from 'elysia';
+
+// Shared by every route in the domain that addresses an agent by its id.
+export const agentParams = t.Object({
+ projectKey: t.String(),
+ agentId: t.Numeric({ description: 'Agent id from list_ai_agents.' }),
+});
diff --git a/apps/api/src/agent-schedules/__tests__/integration/agent-schedules.test.ts b/apps/api/src/modules/agents/schedules/__tests__/integration/agent-schedules.test.ts
similarity index 96%
rename from apps/api/src/agent-schedules/__tests__/integration/agent-schedules.test.ts
rename to apps/api/src/modules/agents/schedules/__tests__/integration/agent-schedules.test.ts
index 40b2167c..f5bb6810 100644
--- a/apps/api/src/agent-schedules/__tests__/integration/agent-schedules.test.ts
+++ b/apps/api/src/modules/agents/schedules/__tests__/integration/agent-schedules.test.ts
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-import { untaggedRoutes } from '../../../__tests__/helpers/mcp';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { untaggedRoutes } from '#tests/helpers/mcp';
// A schedule sends a fixed task to an internal agent on a cron, in UTC. The worker
// picks up the queued runs, so a run created here stays pending. Access is the
diff --git a/apps/api/src/agent-schedules/__tests__/unit/cron.test.ts b/apps/api/src/modules/agents/schedules/__tests__/unit/cron.test.ts
similarity index 100%
rename from apps/api/src/agent-schedules/__tests__/unit/cron.test.ts
rename to apps/api/src/modules/agents/schedules/__tests__/unit/cron.test.ts
diff --git a/apps/api/src/agent-schedules/cron.ts b/apps/api/src/modules/agents/schedules/cron.ts
similarity index 89%
rename from apps/api/src/agent-schedules/cron.ts
rename to apps/api/src/modules/agents/schedules/cron.ts
index 569f4586..1c34ef6e 100644
--- a/apps/api/src/agent-schedules/cron.ts
+++ b/apps/api/src/modules/agents/schedules/cron.ts
@@ -1,5 +1,5 @@
import { Cron } from 'croner';
-import { HttpError } from '../shared/lib';
+import { HttpError } from '#shared/lib';
export function nextCronRun(expression: string, from = new Date()): Date {
try {
diff --git a/apps/api/src/agent-schedules/routes.ts b/apps/api/src/modules/agents/schedules/index.ts
similarity index 60%
rename from apps/api/src/agent-schedules/routes.ts
rename to apps/api/src/modules/agents/schedules/index.ts
index 58a43165..fe1c87f3 100644
--- a/apps/api/src/agent-schedules/routes.ts
+++ b/apps/api/src/modules/agents/schedules/index.ts
@@ -1,11 +1,20 @@
import { Elysia, t } from 'elysia';
-import { authContext } from '../shared/auth-context';
-import { guards } from '../shared/guards';
-import { noContent } from '../shared/http';
-import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
-import { mcpTool } from '../mcp/generate';
+import { authContext } from '#shared/auth-context';
+import { guards } from '#shared/guards';
+import { noContent } from '#shared/http';
+import { HttpError } from '#shared/lib';
+import { accessErrors, commonErrors } from '#shared/responses';
+import { mcpTool } from '#mcp/generate';
import { nextCronRun } from './cron';
+import {
+ AgentScheduleResponse,
+ AgentScheduleListResponse,
+ QueuedRunResponse,
+ ScheduleRunListResponse,
+ createScheduleBody,
+ scheduleParams,
+ updateScheduleBody,
+} from './model';
import {
createAgentSchedule,
deleteAgentSchedule,
@@ -14,65 +23,7 @@ import {
listAgentSchedules,
listScheduleRuns,
updateAgentSchedule,
-} from './store';
-
-const params = t.Object({
- projectKey: t.String(),
- scheduleId: t.Numeric({ description: 'Schedule id from list_agent_schedules.' }),
-});
-const status = t.UnionEnum(['active', 'paused'], {
- description: "'active' runs on the cron, 'paused' does not run until it is set back to 'active'.",
-});
-const scheduleBody = t.Object({
- agentId: t.Number({ description: 'Internal agent id from list_ai_agents that runs the task.' }),
- name: t.String({ minLength: 1, maxLength: 120, description: 'Display name of the schedule.' }),
- prompt: t.String({
- minLength: 1,
- maxLength: 20_000,
- description: 'Task sent to the agent on every run.',
- }),
- cron: t.String({
- minLength: 1,
- maxLength: 120,
- description: "Five-field cron expression in UTC, e.g. '0 9 * * 1' for Mondays at 09:00.",
- }),
- status: t.Optional(status),
-});
-
-// A schedule DTO (AgentScheduleRow from the store).
-const AgentScheduleResponse = t.Object({
- id: t.Number(),
- agentId: t.Number(),
- agentName: t.String(),
- name: t.String(),
- prompt: t.String(),
- cron: t.String(),
- timezone: t.Literal('UTC'),
- status,
- nextRunAt: t.String(),
- lastRunAt: t.Nullable(t.String()),
- lastRunStatus: t.Nullable(t.String()),
- createdAt: t.String(),
- updatedAt: t.String(),
-});
-
-// One run of a schedule (ScheduleRunRow from the store), with the agent's answer in
-// `output` once the run has finished.
-const ScheduleRunResponse = t.Object({
- id: t.Number(),
- status: t.String(),
- trigger: t.String(),
- prompt: t.String(),
- attempts: t.Number(),
- lastError: t.Nullable(t.String()),
- output: t.Nullable(t.String()),
- scheduledFor: t.Nullable(t.String()),
- startedAt: t.Nullable(t.String()),
- finishedAt: t.Nullable(t.String()),
- createdAt: t.String(),
-});
-
-const QueuedRunResponse = t.Object({ runId: t.Number() });
+} from './service';
function requiredText(value: string, field: string): string {
const trimmed = value.trim();
@@ -88,12 +39,7 @@ export const agentScheduleRoutes = new Elysia({
.use(guards)
.get('/projects/:projectKey/agent-schedules', ({ project }) => listAgentSchedules(project.id), {
permission: ['ai_agents', 'read'],
- response: {
- 200: t.Array(AgentScheduleResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: AgentScheduleListResponse, ...accessErrors },
detail: {
summary: 'List agent schedules',
description: "List the project's agent schedules with their cron, next run, and last run.",
@@ -118,15 +64,9 @@ export const agentScheduleRoutes = new Elysia({
return row;
},
{
- body: scheduleBody,
+ body: createScheduleBody,
permission: ['ai_agents', 'create'],
- response: {
- 201: AgentScheduleResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: AgentScheduleResponse, ...commonErrors },
detail: {
summary: 'Create an agent schedule',
description: 'Create a schedule that sends a task to an internal agent on a cron.',
@@ -157,16 +97,10 @@ export const agentScheduleRoutes = new Elysia({
return row;
},
{
- params,
- body: t.Partial(scheduleBody),
+ params: scheduleParams,
+ body: updateScheduleBody,
permission: ['ai_agents', 'edit'],
- response: {
- 200: AgentScheduleResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: AgentScheduleResponse, ...commonErrors },
detail: {
summary: 'Update an agent schedule',
description: "Update a schedule's agent, task, cron, or status.",
@@ -183,15 +117,9 @@ export const agentScheduleRoutes = new Elysia({
return noContent();
},
{
- params,
+ params: scheduleParams,
permission: ['ai_agents', 'delete'],
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete an agent schedule',
description: 'Delete a schedule with its run history. Irreversible.',
@@ -208,15 +136,9 @@ export const agentScheduleRoutes = new Elysia({
return { runId };
},
{
- params,
+ params: scheduleParams,
permission: ['ai_agents', 'edit'],
- response: {
- 202: QueuedRunResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 202: QueuedRunResponse, ...commonErrors },
detail: {
summary: 'Run an agent schedule now',
description:
@@ -234,15 +156,9 @@ export const agentScheduleRoutes = new Elysia({
return rows;
},
{
- params,
+ params: scheduleParams,
permission: ['ai_agents', 'read'],
- response: {
- 200: t.Array(ScheduleRunResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ScheduleRunListResponse, ...commonErrors },
detail: {
summary: 'List agent schedule runs',
description:
diff --git a/apps/api/src/modules/agents/schedules/model.ts b/apps/api/src/modules/agents/schedules/model.ts
new file mode 100644
index 00000000..7e208f80
--- /dev/null
+++ b/apps/api/src/modules/agents/schedules/model.ts
@@ -0,0 +1,67 @@
+import { t } from 'elysia';
+
+export const scheduleParams = t.Object({
+ projectKey: t.String(),
+ scheduleId: t.Numeric({ description: 'Schedule id from list_agent_schedules.' }),
+});
+
+export const scheduleStatus = t.UnionEnum(['active', 'paused'], {
+ description: "'active' runs on the cron, 'paused' does not run until it is set back to 'active'.",
+});
+
+export const createScheduleBody = t.Object({
+ agentId: t.Number({ description: 'Internal agent id from list_ai_agents that runs the task.' }),
+ name: t.String({ minLength: 1, maxLength: 120, description: 'Display name of the schedule.' }),
+ prompt: t.String({
+ minLength: 1,
+ maxLength: 20_000,
+ description: 'Task sent to the agent on every run.',
+ }),
+ cron: t.String({
+ minLength: 1,
+ maxLength: 120,
+ description: "Five-field cron expression in UTC, e.g. '0 9 * * 1' for Mondays at 09:00.",
+ }),
+ status: t.Optional(scheduleStatus),
+});
+
+export const updateScheduleBody = t.Partial(createScheduleBody);
+
+// A schedule DTO (AgentScheduleRow from the service).
+export const AgentScheduleResponse = t.Object({
+ id: t.Number(),
+ agentId: t.Number(),
+ agentName: t.String(),
+ name: t.String(),
+ prompt: t.String(),
+ cron: t.String(),
+ timezone: t.Literal('UTC'),
+ status: scheduleStatus,
+ nextRunAt: t.String(),
+ lastRunAt: t.Nullable(t.String()),
+ lastRunStatus: t.Nullable(t.String()),
+ createdAt: t.String(),
+ updatedAt: t.String(),
+});
+
+export const AgentScheduleListResponse = t.Array(AgentScheduleResponse);
+
+// One run of a schedule (ScheduleRunRow from the service), with the agent's answer in
+// `output` once the run has finished.
+export const ScheduleRunResponse = t.Object({
+ id: t.Number(),
+ status: t.String(),
+ trigger: t.String(),
+ prompt: t.String(),
+ attempts: t.Number(),
+ lastError: t.Nullable(t.String()),
+ output: t.Nullable(t.String()),
+ scheduledFor: t.Nullable(t.String()),
+ startedAt: t.Nullable(t.String()),
+ finishedAt: t.Nullable(t.String()),
+ createdAt: t.String(),
+});
+
+export const ScheduleRunListResponse = t.Array(ScheduleRunResponse);
+
+export const QueuedRunResponse = t.Object({ runId: t.Number() });
diff --git a/apps/api/src/agent-schedules/store.ts b/apps/api/src/modules/agents/schedules/service.ts
similarity index 97%
rename from apps/api/src/agent-schedules/store.ts
rename to apps/api/src/modules/agents/schedules/service.ts
index 985d4167..d869c118 100644
--- a/apps/api/src/agent-schedules/store.ts
+++ b/apps/api/src/modules/agents/schedules/service.ts
@@ -1,7 +1,7 @@
import { db, agentRun, agentSchedule, aiAgent, user } from '@repo/db';
import { and, desc, eq, sql } from 'drizzle-orm';
-import { iso } from '../shared/lib';
-import { deleteThreadsWhere } from '../ai-agents/runtime/memory';
+import { iso } from '#shared/lib';
+import { deleteThreadsWhere } from '../core/runtime/memory';
export type AgentScheduleStatus = 'active' | 'paused';
@@ -150,7 +150,7 @@ export async function updateAgentSchedule(
}
// Deletes a schedule and the conversation thread its runs shared, which lives outside
-// the database cascades (see ai-agents/runtime/memory).
+// the database cascades (see ../core/runtime/memory).
export async function deleteAgentSchedule(projectId: number, scheduleId: number): Promise<boolean> {
const current = await getAgentSchedule(projectId, scheduleId);
if (!current) return false;
diff --git a/apps/api/src/agent-skills/__tests__/integration/agent-skills.test.ts b/apps/api/src/modules/agents/skills/__tests__/integration/agent-skills.test.ts
similarity index 96%
rename from apps/api/src/agent-skills/__tests__/integration/agent-skills.test.ts
rename to apps/api/src/modules/agents/skills/__tests__/integration/agent-skills.test.ts
index 8d08d12b..d9cd1c3f 100644
--- a/apps/api/src/agent-skills/__tests__/integration/agent-skills.test.ts
+++ b/apps/api/src/modules/agents/skills/__tests__/integration/agent-skills.test.ts
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-import { untaggedRoutes } from '../../../__tests__/helpers/mcp';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { untaggedRoutes } from '#tests/helpers/mcp';
// The project skill library: SKILL.md documents (plus optional reference files) given
// to internal agents. Content lives in the object store; the row holds metadata.
diff --git a/apps/api/src/agent-skills/__tests__/unit/skill-format.test.ts b/apps/api/src/modules/agents/skills/__tests__/unit/skill-format.test.ts
similarity index 100%
rename from apps/api/src/agent-skills/__tests__/unit/skill-format.test.ts
rename to apps/api/src/modules/agents/skills/__tests__/unit/skill-format.test.ts
diff --git a/apps/api/src/agent-skills/routes.ts b/apps/api/src/modules/agents/skills/index.ts
similarity index 64%
rename from apps/api/src/agent-skills/routes.ts
rename to apps/api/src/modules/agents/skills/index.ts
index 08198be1..43777aae 100644
--- a/apps/api/src/agent-skills/routes.ts
+++ b/apps/api/src/modules/agents/skills/index.ts
@@ -1,11 +1,27 @@
import { Elysia, t } from 'elysia';
-import { noContent } from '../shared/http';
-import { guards } from '../shared/guards';
-import { authContext } from '../shared/auth-context';
-import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
-import { mcpTool } from '../mcp/generate';
+import { noContent } from '#shared/http';
+import { guards } from '#shared/guards';
+import { authContext } from '#shared/auth-context';
+import { HttpError } from '#shared/lib';
+import { accessErrors, commonErrors, errors } from '#shared/responses';
+import { mcpTool } from '#mcp/generate';
import { MAX_SKILL_BYTES, importGithubSkill, discoverGithubSkills } from './skill-format';
+import {
+ DiscoveredSkillListResponse,
+ RefContentResponse,
+ SkillListResponse,
+ SkillMarkdownResponse,
+ SkillResponse,
+ agentParams,
+ createSkillBody,
+ discoverSkillsBody,
+ refPathQuery,
+ setAgentSkillsBody,
+ skillParams,
+ updateReferenceBody,
+ updateSkillBody,
+ uploadReferenceBody,
+} from './model';
import {
listSkills,
getSkill,
@@ -20,38 +36,8 @@ import {
deleteReference,
listAgentSkills,
setAgentSkills,
- agentInProject,
-} from './store';
-
-const skillParams = t.Object({
- projectKey: t.String(),
- skillId: t.Numeric({ description: 'Skill id from list_agent_skills.' }),
-});
-const agentParams = t.Object({
- projectKey: t.String(),
- agentId: t.Numeric({ description: 'Agent id from list_ai_agents.' }),
-});
-
-const refPath = t.String({
- description: "Reference file path from the skill's files, e.g. 'refs/example.md'.",
-});
-
-const SkillRefSchema = t.Object({
- path: t.String(),
- s3Key: t.String(),
- size: t.Number(),
-});
-
-const SkillResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- name: t.String(),
- description: t.String(),
- source: t.Union([t.Literal('upload'), t.Literal('inline'), t.Literal('github')]),
- sourceUrl: t.Nullable(t.String()),
- files: t.Array(SkillRefSchema),
- createdAt: t.String(),
-});
+} from './service';
+import { agentInProject } from '../core/service';
// Reference-file bytes are capped like the skill markdown.
const MAX_REF_BYTES = MAX_SKILL_BYTES;
@@ -66,12 +52,7 @@ export const agentSkillRoutes = new Elysia({
.get('/projects/:projectKey/agent-skills', ({ project }) => listSkills(project.id), {
permission: ['agent_skills', 'read'],
- response: {
- 200: t.Array(SkillResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: SkillListResponse, ...accessErrors },
detail: {
summary: 'List agent skills',
description: "List the project's skill library, each skill with its reference files.",
@@ -89,12 +70,7 @@ export const agentSkillRoutes = new Elysia({
{
params: skillParams,
permission: ['agent_skills', 'read'],
- response: {
- 200: SkillResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: SkillResponse, ...accessErrors },
detail: {
summary: 'Get an agent skill',
description:
@@ -114,12 +90,7 @@ export const agentSkillRoutes = new Elysia({
{
params: skillParams,
permission: ['agent_skills', 'read'],
- response: {
- 200: t.Object({ markdown: t.String() }),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: SkillMarkdownResponse, ...accessErrors },
detail: {
summary: 'Get skill markdown',
description: "Get a skill's SKILL.md content.",
@@ -137,14 +108,9 @@ export const agentSkillRoutes = new Elysia({
},
{
params: skillParams,
- query: t.Object({ path: refPath }),
+ query: refPathQuery,
permission: ['agent_skills', 'read'],
- response: {
- 200: t.Object({ content: t.String() }),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: RefContentResponse, ...accessErrors },
detail: {
summary: 'Get reference file content',
description: "Get the text of one of a skill's reference files by path.",
@@ -158,25 +124,9 @@ export const agentSkillRoutes = new Elysia({
'/projects/:projectKey/agent-skills/github/discover',
({ body }) => discoverGithubSkills(body.url),
{
- body: t.Object({
- url: t.String({ description: 'GitHub URL of a repo, a folder, or a SKILL.md file.' }),
- }),
+ body: discoverSkillsBody,
permission: ['agent_skills', 'create'],
- response: {
- 200: t.Array(
- t.Object({
- name: t.String(),
- description: t.String(),
- subpath: t.String(),
- url: t.String(),
- }),
- ),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 502: ErrorResponse,
- },
+ response: { 200: DiscoveredSkillListResponse, ...commonErrors, ...errors(502) },
detail: {
summary: 'Discover GitHub skills',
description:
@@ -222,42 +172,9 @@ export const agentSkillRoutes = new Elysia({
});
},
{
- body: t.Object({
- source: t.Union([t.Literal('upload'), t.Literal('inline'), t.Literal('github')], {
- description:
- "'inline' for markdown written here, 'upload' for markdown from a file, 'github' to import from sourceUrl.",
- }),
- name: t.Optional(
- t.Nullable(t.String({ description: 'Defaults to the SKILL.md frontmatter name.' })),
- ),
- description: t.Optional(
- t.Nullable(
- t.String({ description: 'Defaults to the SKILL.md frontmatter description.' }),
- ),
- ),
- markdown: t.Optional(
- t.String({ description: "SKILL.md content; required unless source is 'github'." }),
- ),
- sourceUrl: t.Optional(
- t.Nullable(
- t.String({
- description:
- "GitHub URL of one skill folder or SKILL.md, from discover_github_skills; required for source 'github'.",
- }),
- ),
- ),
- }),
+ body: createSkillBody,
permission: ['agent_skills', 'create'],
- response: {
- 201: SkillResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- 413: ErrorResponse,
- 502: ErrorResponse,
- },
+ response: { 201: SkillResponse, ...commonErrors, ...errors(409, 413, 502) },
detail: {
summary: 'Create an agent skill',
description:
@@ -278,24 +195,10 @@ export const agentSkillRoutes = new Elysia({
return skill;
},
{
- body: t.Object({
- name: t.Optional(t.String({ minLength: 1, description: 'New skill name.' })),
- description: t.Optional(
- t.String({ description: 'New one-line description of what the skill is for.' }),
- ),
- markdown: t.Optional(t.String({ description: 'Replaces the SKILL.md content whole.' })),
- }),
+ body: updateSkillBody,
params: skillParams,
permission: ['agent_skills', 'edit'],
- response: {
- 200: SkillResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- 413: ErrorResponse,
- },
+ response: { 200: SkillResponse, ...commonErrors, ...errors(409, 413) },
detail: {
summary: 'Update an agent skill',
description: "Update a skill's name, description, or SKILL.md content.",
@@ -314,12 +217,7 @@ export const agentSkillRoutes = new Elysia({
{
params: skillParams,
permission: ['agent_skills', 'delete'],
- response: {
- 204: t.Void(),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...accessErrors },
detail: {
summary: 'Delete an agent skill',
description: 'Delete a skill, its reference files, and its links to agents.',
@@ -349,17 +247,10 @@ export const agentSkillRoutes = new Elysia({
return skill;
},
{
- body: t.Object({ file: t.File() }),
+ body: uploadReferenceBody,
params: skillParams,
permission: ['agent_skills', 'edit'],
- response: {
- 200: SkillResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 413: ErrorResponse,
- },
+ response: { 200: SkillResponse, ...commonErrors, ...errors(413) },
detail: {
summary: 'Add a reference file',
description: 'Add a reference file to a skill.',
@@ -384,17 +275,10 @@ export const agentSkillRoutes = new Elysia({
return skill;
},
{
- body: t.Object({ path: refPath, content: t.String({ description: 'The new file text.' }) }),
+ body: updateReferenceBody,
params: skillParams,
permission: ['agent_skills', 'edit'],
- response: {
- 200: SkillResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 413: ErrorResponse,
- },
+ response: { 200: SkillResponse, ...commonErrors, ...errors(413) },
detail: {
summary: 'Update reference file content',
description: "Replace the text of a skill's existing reference file, addressed by path.",
@@ -412,14 +296,9 @@ export const agentSkillRoutes = new Elysia({
},
{
params: skillParams,
- query: t.Object({ path: refPath }),
+ query: refPathQuery,
permission: ['agent_skills', 'edit'],
- response: {
- 200: SkillResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: SkillResponse, ...accessErrors },
detail: {
summary: 'Delete a reference file',
description: "Delete a skill's reference file by path.",
@@ -439,12 +318,7 @@ export const agentSkillRoutes = new Elysia({
{
params: agentParams,
permission: ['agent_skills', 'read'],
- response: {
- 200: t.Array(SkillResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: SkillListResponse, ...accessErrors },
detail: {
summary: "List an agent's enabled skills",
description: 'List the skills enabled on an agent.',
@@ -463,21 +337,10 @@ export const agentSkillRoutes = new Elysia({
return listAgentSkills(params.agentId);
},
{
- body: t.Object({
- skillIds: t.Array(t.Number(), {
- description:
- 'Skill ids from list_agent_skills. Replaces the whole set, so send every skill that stays enabled.',
- }),
- }),
+ body: setAgentSkillsBody,
params: agentParams,
permission: ['agent_skills', 'edit'],
- response: {
- 200: t.Array(SkillResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: SkillListResponse, ...commonErrors },
detail: {
summary: "Set an agent's enabled skills",
description:
diff --git a/apps/api/src/modules/agents/skills/model.ts b/apps/api/src/modules/agents/skills/model.ts
new file mode 100644
index 00000000..d34bb4ac
--- /dev/null
+++ b/apps/api/src/modules/agents/skills/model.ts
@@ -0,0 +1,98 @@
+import { t } from 'elysia';
+
+export { agentParams } from '../model';
+
+export const skillParams = t.Object({
+ projectKey: t.String(),
+ skillId: t.Numeric({ description: 'Skill id from list_agent_skills.' }),
+});
+
+const refPath = t.String({
+ description: "Reference file path from the skill's files, e.g. 'refs/example.md'.",
+});
+
+export const refPathQuery = t.Object({ path: refPath });
+
+const skillSource = t.Union([t.Literal('upload'), t.Literal('inline'), t.Literal('github')]);
+
+const SkillRefSchema = t.Object({
+ path: t.String(),
+ s3Key: t.String(),
+ size: t.Number(),
+});
+
+export const SkillResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ name: t.String(),
+ description: t.String(),
+ source: skillSource,
+ sourceUrl: t.Nullable(t.String()),
+ files: t.Array(SkillRefSchema),
+ createdAt: t.String(),
+});
+
+export const SkillListResponse = t.Array(SkillResponse);
+
+export const SkillMarkdownResponse = t.Object({ markdown: t.String() });
+
+export const RefContentResponse = t.Object({ content: t.String() });
+
+export const DiscoveredSkillListResponse = t.Array(
+ t.Object({
+ name: t.String(),
+ description: t.String(),
+ subpath: t.String(),
+ url: t.String(),
+ }),
+);
+
+export const discoverSkillsBody = t.Object({
+ url: t.String({ description: 'GitHub URL of a repo, a folder, or a SKILL.md file.' }),
+});
+
+export const createSkillBody = t.Object({
+ source: t.Union([t.Literal('upload'), t.Literal('inline'), t.Literal('github')], {
+ description:
+ "'inline' for markdown written here, 'upload' for markdown from a file, 'github' to import from sourceUrl.",
+ }),
+ name: t.Optional(
+ t.Nullable(t.String({ description: 'Defaults to the SKILL.md frontmatter name.' })),
+ ),
+ description: t.Optional(
+ t.Nullable(t.String({ description: 'Defaults to the SKILL.md frontmatter description.' })),
+ ),
+ markdown: t.Optional(
+ t.String({ description: "SKILL.md content; required unless source is 'github'." }),
+ ),
+ sourceUrl: t.Optional(
+ t.Nullable(
+ t.String({
+ description:
+ "GitHub URL of one skill folder or SKILL.md, from discover_github_skills; required for source 'github'.",
+ }),
+ ),
+ ),
+});
+
+export const updateSkillBody = t.Object({
+ name: t.Optional(t.String({ minLength: 1, description: 'New skill name.' })),
+ description: t.Optional(
+ t.String({ description: 'New one-line description of what the skill is for.' }),
+ ),
+ markdown: t.Optional(t.String({ description: 'Replaces the SKILL.md content whole.' })),
+});
+
+export const uploadReferenceBody = t.Object({ file: t.File() });
+
+export const updateReferenceBody = t.Object({
+ path: refPath,
+ content: t.String({ description: 'The new file text.' }),
+});
+
+export const setAgentSkillsBody = t.Object({
+ skillIds: t.Array(t.Number(), {
+ description:
+ 'Skill ids from list_agent_skills. Replaces the whole set, so send every skill that stays enabled.',
+ }),
+});
diff --git a/apps/api/src/agent-skills/store.ts b/apps/api/src/modules/agents/skills/service.ts
similarity index 95%
rename from apps/api/src/agent-skills/store.ts
rename to apps/api/src/modules/agents/skills/service.ts
index 09a37195..644fdfd8 100644
--- a/apps/api/src/agent-skills/store.ts
+++ b/apps/api/src/modules/agents/skills/service.ts
@@ -1,7 +1,7 @@
-import { db, agentSkill, agentSkillLink, aiAgent } from '@repo/db';
+import { db, agentSkill, agentSkillLink } from '@repo/db';
import { and, eq, inArray } from 'drizzle-orm';
-import { iso, rethrowDuplicate, HttpError } from '../shared/lib';
-import { putObject, getObjectText, deleteObjects } from '../shared/s3';
+import { iso, rethrowDuplicate, HttpError } from '#shared/lib';
+import { putObject, getObjectText, deleteObjects } from '#shared/s3';
import { parseFrontmatter, isDisallowedRef } from './skill-format';
// Data access for the project skill library. A skill's SKILL.md and reference files
@@ -347,13 +347,3 @@ export async function setAgentSkills(
}
});
}
-
-// True if the agent belongs to the project (guards addressing an agent by id).
-export async function agentInProject(agentId: number, projectId: number): Promise<boolean> {
- const rows = await db
- .select({ id: aiAgent.id })
- .from(aiAgent)
- .where(and(eq(aiAgent.id, agentId), eq(aiAgent.projectId, projectId)))
- .limit(1);
- return rows.length > 0;
-}
diff --git a/apps/api/src/agent-skills/skill-format.ts b/apps/api/src/modules/agents/skills/skill-format.ts
similarity index 99%
rename from apps/api/src/agent-skills/skill-format.ts
rename to apps/api/src/modules/agents/skills/skill-format.ts
index 319ca301..2bd5ae96 100644
--- a/apps/api/src/agent-skills/skill-format.ts
+++ b/apps/api/src/modules/agents/skills/skill-format.ts
@@ -1,4 +1,4 @@
-import { HttpError } from '../shared/lib';
+import { HttpError } from '#shared/lib';
// Parsing and validation for skills in the Anthropic Agent Skill format: a SKILL.md
// with YAML frontmatter (name/description) plus optional reference files, no
diff --git a/apps/api/src/agent-tools/__tests__/integration/agent-tools.test.ts b/apps/api/src/modules/agents/tools/__tests__/integration/agent-tools.test.ts
similarity index 95%
rename from apps/api/src/agent-tools/__tests__/integration/agent-tools.test.ts
rename to apps/api/src/modules/agents/tools/__tests__/integration/agent-tools.test.ts
index 929d32cf..edfbac27 100644
--- a/apps/api/src/agent-tools/__tests__/integration/agent-tools.test.ts
+++ b/apps/api/src/modules/agents/tools/__tests__/integration/agent-tools.test.ts
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-import { untaggedRoutes } from '../../../__tests__/helpers/mcp';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { untaggedRoutes } from '#tests/helpers/mcp';
// Configured tools for a project: a catalog tool bound to an integration credential.
// The secret lives on the credential, so a configured tool carries no secret. Access
diff --git a/apps/api/src/agent-tools/routes.ts b/apps/api/src/modules/agents/tools/index.ts
similarity index 57%
rename from apps/api/src/agent-tools/routes.ts
rename to apps/api/src/modules/agents/tools/index.ts
index 077a8f0d..5dc2a8c5 100644
--- a/apps/api/src/agent-tools/routes.ts
+++ b/apps/api/src/modules/agents/tools/index.ts
@@ -1,48 +1,28 @@
import { Elysia, t } from 'elysia';
-import { noContent } from '../shared/http';
-import { guards } from '../shared/guards';
-import { authContext } from '../shared/auth-context';
-import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
-import { mcpTool } from '../mcp/generate';
-import { agentInProject } from '../agent-skills/store';
-import { AGENT_ACTIONS, ALWAYS_ON_ACTIONS } from '../ai-agents/runtime/tools/catalog';
+import { noContent } from '#shared/http';
+import { guards } from '#shared/guards';
+import { authContext } from '#shared/auth-context';
+import { HttpError } from '#shared/lib';
+import { accessErrors, commonErrors, errors } from '#shared/responses';
+import { mcpTool } from '#mcp/generate';
+import { agentInProject } from '../core/service';
+import { AGENT_ACTIONS, ALWAYS_ON_ACTIONS } from '../core/runtime/tools/catalog';
+import {
+ AgentToolListResponse,
+ AgentToolResponse,
+ ToolMetaListResponse,
+ agentParams,
+ createAgentToolBody,
+ setAgentToolsBody,
+ toolParams,
+} from './model';
import {
listAgentTools,
createAgentTool,
deleteAgentTool,
listAgentToolLinks,
setAgentTools,
-} from './store';
-
-const toolParams = t.Object({ projectKey: t.String(), agentToolId: t.Numeric() });
-const agentParams = t.Object({
- projectKey: t.String(),
- agentId: t.Numeric({ description: 'Agent id from list_ai_agents.' }),
-});
-
-// A built-in agent action in the catalog (ToolMeta from ai-agents/runtime/tools).
-// `always` marks the read-only actions granted unconditionally, that cannot be
-// toggled off.
-const ToolMetaResponse = t.Object({
- key: t.String(),
- label: t.String(),
- description: t.String(),
- always: t.Boolean(),
-});
-
-// A configured tool DTO: the tool bound to a credential, enriched with the credential's
-// integration and label for display. The tool catalog itself is served by the
-// integrations catalog (kind 'tool').
-const AgentToolResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- toolKey: t.String(),
- credentialId: t.Number(),
- integrationKey: t.String(),
- credentialLabel: t.Nullable(t.String()),
- createdAt: t.String(),
-});
+} from './service';
// Two tool systems live under this tag. Built-in agent actions (create_issue,
// search_issues, ...) are the catalog an internal agent is granted through its
@@ -57,16 +37,9 @@ export const agentToolRoutes = new Elysia({
.use(authContext)
.use(guards)
- // The built-in actions an internal agent can be granted, followed by the always-on
- // read-only ones. Feeds the `tools` field on create_ai_agent / update_ai_agent.
.get('/projects/:projectKey/ai-agents/tools', () => [...AGENT_ACTIONS, ...ALWAYS_ON_ACTIONS], {
permission: ['ai_agents', 'read'],
- response: {
- 200: t.Array(ToolMetaResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ToolMetaListResponse, ...accessErrors },
detail: {
summary: 'List built-in agent actions',
description:
@@ -78,12 +51,7 @@ export const agentToolRoutes = new Elysia({
.get('/projects/:projectKey/agent-tools', ({ project }) => listAgentTools(project.id), {
permission: ['agent_tools', 'read'],
- response: {
- 200: t.Array(AgentToolResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: AgentToolListResponse, ...accessErrors },
detail: {
summary: 'List configured tools',
description:
@@ -101,16 +69,9 @@ export const agentToolRoutes = new Elysia({
return createAgentTool(project.id, body);
},
{
- body: t.Object({ toolKey: t.String({ minLength: 1 }), credentialId: t.Number() }),
+ body: createAgentToolBody,
permission: ['agent_tools', 'create'],
- response: {
- 201: AgentToolResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 201: AgentToolResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Configure a tool',
description: 'Bind a tool to an integration credential.',
@@ -128,12 +89,7 @@ export const agentToolRoutes = new Elysia({
{
params: toolParams,
permission: ['agent_tools', 'delete'],
- response: {
- 204: t.Void(),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...accessErrors },
detail: { summary: 'Delete a configured tool', description: 'Delete a configured tool.' },
},
)
@@ -149,12 +105,7 @@ export const agentToolRoutes = new Elysia({
{
params: agentParams,
permission: ['agent_tools', 'read'],
- response: {
- 200: t.Array(AgentToolResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: AgentToolListResponse, ...accessErrors },
detail: {
summary: "List an agent's enabled tools",
description: 'List the configured tools enabled on an agent.',
@@ -173,20 +124,10 @@ export const agentToolRoutes = new Elysia({
return listAgentToolLinks(params.agentId);
},
{
- body: t.Object({
- agentToolIds: t.Array(t.Number(), {
- description: 'Configured tool ids from list_configured_tools.',
- }),
- }),
+ body: setAgentToolsBody,
params: agentParams,
permission: ['agent_tools', 'edit'],
- response: {
- 200: t.Array(AgentToolResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: AgentToolListResponse, ...commonErrors },
detail: {
summary: "Set an agent's enabled tools",
description:
diff --git a/apps/api/src/modules/agents/tools/model.ts b/apps/api/src/modules/agents/tools/model.ts
new file mode 100644
index 00000000..5e98eb87
--- /dev/null
+++ b/apps/api/src/modules/agents/tools/model.ts
@@ -0,0 +1,41 @@
+import { t } from 'elysia';
+
+export { agentParams } from '../model';
+
+export const toolParams = t.Object({ projectKey: t.String(), agentToolId: t.Numeric() });
+
+// A built-in agent action in the catalog (ToolMeta from ../core/runtime/tools).
+// `always` marks the read-only actions granted unconditionally, that cannot be
+// toggled off.
+const ToolMetaResponse = t.Object({
+ key: t.String(),
+ label: t.String(),
+ description: t.String(),
+ always: t.Boolean(),
+});
+
+export const ToolMetaListResponse = t.Array(ToolMetaResponse);
+
+// The tool catalog itself is served by the integrations catalog (kind 'tool').
+export const AgentToolResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ toolKey: t.String(),
+ credentialId: t.Number(),
+ integrationKey: t.String(),
+ credentialLabel: t.Nullable(t.String()),
+ createdAt: t.String(),
+});
+
+export const AgentToolListResponse = t.Array(AgentToolResponse);
+
+export const createAgentToolBody = t.Object({
+ toolKey: t.String({ minLength: 1 }),
+ credentialId: t.Number(),
+});
+
+export const setAgentToolsBody = t.Object({
+ agentToolIds: t.Array(t.Number(), {
+ description: 'Configured tool ids from list_configured_tools.',
+ }),
+});
diff --git a/apps/api/src/agent-tools/store.ts b/apps/api/src/modules/agents/tools/service.ts
similarity index 89%
rename from apps/api/src/agent-tools/store.ts
rename to apps/api/src/modules/agents/tools/service.ts
index b77d4b3c..97e6f707 100644
--- a/apps/api/src/agent-tools/store.ts
+++ b/apps/api/src/modules/agents/tools/service.ts
@@ -1,9 +1,9 @@
import { db, agentTool, agentToolLink, integrationCredential } from '@repo/db';
import { and, eq, inArray } from 'drizzle-orm';
import { getTool, type ToolConfig } from '@repo/agent-tools';
-import { iso, HttpError, rethrowDuplicate } from '../shared/lib';
+import { iso, HttpError, rethrowDuplicate } from '#shared/lib';
import { decryptSecret } from '@repo/crypto';
-import { getCredentialById } from '../integrations/store';
+import { getCredentialById } from '../integrations/service';
// Data access for configured tools. A configured tool binds a catalog tool (tool_key)
// to one integration_credential. The secret lives on the credential, so a row here
@@ -62,15 +62,14 @@ export async function createAgentTool(
projectId: number,
input: NewAgentToolInput,
): Promise<AgentToolRow> {
- const found = getTool(input.toolKey);
- if (!found) throw new HttpError(400, `Unknown tool: ${input.toolKey}`);
+ const tool = getTool(input.toolKey);
+ if (!tool) throw new HttpError(400, `Unknown tool: ${input.toolKey}`);
const credential = await getCredentialById(input.credentialId, projectId);
if (!credential) throw new HttpError(400, 'Credential not found');
- // The bound credential must belong to the tool's integration.
- if (credential.integrationKey !== found.integration.key) {
+ if (credential.integrationKey !== tool.integration.key) {
throw new HttpError(
400,
- `This tool needs a ${found.integration.label} credential, not ${credential.integrationKey}.`,
+ `This tool needs a ${tool.integration.label} credential, not ${credential.integrationKey}.`,
);
}
try {
@@ -132,8 +131,7 @@ export async function listAgentToolsForRun(
}));
}
-// Replaces the set of configured tools enabled on an agent. Only tools in the agent's
-// project are accepted; unknown or cross-project ids are ignored.
+// Unknown ids and ids from another project are ignored, not rejected.
export async function setAgentTools(
agentId: number,
projectId: number,
diff --git a/apps/api/src/analytics/__tests__/integration/analytics.test.ts b/apps/api/src/modules/analytics/__tests__/integration/analytics.test.ts
similarity index 98%
rename from apps/api/src/analytics/__tests__/integration/analytics.test.ts
rename to apps/api/src/modules/analytics/__tests__/integration/analytics.test.ts
index 8ae5ad36..21e1cb74 100644
--- a/apps/api/src/analytics/__tests__/integration/analytics.test.ts
+++ b/apps/api/src/modules/analytics/__tests__/integration/analytics.test.ts
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser, type TestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-import { pulseRows } from '../../store';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser, type TestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { pulseRows } from '../../service';
// Read-only project analytics. Every figure is derived from the issue /
// project_column / issue_activity tables, so the tests build state through the
diff --git a/apps/api/src/modules/analytics/index.ts b/apps/api/src/modules/analytics/index.ts
new file mode 100644
index 00000000..3e5e260e
--- /dev/null
+++ b/apps/api/src/modules/analytics/index.ts
@@ -0,0 +1,232 @@
+import { Elysia } from 'elysia';
+import { guards } from '#shared/guards';
+import { mcpTool } from '#mcp/generate';
+import { accessErrors, commonErrors } from '#shared/responses';
+import {
+ ActivityPage,
+ AgentRunFeedListResponse,
+ AgentRunStatsDto,
+ AgentWorkloadListResponse,
+ BreakdownListResponse,
+ PulseListResponse,
+ StatsDto,
+ ThroughputListResponse,
+ WebhookStatsDto,
+ activityQuery,
+ agentRunFeedQuery,
+ breakdownQuery,
+ daysQuery,
+ pulseQuery,
+ throughputQuery,
+} from './model';
+import {
+ getStats,
+ getBreakdown,
+ getPulse,
+ getThroughput,
+ listActivity,
+ listAgentRunFeed,
+ getAgentRunStats,
+ getWebhookStats,
+ getAgentWorkload,
+ type ActivityCursor,
+ type PulseUnit,
+} from './service';
+
+// Read-only project analytics that back the dashboard widgets. Every route is
+// under /projects/:projectKey/analytics and gated by the dashboards read
+// permission (the analytics feed the dashboards). All figures come from existing
+// tables; see service.ts.
+
+// Caps the generated bucket axis per unit. Hour columns hold 24 cells each, so
+// their cap is the lowest.
+const MAX_PULSE_COLUMNS: Record<PulseUnit, number> = {
+ hour: 140,
+ day: 160,
+ week: 130,
+};
+
+export const analyticsRoutes = new Elysia({
+ name: 'analytics',
+ detail: { tags: ['Analytics'] },
+})
+ .use(guards)
+ .get(
+ '/projects/:projectKey/analytics/stats',
+ async ({ project }) => {
+ return getStats(project.id);
+ },
+ {
+ permission: ['dashboards', 'read'],
+ response: { 200: StatsDto, ...accessErrors },
+ detail: {
+ summary: 'Get project stats',
+ description: 'Issue counts by state (open, in progress, overdue, and more).',
+ ...mcpTool('get_project_stats'),
+ },
+ },
+ )
+
+ .get(
+ '/projects/:projectKey/analytics/breakdown',
+ async ({ project, query }) => {
+ return getBreakdown(project.id, query.by);
+ },
+ {
+ query: breakdownQuery,
+ permission: ['dashboards', 'read'],
+ response: { 200: BreakdownListResponse, ...commonErrors },
+ detail: {
+ summary: 'Get project breakdown',
+ description: 'Issue counts grouped by a chosen dimension.',
+ ...mcpTool('get_project_breakdown'),
+ },
+ },
+ )
+
+ .get(
+ '/projects/:projectKey/analytics/pulse',
+ async ({ project, query }) => {
+ const unit = query.unit ?? 'day';
+ const columns =
+ query.columns != null ? Math.min(Math.max(query.columns, 1), MAX_PULSE_COLUMNS[unit]) : 26;
+ return getPulse(project.id, unit, columns);
+ },
+ {
+ query: pulseQuery,
+ permission: ['dashboards', 'read'],
+ response: { 200: PulseListResponse, ...commonErrors },
+ detail: {
+ summary: 'Get project pulse',
+ description: 'Activity counts over time for a heatmap.',
+ ...mcpTool('get_project_pulse'),
+ },
+ },
+ )
+
+ .get(
+ '/projects/:projectKey/analytics/throughput',
+ async ({ project, query }) => {
+ const weeks = query.weeks != null ? Math.min(Math.max(query.weeks, 1), 52) : 12;
+ return getThroughput(project.id, weeks);
+ },
+ {
+ query: throughputQuery,
+ permission: ['dashboards', 'read'],
+ response: { 200: ThroughputListResponse, ...commonErrors },
+ detail: {
+ summary: 'Get project throughput',
+ description: 'Created versus closed issues over time.',
+ ...mcpTool('get_project_throughput'),
+ },
+ },
+ )
+
+ .get(
+ '/projects/:projectKey/analytics/activity',
+ async ({ project, query }) => {
+ const limit = query.limit ?? 25;
+ let before: ActivityCursor | null = null;
+ if (query.cursor) {
+ try {
+ before = JSON.parse(query.cursor);
+ } catch {
+ // Ignore a malformed cursor and serve the first page.
+ }
+ }
+ const issueIds =
+ query.issueIds != null
+ ? query.issueIds
+ .split(',')
+ .map(Number)
+ .filter((n) => Number.isInteger(n))
+ : null;
+ return listActivity(project.id, {
+ before,
+ limit,
+ actorUserId: query.actorUserId ?? null,
+ action: query.action ?? null,
+ issueIds,
+ });
+ },
+ {
+ query: activityQuery,
+ permission: ['dashboards', 'read'],
+ response: { 200: ActivityPage, ...commonErrors },
+ detail: {
+ summary: 'Get project activity',
+ description: 'Project-wide feed of issue activity.',
+ ...mcpTool('get_project_activity'),
+ },
+ },
+ )
+
+ .get(
+ '/projects/:projectKey/analytics/agent-runs',
+ async ({ project, query }) => {
+ const limit = query.limit ?? 20;
+ return listAgentRunFeed(project.id, { status: query.status ?? null, limit });
+ },
+ {
+ query: agentRunFeedQuery,
+ permission: ['dashboards', 'read'],
+ response: { 200: AgentRunFeedListResponse, ...commonErrors },
+ detail: {
+ summary: 'List agent runs',
+ description: 'Project-wide feed of agent runs.',
+ ...mcpTool('list_agent_runs'),
+ },
+ },
+ )
+
+ .get(
+ '/projects/:projectKey/analytics/agent-run-stats',
+ async ({ project, query }) => {
+ const days = query.days != null ? Math.min(Math.max(query.days, 1), 90) : 30;
+ return getAgentRunStats(project.id, days);
+ },
+ {
+ query: daysQuery,
+ permission: ['dashboards', 'read'],
+ response: { 200: AgentRunStatsDto, ...commonErrors },
+ detail: {
+ summary: 'Get agent run stats',
+ description: 'Agent run outcome counts (success, failed, pending).',
+ ...mcpTool('get_agent_run_stats'),
+ },
+ },
+ )
+
+ .get(
+ '/projects/:projectKey/analytics/webhook-stats',
+ async ({ project, query }) => {
+ const days = query.days != null ? Math.min(Math.max(query.days, 1), 90) : 30;
+ return getWebhookStats(project.id, days);
+ },
+ {
+ query: daysQuery,
+ permission: ['dashboards', 'read'],
+ response: { 200: WebhookStatsDto, ...commonErrors },
+ detail: {
+ summary: 'Get webhook stats',
+ description: 'Webhook delivery outcomes and active/disabled webhook counts.',
+ ...mcpTool('get_webhook_stats'),
+ },
+ },
+ )
+
+ .get(
+ '/projects/:projectKey/analytics/agent-workload',
+ async ({ project }) => {
+ return getAgentWorkload(project.id);
+ },
+ {
+ permission: ['dashboards', 'read'],
+ response: { 200: AgentWorkloadListResponse, ...accessErrors },
+ detail: {
+ summary: 'Get agent workload',
+ description: 'Per-agent open delegated issues and run outcomes.',
+ ...mcpTool('get_agent_workload'),
+ },
+ },
+ );
diff --git a/apps/api/src/modules/analytics/model.ts b/apps/api/src/modules/analytics/model.ts
new file mode 100644
index 00000000..05f75660
--- /dev/null
+++ b/apps/api/src/modules/analytics/model.ts
@@ -0,0 +1,141 @@
+import { t } from 'elysia';
+
+export const StatsDto = t.Object({
+ open: t.Number(),
+ inProgress: t.Number(),
+ backlog: t.Number(),
+ overdue: t.Number(),
+ unassigned: t.Number(),
+ closedLast7d: t.Number(),
+});
+
+const BreakdownItem = t.Object({
+ key: t.String(),
+ label: t.String(),
+ count: t.Number(),
+ color: t.Nullable(t.String()),
+});
+
+const PulseBucket = t.Object({
+ label: t.String(),
+ count: t.Number(),
+});
+
+const ThroughputWeek = t.Object({
+ week: t.String(),
+ created: t.Number(),
+ closed: t.Number(),
+});
+
+const ActivityItem = t.Object({
+ id: t.Number(),
+ issueId: t.Number(),
+ issueSequence: t.Number(),
+ issueTitle: t.String(),
+ kind: t.String(),
+ actorUserId: t.Nullable(t.String()),
+ actorName: t.Nullable(t.String()),
+ body: t.Nullable(t.String()),
+ action: t.Nullable(t.String()),
+ subject: t.Nullable(t.String()),
+ fromText: t.Nullable(t.String()),
+ toText: t.Nullable(t.String()),
+ createdAt: t.String(),
+});
+
+const ActivityCursorDto = t.Object({
+ ts: t.String(),
+ id: t.Number(),
+});
+
+export const ActivityPage = t.Object({
+ items: t.Array(ActivityItem),
+ nextCursor: t.Nullable(ActivityCursorDto),
+});
+
+const AgentRunFeedItem = t.Object({
+ id: t.Number(),
+ status: t.String(),
+ trigger: t.Union([
+ t.Literal('mention'),
+ t.Literal('delegation'),
+ t.Literal('schedule'),
+ t.Literal('manual'),
+ ]),
+ agentId: t.Number(),
+ agentName: t.String(),
+ issueId: t.Nullable(t.Number()),
+ issueSequence: t.Nullable(t.Number()),
+ lastError: t.Nullable(t.String()),
+ createdAt: t.String(),
+});
+
+export const AgentRunStatsDto = t.Object({
+ total: t.Number(),
+ success: t.Number(),
+ failed: t.Number(),
+ pending: t.Number(),
+});
+
+export const WebhookStatsDto = t.Object({
+ total: t.Number(),
+ success: t.Number(),
+ failed: t.Number(),
+ pending: t.Number(),
+ activeWebhooks: t.Number(),
+ disabledWebhooks: t.Number(),
+});
+
+const AgentWorkloadItem = t.Object({
+ agentId: t.Number(),
+ agentName: t.String(),
+ kind: t.String(),
+ delegatedOpen: t.Number(),
+ runsTotal: t.Number(),
+ runsSuccess: t.Number(),
+ runsFailed: t.Number(),
+});
+
+export const BreakdownListResponse = t.Array(BreakdownItem);
+
+export const PulseListResponse = t.Array(PulseBucket);
+
+export const ThroughputListResponse = t.Array(ThroughputWeek);
+
+export const AgentRunFeedListResponse = t.Array(AgentRunFeedItem);
+
+export const AgentWorkloadListResponse = t.Array(AgentWorkloadItem);
+
+export const breakdownQuery = t.Object({
+ by: t.Union([
+ t.Literal('status'),
+ t.Literal('priority'),
+ t.Literal('type'),
+ t.Literal('assignee'),
+ t.Literal('delegate'),
+ ]),
+});
+
+export const pulseQuery = t.Object({
+ unit: t.Optional(t.Union([t.Literal('hour'), t.Literal('day'), t.Literal('week')])),
+ columns: t.Optional(t.Numeric()),
+});
+
+export const throughputQuery = t.Object({ weeks: t.Optional(t.Numeric()) });
+
+export const activityQuery = t.Object({
+ limit: t.Optional(t.Numeric()),
+ cursor: t.Optional(t.String()),
+ actorUserId: t.Optional(t.String()),
+ action: t.Optional(t.String()),
+ // Comma-separated issue ids the client resolved from the widget's work items
+ // filter; absent means no issue-scope restriction.
+ issueIds: t.Optional(t.String()),
+});
+
+export const agentRunFeedQuery = t.Object({
+ status: t.Optional(t.Union([t.Literal('pending'), t.Literal('success'), t.Literal('failed')])),
+ limit: t.Optional(t.Numeric()),
+});
+
+export const daysQuery = t.Object({ days: t.Optional(t.Numeric()) });
diff --git a/apps/api/src/analytics/store.ts b/apps/api/src/modules/analytics/service.ts
similarity index 99%
rename from apps/api/src/analytics/store.ts
rename to apps/api/src/modules/analytics/service.ts
index be511d65..f50ddcf2 100644
--- a/apps/api/src/analytics/store.ts
+++ b/apps/api/src/modules/analytics/service.ts
@@ -11,7 +11,7 @@ import {
webhookDelivery,
} from '@repo/db';
import { and, desc, eq, inArray, isNull, isNotNull, sql } from 'drizzle-orm';
-import { iso } from '../shared/lib';
+import { iso } from '#shared/lib';
// Read-only project metrics for the dashboards feature. Every figure is derived
// from the existing issue / project_column / issue_activity tables — there is no
diff --git a/apps/api/src/attachments/__tests__/integration/attachments.test.ts b/apps/api/src/modules/attachments/__tests__/integration/attachments.test.ts
similarity index 98%
rename from apps/api/src/attachments/__tests__/integration/attachments.test.ts
rename to apps/api/src/modules/attachments/__tests__/integration/attachments.test.ts
index 1dae23bd..88d2600a 100644
--- a/apps/api/src/attachments/__tests__/integration/attachments.test.ts
+++ b/apps/api/src/modules/attachments/__tests__/integration/attachments.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { api, authedApi } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { api, authedApi } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
// Attachments feature: metadata in Postgres, bytes in the object store (shared/
// s3.ts against a real MinIO — see the Tests setup for S3_* env). This is the
diff --git a/apps/api/src/attachments/routes.ts b/apps/api/src/modules/attachments/index.ts
similarity index 85%
rename from apps/api/src/attachments/routes.ts
rename to apps/api/src/modules/attachments/index.ts
index f4092612..a930d0fd 100644
--- a/apps/api/src/attachments/routes.ts
+++ b/apps/api/src/modules/attachments/index.ts
@@ -1,15 +1,23 @@
import { Elysia, t } from 'elysia';
import { randomUUID, createHash } from 'node:crypto';
-import { noContent } from '../shared/http';
-import { authContext } from '../shared/auth-context';
-import { entityGuard } from '../shared/guards';
-import { HttpError } from '../shared/lib';
-import { putObject, getObject, deleteObject } from '../shared/s3';
-import { assertPublicHttpUrl } from '../shared/net';
-import { getIssueProjectId } from '../issues/store';
-import { mcpTool } from '../mcp/generate';
-import { ErrorResponse } from '../shared/responses';
-import { getStorageSettings, mimeAllowed, MB, type StorageSettings } from '../settings/storage';
+import { noContent } from '#shared/http';
+import { authContext } from '#shared/auth-context';
+import { entityGuard } from '#shared/guards';
+import { HttpError } from '#shared/lib';
+import { putObject, getObject, deleteObject } from '#shared/s3';
+import { assertPublicHttpUrl } from '#shared/net';
+import { mcpTool } from '#mcp/generate';
+import { accessErrors, commonErrors, errors } from '#shared/responses';
+import { getIssueProjectId } from '../../issues/store';
+import { getStorageSettings, mimeAllowed, MB, type StorageSettings } from '../../settings/storage';
+import {
+ AttachmentResponse,
+ AttachmentListResponse,
+ importAttachmentBody,
+ issueParams,
+ rawAttachmentQuery,
+ uploadAttachmentBody,
+} from './model';
import {
createAttachment,
listAttachments,
@@ -19,19 +27,9 @@ import {
removeAttachmentEmbeds,
getProjectAttachmentBytes,
type AttachmentRow,
-} from './store';
-
-// Wire shape produced by attachmentDto (see there for what it omits).
-const AttachmentSchema = t.Object({
- id: t.String(),
- filename: t.String(),
- contentType: t.String(),
- sizeBytes: t.Number(),
- createdAt: t.String(),
- url: t.String(),
-});
+} from './service';
-// The upload limits are instance settings (see ../settings/storage.ts), read per
+// The upload limits are instance settings (see ../../settings/storage.ts), read per
// request so a change in god mode takes effect without a restart.
async function assertUploadAllowed(
limits: StorageSettings,
@@ -97,8 +95,6 @@ function attachmentDto(a: AttachmentRow) {
};
}
-const issueParams = t.Object({ issueId: t.Numeric() });
-
export const attachmentRoutes = new Elysia({
name: 'attachments',
detail: { tags: ['Attachments'] },
@@ -126,13 +122,7 @@ export const attachmentRoutes = new Elysia({
{
params: issueParams,
issueAttachment: 'read',
- response: {
- 200: t.Array(AttachmentSchema),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: AttachmentListResponse, ...commonErrors },
detail: {
summary: 'List attachments',
description: "List an issue's attachments by its numeric id.",
@@ -169,18 +159,10 @@ export const attachmentRoutes = new Elysia({
return attachmentDto(row);
},
{
- body: t.Object({ file: t.File() }),
+ body: uploadAttachmentBody,
params: issueParams,
issueAttachment: 'create',
- response: {
- 201: AttachmentSchema,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 413: ErrorResponse,
- 502: ErrorResponse,
- },
+ response: { 201: AttachmentResponse, ...commonErrors, ...errors(413, 502) },
detail: { summary: 'Upload an attachment' },
},
)
@@ -247,22 +229,9 @@ export const attachmentRoutes = new Elysia({
},
{
params: issueParams,
- body: t.Object({
- filename: t.String({ minLength: 1 }),
- url: t.Optional(t.String()),
- contentBase64: t.Optional(t.String()),
- contentType: t.Optional(t.String()),
- }),
+ body: importAttachmentBody,
issueAttachment: 'create',
- response: {
- 201: AttachmentSchema,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 413: ErrorResponse,
- 502: ErrorResponse,
- },
+ response: { 201: AttachmentResponse, ...commonErrors, ...errors(413, 502) },
detail: {
summary: 'Add an attachment from a URL or base64',
description: 'Attach a file to an issue without a multipart upload.',
@@ -317,17 +286,9 @@ export const attachmentRoutes = new Elysia({
return attachmentDto(row);
},
{
- body: t.Object({ file: t.File() }),
+ body: uploadAttachmentBody,
attachment: 'edit',
- response: {
- 200: AttachmentSchema,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 413: ErrorResponse,
- 502: ErrorResponse,
- },
+ response: { 200: AttachmentResponse, ...commonErrors, ...errors(413, 502) },
detail: { summary: "Replace an attachment's file" },
},
)
@@ -352,12 +313,7 @@ export const attachmentRoutes = new Elysia({
},
{
attachment: 'delete',
- response: {
- 204: t.Void(),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...accessErrors },
detail: {
summary: 'Delete an attachment',
description: 'Delete an attachment. Irreversible.',
@@ -413,12 +369,10 @@ export const attachmentRoutes = new Elysia({
return new Response(obj.body, { headers });
},
{
- query: t.Object({ download: t.Optional(t.String()) }),
+ query: rawAttachmentQuery,
// Public route: no 401/403. Returns a raw Response (bytes), so no typed 200
// body — Elysia cannot validate a raw Response. Only the 404 it can throw.
- response: {
- 404: ErrorResponse,
- },
+ response: { ...errors(404) },
detail: { summary: 'Download or preview an attachment (public, no auth)' },
},
);
diff --git a/apps/api/src/modules/attachments/model.ts b/apps/api/src/modules/attachments/model.ts
new file mode 100644
index 00000000..9a419bf6
--- /dev/null
+++ b/apps/api/src/modules/attachments/model.ts
@@ -0,0 +1,26 @@
+import { t } from 'elysia';
+
+// Wire shape produced by attachmentDto (see the controller for what it omits).
+export const AttachmentResponse = t.Object({
+ id: t.String(),
+ filename: t.String(),
+ contentType: t.String(),
+ sizeBytes: t.Number(),
+ createdAt: t.String(),
+ url: t.String(),
+});
+
+export const AttachmentListResponse = t.Array(AttachmentResponse);
+
+export const issueParams = t.Object({ issueId: t.Numeric() });
+
+export const uploadAttachmentBody = t.Object({ file: t.File() });
+
+export const importAttachmentBody = t.Object({
+ filename: t.String({ minLength: 1 }),
+ url: t.Optional(t.String()),
+ contentBase64: t.Optional(t.String()),
+ contentType: t.Optional(t.String()),
+});
+
+export const rawAttachmentQuery = t.Object({ download: t.Optional(t.String()) });
diff --git a/apps/api/src/attachments/store.ts b/apps/api/src/modules/attachments/service.ts
similarity index 97%
rename from apps/api/src/attachments/store.ts
rename to apps/api/src/modules/attachments/service.ts
index b4d782c8..51e51d96 100644
--- a/apps/api/src/attachments/store.ts
+++ b/apps/api/src/modules/attachments/service.ts
@@ -1,9 +1,9 @@
import { db, issue, issueAttachment, issueFieldValue } from '@repo/db';
import { eq, sql } from 'drizzle-orm';
-import { iso, num } from '../shared/lib';
+import { iso, num } from '#shared/lib';
// Data access for issue attachments. File bytes live in the S3-compatible object
-// store (../shared/s3.ts); these rows hold the metadata and the object key. publicId is
+// store (#shared/s3); these rows hold the metadata and the object key. publicId is
// the unguessable id used in the public download URL.
export interface AttachmentRow {
diff --git a/apps/api/src/modules/avatars/index.ts b/apps/api/src/modules/avatars/index.ts
new file mode 100644
index 00000000..aa326f4e
--- /dev/null
+++ b/apps/api/src/modules/avatars/index.ts
@@ -0,0 +1,61 @@
+import { Elysia, t } from 'elysia';
+import { noContent } from '#shared/http';
+import { authContext } from '#shared/auth-context';
+import { requireUser } from '#shared/access';
+import { errors } from '#shared/responses';
+import { AvatarResponse, avatarParams, uploadAvatarBody } from './model';
+import { clearAvatar, readAvatar, replaceAvatar } from './service';
+
+export const avatarRoutes = new Elysia({ name: 'avatars', detail: { tags: ['Avatars'] } })
+ .use(authContext)
+
+ .post(
+ '/me/avatar',
+ async ({ user: sessionUser, body }) => {
+ const current = requireUser(sessionUser);
+ const image = await replaceAvatar(current.id, sessionUser?.image, body.file);
+ return { image };
+ },
+ {
+ body: uploadAvatarBody,
+ response: { 200: AvatarResponse, ...errors(400, 401, 413, 502) },
+ detail: { summary: "Upload the current user's avatar" },
+ },
+ )
+
+ .delete(
+ '/me/avatar',
+ async ({ user: sessionUser }) => {
+ const current = requireUser(sessionUser);
+ await clearAvatar(current.id, sessionUser?.image);
+ return noContent();
+ },
+ {
+ response: { 204: t.Void(), ...errors(401) },
+ detail: { summary: "Remove the current user's avatar" },
+ },
+ )
+
+ // Public preview URL: unauthenticated so it works in an <img> tag. The id is an
+ // unguessable uuid. Only raster image types are stored, and nosniff plus the
+ // media allowlist keep the bytes from being interpreted as anything executable.
+ .get(
+ '/avatars/:id/raw',
+ async ({ params }) => {
+ const obj = await readAvatar(params.id);
+ const ct = /^image\//i.test(obj.contentType) ? obj.contentType : 'application/octet-stream';
+ const headers: Record<string, string> = {
+ 'Content-Type': ct,
+ 'X-Content-Type-Options': 'nosniff',
+ 'Cache-Control': 'public, max-age=31536000, immutable',
+ };
+ if (obj.contentLength != null) headers['Content-Length'] = String(obj.contentLength);
+ return new Response(obj.body, { headers });
+ },
+ {
+ params: avatarParams,
+ // Public route: no 401/403. Returns raw bytes, so no typed 200 body.
+ response: { ...errors(404) },
+ detail: { summary: "Preview a user's avatar (public, no auth)" },
+ },
+ );
diff --git a/apps/api/src/modules/avatars/model.ts b/apps/api/src/modules/avatars/model.ts
new file mode 100644
index 00000000..0ce01c07
--- /dev/null
+++ b/apps/api/src/modules/avatars/model.ts
@@ -0,0 +1,8 @@
+import { t } from 'elysia';
+
+export const avatarParams = t.Object({ id: t.String() });
+
+export const uploadAvatarBody = t.Object({ file: t.File() });
+
+// The relative serve URL stored on the account, returned after an upload.
+export const AvatarResponse = t.Object({ image: t.String() });
diff --git a/apps/api/src/modules/avatars/service.ts b/apps/api/src/modules/avatars/service.ts
new file mode 100644
index 00000000..5d6be088
--- /dev/null
+++ b/apps/api/src/modules/avatars/service.ts
@@ -0,0 +1,96 @@
+import { db, user } from '@repo/db';
+import { eq } from 'drizzle-orm';
+import { randomUUID } from 'node:crypto';
+import { HttpError } from '#shared/lib';
+import { putObject, getObject, deleteObject } from '#shared/s3';
+import { getStorageSettings, MB } from '../../settings/storage';
+
+// Avatar images for the signed-in user. The bytes live in the S3-compatible
+// object store under `avatars/<uuid>`; the user's `image` column (managed by
+// better-auth) holds the relative serve URL.
+
+// Raster image types only. SVG is excluded on purpose: it can carry script and
+// the raw route is public and same-origin, so an inline SVG would be stored XSS.
+const ALLOWED_TYPES = /^image\/(png|jpe?g|gif|webp|avif)$/i;
+
+// The relative URL stored in user.image for one of our avatars. The frontend
+// prefixes it with the API origin when rendering.
+const avatarUrl = (id: string) => `/avatars/${id}/raw`;
+
+const avatarKey = (id: string) => `avatars/${id}`;
+
+// Pulls the avatar id out of a stored user.image URL, or null if it is not one
+// of our avatars (an external/OAuth image or empty). Used to delete the previous
+// object when the avatar is replaced or removed.
+function avatarIdFromImage(image: string | null | undefined): string | null {
+ if (!image) return null;
+ const match = image.match(/\/avatars\/([^/]+)\/raw$/);
+ return match ? match[1] : null;
+}
+
+async function setUserImage(userId: string, image: string | null): Promise<void> {
+ await db.update(user).set({ image }).where(eq(user.id, userId));
+}
+
+async function deletePreviousAvatar(image: string | null | undefined): Promise<void> {
+ const id = avatarIdFromImage(image);
+ if (!id) return;
+ await deleteObject(avatarKey(id)).catch((err) => {
+ console.error(
+ `[planner] failed to delete previous avatar ${id}:`,
+ err instanceof Error ? err.message : err,
+ );
+ });
+}
+
+// The size limit is an instance setting (see ../../settings/storage.ts), read per
+// call so a change in god mode takes effect without a restart.
+export async function replaceAvatar(
+ userId: string,
+ currentImage: string | null | undefined,
+ file: unknown,
+): Promise<string> {
+ if (!(file instanceof File)) throw new HttpError(400, 'No file uploaded (form field "file")');
+ if (file.size === 0) throw new HttpError(400, 'Uploaded file is empty');
+ const { maxAvatarMb } = await getStorageSettings();
+ if (file.size > maxAvatarMb * MB) {
+ throw new HttpError(413, `Image exceeds the ${maxAvatarMb} MB limit`);
+ }
+ const contentType = file.type || '';
+ if (!ALLOWED_TYPES.test(contentType)) {
+ throw new HttpError(400, 'Avatar must be a PNG, JPEG, GIF, WebP, or AVIF image');
+ }
+
+ const id = randomUUID();
+ const key = avatarKey(id);
+ try {
+ await putObject(key, Buffer.from(await file.arrayBuffer()), contentType);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ console.error(`[planner] avatar PUT failed (key=${key}, size=${file.size}):`, err);
+ throw new HttpError(502, `Object store error: ${msg}`);
+ }
+
+ const url = avatarUrl(id);
+ // Point the account at the new object first, then drop the old one (the session
+ // user still carries the previous image); a failed cleanup only orphans bytes.
+ await setUserImage(userId, url);
+ await deletePreviousAvatar(currentImage);
+ return url;
+}
+
+export async function clearAvatar(
+ userId: string,
+ currentImage: string | null | undefined,
+): Promise<void> {
+ await setUserImage(userId, null);
+ await deletePreviousAvatar(currentImage);
+}
+
+export async function readAvatar(id: string) {
+ try {
+ return await getObject(avatarKey(id));
+ } catch (err) {
+ throw new HttpError(404, err instanceof Error ? err.message : 'Object not found');
+ }
+}
diff --git a/apps/api/src/columns/__tests__/integration/columns.test.ts b/apps/api/src/modules/columns/__tests__/integration/columns.test.ts
similarity index 98%
rename from apps/api/src/columns/__tests__/integration/columns.test.ts
rename to apps/api/src/modules/columns/__tests__/integration/columns.test.ts
index b662049f..791a54ff 100644
--- a/apps/api/src/columns/__tests__/integration/columns.test.ts
+++ b/apps/api/src/modules/columns/__tests__/integration/columns.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
// Columns (kanban states). There is no GET /columns route — a column is read back
// through the project view (GET /projects/:projectKey), whose `columns` field is
@@ -303,7 +303,7 @@ describe('columns', () => {
});
// A column is addressed as /projects/:projectKey/columns/:columnId. The
- // permission guard runs on :projectKey, so the store must also scope the column
+ // permission guard runs on :projectKey, so the service must also scope the column
// to that project — otherwise a member of one project could edit or delete a
// column of another project by passing its id.
describe('cross-project isolation', () => {
diff --git a/apps/api/src/modules/columns/index.ts b/apps/api/src/modules/columns/index.ts
new file mode 100644
index 00000000..a08a2dff
--- /dev/null
+++ b/apps/api/src/modules/columns/index.ts
@@ -0,0 +1,102 @@
+import { Elysia, t } from 'elysia';
+import { mcpTool } from '#mcp/generate';
+import { noContent } from '#shared/http';
+import { authContext } from '#shared/auth-context';
+import { guards } from '#shared/guards';
+import { requireUser } from '#shared/access';
+import { HttpError } from '#shared/lib';
+import { commonErrors } from '#shared/responses';
+import {
+ ColumnListResponse,
+ ColumnResponse,
+ columnParams,
+ createColumnBody,
+ deleteColumnBody,
+ reorderColumnsBody,
+ updateColumnBody,
+} from './model';
+import { listColumns, createColumn, updateColumn, reorderColumns, deleteColumn } from './service';
+
+export const columnRoutes = new Elysia({ name: 'columns', detail: { tags: ['Columns'] } })
+ .use(authContext)
+ .use(guards)
+ .post(
+ '/projects/:projectKey/columns',
+ async ({ project, body, set }) => {
+ set.status = 201;
+ return createColumn({ projectId: project.id, ...body });
+ },
+ {
+ body: createColumnBody,
+ permission: ['states', 'create'],
+ response: { 201: ColumnResponse, ...commonErrors },
+ detail: {
+ summary: 'Create a column',
+ description:
+ 'Create a column (workflow state). stateType is one of ' +
+ 'backlog/unstarted/started/completed/canceled.',
+ ...mcpTool('create_column'),
+ },
+ },
+ )
+
+ .put(
+ '/projects/:projectKey/columns/reorder',
+ async ({ project, body }) => {
+ await reorderColumns(project.id, body.orderedIds);
+ return listColumns(project.id);
+ },
+ {
+ body: reorderColumnsBody,
+ permission: ['states', 'edit'],
+ response: { 200: ColumnListResponse, ...commonErrors },
+ detail: {
+ summary: 'Reorder columns',
+ description:
+ "Reorder a project's columns. orderedIds is the full left-to-right list of " +
+ 'column ids. Returns the reordered columns.',
+ ...mcpTool('reorder_columns'),
+ },
+ },
+ )
+
+ .patch(
+ '/projects/:projectKey/columns/:columnId',
+ async ({ params, project, body }) => {
+ const column = await updateColumn(params.columnId, project.id, body);
+ if (!column) throw new HttpError(404, 'Column not found');
+ return column;
+ },
+ {
+ body: updateColumnBody,
+ params: columnParams,
+ permission: ['states', 'edit'],
+ response: { 200: ColumnResponse, ...commonErrors },
+ detail: {
+ summary: 'Update a column',
+ description: "Update a column's name, stateType, or color.",
+ ...mcpTool('update_column'),
+ },
+ },
+ )
+
+ .delete(
+ '/projects/:projectKey/columns/:columnId',
+ async ({ params, project, body, user }) => {
+ await deleteColumn(params.columnId, project.id, body, requireUser(user).id);
+ return noContent();
+ },
+ {
+ body: deleteColumnBody,
+ params: columnParams,
+ permission: ['states', 'delete'],
+ response: { 204: t.Void(), ...commonErrors },
+ detail: {
+ summary: 'Delete a column',
+ description:
+ "Delete a column. Body mode 'move' reassigns its issues to targetColumnId, " +
+ "'delete' removes them. Backlog columns cannot be deleted.",
+ ...mcpTool('delete_column'),
+ },
+ },
+ );
diff --git a/apps/api/src/modules/columns/model.ts b/apps/api/src/modules/columns/model.ts
new file mode 100644
index 00000000..daafa3bd
--- /dev/null
+++ b/apps/api/src/modules/columns/model.ts
@@ -0,0 +1,39 @@
+import { t } from 'elysia';
+
+const stateType = t.Union([
+ t.Literal('backlog'),
+ t.Literal('unstarted'),
+ t.Literal('started'),
+ t.Literal('completed'),
+ t.Literal('canceled'),
+]);
+
+export const columnParams = t.Object({ projectKey: t.String(), columnId: t.Numeric() });
+
+export const ColumnResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ name: t.String(),
+ stateType: t.String(),
+ color: t.String(),
+ position: t.Number(),
+});
+
+export const ColumnListResponse = t.Array(ColumnResponse);
+
+export const createColumnBody = t.Object({
+ name: t.String({ minLength: 1 }),
+ stateType,
+ color: t.Optional(t.String()),
+});
+
+export const updateColumnBody = t.Partial(createColumnBody);
+
+export const reorderColumnsBody = t.Object({
+ orderedIds: t.Array(t.Integer(), { minItems: 1 }),
+});
+
+export const deleteColumnBody = t.Union([
+ t.Object({ mode: t.Literal('move'), targetColumnId: t.Integer() }),
+ t.Object({ mode: t.Literal('delete') }),
+]);
diff --git a/apps/api/src/columns/store.ts b/apps/api/src/modules/columns/service.ts
similarity index 76%
rename from apps/api/src/columns/store.ts
rename to apps/api/src/modules/columns/service.ts
index 393d553d..9237980c 100644
--- a/apps/api/src/columns/store.ts
+++ b/apps/api/src/modules/columns/service.ts
@@ -1,10 +1,7 @@
import { db, projectColumn, issue, issueLabel, issueFieldValue, issueFieldOption } from '@repo/db';
import { and, eq, inArray, sql } from 'drizzle-orm';
-import { HttpError } from '../shared/lib';
-import { recordActivityForIssues } from '../issues/activity';
-
-// Data access for columns (kanban states). A column belongs to one project and
-// has a state type that fixes its place in the work items view's left-to-right order.
+import { HttpError } from '#shared/lib';
+import { recordActivityForIssues } from '../../issues/activity';
export interface ColumnRow {
id: number;
@@ -26,10 +23,8 @@ function mapColumn(row: typeof projectColumn.$inferSelect): ColumnRow {
};
}
-// Columns are ordered by state type (backlog → unstarted → started → completed
-// → canceled), then by position within a type. This is the work items view's left-to-right
-// order, so a newly added column appears next to the others of its state type
-// rather than at the end.
+// The work items view's left-to-right order: sorting by state type before position
+// keeps a newly added column next to the others of its type rather than at the end.
const STATE_TYPE_ORDER = sql`CASE ${projectColumn.stateType}
WHEN 'backlog' THEN 0
WHEN 'unstarted' THEN 1
@@ -71,7 +66,7 @@ export async function createColumn(input: {
return mapColumn(row);
}
-export async function getColumnById(id: number): Promise<ColumnRow | null> {
+async function getColumnById(id: number): Promise<ColumnRow | null> {
const rows = await db.select().from(projectColumn).where(eq(projectColumn.id, id));
return rows[0] ? mapColumn(rows[0]) : null;
}
@@ -96,10 +91,9 @@ export async function updateColumn(
return row ? mapColumn(row) : null;
}
-// Renumbers the project's columns to match orderedIds (the desired left-to-right
-// order). Any column not listed is appended in its current order. Runs a two-pass
-// update — first shift every position out of range, then assign 0..n-1 — so the
-// UNIQUE(project_id, position) constraint never sees a transient duplicate.
+// Any column missing from orderedIds is appended in its current order. The two-pass
+// update — shift every position out of range, then assign 0..n-1 — keeps the
+// UNIQUE(project_id, position) constraint from seeing a transient duplicate.
export async function reorderColumns(projectId: number, orderedIds: number[]): Promise<void> {
const existing = await listColumns(projectId);
const known = new Set(existing.map((c) => c.id));
@@ -120,13 +114,11 @@ export async function reorderColumns(projectId: number, orderedIds: number[]): P
});
}
-// Deletes a column. `move` reassigns the column's issues to targetColumnId before
-// dropping the column; `delete` removes the issues and their dependent rows
-// (labels, custom field values/options) first. Backlog columns cannot be deleted,
-// which keeps at least one column on every project. Runs in one transaction so the
-// column and its issues are never left half-deleted.
export type DeleteColumnOptions = { mode: 'move'; targetColumnId: number } | { mode: 'delete' };
+// Backlog columns cannot be deleted, which keeps at least one column on every
+// project. The column and its issues go in one transaction so neither is left
+// half-deleted.
export async function deleteColumn(
columnId: number,
projectId: number,
@@ -134,8 +126,6 @@ export async function deleteColumn(
actorUserId?: string | null,
): Promise<void> {
const column = await getColumnById(columnId);
- // Scoped to projectId: a column id outside the caller's project is a 404, not a
- // cross-project delete.
if (!column || column.projectId !== projectId)
throw new HttpError(404, `Column ${columnId} not found`);
if (column.stateType === 'backlog') throw new HttpError(400, 'Backlog columns cannot be deleted');
@@ -169,9 +159,8 @@ export async function deleteColumn(
return moved;
});
- // A reassignment is a status change like any other, so it belongs in the change
- // log: the issue's status timeline reads its stretches from these entries, and
- // without one the issue keeps counting time under the column it no longer sits in.
+ // The status timeline reads its stretches from the change log: without an entry
+ // the issue keeps counting time under the column it no longer sits in.
if (target)
await recordActivityForIssues(
movedIssueIds,
diff --git a/apps/api/src/custom-fields/__tests__/integration/custom-fields.test.ts b/apps/api/src/modules/custom-fields/__tests__/integration/custom-fields.test.ts
similarity index 97%
rename from apps/api/src/custom-fields/__tests__/integration/custom-fields.test.ts
rename to apps/api/src/modules/custom-fields/__tests__/integration/custom-fields.test.ts
index 2c9ce002..3486086b 100644
--- a/apps/api/src/custom-fields/__tests__/integration/custom-fields.test.ts
+++ b/apps/api/src/modules/custom-fields/__tests__/integration/custom-fields.test.ts
@@ -1,12 +1,12 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
// Custom fields belong to a project. A field with issueTypeId null is
// project-wide; a field with issueTypeId set applies only to issues of that
// type. Routes live under /projects/:projectKey/custom-fields, so the permission
-// guard runs on :projectKey and the store scopes every field to that project.
+// guard runs on :projectKey and the service scopes every field to that project.
// Fields are read back through GET /projects/:projectKey/custom-fields, which
// takes an optional issueTypeId query to include that type's own fields.
@@ -263,7 +263,7 @@ describe('custom-fields', () => {
});
// A field is addressed as /projects/:projectKey/custom-fields/:fieldId. The
- // permission guard runs on :projectKey, so the store scopes the field to that
+ // permission guard runs on :projectKey, so the service scopes the field to that
// project — a member of one project must not edit or delete another project's
// field by passing its id.
describe('cross-project isolation', () => {
diff --git a/apps/api/src/modules/custom-fields/index.ts b/apps/api/src/modules/custom-fields/index.ts
new file mode 100644
index 00000000..13fff380
--- /dev/null
+++ b/apps/api/src/modules/custom-fields/index.ts
@@ -0,0 +1,101 @@
+import { Elysia, t } from 'elysia';
+import { noContent } from '#shared/http';
+import { guards } from '#shared/guards';
+import { HttpError } from '#shared/lib';
+import { commonErrors } from '#shared/responses';
+import { mcpTool } from '#mcp/generate';
+import {
+ CustomFieldListResponse,
+ CustomFieldResponse,
+ createCustomFieldBody,
+ fieldParams,
+ listFieldsQuery,
+ updateCustomFieldBody,
+} from './model';
+import {
+ listCustomFields,
+ createCustomField,
+ updateCustomField,
+ deleteCustomField,
+} from './service';
+
+export const customFieldRoutes = new Elysia({
+ name: 'custom-fields',
+ detail: { tags: ['Custom Fields'] },
+})
+ .use(guards)
+ // issueTypeId query param includes that type's own fields alongside the
+ // project-wide ones; omitting it returns only the project-wide fields.
+ .get(
+ '/projects/:projectKey/custom-fields',
+ async ({ project, query }) => {
+ return listCustomFields(project.id, { issueTypeId: query.issueTypeId });
+ },
+ {
+ query: listFieldsQuery,
+ permission: ['custom_fields', 'read'],
+ response: { 200: CustomFieldListResponse, ...commonErrors },
+ detail: {
+ summary: "List a project's custom fields",
+ description: "List a project's custom fields.",
+ ...mcpTool('list_custom_fields'),
+ },
+ },
+ )
+
+ .post(
+ '/projects/:projectKey/custom-fields',
+ async ({ project, body, set }) => {
+ set.status = 201;
+ return createCustomField({ projectId: project.id, ...body });
+ },
+ {
+ body: createCustomFieldBody,
+ permission: ['custom_fields', 'create'],
+ response: { 201: CustomFieldResponse, ...commonErrors },
+ detail: {
+ summary: 'Create a custom field',
+ description: 'Create a custom field for a project.',
+ ...mcpTool('create_custom_field'),
+ },
+ },
+ )
+
+ .patch(
+ '/projects/:projectKey/custom-fields/:fieldId',
+ async ({ project, params, body }) => {
+ const field = await updateCustomField(project.id, params.fieldId, body);
+ if (!field) throw new HttpError(404, 'Custom field not found');
+ return field;
+ },
+ {
+ body: updateCustomFieldBody,
+ params: fieldParams,
+ permission: ['custom_fields', 'edit'],
+ response: { 200: CustomFieldResponse, ...commonErrors },
+ detail: {
+ summary: 'Update a custom field',
+ description: 'Update a custom field.',
+ ...mcpTool('update_custom_field'),
+ },
+ },
+ )
+
+ .delete(
+ '/projects/:projectKey/custom-fields/:fieldId',
+ async ({ project, params }) => {
+ const deleted = await deleteCustomField(project.id, params.fieldId);
+ if (!deleted) throw new HttpError(404, 'Custom field not found');
+ return noContent();
+ },
+ {
+ params: fieldParams,
+ permission: ['custom_fields', 'delete'],
+ response: { 204: t.Void(), ...commonErrors },
+ detail: {
+ summary: 'Delete a custom field',
+ description: 'Delete a custom field.',
+ ...mcpTool('delete_custom_field'),
+ },
+ },
+ );
diff --git a/apps/api/src/modules/custom-fields/model.ts b/apps/api/src/modules/custom-fields/model.ts
new file mode 100644
index 00000000..50c3d0e5
--- /dev/null
+++ b/apps/api/src/modules/custom-fields/model.ts
@@ -0,0 +1,51 @@
+import { t } from 'elysia';
+
+const fieldType = t.Union([
+ t.Literal('text'),
+ t.Literal('markdown'),
+ t.Literal('url'),
+ t.Literal('number'),
+ t.Literal('boolean'),
+ t.Literal('date'),
+ t.Literal('select'),
+ t.Literal('multi_select'),
+]);
+
+export const fieldParams = t.Object({ projectKey: t.String(), fieldId: t.Numeric() });
+
+export const listFieldsQuery = t.Object({ issueTypeId: t.Optional(t.Numeric()) });
+
+// A field option DTO (CustomFieldOptionRow from the service).
+const CustomFieldOptionResponse = t.Object({
+ id: t.Number(),
+ value: t.String(),
+ color: t.String(),
+ position: t.Number(),
+});
+
+// A custom field DTO (CustomFieldRow from the service).
+export const CustomFieldResponse = t.Object({
+ id: t.Number(),
+ issueTypeId: t.Nullable(t.Number()),
+ name: t.String(),
+ fieldType,
+ showInBody: t.Boolean(),
+ position: t.Number(),
+ options: t.Array(CustomFieldOptionResponse),
+});
+
+export const CustomFieldListResponse = t.Array(CustomFieldResponse);
+
+export const createCustomFieldBody = t.Object({
+ issueTypeId: t.Optional(t.Nullable(t.Integer())),
+ name: t.String({ minLength: 1 }),
+ fieldType,
+ showInBody: t.Optional(t.Boolean()),
+ options: t.Optional(t.Array(t.String({ minLength: 1 }))),
+});
+
+// Only the two fields an existing field lets you change; its type and options are fixed.
+export const updateCustomFieldBody = t.Object({
+ name: t.Optional(t.String({ minLength: 1 })),
+ showInBody: t.Optional(t.Boolean()),
+});
diff --git a/apps/api/src/custom-fields/store.ts b/apps/api/src/modules/custom-fields/service.ts
similarity index 88%
rename from apps/api/src/custom-fields/store.ts
rename to apps/api/src/modules/custom-fields/service.ts
index 01ab8693..410a4803 100644
--- a/apps/api/src/custom-fields/store.ts
+++ b/apps/api/src/modules/custom-fields/service.ts
@@ -1,5 +1,7 @@
import { db, customField, customFieldOption } from '@repo/db';
-import { and, asc, eq, inArray, isNull, or, sql } from 'drizzle-orm';
+import { and, asc, eq, inArray, isNull, or, sql, type SQL } from 'drizzle-orm';
+import { HttpError } from '#shared/lib';
+import { getIssueTypeById } from '../../issue-types/store';
// Data access for custom fields and their options. Every field belongs to a
// project. A field with issue_type_id NULL is project-wide (applies to every
@@ -68,19 +70,20 @@ export async function listCustomFields(
projectId: number,
opts: { issueTypeId?: number; allTypes?: boolean } = {},
): Promise<CustomFieldRow[]> {
- const scope = opts.allTypes
- ? undefined
- : opts.issueTypeId != null
- ? or(isNull(customField.issueTypeId), eq(customField.issueTypeId, opts.issueTypeId))
- : isNull(customField.issueTypeId);
+ const conds: SQL[] = [eq(customField.projectId, projectId)];
+ if (!opts.allTypes) {
+ if (opts.issueTypeId != null) {
+ conds.push(
+ or(isNull(customField.issueTypeId), eq(customField.issueTypeId, opts.issueTypeId))!,
+ );
+ } else {
+ conds.push(isNull(customField.issueTypeId));
+ }
+ }
const fields = await db
.select()
.from(customField)
- .where(
- scope
- ? and(eq(customField.projectId, projectId), scope)
- : eq(customField.projectId, projectId),
- )
+ .where(and(...conds))
.orderBy(asc(customField.position));
const options = await optionsByField(fields.map((f) => f.id));
return fields.map((f) => mapField(f, options.get(f.id) ?? []));
@@ -110,6 +113,12 @@ export async function createCustomField(input: {
options?: string[];
}): Promise<CustomFieldRow> {
const issueTypeId = input.issueTypeId ?? null;
+ if (issueTypeId != null) {
+ const type = await getIssueTypeById(issueTypeId);
+ if (!type || type.projectId !== input.projectId) {
+ throw new HttpError(400, 'issueTypeId does not belong to this project');
+ }
+ }
const [{ pos }] = await db
.select({ pos: sql<number>`COALESCE(MAX(${customField.position}), -1) + 1` })
.from(customField)
diff --git a/apps/api/src/cycles/__tests__/integration/cycles.test.ts b/apps/api/src/modules/cycles/__tests__/integration/cycles.test.ts
similarity index 98%
rename from apps/api/src/cycles/__tests__/integration/cycles.test.ts
rename to apps/api/src/modules/cycles/__tests__/integration/cycles.test.ts
index 983f3c0d..c854ba1e 100644
--- a/apps/api/src/cycles/__tests__/integration/cycles.test.ts
+++ b/apps/api/src/modules/cycles/__tests__/integration/cycles.test.ts
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-import { addProjectMember } from '../../../__tests__/helpers/members';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { addProjectMember } from '#tests/helpers/members';
// Cycles are time-boxed periods of work inside a project (sprints). Issues link to
// one through issue.cycleId. The status (upcoming/active/completed) follows from the
diff --git a/apps/api/src/cycles/routes.ts b/apps/api/src/modules/cycles/index.ts
similarity index 53%
rename from apps/api/src/cycles/routes.ts
rename to apps/api/src/modules/cycles/index.ts
index 62cb0673..b0fb07ab 100644
--- a/apps/api/src/cycles/routes.ts
+++ b/apps/api/src/modules/cycles/index.ts
@@ -1,12 +1,25 @@
import { Elysia, t } from 'elysia';
-import { mcpTool } from '../mcp/generate';
-import { noContent } from '../shared/http';
-import { guards, entityGuard } from '../shared/guards';
-import { authContext } from '../shared/auth-context';
-import { requireUser } from '../shared/access';
-import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
-import { transferCycleIssues } from '../issues/store';
+import { mcpTool } from '#mcp/generate';
+import { noContent } from '#shared/http';
+import { guards, entityGuard } from '#shared/guards';
+import { authContext } from '#shared/auth-context';
+import { requireUser } from '#shared/access';
+import { HttpError } from '#shared/lib';
+import { accessErrors, commonErrors } from '#shared/responses';
+import { transferCycleIssues } from '../../issues/store';
+import {
+ CycleListResponse,
+ CycleOptionListResponse,
+ CyclePageResponse,
+ CycleResponse,
+ TransferCycleResponse,
+ completedCyclesQuery,
+ createCycleBody,
+ cycleParams,
+ listCyclesQuery,
+ transferCycleBody,
+ updateCycleBody,
+} from './model';
import {
listCycles,
listPlannedCycles,
@@ -16,29 +29,7 @@ import {
createCycle,
updateCycle,
deleteCycle,
-} from './store';
-
-const cycleParams = t.Object({ cycleId: t.Numeric() });
-
-const IsoDate = t.String({
- pattern: '^\\d{4}-\\d{2}-\\d{2}$',
- description: "Date 'YYYY-MM-DD'.",
-});
-
-// CycleRow from the store. status follows from the dates against today (upcoming /
-// active / completed) and progress is derived issue counts; neither is stored.
-const CycleResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- name: t.String(),
- goal: t.String(),
- startDate: t.String(),
- endDate: t.String(),
- status: t.String(),
- createdAt: t.String(),
- updatedAt: t.String(),
- progress: t.Object({ completed: t.Number(), canceled: t.Number(), total: t.Number() }),
-});
+} from './service';
export const cycleRoutes = new Elysia({
name: 'cycles',
@@ -57,22 +48,9 @@ export const cycleRoutes = new Elysia({
async ({ project, query }) =>
query.status === 'planned' ? listPlannedCycles(project.id) : listCycles(project.id),
{
- params: t.Object({ projectKey: t.String() }),
- query: t.Object({
- status: t.Optional(
- t.Literal('planned', {
- description: 'Only the cycles that have not finished: active and upcoming.',
- }),
- ),
- }),
+ query: listCyclesQuery,
permission: ['cycles', 'read'],
- response: {
- 200: t.Array(CycleResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: CycleListResponse, ...commonErrors },
detail: {
summary: 'List cycles',
description: "A project's cycles, oldest first.",
@@ -91,14 +69,8 @@ export const cycleRoutes = new Elysia({
return cycles.map((c) => ({ id: c.id, name: c.name, status: c.status }));
},
{
- params: t.Object({ projectKey: t.String() }),
permission: ['work_items', 'read'],
- response: {
- 200: t.Array(t.Object({ id: t.Number(), name: t.String(), status: t.String() })),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: CycleOptionListResponse, ...accessErrors },
detail: {
summary: 'List cycle options',
description: 'The cycles an issue can be planned into: id, name and status.',
@@ -118,30 +90,9 @@ export const cycleRoutes = new Elysia({
return { items, total, page, pageSize };
},
{
- params: t.Object({ projectKey: t.String() }),
- query: t.Object({
- page: t.Optional(t.Numeric({ minimum: 1, description: '1-based page. Default 1.' })),
- pageSize: t.Optional(
- t.Numeric({
- minimum: 1,
- maximum: 100,
- description: 'Items per page (1-100). Default 25.',
- }),
- ),
- }),
+ query: completedCyclesQuery,
permission: ['cycles', 'read'],
- response: {
- 200: t.Object({
- items: t.Array(CycleResponse),
- total: t.Number(),
- page: t.Number(),
- pageSize: t.Number(),
- }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: CyclePageResponse, ...commonErrors },
detail: {
summary: 'List completed cycles',
description: "A page of a project's finished cycles, newest first.",
@@ -156,21 +107,9 @@ export const cycleRoutes = new Elysia({
return createCycle(project.id, body);
},
{
- params: t.Object({ projectKey: t.String() }),
- body: t.Object({
- name: t.String({ minLength: 1, description: 'Cycle name.' }),
- goal: t.Optional(t.String({ description: 'What the team commits to in this cycle.' })),
- startDate: IsoDate,
- endDate: IsoDate,
- }),
+ body: createCycleBody,
permission: ['cycles', 'create'],
- response: {
- 201: CycleResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: CycleResponse, ...commonErrors },
detail: {
summary: 'Create a cycle',
description:
@@ -190,13 +129,7 @@ export const cycleRoutes = new Elysia({
{
params: cycleParams,
cycle: 'read',
- response: {
- 200: CycleResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: CycleResponse, ...commonErrors },
detail: {
summary: 'Get a cycle',
description: 'Get a cycle by its numeric id.',
@@ -214,20 +147,9 @@ export const cycleRoutes = new Elysia({
},
{
params: cycleParams,
- body: t.Object({
- name: t.Optional(t.String({ minLength: 1, description: 'New name.' })),
- goal: t.Optional(t.String({ description: 'New goal.' })),
- startDate: t.Optional(IsoDate),
- endDate: t.Optional(IsoDate),
- }),
+ body: updateCycleBody,
cycle: 'edit',
- response: {
- 200: CycleResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: CycleResponse, ...commonErrors },
detail: {
summary: 'Update a cycle',
description:
@@ -246,13 +168,7 @@ export const cycleRoutes = new Elysia({
{
params: cycleParams,
cycle: 'delete',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete a cycle',
description: 'Delete a cycle by its numeric id. Its issues stay, without a cycle.',
@@ -275,22 +191,9 @@ export const cycleRoutes = new Elysia({
},
{
params: cycleParams,
- body: t.Object({
- targetCycleId: t.Nullable(
- t.Integer({
- description:
- 'Cycle to move the unfinished issues to, or null to leave them without a cycle.',
- }),
- ),
- }),
+ body: transferCycleBody,
cycle: 'edit',
- response: {
- 200: t.Object({ moved: t.Number() }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: TransferCycleResponse, ...commonErrors },
detail: {
summary: 'Transfer unfinished issues',
description:
diff --git a/apps/api/src/modules/cycles/model.ts b/apps/api/src/modules/cycles/model.ts
new file mode 100644
index 00000000..ef5f1b47
--- /dev/null
+++ b/apps/api/src/modules/cycles/model.ts
@@ -0,0 +1,61 @@
+import { t } from 'elysia';
+import { pageQueryFields, pageResponse } from '#shared/pagination';
+
+const IsoDate = t.String({
+ pattern: '^\\d{4}-\\d{2}-\\d{2}$',
+ description: "Date 'YYYY-MM-DD'.",
+});
+
+export const cycleParams = t.Object({ cycleId: t.Numeric() });
+
+export const listCyclesQuery = t.Object({
+ status: t.Optional(
+ t.Literal('planned', {
+ description: 'Only the cycles that have not finished: active and upcoming.',
+ }),
+ ),
+});
+
+export const completedCyclesQuery = t.Object(pageQueryFields);
+
+// CycleRow from the service. status follows from the dates against today (upcoming /
+// active / completed) and progress is derived issue counts; neither is stored.
+export const CycleResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ name: t.String(),
+ goal: t.String(),
+ startDate: t.String(),
+ endDate: t.String(),
+ status: t.String(),
+ createdAt: t.String(),
+ updatedAt: t.String(),
+ progress: t.Object({ completed: t.Number(), canceled: t.Number(), total: t.Number() }),
+});
+
+export const CycleListResponse = t.Array(CycleResponse);
+
+export const CyclePageResponse = pageResponse(CycleResponse);
+
+export const CycleOptionListResponse = t.Array(
+ t.Object({ id: t.Number(), name: t.String(), status: t.String() }),
+);
+
+export const createCycleBody = t.Object({
+ name: t.String({ minLength: 1, description: 'Cycle name.' }),
+ goal: t.Optional(t.String({ description: 'What the team commits to in this cycle.' })),
+ startDate: IsoDate,
+ endDate: IsoDate,
+});
+
+export const updateCycleBody = t.Partial(createCycleBody);
+
+export const transferCycleBody = t.Object({
+ targetCycleId: t.Nullable(
+ t.Integer({
+ description: 'Cycle to move the unfinished issues to, or null to leave them without a cycle.',
+ }),
+ ),
+});
+
+export const TransferCycleResponse = t.Object({ moved: t.Number() });
diff --git a/apps/api/src/cycles/store.ts b/apps/api/src/modules/cycles/service.ts
similarity index 99%
rename from apps/api/src/cycles/store.ts
rename to apps/api/src/modules/cycles/service.ts
index aee0b4d8..66bf784c 100644
--- a/apps/api/src/cycles/store.ts
+++ b/apps/api/src/modules/cycles/service.ts
@@ -1,6 +1,6 @@
import { db, cycle, issue, projectColumn } from '@repo/db';
import { and, asc, desc, eq, ne, sql, type SQL } from 'drizzle-orm';
-import { HttpError, iso } from '../shared/lib';
+import { HttpError, iso } from '#shared/lib';
// Data access for cycles: a time-boxed period of work inside a project (a sprint).
// Issues link to a cycle through issue.cycle_id. The status is derived from the
diff --git a/apps/api/src/dashboards/__tests__/integration/dashboards.test.ts b/apps/api/src/modules/dashboards/__tests__/integration/dashboards.test.ts
similarity index 98%
rename from apps/api/src/dashboards/__tests__/integration/dashboards.test.ts
rename to apps/api/src/modules/dashboards/__tests__/integration/dashboards.test.ts
index b151bfe2..fd682db7 100644
--- a/apps/api/src/dashboards/__tests__/integration/dashboards.test.ts
+++ b/apps/api/src/modules/dashboards/__tests__/integration/dashboards.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { authedApi } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
async function setupOwnerProject() {
const owner = await signUpTestUser();
diff --git a/apps/api/src/dashboards/routes.ts b/apps/api/src/modules/dashboards/index.ts
similarity index 50%
rename from apps/api/src/dashboards/routes.ts
rename to apps/api/src/modules/dashboards/index.ts
index b068a52c..6435cb57 100644
--- a/apps/api/src/dashboards/routes.ts
+++ b/apps/api/src/modules/dashboards/index.ts
@@ -1,10 +1,18 @@
import { Elysia, t } from 'elysia';
-import { noContent } from '../shared/http';
-import { guards, entityGuard } from '../shared/guards';
-import { authContext } from '../shared/auth-context';
-import { HttpError } from '../shared/lib';
-import { mcpTool } from '../mcp/generate';
-import { ErrorResponse } from '../shared/responses';
+import { noContent } from '#shared/http';
+import { guards, entityGuard } from '#shared/guards';
+import { authContext } from '#shared/auth-context';
+import { HttpError } from '#shared/lib';
+import { mcpTool } from '#mcp/generate';
+import { accessErrors, commonErrors } from '#shared/responses';
+import {
+ DashboardListResponse,
+ DashboardResponse,
+ createDashboardBody,
+ dashboardParams,
+ reorderDashboardsBody,
+ updateDashboardBody,
+} from './model';
import {
listDashboards,
createDashboard,
@@ -12,26 +20,9 @@ import {
updateDashboard,
deleteDashboard,
reorderDashboards,
-} from './store';
-
-const dashboardParams = t.Object({ dashboardId: t.Numeric() });
-
-// A dashboard DTO (DashboardRow from the store). layout is a jsonb blob owned by
-// the UI and returned verbatim, so it is typed as t.Any().
-const DashboardResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- name: t.String(),
- icon: t.Nullable(t.String()),
- layout: t.Any(),
- position: t.Number(),
- createdAt: t.String(),
-});
+} from './service';
-export const dashboardRoutes = new Elysia({
- name: 'dashboards',
- detail: { tags: ['Dashboards'] },
-})
+export const dashboardRoutes = new Elysia({ name: 'dashboards', detail: { tags: ['Dashboards'] } })
.use(authContext)
.use(guards)
// Guard for routes that address a dashboard by its own id (no :projectKey in
@@ -50,12 +41,7 @@ export const dashboardRoutes = new Elysia({
},
{
permission: ['dashboards', 'read'],
- response: {
- 200: t.Array(DashboardResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: DashboardListResponse, ...accessErrors },
detail: { summary: "List a project's dashboards", ...mcpTool('list_dashboards') },
},
)
@@ -67,39 +53,22 @@ export const dashboardRoutes = new Elysia({
return createDashboard({ projectId: project.id, ...body });
},
{
- body: t.Object({
- name: t.String({ minLength: 1 }),
- icon: t.Optional(t.Nullable(t.String())),
- layout: t.Optional(t.Any()),
- }),
+ body: createDashboardBody,
permission: ['dashboards', 'create'],
- response: {
- 201: DashboardResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: DashboardResponse, ...commonErrors },
detail: { summary: 'Create a dashboard', ...mcpTool('create_dashboard') },
},
)
- // Sets the tab order to orderedIds.
.put(
'/projects/:projectKey/dashboards/reorder',
async ({ project, body }) => {
return reorderDashboards(project.id, body.orderedIds);
},
{
- body: t.Object({ orderedIds: t.Array(t.Integer(), { minItems: 1 }) }),
+ body: reorderDashboardsBody,
permission: ['dashboards', 'edit'],
- response: {
- 200: t.Array(DashboardResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: DashboardListResponse, ...commonErrors },
detail: { summary: 'Reorder dashboards', ...mcpTool('reorder_dashboards') },
},
)
@@ -112,20 +81,10 @@ export const dashboardRoutes = new Elysia({
return dashboard;
},
{
- body: t.Object({
- name: t.Optional(t.String({ minLength: 1 })),
- icon: t.Optional(t.Nullable(t.String())),
- layout: t.Optional(t.Any()),
- }),
+ body: updateDashboardBody,
params: dashboardParams,
dashboard: 'edit',
- response: {
- 200: DashboardResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: DashboardResponse, ...commonErrors },
detail: { summary: 'Update a dashboard', ...mcpTool('update_dashboard') },
},
)
@@ -139,13 +98,7 @@ export const dashboardRoutes = new Elysia({
{
params: dashboardParams,
dashboard: 'delete',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: { summary: 'Delete a dashboard', ...mcpTool('delete_dashboard') },
},
);
diff --git a/apps/api/src/modules/dashboards/model.ts b/apps/api/src/modules/dashboards/model.ts
new file mode 100644
index 00000000..8fbfb9b4
--- /dev/null
+++ b/apps/api/src/modules/dashboards/model.ts
@@ -0,0 +1,29 @@
+import { t } from 'elysia';
+
+export const dashboardParams = t.Object({ dashboardId: t.Numeric() });
+
+// A dashboard DTO (DashboardRow from the service). layout is a jsonb blob owned by
+// the UI and returned verbatim, so it is typed as t.Any().
+export const DashboardResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ name: t.String(),
+ icon: t.Nullable(t.String()),
+ layout: t.Any(),
+ position: t.Number(),
+ createdAt: t.String(),
+});
+
+export const DashboardListResponse = t.Array(DashboardResponse);
+
+export const createDashboardBody = t.Object({
+ name: t.String({ minLength: 1 }),
+ icon: t.Optional(t.Nullable(t.String())),
+ layout: t.Optional(t.Any()),
+});
+
+export const updateDashboardBody = t.Partial(createDashboardBody);
+
+export const reorderDashboardsBody = t.Object({
+ orderedIds: t.Array(t.Integer(), { minItems: 1 }),
+});
diff --git a/apps/api/src/dashboards/store.ts b/apps/api/src/modules/dashboards/service.ts
similarity index 98%
rename from apps/api/src/dashboards/store.ts
rename to apps/api/src/modules/dashboards/service.ts
index 4e2c6e41..cfa7be24 100644
--- a/apps/api/src/dashboards/store.ts
+++ b/apps/api/src/modules/dashboards/service.ts
@@ -1,6 +1,6 @@
import { db, projectDashboard } from '@repo/db';
import { and, eq, sql } from 'drizzle-orm';
-import { iso, num } from '../shared/lib';
+import { iso, num } from '#shared/lib';
// Saved dashboards: the analytics tabs of a project. layout is a jsonb blob owned
// by the UI (an ordered list of widget entries); this layer stores and returns it
diff --git a/apps/api/src/github/__tests__/integration/github-webhook.test.ts b/apps/api/src/modules/github/__tests__/integration/github-webhook.test.ts
similarity index 98%
rename from apps/api/src/github/__tests__/integration/github-webhook.test.ts
rename to apps/api/src/modules/github/__tests__/integration/github-webhook.test.ts
index 22de0f5c..6898c36a 100644
--- a/apps/api/src/github/__tests__/integration/github-webhook.test.ts
+++ b/apps/api/src/modules/github/__tests__/integration/github-webhook.test.ts
@@ -1,9 +1,9 @@
import { createHmac } from 'node:crypto';
import { describe, it, expect, beforeEach } from 'bun:test';
-import { app } from '../../../app';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
+import { app } from '../../../../app';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
// The inbound GitHub webhook: a signed pull_request delivery moves the issues its
// magic words name, through the same path a user's move takes (activity entries,
diff --git a/apps/api/src/github/__tests__/unit/magic-words.test.ts b/apps/api/src/modules/github/__tests__/unit/magic-words.test.ts
similarity index 100%
rename from apps/api/src/github/__tests__/unit/magic-words.test.ts
rename to apps/api/src/modules/github/__tests__/unit/magic-words.test.ts
diff --git a/apps/api/src/github/handler.ts b/apps/api/src/modules/github/handler.ts
similarity index 96%
rename from apps/api/src/github/handler.ts
rename to apps/api/src/modules/github/handler.ts
index 7d57d3d8..3a0af6c9 100644
--- a/apps/api/src/github/handler.ts
+++ b/apps/api/src/modules/github/handler.ts
@@ -1,7 +1,7 @@
-import { getIssueBySequence, updateIssue } from '../issues/store';
-import { recordActivity, type ActivityActor } from '../issues/activity';
+import { getIssueBySequence, updateIssue } from '../../issues/store';
+import { recordActivity, type ActivityActor } from '../../issues/activity';
import { parseMagicWords, type IssueRef } from './magic-words';
-import { columnStateTypes, firstCompletedColumnId, type GithubSettings } from './store';
+import { columnStateTypes, firstCompletedColumnId, type GithubSettings } from './service';
// Applies a GitHub pull_request delivery to the project's issues:
// - a PR merged into the repository's default branch moves the issues named by a
diff --git a/apps/api/src/modules/github/index.ts b/apps/api/src/modules/github/index.ts
new file mode 100644
index 00000000..44a22ddf
--- /dev/null
+++ b/apps/api/src/modules/github/index.ts
@@ -0,0 +1,46 @@
+import { Elysia } from 'elysia';
+import { guards } from '#shared/guards';
+import { authContext } from '#shared/auth-context';
+import { checkPermission } from '#shared/access';
+import { accessErrors, commonErrors } from '#shared/responses';
+import { GithubSettingsResponse, updateGithubSettingsBody } from './model';
+import { getOrCreateGithubSettings, regenerateGithubSecret, updateGithubSettings } from './service';
+
+export const githubSettingsRoutes = new Elysia({
+ name: 'github-settings',
+ detail: { tags: ['GitHub'] },
+})
+ .use(authContext)
+ .use(guards)
+ .get(
+ '/projects/:projectKey/settings/github',
+ async ({ project, user }) => {
+ const settings = await getOrCreateGithubSettings(project.id);
+ const canEdit = await checkPermission(project.id, user, 'integrations', 'edit');
+ return { ...settings, secret: canEdit ? settings.secret : null };
+ },
+ {
+ permission: ['integrations', 'read'],
+ response: { 200: GithubSettingsResponse, ...accessErrors },
+ detail: { summary: "Get a project's GitHub integration settings" },
+ },
+ )
+ .patch(
+ '/projects/:projectKey/settings/github',
+ ({ project, body }) => updateGithubSettings(project.id, body),
+ {
+ permission: ['integrations', 'edit'],
+ body: updateGithubSettingsBody,
+ response: { 200: GithubSettingsResponse, ...commonErrors },
+ detail: { summary: "Update a project's GitHub integration settings" },
+ },
+ )
+ .post(
+ '/projects/:projectKey/settings/github/secret',
+ ({ project }) => regenerateGithubSecret(project.id),
+ {
+ permission: ['integrations', 'edit'],
+ response: { 200: GithubSettingsResponse, ...accessErrors },
+ detail: { summary: "Regenerate a project's GitHub webhook secret" },
+ },
+ );
diff --git a/apps/api/src/github/magic-words.ts b/apps/api/src/modules/github/magic-words.ts
similarity index 100%
rename from apps/api/src/github/magic-words.ts
rename to apps/api/src/modules/github/magic-words.ts
diff --git a/apps/api/src/modules/github/model.ts b/apps/api/src/modules/github/model.ts
new file mode 100644
index 00000000..2ee889fe
--- /dev/null
+++ b/apps/api/src/modules/github/model.ts
@@ -0,0 +1,27 @@
+import { t } from 'elysia';
+
+export const webhookParams = t.Object({ webhookId: t.String() });
+
+export const webhookBody = t.String();
+
+export const WebhookAckResponse = t.Object({ ok: t.Boolean(), handled: t.String() });
+
+// The GitHub settings DTO (GithubSettings from the service). Unlike outgoing
+// webhook secrets, this secret authorizes issue moves through the receiver, so
+// it is shown only to members with integrations edit access; read-only callers
+// get null.
+export const GithubSettingsResponse = t.Object({
+ enabled: t.Boolean(),
+ webhookId: t.String(),
+ secret: t.Nullable(t.String()),
+ onMergeColumnId: t.Nullable(t.Number()),
+ onOpenColumnId: t.Nullable(t.Number()),
+ lastEventAt: t.Nullable(t.String()),
+ lastEventRepo: t.Nullable(t.String()),
+});
+
+export const updateGithubSettingsBody = t.Object({
+ enabled: t.Optional(t.Boolean()),
+ onMergeColumnId: t.Optional(t.Nullable(t.Number())),
+ onOpenColumnId: t.Optional(t.Nullable(t.Number())),
+});
diff --git a/apps/api/src/github/store.ts b/apps/api/src/modules/github/service.ts
similarity index 98%
rename from apps/api/src/github/store.ts
rename to apps/api/src/modules/github/service.ts
index b954c769..0f5534f3 100644
--- a/apps/api/src/github/store.ts
+++ b/apps/api/src/modules/github/service.ts
@@ -2,8 +2,13 @@ import { randomBytes } from 'node:crypto';
import { db, projectColumn, projectSetting } from '@repo/db';
import { and, asc, eq, inArray, sql } from 'drizzle-orm';
import { decryptSecret, encryptSecret, type EncryptedSecret } from '@repo/crypto';
-import { HttpError } from '../shared/lib';
-import { getProjectSetting } from '../settings/store';
+import { HttpError } from '#shared/lib';
+import { getProjectSetting } from '../../settings/store';
+
+// Exported for the project copier, which must not clone this setting: the copy
+// would carry the source's secret and webhook id (a credential disclosure to the
+// copy's owner, and ambiguous inbound routing).
+export const GITHUB_SETTING_KEY = 'github';
// The GitHub integration config for a project, stored in project_setting under
// GITHUB_SETTING_KEY. `webhookId` routes an incoming delivery to the project (it is the
@@ -13,12 +18,6 @@ import { getProjectSetting } from '../settings/store';
// completed column); `onOpenColumnId` is where an issue moves when a linked PR is
// opened (null = no action). lastEventAt/lastEventRepo show the settings page
// that deliveries arrive.
-
-// Exported for the project copier, which must not clone this setting: the copy
-// would carry the source's secret and webhook id (a credential disclosure to the
-// copy's owner, and ambiguous inbound routing).
-export const GITHUB_SETTING_KEY = 'github';
-
interface StoredGithubSettings {
enabled: boolean;
webhookId: string;
diff --git a/apps/api/src/github/routes.ts b/apps/api/src/modules/github/webhook.ts
similarity index 51%
rename from apps/api/src/github/routes.ts
rename to apps/api/src/modules/github/webhook.ts
index 6f46bce6..3a5d8afd 100644
--- a/apps/api/src/github/routes.ts
+++ b/apps/api/src/modules/github/webhook.ts
@@ -1,19 +1,11 @@
import { createHmac, timingSafeEqual } from 'node:crypto';
-import { Elysia, t } from 'elysia';
-import { guards } from '../shared/guards';
-import { authContext } from '../shared/auth-context';
-import { checkPermission } from '../shared/access';
-import { HttpError } from '../shared/lib';
-import { getProjectById } from '../projects/store';
+import { Elysia } from 'elysia';
+import { HttpError } from '#shared/lib';
+import { errors } from '#shared/responses';
+import { getProjectById } from '../../projects/store';
import { handlePullRequestEvent, type PullRequestPayload } from './handler';
-import {
- claimGithubDelivery,
- findProjectByGithubWebhookId,
- getOrCreateGithubSettings,
- recordGithubEvent,
- regenerateGithubSecret,
- updateGithubSettings,
-} from './store';
+import { WebhookAckResponse, webhookBody, webhookParams } from './model';
+import { claimGithubDelivery, findProjectByGithubWebhookId, recordGithubEvent } from './service';
// GitHub's HMAC over the raw request body, sent as "sha256=<hex>".
function signatureValid(secret: string, rawBody: string, header: string | undefined): boolean {
@@ -66,11 +58,9 @@ export const githubWebhookRoutes = new Elysia({
},
{
parse: 'text',
- body: t.String(),
- params: t.Object({ webhookId: t.String() }),
- response: {
- 200: t.Object({ ok: t.Boolean(), handled: t.String() }),
- },
+ body: webhookBody,
+ params: webhookParams,
+ response: { 200: WebhookAckResponse, ...errors(400, 401, 404) },
detail: {
summary: 'Receive a GitHub webhook',
description:
@@ -79,60 +69,3 @@ export const githubWebhookRoutes = new Elysia({
},
},
);
-
-// The GitHub settings DTO (GithubSettings from the store). Unlike outgoing
-// webhook secrets, this secret authorizes issue moves through the receiver, so
-// it is shown only to members with integrations edit access; read-only callers
-// get null.
-const GithubSettingsResponse = t.Object({
- enabled: t.Boolean(),
- webhookId: t.String(),
- secret: t.Nullable(t.String()),
- onMergeColumnId: t.Nullable(t.Number()),
- onOpenColumnId: t.Nullable(t.Number()),
- lastEventAt: t.Nullable(t.String()),
- lastEventRepo: t.Nullable(t.String()),
-});
-
-export const githubSettingsRoutes = new Elysia({
- name: 'github-settings',
- detail: { tags: ['GitHub'] },
-})
- .use(authContext)
- .use(guards)
- .get(
- '/projects/:projectKey/settings/github',
- async ({ project, user }) => {
- const settings = await getOrCreateGithubSettings(project.id);
- const canEdit = await checkPermission(project.id, user, 'integrations', 'edit');
- return { ...settings, secret: canEdit ? settings.secret : null };
- },
- {
- permission: ['integrations', 'read'],
- response: { 200: GithubSettingsResponse },
- detail: { summary: "Get a project's GitHub integration settings" },
- },
- )
- .patch(
- '/projects/:projectKey/settings/github',
- ({ project, body }) => updateGithubSettings(project.id, body),
- {
- permission: ['integrations', 'edit'],
- body: t.Object({
- enabled: t.Optional(t.Boolean()),
- onMergeColumnId: t.Optional(t.Nullable(t.Number())),
- onOpenColumnId: t.Optional(t.Nullable(t.Number())),
- }),
- response: { 200: GithubSettingsResponse },
- detail: { summary: "Update a project's GitHub integration settings" },
- },
- )
- .post(
- '/projects/:projectKey/settings/github/secret',
- ({ project }) => regenerateGithubSecret(project.id),
- {
- permission: ['integrations', 'edit'],
- response: { 200: GithubSettingsResponse },
- detail: { summary: "Regenerate a project's GitHub webhook secret" },
- },
- );
diff --git a/apps/api/src/initiatives/__tests__/integration/initiatives.test.ts b/apps/api/src/modules/initiatives/__tests__/integration/initiatives.test.ts
similarity index 98%
rename from apps/api/src/initiatives/__tests__/integration/initiatives.test.ts
rename to apps/api/src/modules/initiatives/__tests__/integration/initiatives.test.ts
index 4302a8b0..17ed4947 100644
--- a/apps/api/src/initiatives/__tests__/integration/initiatives.test.ts
+++ b/apps/api/src/modules/initiatives/__tests__/integration/initiatives.test.ts
@@ -1,8 +1,8 @@
import { describe, it, expect, beforeEach } from 'bun:test';
-import { authedApi, type Api } from '../../../__tests__/helpers/app';
-import { signUpTestUser } from '../../../__tests__/helpers/auth';
-import { resetDb } from '../../../__tests__/helpers/db';
-import { addProjectMember } from '../../../__tests__/helpers/members';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { addProjectMember } from '#tests/helpers/members';
// Initiatives are a project-scoped grouping of issues. Issues link to one through
// issue.initiativeId. status is a fixed lifecycle enum; progress and health are
diff --git a/apps/api/src/initiatives/__tests__/unit/health.test.ts b/apps/api/src/modules/initiatives/__tests__/unit/health.test.ts
similarity index 100%
rename from apps/api/src/initiatives/__tests__/unit/health.test.ts
rename to apps/api/src/modules/initiatives/__tests__/unit/health.test.ts
diff --git a/apps/api/src/initiatives/activity.ts b/apps/api/src/modules/initiatives/activity.ts
similarity index 99%
rename from apps/api/src/initiatives/activity.ts
rename to apps/api/src/modules/initiatives/activity.ts
index 4ddd8908..34eae8b1 100644
--- a/apps/api/src/initiatives/activity.ts
+++ b/apps/api/src/modules/initiatives/activity.ts
@@ -1,6 +1,6 @@
import { db, issue, issueActivity, project, user } from '@repo/db';
import { and, desc, eq, inArray, or, sql } from 'drizzle-orm';
-import { iso } from '../shared/lib';
+import { iso } from '#shared/lib';
// An initiative's activity feed merges two kinds of rows from issue_activity:
// events of the initiative itself (initiative_id set) and the activity of the
diff --git a/apps/api/src/initiatives/health.ts b/apps/api/src/modules/initiatives/health.ts
similarity index 100%
rename from apps/api/src/initiatives/health.ts
rename to apps/api/src/modules/initiatives/health.ts
diff --git a/apps/api/src/modules/initiatives/index.ts b/apps/api/src/modules/initiatives/index.ts
new file mode 100644
index 00000000..b9d2e619
--- /dev/null
+++ b/apps/api/src/modules/initiatives/index.ts
@@ -0,0 +1,212 @@
+import { Elysia, t } from 'elysia';
+import { mcpTool } from '#mcp/generate';
+import { noContent } from '#shared/http';
+import { guards, entityGuard } from '#shared/guards';
+import { authContext } from '#shared/auth-context';
+import { requireUser } from '#shared/access';
+import { HttpError } from '#shared/lib';
+import { commonErrors } from '#shared/responses';
+import {
+ FeedPageResponse,
+ InitiativeCountsResponse,
+ InitiativeOptionListResponse,
+ InitiativePageResponse,
+ InitiativeResponse,
+ createInitiativeBody,
+ initiativeFeedQuery,
+ initiativeOptionsQuery,
+ initiativeParams,
+ listInitiativesQuery,
+ updateInitiativeBody,
+} from './model';
+import {
+ listInitiatives,
+ listInitiativeOptions,
+ initiativeStatusCounts,
+ getInitiative,
+ getInitiativeProjectId,
+ createInitiative,
+ updateInitiative,
+ deleteInitiative,
+} from './service';
+import { listFeed } from './activity';
+
+export const initiativeRoutes = new Elysia({
+ name: 'initiatives',
+ detail: { tags: ['Initiatives'] },
+})
+ .use(authContext)
+ .use(guards)
+ // Guard for routes that address an initiative by its own id (no :projectKey in
+ // the path). Set `initiative: "<action>"` in the route options.
+ .macro({
+ initiative: entityGuard('initiatives', 'Initiative not found', (p) =>
+ getInitiativeProjectId(Number(p.initiativeId)),
+ ),
+ })
+
+ .get(
+ '/projects/:projectKey/initiatives',
+ async ({ project, query }) => {
+ const statuses = query.status
+ ? query.status
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean)
+ : undefined;
+ const page = query.page ?? 1;
+ const pageSize = query.pageSize ?? 25;
+ const { items, total } = await listInitiatives(project.id, {
+ statuses,
+ search: query.search,
+ sort: query.sort,
+ dir: query.dir,
+ limit: pageSize,
+ offset: (page - 1) * pageSize,
+ });
+ return { items, total, page, pageSize };
+ },
+ {
+ query: listInitiativesQuery,
+ permission: ['initiatives', 'read'],
+ response: { 200: InitiativePageResponse, ...commonErrors },
+ detail: {
+ summary: 'List initiatives',
+ description: "List a project's initiatives, filtered, sorted and paged.",
+ ...mcpTool('list_initiatives'),
+ },
+ },
+ )
+
+ // Fills the initiative picker on an issue. Read under work items: linking an issue
+ // needs the titles, not the initiative pages the `initiatives` resource gates.
+ .get(
+ '/projects/:projectKey/initiatives/options',
+ async ({ project, query }) => listInitiativeOptions(project.id, query),
+ {
+ query: initiativeOptionsQuery,
+ permission: ['work_items', 'read'],
+ response: { 200: InitiativeOptionListResponse, ...commonErrors },
+ detail: {
+ summary: 'List initiative options',
+ description: 'The initiatives an issue can be linked to: id, title and status.',
+ },
+ },
+ )
+
+ .get(
+ '/projects/:projectKey/initiatives/counts',
+ async ({ project }) => initiativeStatusCounts(project.id),
+ {
+ permission: ['initiatives', 'read'],
+ response: { 200: InitiativeCountsResponse, ...commonErrors },
+ detail: {
+ summary: 'Initiative status counts',
+ description: "Per-status initiative counts for a project, for the list's tabs.",
+ },
+ },
+ )
+
+ .post(
+ '/projects/:projectKey/initiatives',
+ async ({ project, body, user, set }) => {
+ set.status = 201;
+ return createInitiative(project.id, body, requireUser(user).id);
+ },
+ {
+ body: createInitiativeBody,
+ permission: ['initiatives', 'create'],
+ response: { 201: InitiativeResponse, ...commonErrors },
+ detail: {
+ summary: 'Create an initiative',
+ description: 'Create an initiative in a project.',
+ ...mcpTool('create_initiative'),
+ },
+ },
+ )
+
+ .get(
+ '/initiatives/:initiativeId',
+ async ({ params }) => {
+ const found = await getInitiative(params.initiativeId);
+ if (!found) throw new HttpError(404, 'Initiative not found');
+ return found;
+ },
+ {
+ params: initiativeParams,
+ initiative: 'read',
+ response: { 200: InitiativeResponse, ...commonErrors },
+ detail: {
+ summary: 'Get an initiative',
+ description: 'Get an initiative by its numeric id.',
+ ...mcpTool('get_initiative'),
+ },
+ },
+ )
+
+ .patch(
+ '/initiatives/:initiativeId',
+ async ({ params, body, user }) => {
+ const actorUserId = requireUser(user).id;
+ const updated = await updateInitiative(params.initiativeId, body, actorUserId);
+ if (!updated) throw new HttpError(404, 'Initiative not found');
+ return updated;
+ },
+ {
+ params: initiativeParams,
+ body: updateInitiativeBody,
+ initiative: 'edit',
+ response: { 200: InitiativeResponse, ...commonErrors },
+ detail: {
+ summary: 'Update an initiative',
+ description:
+ "Update an initiative by its numeric id. labelIds replaces the initiative's labels.",
+ ...mcpTool('update_initiative'),
+ },
+ },
+ )
+
+ .delete(
+ '/initiatives/:initiativeId',
+ async ({ params }) => {
+ await deleteInitiative(params.initiativeId);
+ return noContent();
+ },
+ {
+ params: initiativeParams,
+ initiative: 'delete',
+ response: { 204: t.Void(), ...commonErrors },
+ detail: {
+ summary: 'Delete an initiative',
+ description: 'Delete an initiative by its numeric id. Irreversible.',
+ ...mcpTool('delete_initiative'),
+ },
+ },
+ )
+
+ .get(
+ '/initiatives/:initiativeId/feed',
+ async ({ params, query }) => {
+ const limit = query.limit != null ? Number(query.limit) : undefined;
+ let before = null;
+ if (query.cursor) {
+ try {
+ before = JSON.parse(query.cursor);
+ } catch {
+ // Ignore a malformed cursor and serve the first page.
+ }
+ }
+ return listFeed(params.initiativeId, { before, limit });
+ },
+ {
+ params: initiativeParams,
+ query: initiativeFeedQuery,
+ initiative: 'read',
+ response: { 200: FeedPageResponse, ...commonErrors },
+ detail: {
+ summary: 'Get an initiative feed',
+ description: "Get an initiative's activity feed by its numeric id.",
+ ...mcpTool('list_initiative_activity'),
+ },
+ },
+ );
diff --git a/apps/api/src/modules/initiatives/model.ts b/apps/api/src/modules/initiatives/model.ts
new file mode 100644
index 00000000..48500217
--- /dev/null
+++ b/apps/api/src/modules/initiatives/model.ts
@@ -0,0 +1,126 @@
+import { t } from 'elysia';
+import { pageQueryFields, pageResponse } from '#shared/pagination';
+
+// The initiative lifecycle enum, validated at the edge so an invalid value is a
+// 400 (not a Postgres CHECK violation → 500). Mirrors the DB check constraint.
+const InitiativeStatus = t.Union([
+ t.Literal('proposed'),
+ t.Literal('planned'),
+ t.Literal('active'),
+ t.Literal('completed'),
+ t.Literal('canceled'),
+]);
+
+export const initiativeParams = t.Object({ initiativeId: t.Numeric() });
+
+export const listInitiativesQuery = t.Object({
+ status: t.Optional(
+ t.String({
+ description:
+ 'Filter by status: a comma-separated subset of proposed,planned,active,completed,canceled. Omit for all.',
+ }),
+ ),
+ search: t.Optional(t.String({ description: 'Case-insensitive match on the title.' })),
+ sort: t.Optional(
+ t.Union(
+ [t.Literal('title'), t.Literal('priority'), t.Literal('targetDate'), t.Literal('owner')],
+ { description: 'Sort column. Omit for the manual position order.' },
+ ),
+ ),
+ dir: t.Optional(
+ t.Union([t.Literal('asc'), t.Literal('desc')], { description: 'Sort direction. Default asc.' }),
+ ),
+ ...pageQueryFields,
+});
+
+export const initiativeOptionsQuery = t.Object({
+ search: t.Optional(t.String({ description: 'Match by title.' })),
+ include: t.Optional(
+ t.Numeric({ description: 'Keep this initiative in the list even when it is closed.' }),
+ ),
+});
+
+export const initiativeFeedQuery = t.Object({
+ limit: t.Optional(t.String({ description: 'Max items per page (1-100). Default 25.' })),
+ cursor: t.Optional(t.String({ description: 'nextCursor from the previous page, for paging.' })),
+});
+
+// InitiativeRow from the service. progress is derived issue counts; health is
+// computed on the fly (on_track/at_risk/off_track, or null when there is nothing
+// to judge).
+export const InitiativeResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ title: t.String(),
+ description: t.String(),
+ status: t.String(),
+ ownerUserId: t.Nullable(t.String()),
+ priority: t.Nullable(t.String()),
+ startDate: t.Nullable(t.String()),
+ targetDate: t.Nullable(t.String()),
+ position: t.Number(),
+ createdAt: t.String(),
+ updatedAt: t.String(),
+ labelIds: t.Array(t.Number()),
+ progress: t.Object({ completed: t.Number(), canceled: t.Number(), total: t.Number() }),
+ health: t.Nullable(t.String()),
+});
+
+export const InitiativePageResponse = pageResponse(InitiativeResponse);
+
+export const InitiativeOptionListResponse = t.Array(
+ t.Object({ id: t.Number(), title: t.String(), status: t.String() }),
+);
+
+export const InitiativeCountsResponse = t.Object({
+ total: t.Number(),
+ proposed: t.Number(),
+ planned: t.Number(),
+ active: t.Number(),
+ completed: t.Number(),
+ canceled: t.Number(),
+});
+
+// InitiativeFeedItemRow from activity.ts: one timeline entry, from the initiative
+// itself (source 'initiative') or a linked issue (source 'issue').
+const FeedItemResponse = t.Object({
+ id: t.Number(),
+ source: t.String(),
+ kind: t.String(),
+ actorUserId: t.Nullable(t.String()),
+ actorName: t.Nullable(t.String()),
+ body: t.Nullable(t.String()),
+ action: t.Nullable(t.String()),
+ subject: t.Nullable(t.String()),
+ fromText: t.Nullable(t.String()),
+ toText: t.Nullable(t.String()),
+ createdAt: t.String(),
+ issueId: t.Nullable(t.Number()),
+ issueIdentifier: t.Nullable(t.String()),
+});
+
+export const FeedPageResponse = t.Object({
+ items: t.Array(FeedItemResponse),
+ nextCursor: t.Nullable(t.Object({ ts: t.String(), id: t.Number() })),
+});
+
+export const createInitiativeBody = t.Object({
+ title: t.String({ minLength: 1, description: 'Initiative title.' }),
+ description: t.Optional(t.String({ description: 'Initiative description.' })),
+ status: t.Optional(InitiativeStatus),
+ ownerUserId: t.Optional(
+ t.Nullable(t.String({ description: 'Owner user id (a project member), or null.' })),
+ ),
+ priority: t.Optional(
+ t.Nullable(t.String({ description: 'One of: urgent, high, medium, low. Or null.' })),
+ ),
+ startDate: t.Optional(t.Nullable(t.String({ description: "Start date 'YYYY-MM-DD', or null." }))),
+ targetDate: t.Optional(
+ t.Nullable(t.String({ description: "Target date 'YYYY-MM-DD', or null." })),
+ ),
+ labelIds: t.Optional(
+ t.Array(t.Integer(), { description: 'Label ids to attach. From get_project.labels.' }),
+ ),
+});
+
+export const updateInitiativeBody = t.Partial(createInitiativeBody);
diff --git a/apps/api/src/initiatives/store.ts b/apps/api/src/modules/initiatives/service.ts
similarity index 98%
rename from apps/api/src/initiatives/store.ts
rename to apps/api/src/modules/initiatives/service.ts
index e1c8712c..7355bf5d 100644
--- a/apps/api/src/initiatives/store.ts
+++ b/apps/api/src/modules/initiatives/service.ts
@@ -1,8 +1,8 @@
import { db, initiative, initiativeLabel, issue, label, projectColumn, user } from '@repo/db';
import { and, asc, desc, eq, ilike, inArray, or, sql } from 'drizzle-orm';
-import { labelNames } from '../issues/activity';
-import { getMembership } from '../members/store';
-import { HttpError, iso, num } from '../shared/lib';
+import { labelNames } from '../../issues/activity';
+import { getMembership } from '../../members/store';
+import { HttpError, iso, num } from '#shared/lib';
import { computeHealth, type Health } from './health';
import { recordActivity, logInitiativeUpdate, type InitiativeSnapshot } from './activity';
diff --git a/apps/api/src/note-boards/routes.ts b/apps/api/src/note-boards/routes.ts
index d0618794..c13af329 100644
--- a/apps/api/src/note-boards/routes.ts
+++ b/apps/api/src/note-boards/routes.ts
@@ -5,7 +5,7 @@ import { authContext } from '../shared/auth-context';
import { requireUser } from '../shared/access';
import { HttpError } from '../shared/lib';
import { mcpTool } from '../mcp/generate';
-import { ErrorResponse } from '../shared/responses';
+import { accessErrors, commonErrors } from '../shared/responses';
import {
listNoteBoards,
createNoteBoard,
@@ -109,12 +109,7 @@ export const noteBoardRoutes = new Elysia({
limit: t.Optional(t.Numeric({ minimum: 1, maximum: 50 })),
offset: t.Optional(t.Numeric({ minimum: 0 })),
}),
- response: {
- 200: t.Array(NoteBoardSummaryResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(NoteBoardSummaryResponse), ...accessErrors },
detail: {
summary: "List a project's note boards",
description:
@@ -129,12 +124,7 @@ export const noteBoardRoutes = new Elysia({
async ({ project }) => listNoteBoardAccessCandidates(project.id),
{
permission: ['note_boards', 'edit'],
- response: {
- 200: t.Array(NoteBoardAccessCandidateResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(NoteBoardAccessCandidateResponse), ...accessErrors },
detail: {
summary: 'List who a board can be shared with',
description:
@@ -151,12 +141,7 @@ export const noteBoardRoutes = new Elysia({
{
permission: ['note_boards', 'read'],
params: boardParams,
- response: {
- 200: NoteBoardResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: NoteBoardResponse, ...accessErrors },
detail: {
summary: 'Get a note board with its canvas',
description:
@@ -186,13 +171,7 @@ export const noteBoardRoutes = new Elysia({
visibility: t.Optional(t.Union([t.Literal('public'), t.Literal('private')])),
canvas: t.Optional(t.Any()),
}),
- response: {
- 201: NoteBoardResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: NoteBoardResponse, ...commonErrors },
detail: {
summary: 'Create a note board',
description:
@@ -246,13 +225,7 @@ export const noteBoardRoutes = new Elysia({
visibility: t.Optional(Visibility),
memberIds: t.Optional(t.Array(t.String())),
}),
- response: {
- 200: NoteBoardResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: NoteBoardResponse, ...commonErrors },
detail: {
summary: 'Update a note board',
description:
@@ -272,12 +245,7 @@ export const noteBoardRoutes = new Elysia({
{
permission: ['note_boards', 'delete'],
params: boardParams,
- response: {
- 204: t.Void(),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...accessErrors },
detail: {
summary: 'Delete a note board',
description: 'Permanently delete a note board and every note on it.',
diff --git a/apps/api/src/notification-preferences/routes.ts b/apps/api/src/notification-preferences/routes.ts
index 76fb20d8..65b5bce1 100644
--- a/apps/api/src/notification-preferences/routes.ts
+++ b/apps/api/src/notification-preferences/routes.ts
@@ -2,7 +2,7 @@ import { Elysia, t } from 'elysia';
import { guards } from '../shared/guards';
import { authContext } from '../shared/auth-context';
import { requireUser } from '../shared/access';
-import { ErrorResponse } from '../shared/responses';
+import { accessErrors, commonErrors } from '../shared/responses';
import { getPreferences, setPreferences } from './store';
const EventToggles = t.Object({
@@ -35,12 +35,7 @@ export const notificationPreferenceRoutes = new Elysia({
({ project, user }) => getPreferences(requireUser(user).id, project.id),
{
projectMember: true,
- response: {
- 200: PreferenceBody,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: PreferenceBody, ...accessErrors },
detail: {
summary: 'Get notification preferences',
description: "Get the current user's notification preferences for a project.",
@@ -54,13 +49,7 @@ export const notificationPreferenceRoutes = new Elysia({
{
body: PreferenceBody,
projectMember: true,
- response: {
- 200: PreferenceBody,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: PreferenceBody, ...commonErrors },
detail: {
summary: 'Update notification preferences',
description: "Update the current user's notification preferences for a project.",
diff --git a/apps/api/src/notification-settings/routes.ts b/apps/api/src/notification-settings/routes.ts
index 628e786e..aaa7aef6 100644
--- a/apps/api/src/notification-settings/routes.ts
+++ b/apps/api/src/notification-settings/routes.ts
@@ -1,7 +1,7 @@
import { Elysia, t } from 'elysia';
import { guards } from '../shared/guards';
import { authContext } from '../shared/auth-context';
-import { ErrorResponse } from '../shared/responses';
+import { accessErrors, commonErrors } from '../shared/responses';
import { getProjectEmailConfig } from '@repo/auth';
import {
ENCRYPTION_MODES,
@@ -76,12 +76,7 @@ export const notificationSettingsRoutes = new Elysia({
async ({ project }) => withSystemAvailability(await getNotificationSettings(project.id)),
{
permission: ['danger_zone', 'read'],
- response: {
- 200: NotificationSettingsResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: NotificationSettingsResponse, ...accessErrors },
detail: {
summary: 'Get notification provider settings',
description: "Get a project's notification provider settings (secrets redacted).",
@@ -96,13 +91,7 @@ export const notificationSettingsRoutes = new Elysia({
{
body: NotificationSettingsBody,
permission: ['danger_zone', 'edit'],
- response: {
- 200: NotificationSettingsResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: NotificationSettingsResponse, ...commonErrors },
detail: {
summary: 'Update notification provider settings',
description: "Update a project's notification provider settings.",
diff --git a/apps/api/src/notifications/routes.ts b/apps/api/src/notifications/routes.ts
index 95a52893..b123617c 100644
--- a/apps/api/src/notifications/routes.ts
+++ b/apps/api/src/notifications/routes.ts
@@ -3,7 +3,7 @@ import { noContent } from '../shared/http';
import { authContext } from '../shared/auth-context';
import { requireUser } from '../shared/access';
import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
+import { errors } from '../shared/responses';
import {
listNotifications,
unreadCount,
@@ -100,7 +100,7 @@ export const notificationRoutes = new Elysia({
t.String({ description: "'true' shows snoozed. Default false." }),
),
}),
- response: { 200: NotificationPageResponse, 401: ErrorResponse },
+ response: { 200: NotificationPageResponse, ...errors(401) },
detail: { summary: 'List inbox notifications' },
},
)
@@ -117,7 +117,7 @@ export const notificationRoutes = new Elysia({
query: t.Object({
projectId: t.Optional(t.String({ description: 'Scope the count to one project.' })),
}),
- response: { 200: t.Object({ unread: t.Number() }), 401: ErrorResponse },
+ response: { 200: t.Object({ unread: t.Number() }), ...errors(401) },
detail: { summary: 'Get unread notification count' },
},
)
@@ -131,7 +131,7 @@ export const notificationRoutes = new Elysia({
},
{
body: t.Optional(t.Object({ projectId: t.Optional(t.Number()) })),
- response: { 200: t.Object({ count: t.Number() }), 401: ErrorResponse },
+ response: { 200: t.Object({ count: t.Number() }), ...errors(401) },
detail: { summary: 'Mark all notifications read' },
},
)
@@ -154,7 +154,7 @@ export const notificationRoutes = new Elysia({
),
projectId: t.Optional(t.String({ description: 'Scope the delete to one project.' })),
}),
- response: { 200: t.Object({ count: t.Number() }), 401: ErrorResponse },
+ response: { 200: t.Object({ count: t.Number() }), ...errors(401) },
detail: { summary: 'Delete inbox notifications' },
},
)
@@ -171,7 +171,7 @@ export const notificationRoutes = new Elysia({
{
params: idParams,
body: t.Optional(t.Object({ read: t.Optional(t.Boolean()) })),
- response: { 204: t.Void(), 401: ErrorResponse, 404: ErrorResponse },
+ response: { 204: t.Void(), ...errors(401, 404) },
detail: { summary: 'Mark a notification read or unread' },
},
)
@@ -189,7 +189,7 @@ export const notificationRoutes = new Elysia({
{
params: idParams,
body: t.Object({ until: t.Nullable(t.String()) }),
- response: { 204: t.Void(), 400: ErrorResponse, 401: ErrorResponse, 404: ErrorResponse },
+ response: { 204: t.Void(), ...errors(400, 401, 404) },
detail: {
summary: 'Snooze a notification',
description: 'Snooze a notification until a time, or clear its snooze.',
@@ -207,7 +207,7 @@ export const notificationRoutes = new Elysia({
},
{
params: idParams,
- response: { 204: t.Void(), 401: ErrorResponse, 404: ErrorResponse },
+ response: { 204: t.Void(), ...errors(401, 404) },
detail: { summary: 'Delete a notification' },
},
);
diff --git a/apps/api/src/notifications/store.ts b/apps/api/src/notifications/store.ts
index 75a86540..b193694e 100644
--- a/apps/api/src/notifications/store.ts
+++ b/apps/api/src/notifications/store.ts
@@ -9,7 +9,7 @@ import {
projectColumn,
} from '@repo/db';
import { and, desc, eq, inArray, lt, or, sql, isNull } from 'drizzle-orm';
-import { parseMentions } from '../ai-agents/mentions';
+import { parseMentions } from '#modules/agents/core/mentions';
import { autoWatchIssue, watcherUserIds } from '../issues/watchers';
import { iso } from '../shared/lib';
import { enqueueOutbound } from './outbound';
diff --git a/apps/api/src/planner.ts b/apps/api/src/planner.ts
index cf6e8d40..6f06b6d9 100644
--- a/apps/api/src/planner.ts
+++ b/apps/api/src/planner.ts
@@ -5,30 +5,30 @@ import { projectRoutes } from './projects/routes';
import { memberRoutes } from './members/routes';
import { roleRoutes } from './roles/routes';
import { inviteRoutes } from './invites/routes';
-import { columnRoutes } from './columns/routes';
+import { columnRoutes } from './modules/columns';
import { issueTypeRoutes } from './issue-types/routes';
import { labelRoutes } from './labels/routes';
-import { aiAgentRoutes } from './ai-agents/routes';
-import { integrationRoutes } from './integrations/routes';
-import { agentSkillRoutes } from './agent-skills/routes';
-import { agentToolRoutes } from './agent-tools/routes';
-import { customFieldRoutes } from './custom-fields/routes';
+import { aiAgentRoutes } from './modules/agents/core';
+import { integrationRoutes } from './modules/agents/integrations';
+import { agentSkillRoutes } from './modules/agents/skills';
+import { agentToolRoutes } from './modules/agents/tools';
+import { customFieldRoutes } from './modules/custom-fields';
import { issueRoutes } from './issues/routes';
-import { initiativeRoutes } from './initiatives/routes';
-import { cycleRoutes } from './cycles/routes';
-import { attachmentRoutes } from './attachments/routes';
-import { avatarRoutes } from './avatars/routes';
+import { initiativeRoutes } from './modules/initiatives';
+import { cycleRoutes } from './modules/cycles';
+import { attachmentRoutes } from './modules/attachments';
+import { avatarRoutes } from './modules/avatars';
import { viewRoutes } from './views/routes';
import { shareRoutes } from './share/routes';
-import { actionRoutes } from './actions/routes';
+import { actionRoutes } from './modules/actions';
import { webhookRoutes } from './webhooks/routes';
-import { githubSettingsRoutes } from './github/routes';
-import { dashboardRoutes } from './dashboards/routes';
+import { githubSettingsRoutes } from './modules/github';
+import { dashboardRoutes } from './modules/dashboards';
import { noteBoardRoutes } from './note-boards/routes';
-import { analyticsRoutes } from './analytics/routes';
+import { analyticsRoutes } from './modules/analytics';
import { settingsRoutes } from './settings/routes';
import { godRoutes } from './god/routes';
-import { agentScheduleRoutes } from './agent-schedules/routes';
+import { agentScheduleRoutes } from './modules/agents/schedules';
import { notificationRoutes } from './notifications/routes';
import { notificationSettingsRoutes } from './notification-settings/routes';
import { notificationPreferenceRoutes } from './notification-preferences/routes';
diff --git a/apps/api/src/projects/copy.ts b/apps/api/src/projects/copy.ts
index fa01df67..01b6f913 100644
--- a/apps/api/src/projects/copy.ts
+++ b/apps/api/src/projects/copy.ts
@@ -22,18 +22,18 @@ import { eq, inArray } from 'drizzle-orm';
import { iso } from '../shared/lib';
import { defaultMemberPermissions } from '../shared/permissions';
import { DEFAULT_COLUMNS, type ProjectRow } from './store';
-import { GITHUB_SETTING_KEY } from '../github/store';
-import { listAgents, createAgent, type NewAgentInput } from '../ai-agents/store';
+import { GITHUB_SETTING_KEY } from '#modules/github/service';
+import { listAgents, createAgent, type NewAgentInput } from '#modules/agents/core/service';
import {
listSkills,
getSkillMarkdown,
createSkillFromFiles,
setAgentSkills,
listAgentSkills,
-} from '../agent-skills/store';
-import { listAgentToolLinks, setAgentTools } from '../agent-tools/store';
-import { listAgentSchedules, createAgentSchedule } from '../agent-schedules/store';
-import { nextCronRun } from '../agent-schedules/cron';
+} from '#modules/agents/skills/service';
+import { listAgentToolLinks, setAgentTools } from '#modules/agents/tools/service';
+import { listAgentSchedules, createAgentSchedule } from '#modules/agents/schedules/service';
+import { nextCronRun } from '#modules/agents/schedules/cron';
import { getObject } from '../shared/s3';
// Which parts of a source project the copy carries over. Each key mirrors a section
diff --git a/apps/api/src/projects/routes.ts b/apps/api/src/projects/routes.ts
index 27e50a8c..1eb5c4a7 100644
--- a/apps/api/src/projects/routes.ts
+++ b/apps/api/src/projects/routes.ts
@@ -6,7 +6,7 @@ import { authContext } from '../shared/auth-context';
import { guards } from '../shared/guards';
import { requireUser } from '../shared/access';
import { isMcpRequest } from '../shared/mcp-request';
-import { ErrorResponse } from '../shared/responses';
+import { accessErrors, commonErrors, errors } from '../shared/responses';
import { getMemberContext, listAssigneeCandidates } from '../members/store';
import {
listProjects,
@@ -23,10 +23,11 @@ import {
ISSUE_TYPE_PRESET_KEYS,
} from './store';
import { copyProject, COPY_INCLUDE_KEYS } from './copy';
-import { listColumns } from '../columns/store';
+import { listColumns } from '#modules/columns/service';
+import { ColumnResponse } from '#modules/columns/model';
import { listIssueTypes } from '../issue-types/store';
import { listLabels, listLabelGroups } from '../labels/store';
-import { listCustomFields } from '../custom-fields/store';
+import { listCustomFields } from '#modules/custom-fields/service';
const projectBody = t.Object({
key: t.String({ minLength: 1 }),
@@ -96,16 +97,6 @@ const ProjectListItemResponse = t.Composite([
}),
]);
-// A column (ColumnRow from columns/store).
-const ColumnResponse = t.Object({
- id: t.Number(),
- projectId: t.Number(),
- name: t.String(),
- stateType: t.String(),
- color: t.String(),
- position: t.Number(),
-});
-
// An issue type (IssueTypeRow from issue-types/store).
const IssueTypeResponse = t.Object({
id: t.Number(),
@@ -236,10 +227,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
}),
),
}),
- response: {
- 200: t.Array(ProjectListItemResponse),
- 401: ErrorResponse,
- },
+ response: { 200: t.Array(ProjectListItemResponse), ...errors(401) },
detail: {
summary: 'List projects',
description:
@@ -258,11 +246,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
},
{
body: createProjectBody,
- response: {
- 201: ProjectResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- },
+ response: { 201: ProjectResponse, ...errors(400, 401) },
detail: {
summary: 'Create a project',
description:
@@ -296,13 +280,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
{
body: copyProjectBody,
permission: ['work_items', 'read'],
- response: {
- 201: ProjectResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: ProjectResponse, ...commonErrors },
detail: {
summary: 'Copy a project',
description:
@@ -354,12 +332,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
},
{
projectMember: true,
- response: {
- 200: ProjectBoardResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ProjectBoardResponse, ...accessErrors },
detail: {
summary: 'Get a project',
description:
@@ -386,13 +359,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
description: t.Optional(t.String()),
}),
projectOwner: true,
- response: {
- 200: ProjectResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ProjectResponse, ...commonErrors },
detail: {
summary: 'Update a project',
description: "Update a project's name and/or description. The key is immutable.",
@@ -411,12 +378,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
}),
{
projectMember: true,
- response: {
- 200: ProjectSettingsResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ProjectSettingsResponse, ...accessErrors },
detail: { summary: "Get a project's settings" },
},
)
@@ -457,13 +419,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
),
}),
projectOwner: true,
- response: {
- 200: ProjectSettingsResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ProjectSettingsResponse, ...commonErrors },
detail: { summary: "Update a project's settings" },
},
)
@@ -476,12 +432,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
({ project }) => getAutoArchiveSettings(project.id),
{
permission: ['workflow_config', 'read'],
- response: {
- 200: AutoArchiveResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: AutoArchiveResponse, ...accessErrors },
detail: { summary: "Get a project's auto-archive thresholds" },
},
)
@@ -497,13 +448,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
canceledDays: t.Nullable(t.Integer({ minimum: 1 })),
}),
permission: ['workflow_config', 'edit'],
- response: {
- 200: AutoArchiveResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: AutoArchiveResponse, ...commonErrors },
detail: { summary: "Update a project's auto-archive thresholds" },
},
)
@@ -513,12 +458,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
({ project }) => getSubtaskAutomationSettings(project.id),
{
permission: ['workflow_config', 'read'],
- response: {
- 200: SubtaskAutomationResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: SubtaskAutomationResponse, ...accessErrors },
detail: { summary: "Get a project's subtask automations" },
},
)
@@ -533,13 +473,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
closeSubtasks: t.Boolean(),
}),
permission: ['workflow_config', 'edit'],
- response: {
- 200: SubtaskAutomationResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: SubtaskAutomationResponse, ...commonErrors },
detail: { summary: "Update a project's subtask automations" },
},
)
@@ -554,12 +488,7 @@ export const projectRoutes = new Elysia({ name: 'projects', detail: { tags: ['Pr
},
{
permission: ['danger_zone', 'delete'],
- response: {
- 204: t.Void(),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...accessErrors },
detail: {
summary: 'Delete a project',
description: 'Permanently delete a project and everything in it. Irreversible.',
diff --git a/apps/api/src/projects/store.ts b/apps/api/src/projects/store.ts
index e95c9e17..b6e9b184 100644
--- a/apps/api/src/projects/store.ts
+++ b/apps/api/src/projects/store.ts
@@ -16,7 +16,7 @@ import {
type Permissions,
} from '../shared/permissions';
import { getProjectSetting, setProjectSetting } from '../settings/store';
-import { deleteThreadsWhere } from '../ai-agents/runtime/memory';
+import { deleteThreadsWhere } from '#modules/agents/core/runtime/memory';
// Data access for projects: the top-level container that groups its own columns,
// issue types, labels, assignees, custom fields, issues, saved views, and
diff --git a/apps/api/src/roles/routes.ts b/apps/api/src/roles/routes.ts
index 04483d72..a213e171 100644
--- a/apps/api/src/roles/routes.ts
+++ b/apps/api/src/roles/routes.ts
@@ -4,7 +4,7 @@ import { noContent } from '../shared/http';
import { guards } from '../shared/guards';
import { HttpError, rethrowDuplicate } from '../shared/lib';
import { PERMISSION_RESOURCES, PERMISSION_ACTIONS } from '../shared/permissions';
-import { ErrorResponse } from '../shared/responses';
+import { accessErrors, commonErrors, errors } from '../shared/responses';
import { listRoles, getRole, createRole, updateRole, deleteRole } from './store';
const roleParams = t.Object({ projectKey: t.String(), roleId: t.Numeric() });
@@ -46,10 +46,7 @@ export const roleRoutes = new Elysia({ name: 'roles', detail: { tags: ['Roles']
'/permission-catalog',
() => ({ resources: [...PERMISSION_RESOURCES], actions: [...PERMISSION_ACTIONS] }),
{
- response: {
- 200: PermissionCatalogResponse,
- 401: ErrorResponse,
- },
+ response: { 200: PermissionCatalogResponse, ...errors(401) },
detail: {
summary: 'List the permission catalog',
description: "List the resources and actions a role's permission matrix is built from.",
@@ -66,12 +63,7 @@ export const roleRoutes = new Elysia({ name: 'roles', detail: { tags: ['Roles']
{
params: t.Object({ projectKey: t.String() }),
projectMember: true,
- response: {
- 200: t.Array(RoleResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(RoleResponse), ...accessErrors },
detail: { summary: "List a project's roles", ...mcpTool('list_roles') },
},
)
@@ -90,14 +82,7 @@ export const roleRoutes = new Elysia({ name: 'roles', detail: { tags: ['Roles']
params: t.Object({ projectKey: t.String() }),
body: t.Object({ name: t.String({ minLength: 1 }), permissions }),
projectOwner: true,
- response: {
- 201: RoleResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 201: RoleResponse, ...commonErrors, ...errors(409) },
detail: { summary: 'Create a role', ...mcpTool('create_role') },
},
)
@@ -121,14 +106,7 @@ export const roleRoutes = new Elysia({ name: 'roles', detail: { tags: ['Roles']
permissions: t.Optional(permissions),
}),
projectOwner: true,
- response: {
- 200: RoleResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- 409: ErrorResponse,
- },
+ response: { 200: RoleResponse, ...commonErrors, ...errors(409) },
detail: {
summary: 'Update a role',
description: 'Update a role.',
@@ -151,13 +129,7 @@ export const roleRoutes = new Elysia({ name: 'roles', detail: { tags: ['Roles']
{
params: roleParams,
projectOwner: true,
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete a role',
description: 'Delete a custom role. The default role cannot be deleted.',
diff --git a/apps/api/src/settings/routes.ts b/apps/api/src/settings/routes.ts
index 0499002e..94519bb5 100644
--- a/apps/api/src/settings/routes.ts
+++ b/apps/api/src/settings/routes.ts
@@ -1,6 +1,6 @@
import { Elysia, t } from 'elysia';
import { authContext } from '../shared/auth-context';
-import { ErrorResponse } from '../shared/responses';
+import { errors } from '../shared/responses';
import { getStorageSettings, StorageSettingsSchema } from './storage';
import { getHotkeySettings, HotkeyCombosSchema } from './hotkeys';
import { getAppVersion } from './updates';
@@ -16,7 +16,7 @@ export const settingsRoutes = new Elysia({
})
.use(authContext)
.get('/settings/storage', () => getStorageSettings(), {
- response: { 200: StorageSettingsSchema, 401: ErrorResponse },
+ response: { 200: StorageSettingsSchema, ...errors(401) },
detail: {
summary: 'Get storage limits',
description: 'Get the instance upload limits the UI shows before a file is picked.',
@@ -24,7 +24,7 @@ export const settingsRoutes = new Elysia({
})
.get('/settings/hotkeys', () => getHotkeySettings(), {
- response: { 200: HotkeyCombosSchema, 401: ErrorResponse },
+ response: { 200: HotkeyCombosSchema, ...errors(401) },
detail: {
summary: 'Get instance keyboard shortcuts',
description:
@@ -37,7 +37,7 @@ export const settingsRoutes = new Elysia({
// required: the version tells an anonymous visitor which release to look up
// vulnerabilities for.
.get('/settings/version', () => ({ version: getAppVersion() }), {
- response: { 200: t.Object({ version: t.String() }), 401: ErrorResponse },
+ response: { 200: t.Object({ version: t.String() }), ...errors(401) },
detail: {
summary: 'Get the running version',
description: 'Get the version of the app this instance runs.',
diff --git a/apps/api/src/share/routes.ts b/apps/api/src/share/routes.ts
index cad81505..1744c0ee 100644
--- a/apps/api/src/share/routes.ts
+++ b/apps/api/src/share/routes.ts
@@ -3,7 +3,7 @@ import { noContent } from '../shared/http';
import { guards, entityGuard } from '../shared/guards';
import { authContext } from '../shared/auth-context';
import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
+import { commonErrors, errors } from '../shared/responses';
import { getIssueProjectId } from '../issues/store';
import { getView } from '../views/store';
import {
@@ -72,13 +72,7 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']
params: t.Object({ issueId: t.Numeric() }),
body: ShareExtendedBody,
workItem: 'edit',
- response: {
- 200: ShareTokenResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ShareTokenResponse, ...commonErrors },
detail: { summary: 'Enable issue sharing' },
},
)
@@ -93,13 +87,7 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']
{
params: t.Object({ issueId: t.Numeric() }),
workItem: 'edit',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: { summary: 'Revoke issue sharing' },
},
)
@@ -115,13 +103,7 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']
params: t.Object({ viewId: t.Numeric() }),
body: ShareExtendedBody,
savedView: 'edit',
- response: {
- 200: ShareTokenResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ShareTokenResponse, ...commonErrors },
detail: { summary: 'Enable view sharing' },
},
)
@@ -136,13 +118,7 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']
{
params: t.Object({ viewId: t.Numeric() }),
savedView: 'edit',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: { summary: 'Revoke view sharing' },
},
)
@@ -158,7 +134,7 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']
},
{
params: tokenParams,
- response: { 200: BundleResponse, 400: ErrorResponse, 404: ErrorResponse },
+ response: { 200: BundleResponse, ...errors(400, 404) },
detail: { summary: 'Get a shared issue' },
},
)
@@ -172,7 +148,7 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']
},
{
params: tokenParams,
- response: { 200: BundleResponse, 400: ErrorResponse, 404: ErrorResponse },
+ response: { 200: BundleResponse, ...errors(400, 404) },
detail: { summary: 'Get a shared view' },
},
)
@@ -186,7 +162,7 @@ export const shareRoutes = new Elysia({ name: 'share', detail: { tags: ['Share']
},
{
params: t.Object({ token: t.String({ format: 'uuid' }), issueId: t.Numeric() }),
- response: { 200: BundleResponse, 400: ErrorResponse, 404: ErrorResponse },
+ response: { 200: BundleResponse, ...errors(400, 404) },
detail: { summary: 'Get an issue from a shared view' },
},
);
diff --git a/apps/api/src/share/store.ts b/apps/api/src/share/store.ts
index c5ee28d0..7e32cba5 100644
--- a/apps/api/src/share/store.ts
+++ b/apps/api/src/share/store.ts
@@ -2,10 +2,10 @@ import { randomUUID } from 'node:crypto';
import { db, issue, projectView } from '@repo/db';
import { eq } from 'drizzle-orm';
import { getProjectById, type ProjectRow } from '../projects/store';
-import { listColumns } from '../columns/store';
+import { listColumns } from '#modules/columns/service';
import { listIssueTypes } from '../issue-types/store';
import { listLabels, listLabelGroups } from '../labels/store';
-import { listCustomFields } from '../custom-fields/store';
+import { listCustomFields } from '#modules/custom-fields/service';
import { listAssigneeCandidates } from '../members/store';
import { getIssue, getIssueFieldValues, listIssues, type IssueRow } from '../issues/store';
import { listFeed, type FeedItemRow } from '../issues/activity';
diff --git a/apps/api/src/shared/pagination.ts b/apps/api/src/shared/pagination.ts
new file mode 100644
index 00000000..cf8ce8b1
--- /dev/null
+++ b/apps/api/src/shared/pagination.ts
@@ -0,0 +1,21 @@
+import { t, type TSchema } from 'elysia';
+
+// The page/pageSize pair a paged list route takes, and the envelope it answers
+// with. Spread the fields into a route's own query schema:
+//
+// export const listQuery = t.Object({ search: t.Optional(t.String()), ...pageQueryFields });
+// export const listResponse = pageResponse(ThingResponse);
+export const pageQueryFields = {
+ page: t.Optional(t.Numeric({ minimum: 1, description: '1-based page. Default 1.' })),
+ pageSize: t.Optional(
+ t.Numeric({ minimum: 1, maximum: 100, description: 'Items per page (1-100). Default 25.' }),
+ ),
+};
+
+export const pageResponse = <T extends TSchema>(item: T) =>
+ t.Object({
+ items: t.Array(item),
+ total: t.Number(),
+ page: t.Number(),
+ pageSize: t.Number(),
+ });
diff --git a/apps/api/src/shared/responses.ts b/apps/api/src/shared/responses.ts
index 5855a234..544cc6f9 100644
--- a/apps/api/src/shared/responses.ts
+++ b/apps/api/src/shared/responses.ts
@@ -6,3 +6,18 @@ import { t } from 'elysia';
// otherwise). Referenced by each route's `response` map so the OpenAPI docs
// describe the error bodies alongside the success shape.
export const ErrorResponse = t.Object({ error: t.String() });
+
+// Maps the statuses a route can fail with to that one body. A route lists only
+// the codes it produces; spread the result into `response` next to the success
+// shape.
+export const errors = <const C extends readonly number[]>(...codes: C) =>
+ Object.fromEntries(codes.map((code) => [code, ErrorResponse])) as {
+ [K in C[number]]: typeof ErrorResponse;
+ };
+
+// The failures of a project-guarded route: no session, the permission check, an
+// unknown project or entity.
+export const accessErrors = errors(401, 403, 404);
+
+// The same plus a schema rejection, for a route that validates a body or params.
+export const commonErrors = errors(400, 401, 403, 404);
diff --git a/apps/api/src/sync/routes.ts b/apps/api/src/sync/routes.ts
index 21314a5c..176718bd 100644
--- a/apps/api/src/sync/routes.ts
+++ b/apps/api/src/sync/routes.ts
@@ -2,7 +2,7 @@ import { Elysia, t } from 'elysia';
import { authContext } from '../shared/auth-context';
import { requireUser } from '../shared/access';
import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
+import { errors } from '../shared/responses';
import { NO_REV, readRevs, scopeKind, type ScopeRead } from './store';
const MAX_SCOPES = 20;
@@ -54,11 +54,7 @@ export const syncRoutes = new Elysia({ name: 'sync', detail: { tags: ['Sync'] }
"Comma-separated scopes to read, each '<kind>:<id>' — board, issue, initiative, or inbox (by project id).",
}),
}),
- response: {
- 200: t.Object({ revs: t.Record(t.String(), t.String()) }),
- 400: ErrorResponse,
- 401: ErrorResponse,
- },
+ response: { 200: t.Object({ revs: t.Record(t.String(), t.String()) }), ...errors(400, 401) },
detail: {
summary: 'Get change markers',
description:
diff --git a/apps/api/src/telegram/routes.ts b/apps/api/src/telegram/routes.ts
index 61b06d95..23f42d8c 100644
--- a/apps/api/src/telegram/routes.ts
+++ b/apps/api/src/telegram/routes.ts
@@ -2,7 +2,7 @@ import { Elysia, t } from 'elysia';
import { authContext } from '../shared/auth-context';
import { requireUser } from '../shared/access';
import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
+import { errors } from '../shared/responses';
import { noContent } from '../shared/http';
import {
getInstanceBotConfig,
@@ -55,7 +55,7 @@ export const telegramRoutes = new Elysia({ name: 'telegram', detail: { tags: ['T
};
},
{
- response: { 200: TelegramAccountResponse, 401: ErrorResponse },
+ response: { 200: TelegramAccountResponse, ...errors(401) },
detail: {
summary: 'Get the linked Telegram account',
description:
@@ -76,7 +76,7 @@ export const telegramRoutes = new Elysia({ name: 'telegram', detail: { tags: ['T
return { url: `https://t.me/${config.botUsername}?start=${code}`, expiresAt };
},
{
- response: { 200: TelegramLinkStartResponse, 400: ErrorResponse, 401: ErrorResponse },
+ response: { 200: TelegramLinkStartResponse, ...errors(400, 401) },
detail: {
summary: 'Start linking a Telegram account',
description:
@@ -93,7 +93,7 @@ export const telegramRoutes = new Elysia({ name: 'telegram', detail: { tags: ['T
return noContent();
},
{
- response: { 204: t.Void(), 401: ErrorResponse },
+ response: { 204: t.Void(), ...errors(401) },
detail: { summary: 'Unlink the Telegram account' },
},
);
diff --git a/apps/api/src/user-preferences/routes.ts b/apps/api/src/user-preferences/routes.ts
index da18e16f..30999ea4 100644
--- a/apps/api/src/user-preferences/routes.ts
+++ b/apps/api/src/user-preferences/routes.ts
@@ -3,7 +3,7 @@ import { authContext } from '../shared/auth-context';
import { requireUser } from '../shared/access';
import { getMembership } from '../members/store';
import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
+import { errors } from '../shared/responses';
import { HotkeyCombosSchema } from '../settings/hotkeys';
import { getPreferences, isValidTimezone, updatePreferences } from './store';
@@ -67,7 +67,7 @@ export const userPreferenceRoutes = new Elysia({
.use(authContext)
.get('/account/preferences', ({ user }) => getPreferences(requireUser(user).id), {
- response: { 200: PreferenceResponse, 401: ErrorResponse },
+ response: { 200: PreferenceResponse, ...errors(401) },
detail: {
summary: 'Get account preferences',
description:
@@ -91,12 +91,7 @@ export const userPreferenceRoutes = new Elysia({
},
{
body: PreferencePatch,
- response: {
- 200: PreferenceResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- },
+ response: { 200: PreferenceResponse, ...errors(400, 401, 403) },
detail: {
summary: 'Update account preferences',
description:
diff --git a/apps/api/src/views/filters.ts b/apps/api/src/views/filters.ts
index faaf6e28..167fc665 100644
--- a/apps/api/src/views/filters.ts
+++ b/apps/api/src/views/filters.ts
@@ -1,5 +1,5 @@
import type { IssueRow } from '../issues/store';
-import type { ColumnRow } from '../columns/store';
+import type { ColumnRow } from '#modules/columns/service';
// Server-side copy of the view filter engine. The web app (utils/filters.ts) stores
// a view's filters as a FilterSet and applies them client-side to every layout; the
diff --git a/apps/api/src/views/routes.ts b/apps/api/src/views/routes.ts
index f4bef530..30282a58 100644
--- a/apps/api/src/views/routes.ts
+++ b/apps/api/src/views/routes.ts
@@ -4,7 +4,7 @@ import { guards, entityGuard } from '../shared/guards';
import { authContext } from '../shared/auth-context';
import { requireUser } from '../shared/access';
import { HttpError } from '../shared/lib';
-import { ErrorResponse } from '../shared/responses';
+import { accessErrors, commonErrors } from '../shared/responses';
import { mcpTool } from '../mcp/generate';
import {
listViews,
@@ -56,12 +56,7 @@ export const viewRoutes = new Elysia({ name: 'views', detail: { tags: ['Views']
},
{
permission: ['views', 'read'],
- response: {
- 200: t.Array(ViewResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(ViewResponse), ...accessErrors },
detail: {
summary: 'List saved views',
description: "List a project's saved views.",
@@ -84,13 +79,7 @@ export const viewRoutes = new Elysia({ name: 'views', detail: { tags: ['Views']
display: t.Optional(t.Any()),
}),
permission: ['views', 'create'],
- response: {
- 201: ViewResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: ViewResponse, ...commonErrors },
detail: {
summary: 'Create a saved view',
description: 'Create a saved view in a project.',
@@ -108,13 +97,7 @@ export const viewRoutes = new Elysia({ name: 'views', detail: { tags: ['Views']
{
body: t.Object({ orderedIds: t.Array(t.Integer(), { minItems: 1 }) }),
permission: ['views', 'edit'],
- response: {
- 200: t.Array(ViewResponse),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(ViewResponse), ...commonErrors },
detail: {
summary: 'Reorder saved views',
description: "Set the display order of a project's saved views.",
@@ -139,13 +122,7 @@ export const viewRoutes = new Elysia({ name: 'views', detail: { tags: ['Views']
}),
params: viewParams,
savedView: 'edit',
- response: {
- 200: ViewResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: ViewResponse, ...commonErrors },
detail: {
summary: 'Update a saved view',
description: 'Update an existing saved view.',
@@ -164,13 +141,7 @@ export const viewRoutes = new Elysia({ name: 'views', detail: { tags: ['Views']
{
params: viewParams,
savedView: 'read',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Favorite a saved view',
description: "Add a saved view to the caller's favorites.",
@@ -187,13 +158,7 @@ export const viewRoutes = new Elysia({ name: 'views', detail: { tags: ['Views']
{
params: viewParams,
savedView: 'read',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Unfavorite a saved view',
description: "Remove a saved view from the caller's favorites.",
@@ -210,13 +175,7 @@ export const viewRoutes = new Elysia({ name: 'views', detail: { tags: ['Views']
{
params: viewParams,
savedView: 'delete',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: {
summary: 'Delete a saved view',
description: 'Delete a saved view. Irreversible.',
diff --git a/apps/api/src/webhooks/routes.ts b/apps/api/src/webhooks/routes.ts
index cbce09f4..388b1f71 100644
--- a/apps/api/src/webhooks/routes.ts
+++ b/apps/api/src/webhooks/routes.ts
@@ -4,7 +4,7 @@ import { guards, entityGuard } from '../shared/guards';
import { authContext } from '../shared/auth-context';
import { HttpError } from '../shared/lib';
import { mcpTool } from '../mcp/generate';
-import { ErrorResponse } from '../shared/responses';
+import { accessErrors, commonErrors } from '../shared/responses';
import {
WEBHOOK_EVENT_TYPES,
listWebhooks,
@@ -124,12 +124,7 @@ export const webhookRoutes = new Elysia({ name: 'webhooks', detail: { tags: ['We
},
{
permission: ['webhooks', 'read'],
- response: {
- 200: t.Array(WebhookResponse),
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: t.Array(WebhookResponse), ...accessErrors },
detail: { summary: "List a project's webhooks", ...mcpTool('list_webhooks') },
},
)
@@ -152,13 +147,7 @@ export const webhookRoutes = new Elysia({ name: 'webhooks', detail: { tags: ['We
isActive: t.Optional(t.Boolean()),
}),
permission: ['webhooks', 'create'],
- response: {
- 201: WebhookResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 201: WebhookResponse, ...commonErrors },
detail: { summary: 'Create a webhook', ...mcpTool('create_webhook') },
},
)
@@ -182,13 +171,7 @@ export const webhookRoutes = new Elysia({ name: 'webhooks', detail: { tags: ['We
}),
params: webhookParams,
webhook: 'edit',
- response: {
- 200: WebhookResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: WebhookResponse, ...commonErrors },
detail: { summary: 'Update a webhook', ...mcpTool('update_webhook') },
},
)
@@ -202,13 +185,7 @@ export const webhookRoutes = new Elysia({ name: 'webhooks', detail: { tags: ['We
{
params: webhookParams,
webhook: 'delete',
- response: {
- 204: t.Void(),
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 204: t.Void(), ...commonErrors },
detail: { summary: 'Delete a webhook', ...mcpTool('delete_webhook') },
},
)
@@ -225,13 +202,7 @@ export const webhookRoutes = new Elysia({ name: 'webhooks', detail: { tags: ['We
limit: t.Optional(t.Numeric()),
}),
webhook: 'read',
- response: {
- 200: WebhookDeliveryPageResponse,
- 400: ErrorResponse,
- 401: ErrorResponse,
- 403: ErrorResponse,
- 404: ErrorResponse,
- },
+ response: { 200: WebhookDeliveryPageResponse, ...commonErrors },
detail: {
summary: 'List webhook deliveries',
description: "List a webhook's delivery attempts.",