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.

feat: chat with an external agent (#163)

Croff327f939edc7c
diff --git a/.env.example b/.env.example
index 9f26a6b4..47db935d 100644
--- a/.env.example
+++ b/.env.example
@@ -85,6 +85,14 @@ WORKER_INTERNAL_TOKEN=change-me-please-generate-a-real-secret
# NOTIFICATION_MAX_ATTEMPTS=5 # attempts before a delivery is marked failed
# NOTIFICATION_LEASE_SECONDS=120 # claim lease for crash recovery
+# ── Chat with an external agent (apps/api): the feed its runner drains ──
+# AGENT_CHAT_LEASE_SECONDS=300 # claim lease; an abandoned answer is served again after this
+# AGENT_CHAT_MAX_ATTEMPTS=3 # attempts before an answer is marked failed
+# AGENT_CHAT_CLAIM_WAIT_MS=25000 # how long a runner's claim waits for work before it returns
+# AGENT_CHAT_CLAIM_POLL_MS=500 # how often that claim looks for work while it waits
+# AGENT_CHAT_STREAM_POLL_MS=300 # how often an open stream looks for new events
+# AGENT_CHAT_HISTORY_MESSAGES=20 # thread messages sent to the runner as context
+
# From address for outbound email. Required for Resend (verified sender); for SMTP
# defaults to the SMTP username. NOTIFICATIONS_EMAIL_FROM is read as a fallback.
# EMAIL_FROM=Its a Plan <[email protected]>
diff --git a/AGENTS.md b/AGENTS.md
index 512b6d9d..602306bf 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -251,9 +251,10 @@ tidy moves the code. This is separate from the CI gate (`format:check` + `lint`
`bun run auth:generate` then `bun run db:generate` + `db:migrate`.
- Frontend and backend on different domains in prod: adjust cookie `sameSite`/`secure`
and `APP_URL` (see `packages/auth/AGENTS.md`).
-- Tests run on `bun test` with Eden Treaty. Only `apps/api` has a suite so far; its
- setup and the rules for writing tests are in `apps/api/AGENTS.md`. They are
- integration tests against a real test Postgres (`.env.test`), not mocks.
+- Tests run on `bun test`. `apps/api` uses Eden Treaty; its setup and the rules for
+ writing tests are in `apps/api/AGENTS.md`. They are integration tests against a real
+ test Postgres (`.env.test`), not mocks. `packages/runner` has plain unit tests that
+ need nothing running.
- `bun --filter` needs the `=` form: `bun --filter='@repo/db' run <script>`. The space form
`bun --filter <name> run <script>` matches no packages in Bun 1.3.9.
diff --git a/README.md b/README.md
index dc859a99..2f681f95 100644
--- a/README.md
+++ b/README.md
@@ -63,7 +63,9 @@ stable release.
on your own machine, under your own account
- Mention an agent in a comment to trigger a run
- Scheduled agent runs
-- Built-in chat with per-agent conversation history
+- Built-in chat with per-agent conversation history, with an external agent too: the runner
+ answers from your machine, streaming the reply and the tools it uses, and resumes the same
+ coding agent session on every message of the conversation
**Platform**
@@ -102,6 +104,7 @@ first account registered becomes the instance admin.
- [Self-hosting](docs/self-hosting.md) — the full production setup, secrets, and updates
- [Deploy on Coolify](docs/coolify.md) — the same stack on a Coolify instance
- [Local development](docs/development.md) — running the apps on the host, and the tests
+- [Coding agent setup](docs/runner.md) — the config for each CLI that `@itsaplan/runner` runs
## Built with
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md
index 19ba804a..33a0f625 100644
--- a/apps/api/AGENTS.md
+++ b/apps/api/AGENTS.md
@@ -9,10 +9,10 @@ Rules and invariants for this package below; read the code for the walkthrough.
`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`).
+ `modules/agents/{core,chat,runner,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).
diff --git a/apps/api/src/__tests__/helpers/app.ts b/apps/api/src/__tests__/helpers/app.ts
index 1e7fb2a2..faa350eb 100644
--- a/apps/api/src/__tests__/helpers/app.ts
+++ b/apps/api/src/__tests__/helpers/app.ts
@@ -1,6 +1,10 @@
import { treaty } from '@elysiajs/eden';
import { app } from '../../app';
+// The app itself, for a route Treaty cannot drive (an event stream, where there is no
+// JSON body to hand back).
+export { app };
+
// Anonymous Eden Treaty client bound to the in-memory app (no network, no port).
// Use for unauthenticated routes; planner routes return 401 through this.
export const api = treaty(app);
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index 26623e70..38a17d22 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -67,6 +67,10 @@ export const app = new Elysia()
name: 'Agent Runner',
description: "Run queue an external agent's runner drains with the agent's API key",
},
+ {
+ name: 'Agent Chat',
+ description: "Chat with an external agent: the member's messages and its runner's feed",
+ },
{
name: 'Agent Tools',
description: 'Tools configured on a credential and given to agents',
diff --git a/apps/api/src/modules/agents/chat-parts.ts b/apps/api/src/modules/agents/chat-parts.ts
new file mode 100644
index 00000000..cf840dcd
--- /dev/null
+++ b/apps/api/src/modules/agents/chat-parts.ts
@@ -0,0 +1,37 @@
+import type { ChatPart } from './model';
+
+// Building the parts of one chat message, shared by both kinds of agent: an internal
+// agent's are read from the runtime's memory, an external agent's from the events its
+// runner reported.
+
+// How much of a call's arguments or result is kept. Cutting one breaks the JSON the chat
+// indents and highlights, so the cap only catches an outsized call. The runner caps what
+// it reports at the same size.
+const TOOL_TEXT_LIMIT = 32_000;
+
+// The arguments of a Mastra tool call as the chat shows them, without the runtime's own
+// metadata, which the agent never wrote and the chat has nothing to do with.
+export function toolArgsText(args: unknown): string | undefined {
+ if (!args || typeof args !== 'object') return toolText(args);
+ const rest = { ...(args as Record<string, unknown>) };
+ delete rest.__mastraMetadata;
+ return Object.keys(rest).length > 0 ? toolText(rest) : undefined;
+}
+
+// A call's arguments or result as the chat shows them: a string as it is, anything
+// else as JSON, and nothing at all when the agent reported none.
+export function toolText(value: unknown): string | undefined {
+ if (value === undefined || value === null) return undefined;
+ const text = typeof value === 'string' ? value : JSON.stringify(value);
+ if (!text) return undefined;
+ return text.length <= TOOL_TEXT_LIMIT ? text : `${text.slice(0, TOOL_TEXT_LIMIT)}…`;
+}
+
+// Adds text to the parts built so far, extending the last one when it is text: the
+// stream arrives in chunks, and only a tool call between them starts a new part.
+export function appendTextPart(parts: ChatPart[], text: string): void {
+ if (!text) return;
+ const last = parts[parts.length - 1];
+ if (last?.type === 'text') last.text += text;
+ else parts.push({ type: 'text', text });
+}
diff --git a/apps/api/src/modules/agents/chat/__tests__/integration/agent-chat.test.ts b/apps/api/src/modules/agents/chat/__tests__/integration/agent-chat.test.ts
new file mode 100644
index 00000000..2733159a
--- /dev/null
+++ b/apps/api/src/modules/agents/chat/__tests__/integration/agent-chat.test.ts
@@ -0,0 +1,379 @@
+import { describe, it, expect, beforeEach } from 'bun:test';
+import { app, apiKeyApi, 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';
+
+// Chatting with an external agent: a member sends a message, the agent's runner claims
+// it, reports what its command produces as AG-UI events, and closes it. The claim waits
+// for work on the server, so the wait is shortened here — otherwise every empty-feed
+// assertion would sit out the full production wait.
+process.env.AGENT_CHAT_CLAIM_WAIT_MS = '50';
+process.env.AGENT_CHAT_CLAIM_POLL_MS = '10';
+
+async function setup() {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const asOwner = authedApi(owner.cookie);
+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });
+ const created = await asOwner.projects({ projectKey: 'MKT' })['ai-agents'].post({
+ name: 'Ext Bot',
+ username: 'ext',
+ kind: 'external',
+ });
+ return {
+ owner,
+ asOwner,
+ agent: created.data!.agent,
+ asRunner: apiKeyApi(created.data!.apiKey!),
+ };
+}
+
+function chatOf(api: Api, agentId: number) {
+ return api.projects({ projectKey: 'MKT' })['ai-agents']({ agentId });
+}
+
+function send(api: Api, agentId: number, prompt: string, threadId?: string) {
+ return chatOf(api, agentId).chat.post(threadId ? { prompt, threadId } : { prompt });
+}
+
+// The stream is a raw Response rather than a JSON body, so it is driven through the
+// app directly: Treaty has nothing to hand back for an event stream.
+async function readStream(
+ cookie: string,
+ agentId: number,
+ messageId: number,
+): Promise<{ status: number; frames: string[] }> {
+ const res = await app.handle(
+ new Request(`http://localhost/projects/MKT/ai-agents/${agentId}/chat/${messageId}/stream`, {
+ headers: { cookie },
+ }),
+ );
+ if (!res.body) return { status: res.status, frames: [] };
+ const text = await new Response(res.body).text();
+ return { status: res.status, frames: text.split('\n\n').filter(Boolean) };
+}
+
+describe('external agent chat', () => {
+ beforeEach(async () => {
+ await resetDb();
+ });
+
+ it('queues an answer the runner claims with the message framed as its task', async () => {
+ const { asOwner, asRunner, agent } = await setup();
+
+ const sent = await send(asOwner, agent.id, 'What is left for the launch?');
+ expect(sent.status).toBe(200);
+ expect(sent.data!.threadId).toStartWith(`chat:${agent.id}:`);
+
+ const claimed = await asRunner['agent-chats'].claim.post();
+ expect(claimed.status).toBe(200);
+ expect(claimed.data!.message).toMatchObject({
+ id: sent.data!.messageId,
+ threadId: sent.data!.threadId,
+ attempts: 1,
+ });
+ expect(claimed.data!.message!.prompt).toContain('What is left for the launch?');
+ // A chat is the opposite of an autonomous run: someone is waiting, and the agent
+ // is told so along with the project it works in.
+ expect(claimed.data!.message!.systemPrompt).toContain('Run mode');
+ expect(claimed.data!.message!.systemPrompt).toContain('Marketing');
+ });
+
+ it("mixes the agent's own instructions into the system prompt", async () => {
+ const { asOwner, asRunner, agent } = await setup();
+ await chatOf(asOwner, agent.id).patch({ instructions: 'Always answer in German.' });
+ await send(asOwner, agent.id, 'Status?');
+
+ const claimed = await asRunner['agent-chats'].claim.post();
+ expect(claimed.data!.message!.systemPrompt).toContain('Always answer in German.');
+ });
+
+ it('carries the conversation so far into the next task', async () => {
+ const { asOwner, asRunner, agent } = await setup();
+ const first = await send(asOwner, agent.id, 'Who owns the launch?');
+ const answer = (await asRunner['agent-chats'].claim.post()).data!.message!;
+ await asRunner['agent-chats']({ messageId: answer.id }).events.post({
+ events: [{ type: 'TEXT_MESSAGE_CONTENT', messageId: 'm1', delta: 'Maria does.' }],
+ });
+ await asRunner['agent-chats']({ messageId: answer.id }).result.post({ status: 'success' });
+
+ await send(asOwner, agent.id, 'And the launch date?', first.data!.threadId);
+ const second = (await asRunner['agent-chats'].claim.post()).data!.message!;
+ expect(second.threadId).toBe(first.data!.threadId);
+ expect(second.prompt).toContain('Who owns the launch?');
+ expect(second.prompt).toContain('Maria does.');
+ expect(second.prompt).toContain('And the launch date?');
+ });
+
+ it('returns nothing when the feed is empty', async () => {
+ const { asRunner } = await setup();
+ const res = await asRunner['agent-chats'].claim.post();
+ expect(res.status).toBe(200);
+ expect(res.data!.message).toBeNull();
+ });
+
+ // A thread bound to a session on the runner's machine is sent only the new message:
+ // that session holds the rest, in fuller form than this transcript keeps it.
+ it('sends only the new message once the thread is bound to a session', async () => {
+ const { asOwner, asRunner, agent } = await setup();
+ const first = await send(asOwner, agent.id, 'Who owns the launch?');
+ const answer = (await asRunner['agent-chats'].claim.post()).data!.message!;
+ expect(answer.sessionId).toBeNull();
+
+ await asRunner['agent-chats']({ messageId: answer.id }).events.post({
+ events: [{ type: 'TEXT_MESSAGE_CONTENT', messageId: 'm1', delta: 'Maria does.' }],
+ sessionId: 'sess-abc',
+ });
+ await asRunner['agent-chats']({ messageId: answer.id }).result.post({ status: 'success' });
+
+ await send(asOwner, agent.id, 'And the launch date?', first.data!.threadId);
+ const second = (await asRunner['agent-chats'].claim.post()).data!.message!;
+ expect(second.sessionId).toBe('sess-abc');
+ expect(second.prompt).toBe('And the launch date?');
+ expect(second.prompt).not.toContain('Who owns the launch?');
+ // The session was started with it, so repeating it would only cost context.
+ expect(second.systemPrompt).toBe('');
+ });
+
+ it('keeps the session a thread was first bound to', async () => {
+ const { asOwner, asRunner, agent } = await setup();
+ const sent = await send(asOwner, agent.id, 'Status?');
+ const answer = (await asRunner['agent-chats'].claim.post()).data!.message!;
+ const events = { events: [{ type: 'RUN_STARTED' as const }] };
+
+ await asRunner['agent-chats']({ messageId: answer.id }).events.post({
+ ...events,
+ sessionId: 'sess-first',
+ });
+ await asRunner['agent-chats']({ messageId: answer.id }).events.post({
+ ...events,
+ sessionId: 'sess-second',
+ });
+
+ const threads = await chatOf(asOwner, agent.id).threads.get();
+ expect(threads.data!.find((t) => t.id === sent.data!.threadId)!.cliSessionId).toBe(
+ 'sess-first',
+ );
+ });
+
+ it('shows the bound session in the thread list, and none for a fresh thread', async () => {
+ const { asOwner, asRunner, agent } = await setup();
+ const sent = await send(asOwner, agent.id, 'Status?');
+
+ const before = await chatOf(asOwner, agent.id).threads.get();
+ expect(before.data!.find((t) => t.id === sent.data!.threadId)!.cliSessionId).toBeNull();
+
+ const answer = (await asRunner['agent-chats'].claim.post()).data!.message!;
+ await asRunner['agent-chats']({ messageId: answer.id }).events.post({
+ events: [{ type: 'RUN_STARTED' }],
+ sessionId: 'sess-abc',
+ });
+
+ const after = await chatOf(asOwner, agent.id).threads.get();
+ expect(after.data!.find((t) => t.id === sent.data!.threadId)!.cliSessionId).toBe('sess-abc');
+ });
+
+ it('hands a claimed answer to no one else until its lease expires', async () => {
+ const { asOwner, asRunner, agent } = await setup();
+ await send(asOwner, agent.id, 'Hello');
+
+ expect((await asRunner['agent-chats'].claim.post()).data!.message).not.toBeNull();
+ expect((await asRunner['agent-chats'].claim.post()).data!.message).toBeNull();
+ });
+
+ it('reports events back with a cursor and builds the answer text from them', async () => {
+ const { asOwner, asRunner, agent } = await setup();
+ const sent = await send(asOwner, agent.id, 'Summarise the sprint');
+ const answer = (await asRunner['agent-chats'].claim.post()).data!.message!;
+
+ const reported = await asRunner['agent-chats']({ messageId: answer.id }).events.post({
+ events: [
+ { type: 'RUN_STARTED' },
+ { type: 'TEXT_MESSAGE_START', messageId: 'm1', role: 'assistant' },
+ { type: 'TEXT_MESSAGE_CONTENT', messageId: 'm1', delta: 'Two things ' },
+ { type: 'TOOL_CALL_START', toolCallId: 't1', toolCallName: 'list_issues' },
+ { type: 'TOOL_CALL_ARGS', toolCallId: 't1', delta: '{"status":' },
+ { type: 'TOOL_CALL_ARGS', toolCallId: 't1', delta: '"open"}' },
+ { type: 'TOOL_CALL_END', toolCallId: 't1' },
+ { type: 'TOOL_CALL_RESULT', messageId: 'm1', toolCallId: 't1', content: '2 issues' },
+ { type: 'TEXT_MESSAGE_CONTENT', messageId: 'm1', delta: 'are left.' },
+ ],
+ });
+ expect(reported.status).toBe(204);
+
+ const events = await chatOf(asOwner, agent.id).chat({ messageId: answer.id }).events.get();
+ expect(events.status).toBe(200);
+ expect(events.data!.status).toBe('streaming');
+ expect(events.data!.items.map((item) => item.event.type)).toEqual([
+ 'RUN_STARTED',
+ 'TEXT_MESSAGE_START',
+ 'TEXT_MESSAGE_CONTENT',
+ 'TOOL_CALL_START',
+ 'TOOL_CALL_ARGS',
+ 'TOOL_CALL_ARGS',
+ 'TOOL_CALL_END',
+ 'TOOL_CALL_RESULT',
+ 'TEXT_MESSAGE_CONTENT',
+ ]);
+
+ // Reading again from the cursor returns only what arrived after it.
+ const cursor = events.data!.nextCursor!;
+ await asRunner['agent-chats']({ messageId: answer.id }).events.post({
+ events: [{ type: 'RUN_FINISHED' }],
+ });
+ const later = await chatOf(asOwner, agent.id)
+ .chat({ messageId: answer.id })
+ .events.get({ query: { after: cursor } });
+ expect(later.data!.items.map((item) => item.event.type)).toEqual(['RUN_FINISHED']);
+
+ await asRunner['agent-chats']({ messageId: answer.id }).result.post({ status: 'success' });
+ const transcript = await chatOf(asOwner, agent.id)
+ .threads({ threadId: sent.data!.threadId })
+ .messages.get();
+ // The tool the runner reported stays where it was called: between the text before
+ // it and the text after it, with the arguments it was given and what it answered.
+ expect(transcript.data!.items).toMatchObject([
+ { role: 'user', parts: [{ type: 'text', text: 'Summarise the sprint' }] },
+ {
+ role: 'assistant',
+ parts: [
+ { type: 'text', text: 'Two things ' },
+ {
+ type: 'tool',
+ toolCallId: 't1',
+ toolName: 'list_issues',
+ args: '{"status":"open"}',
+ result: '2 issues',
+ },
+ { type: 'text', text: 'are left.' },
+ ],
+ },
+ ]);
+ });
+
+ it('streams the answer and always ends on a terminal event', async () => {
+ const { owner, asOwner, asRunner, agent } = await setup();
+ await send(asOwner, agent.id, 'Ping');
+ const answer = (await asRunner['agent-chats'].claim.post()).data!.message!;
+ await asRunner['agent-chats']({ messageId: answer.id }).events.post({
+ events: [{ type: 'TEXT_MESSAGE_CONTENT', messageId: 'm1', delta: 'Pong' }],
+ });
+ await asRunner['agent-chats']({ messageId: answer.id }).result.post({ status: 'success' });
+
+ const stream = await readStream(owner.cookie, agent.id, answer.id);
+ expect(stream.status).toBe(200);
+ // Every frame carries the event's id, which is the cursor a reconnect resumes from.
+ expect(stream.frames[0]).toStartWith('id: ');
+ expect(stream.frames[0]).toContain('Pong');
+ // The runner reported no lifecycle events, so the end is stated for it.
+ expect(stream.frames.at(-1)).toContain('RUN_FINISHED');
+ });
+
+ it('ends a failed answer with the reason it stopped', async () => {
+ const { owner, asOwner, asRunner, agent } = await setup();
+ await send(asOwner, agent.id, 'Ping');
+ const answer = (await asRunner['agent-chats'].claim.post()).data!.message!;
+ await asRunner['agent-chats']({ messageId: answer.id }).result.post({
+ status: 'failed',
+ error: 'claude exited with 1',
+ });
+
+ const stream = await readStream(owner.cookie, agent.id, answer.id);
+ expect(stream.frames.at(-1)).toContain('RUN_ERROR');
+ expect(stream.frames.at(-1)).toContain('claude exited with 1');
+ });
+
+ it('keeps a claimed answer leased through a heartbeat', async () => {
+ const { asOwner, asRunner, agent } = await setup();
+ await send(asOwner, agent.id, 'Hello');
+ const answer = (await asRunner['agent-chats'].claim.post()).data!.message!;
+
+ expect((await asRunner['agent-chats']({ messageId: answer.id }).heartbeat.post()).status).toBe(
+ 204,
+ );
+ });
+
+ it('records the failure the runner reports and stops taking events', async () => {
+ const { asOwner, asRunner, agent } = await setup();
+ await send(asOwner, agent.id, 'Hello');
+ const answer = (await asRunner['agent-chats'].claim.post()).data!.message!;
+
+ await asRunner['agent-chats']({ messageId: answer.id }).result.post({
+ status: 'failed',
+ error: 'claude exited with 1',
+ });
+
+ const events = await chatOf(asOwner, agent.id).chat({ messageId: answer.id }).events.get();
+ expect(events.data!).toMatchObject({ status: 'failed', error: 'claude exited with 1' });
+ expect(
+ (
+ await asRunner['agent-chats']({ messageId: answer.id }).events.post({
+ events: [{ type: 'TEXT_MESSAGE_CONTENT', messageId: 'm1', delta: 'late' }],
+ })
+ ).status,
+ ).toBe(404);
+ expect(
+ (await asRunner['agent-chats']({ messageId: answer.id }).result.post({ status: 'success' }))
+ .status,
+ ).toBe(404);
+ });
+
+ it('lists and deletes the conversations of an external agent', async () => {
+ const { asOwner, agent } = await setup();
+ const sent = await send(asOwner, agent.id, 'First question');
+
+ const threads = await chatOf(asOwner, agent.id).threads.get();
+ expect(threads.data!).toMatchObject([{ id: sent.data!.threadId, title: 'First question' }]);
+
+ expect(
+ (await chatOf(asOwner, agent.id).threads({ threadId: sent.data!.threadId }).delete()).status,
+ ).toBe(204);
+ expect((await chatOf(asOwner, agent.id).threads.get()).data!).toEqual([]);
+ });
+
+ it("refuses another member's thread and another agent's answer", async () => {
+ const { asOwner, asRunner, agent } = await setup();
+ const sent = await send(asOwner, agent.id, 'Private question');
+ const answer = (await asRunner['agent-chats'].claim.post()).data!.message!;
+ const asMember = await addProjectMember(asOwner, 'MKT');
+
+ expect((await send(asMember, agent.id, 'Sneak in', sent.data!.threadId)).status).toBe(404);
+ expect(
+ (await chatOf(asMember, agent.id).chat({ messageId: answer.id }).events.get()).status,
+ ).toBe(404);
+
+ const other = await asOwner
+ .projects({ projectKey: 'MKT' })
+ ['ai-agents'].post({ name: 'Other Bot', username: 'other', kind: 'external' });
+ const asOtherRunner = apiKeyApi(other.data!.apiKey!);
+ expect(
+ (
+ await asOtherRunner['agent-chats']({ messageId: answer.id }).result.post({
+ status: 'success',
+ })
+ ).status,
+ ).toBe(404);
+ });
+
+ it('takes chat messages only for an external agent, and only from its own key', async () => {
+ const { asOwner, agent } = await setup();
+ const internal = await asOwner
+ .projects({ projectKey: 'MKT' })
+ ['ai-agents'].post({ name: 'In Bot', username: 'in', kind: 'internal' });
+
+ // An internal agent is chatted with through /run and /run/stream instead.
+ expect((await send(asOwner, internal.data!.agent.id, 'Hello')).status).toBe(400);
+ // And a member's session is not a runner.
+ expect((await asOwner['agent-chats'].claim.post()).status).toBe(403);
+ expect((await send(asOwner, agent.id, 'Hello')).status).toBe(200);
+ });
+
+ it("keeps an owner-scoped agent's chat to its owner", async () => {
+ const { asOwner, agent } = await setup();
+ await chatOf(asOwner, agent.id).patch({ runnerScope: 'owner' });
+ const asMember = await addProjectMember(asOwner, 'MKT');
+
+ expect((await send(asMember, agent.id, 'Hello')).status).toBe(403);
+ expect((await send(asOwner, agent.id, 'Hello')).status).toBe(200);
+ });
+});
diff --git a/apps/api/src/modules/agents/chat/index.ts b/apps/api/src/modules/agents/chat/index.ts
new file mode 100644
index 00000000..964a5b6d
--- /dev/null
+++ b/apps/api/src/modules/agents/chat/index.ts
@@ -0,0 +1,265 @@
+import { Elysia, t } from 'elysia';
+import { setTimeout as sleep } from 'node:timers/promises';
+import { authContext } from '#shared/auth-context';
+import { guards } from '#shared/guards';
+import { requireUser } from '#shared/access';
+import { noContent, sseFrame, sseResponse } from '#shared/http';
+import { HttpError } from '#shared/lib';
+import { commonErrors, errors } from '#shared/responses';
+import { getAgentById, isTriggerableBy } from '../core/service';
+import { runnerAuth } from '../runner-auth';
+import {
+ ChatEventsResponse,
+ ClaimChatResponse,
+ SendChatResponse,
+ agentParams,
+ chatEventsBody,
+ chatEventsQuery,
+ chatMessageParams,
+ chatResultBody,
+ runnerMessageParams,
+ sendChatBody,
+ type AgUiEventBody,
+} from './model';
+import {
+ agentChatConfig,
+ appendEvents,
+ claimNextMessage,
+ finishMessage,
+ heartbeatMessage,
+ readEvents,
+ sendMessage,
+ setThreadSession,
+} from './service';
+
+// Chatting with an external agent: the member's side (send a message, follow the
+// answer) and the runner's side (take the next answer to produce, report AG-UI events,
+// close it). The answer comes from the operator's machine, so the two sides only ever
+// meet in the database.
+
+// How long one stream stays open with nothing arriving before it ends and lets the
+// browser reconnect. An answer may legitimately wait a long time for a runner to come
+// online, so this is a bound on the connection, not on the answer.
+const STREAM_MAX_MS = 30 * 60_000;
+const KEEPALIVE_MS = 15_000;
+
+// The agent this route acts on, or a 404. Only an external agent has a chat feed: an
+// internal one is run in-process by /run and /run/stream.
+async function requireExternalAgent(agentId: number, projectId: number) {
+ const agent = await getAgentById(agentId, projectId);
+ if (!agent) throw new HttpError(404, 'Agent not found');
+ if (agent.kind !== 'external') {
+ throw new HttpError(400, 'Only external agents are chatted with through the runner feed');
+ }
+ return agent;
+}
+
+export const agentChatRoutes = new Elysia({ name: 'agent-chat', detail: { tags: ['Agent Chat'] } })
+ .use(authContext)
+ .use(guards)
+ .use(runnerAuth)
+
+ .post(
+ '/projects/:projectKey/ai-agents/:agentId/chat',
+ async ({ params, project, body, user }) => {
+ const caller = requireUser(user);
+ const agent = await requireExternalAgent(params.agentId, project.id);
+ if (!isTriggerableBy(agent, caller.id)) {
+ throw new HttpError(403, 'This agent only takes tasks from its owner');
+ }
+ const sent = await sendMessage({
+ agentId: params.agentId,
+ userId: caller.id,
+ prompt: body.prompt,
+ threadId: body.threadId,
+ });
+ if (!sent) throw new HttpError(404, 'Thread not found');
+ return sent;
+ },
+ {
+ body: sendChatBody,
+ params: agentParams,
+ permission: ['ai_agents', 'read'],
+ response: { 200: SendChatResponse, ...commonErrors },
+ detail: {
+ summary: 'Send a chat message',
+ description:
+ "Queue a message for an external agent's runner and return the answer it will " +
+ 'produce. Follow the answer with the stream endpoint.',
+ },
+ },
+ )
+
+ // The answer's events after `after`, as plain JSON. What the stream serves, for a
+ // client that reconnects and for one that would rather poll.
+ .get(
+ '/projects/:projectKey/ai-agents/:agentId/chat/:messageId/events',
+ async ({ params, project, query, user }) => {
+ const caller = requireUser(user);
+ await requireExternalAgent(params.agentId, project.id);
+ const page = await readEvents(params.messageId, params.agentId, caller.id, query.after);
+ if (!page) throw new HttpError(404, 'Message not found');
+ return page;
+ },
+ {
+ params: chatMessageParams,
+ query: chatEventsQuery,
+ permission: ['ai_agents', 'read'],
+ response: { 200: ChatEventsResponse, ...commonErrors },
+ detail: { summary: 'Read answer events' },
+ },
+ )
+
+ // The same events as Server-Sent Events, one `data:` line per JSON-encoded AG-UI
+ // event, as the runner reports them. The connection is held open while the answer is
+ // still being produced — including before a runner has taken it, which is what lets
+ // the chat show that it is waiting.
+ .get(
+ '/projects/:projectKey/ai-agents/:agentId/chat/:messageId/stream',
+ async ({ params, project, query, user }) => {
+ const caller = requireUser(user);
+ await requireExternalAgent(params.agentId, project.id);
+ // Checked before the stream starts, so an unknown answer is a 404 rather than a
+ // stream that ends immediately.
+ const after = query.after ?? 0;
+ if (!(await readEvents(params.messageId, params.agentId, caller.id, after))) {
+ throw new HttpError(404, 'Message not found');
+ }
+ return sseResponse(streamChatEvents(params.messageId, params.agentId, caller.id, after));
+ },
+ {
+ params: chatMessageParams,
+ query: chatEventsQuery,
+ permission: ['ai_agents', 'read'],
+ response: {
+ // The success body is an SSE stream returned as a raw Response, so it is not a
+ // JSON shape the validator can describe.
+ 200: t.Any(),
+ ...commonErrors,
+ },
+ detail: { summary: 'Stream an answer' },
+ },
+ )
+
+ .post('/agent-chats/claim', async ({ agent }) => ({ message: await claimNextMessage(agent) }), {
+ runnerAgent: true,
+ response: { 200: ClaimChatResponse, ...errors(401, 403) },
+ detail: {
+ summary: 'Claim the next chat message',
+ description:
+ "Take the calling agent's next chat message to answer. The call waits for one " +
+ 'and returns message: null when none arrives. It is leased: report events, ' +
+ 'heartbeats, or a result, otherwise it is handed out again.',
+ },
+ })
+
+ .post(
+ '/agent-chats/:messageId/events',
+ async ({ agent, params, body }) => {
+ const ok = await appendEvents(agent.id, params.messageId, body.events);
+ if (!ok) throw new HttpError(404, 'Message not found');
+ if (body.sessionId) await setThreadSession(agent.id, params.messageId, body.sessionId);
+ return noContent();
+ },
+ {
+ runnerAgent: true,
+ params: runnerMessageParams,
+ body: chatEventsBody,
+ response: { 204: t.Void(), ...commonErrors },
+ detail: {
+ summary: 'Report answer events',
+ description:
+ 'Append AG-UI events to a claimed answer: text deltas, tool calls, run ' +
+ 'lifecycle. Reporting also extends the lease, and binds the thread to the ' +
+ 'session when `sessionId` is given.',
+ },
+ },
+ )
+
+ .post(
+ '/agent-chats/:messageId/heartbeat',
+ async ({ agent, params }) => {
+ const ok = await heartbeatMessage(agent.id, params.messageId);
+ if (!ok) throw new HttpError(404, 'Message not found');
+ return noContent();
+ },
+ {
+ runnerAgent: true,
+ params: runnerMessageParams,
+ response: { 204: t.Void(), ...commonErrors },
+ detail: {
+ summary: 'Extend an answer lease',
+ description: 'Keep a claimed answer leased while the runner is still working on it.',
+ },
+ },
+ )
+
+ .post(
+ '/agent-chats/:messageId/result',
+ async ({ agent, params, body }) => {
+ const ok = await finishMessage(agent.id, params.messageId, body);
+ if (!ok) throw new HttpError(404, 'Message not found');
+ return noContent();
+ },
+ {
+ runnerAgent: true,
+ params: runnerMessageParams,
+ body: chatResultBody,
+ response: { 204: t.Void(), ...commonErrors },
+ detail: {
+ summary: 'Finish an answer',
+ description: 'Close a claimed answer as success or failed. A failure is not retried.',
+ },
+ },
+ );
+
+// The frames one stream sends: every event stored for the answer, in order, and then
+// whatever arrives while it is still being produced. Each frame carries the event's id,
+// which a client that reconnects passes back as `after` to resume where it stopped.
+//
+// The answer always ends on RUN_FINISHED or RUN_ERROR, synthesized when the runner
+// reported neither, so a stream that closes without one means the connection dropped
+// rather than the answer ending. Comment frames keep the connection alive through a
+// proxy that would otherwise drop it while the agent is thinking.
+async function* streamChatEvents(
+ messageId: number,
+ agentId: number,
+ userId: string,
+ after: number,
+): AsyncGenerator<string> {
+ const until = Date.now() + STREAM_MAX_MS;
+ let cursor = after;
+ let ended = false;
+ let quietSince = Date.now();
+ for (;;) {
+ const page = await readEvents(messageId, agentId, userId, cursor);
+ if (!page) return;
+ for (const item of page.items) {
+ if (item.event.type === 'RUN_ERROR' || item.event.type === 'RUN_FINISHED') ended = true;
+ yield sseFrame(item.event, item.id);
+ }
+ if (page.nextCursor != null) {
+ cursor = page.nextCursor;
+ quietSince = Date.now();
+ }
+ // More is already stored than one read hands out: take it before deciding the
+ // answer is over or waiting for the next tick.
+ if (page.hasMore) continue;
+ if (page.status === 'success' || page.status === 'failed') {
+ if (!ended) yield sseFrame(terminalEvent(page.status, page.error), cursor);
+ return;
+ }
+ if (Date.now() >= until) return;
+ if (Date.now() - quietSince >= KEEPALIVE_MS) {
+ yield ': ping\n\n';
+ quietSince = Date.now();
+ }
+ await sleep(agentChatConfig.streamPollMs());
+ }
+}
+
+function terminalEvent(status: 'success' | 'failed', error: string | null): AgUiEventBody {
+ return status === 'success'
+ ? { type: 'RUN_FINISHED' }
+ : { type: 'RUN_ERROR', message: error ?? 'The agent did not finish the answer' };
+}
diff --git a/apps/api/src/modules/agents/chat/model.ts b/apps/api/src/modules/agents/chat/model.ts
new file mode 100644
index 00000000..0666d9bd
--- /dev/null
+++ b/apps/api/src/modules/agents/chat/model.ts
@@ -0,0 +1,176 @@
+import { t } from 'elysia';
+
+export { agentParams } from '../model';
+
+// A chat with an external agent is carried by AG-UI events (https://docs.ag-ui.com):
+// the runner reports what its coding agent produces as this event stream, and the
+// browser is served the same events. The schemas below are the subset the chat needs,
+// with the field names the protocol defines, so a runner that already speaks AG-UI
+// needs no translation. Lifecycle ids are optional here because the server knows the
+// thread and the answer they belong to; everything else is required as specified.
+
+// The longest text delta accepted in one event. A runner buffers its output rather
+// than sending a request per token, and this bounds how much one event may carry.
+const DELTA_LIMIT = 12_000;
+
+// The longest arguments or result accepted for one tool call. A runner reports each of
+// them whole, and cutting one breaks the JSON the chat indents and highlights.
+const TOOL_TEXT_LIMIT = 32_000;
+
+const RunStartedEvent = t.Object({
+ type: t.Literal('RUN_STARTED'),
+ threadId: t.Optional(t.String()),
+ runId: t.Optional(t.String()),
+});
+
+const RunFinishedEvent = t.Object({
+ type: t.Literal('RUN_FINISHED'),
+ threadId: t.Optional(t.String()),
+ runId: t.Optional(t.String()),
+});
+
+const RunErrorEvent = t.Object({
+ type: t.Literal('RUN_ERROR'),
+ message: t.String({ maxLength: 2000 }),
+ code: t.Optional(t.String({ maxLength: 200 })),
+});
+
+const TextMessageStartEvent = t.Object({
+ type: t.Literal('TEXT_MESSAGE_START'),
+ messageId: t.String({ maxLength: 200 }),
+ role: t.Literal('assistant'),
+});
+
+const TextMessageContentEvent = t.Object({
+ type: t.Literal('TEXT_MESSAGE_CONTENT'),
+ messageId: t.String({ maxLength: 200 }),
+ delta: t.String({ maxLength: DELTA_LIMIT }),
+});
+
+const TextMessageEndEvent = t.Object({
+ type: t.Literal('TEXT_MESSAGE_END'),
+ messageId: t.String({ maxLength: 200 }),
+});
+
+const ToolCallStartEvent = t.Object({
+ type: t.Literal('TOOL_CALL_START'),
+ toolCallId: t.String({ maxLength: 200 }),
+ toolCallName: t.String({ maxLength: 200 }),
+ parentMessageId: t.Optional(t.String({ maxLength: 200 })),
+});
+
+const ToolCallArgsEvent = t.Object({
+ type: t.Literal('TOOL_CALL_ARGS'),
+ toolCallId: t.String({ maxLength: 200 }),
+ delta: t.String({ maxLength: TOOL_TEXT_LIMIT }),
+});
+
+const ToolCallEndEvent = t.Object({
+ type: t.Literal('TOOL_CALL_END'),
+ toolCallId: t.String({ maxLength: 200 }),
+});
+
+const ToolCallResultEvent = t.Object({
+ type: t.Literal('TOOL_CALL_RESULT'),
+ messageId: t.String({ maxLength: 200 }),
+ toolCallId: t.String({ maxLength: 200 }),
+ content: t.String({ maxLength: TOOL_TEXT_LIMIT }),
+ role: t.Optional(t.Literal('tool')),
+});
+
+export const AgUiEvent = t.Union([
+ RunStartedEvent,
+ RunFinishedEvent,
+ RunErrorEvent,
+ TextMessageStartEvent,
+ TextMessageContentEvent,
+ TextMessageEndEvent,
+ ToolCallStartEvent,
+ ToolCallArgsEvent,
+ ToolCallEndEvent,
+ ToolCallResultEvent,
+]);
+
+export type AgUiEventBody = typeof AgUiEvent.static;
+
+export const chatMessageParams = t.Object({
+ projectKey: t.String(),
+ agentId: t.Numeric(),
+ messageId: t.Numeric(),
+});
+
+export const runnerMessageParams = t.Object({ messageId: t.Numeric() });
+
+export const sendChatBody = t.Object({
+ prompt: t.String({ minLength: 1, description: 'Message to send the agent.' }),
+ threadId: t.Optional(
+ t.String({ description: 'Thread id of an earlier message, to continue that conversation.' }),
+ ),
+});
+
+// What the caller needs to follow the answer: the thread it belongs to and the id of
+// the answer being produced.
+export const SendChatResponse = t.Object({
+ threadId: t.String(),
+ messageId: t.Number(),
+});
+
+// Events are read with a cursor: `after` is the id of the last event already seen.
+export const chatEventsQuery = t.Object({ after: t.Optional(t.Numeric({ minimum: 0 })) });
+
+// Where an answer stands: queued, being produced by a runner, or closed either way.
+export const chatMessageStatus = t.Union([
+ t.Literal('pending'),
+ t.Literal('streaming'),
+ t.Literal('success'),
+ t.Literal('failed'),
+]);
+
+export type ChatMessageStatus = typeof chatMessageStatus.static;
+
+export const ChatEventsResponse = t.Object({
+ items: t.Array(t.Object({ id: t.Number(), event: AgUiEvent })),
+ status: chatMessageStatus,
+ error: t.Nullable(t.String()),
+ nextCursor: t.Nullable(t.Number()),
+ hasMore: t.Boolean(),
+});
+
+// The claimed answer, or null when the agent has nothing waiting. `prompt` carries the
+// conversation so far, framed the same way a run's task is — except when `sessionId` is
+// set, where the runner's session already holds it and only the new message is sent.
+export const ClaimChatResponse = t.Object({
+ message: t.Nullable(
+ t.Object({
+ id: t.Number(),
+ threadId: t.String(),
+ prompt: t.String(),
+ systemPrompt: t.String(),
+ attempts: t.Number(),
+ sessionId: t.Nullable(
+ t.String({
+ description:
+ "The coding agent session this thread is bound to on the runner's machine. " +
+ 'Null when there is none yet: start a fresh one and report the id it got.',
+ }),
+ ),
+ }),
+ ),
+});
+
+export const chatEventsBody = t.Object({
+ events: t.Array(AgUiEvent, { minItems: 1, maxItems: 200 }),
+ sessionId: t.Optional(
+ t.String({
+ maxLength: 200,
+ description:
+ 'The session the runner started for this thread, reported once so later messages ' +
+ 'in it resume that session instead of being sent the conversation again.',
+ }),
+ ),
+});
+
+export const chatResultBody = t.Object({
+ status: t.Union([t.Literal('success'), t.Literal('failed')]),
+ error: t.Optional(t.Nullable(t.String())),
+});
diff --git a/apps/api/src/modules/agents/chat/service.ts b/apps/api/src/modules/agents/chat/service.ts
new file mode 100644
index 00000000..89cb804d
--- /dev/null
+++ b/apps/api/src/modules/agents/chat/service.ts
@@ -0,0 +1,553 @@
+import { db, agentChatEvent, agentChatMessage, agentChatThread } from '@repo/db';
+import { and, asc, desc, eq, gt, inArray, sql } from 'drizzle-orm';
+import { setTimeout as sleep } from 'node:timers/promises';
+import { iso } from '#shared/lib';
+import { appendTextPart } from '../chat-parts';
+import { intEnv } from '../core/helpers/env';
+import { projectPreamble } from '../core/prompt/framing';
+import { peoplePreamble } from '../core/prompt/run-context';
+import type { ChatMessagePage, ChatPart, ChatThreadSummary } from '../model';
+import { newChatThreadId } from '../core/runtime/thread-ids';
+import { touchRunner, type RunnerAgent } from '../runner/service';
+import type { AgUiEventBody, ChatMessageStatus } from './model';
+
+// Chat with an external agent. The answer is produced by a runner on the operator's
+// machine, so it cannot be generated in this process the way an internal agent's is:
+// the member's message is stored, an empty answer is queued next to it, and the runner
+// claims that answer, reports AG-UI events as its coding agent produces them, and
+// closes it. The browser reads the same events back through the chat routes.
+//
+// The feed is deliberately separate from agent_run: a chat turn has no issue, is not
+// retried after a failure the way an autonomous run is, and is claimed by a call that
+// waits for work instead of polling for it.
+
+// Tuning, env-overridable. The lease matches the run queue's: a coding agent can work
+// for minutes, and the lease has to outlast a quiet stretch or the answer is handed to
+// another runner mid-flight.
+export const agentChatConfig = {
+ leaseSeconds: () => intEnv('AGENT_CHAT_LEASE_SECONDS', 300),
+ maxAttempts: () => intEnv('AGENT_CHAT_MAX_ATTEMPTS', 3),
+ // How long a claim waits for work before it answers "nothing", and how often it looks
+ // while it waits. The wait is what makes an answer start the moment it is sent.
+ claimWaitMs: () => intEnv('AGENT_CHAT_CLAIM_WAIT_MS', 25_000),
+ claimPollMs: () => intEnv('AGENT_CHAT_CLAIM_POLL_MS', 500),
+ streamPollMs: () => intEnv('AGENT_CHAT_STREAM_POLL_MS', 300),
+ historyMessages: () => intEnv('AGENT_CHAT_HISTORY_MESSAGES', 20),
+};
+
+const PAGE_SIZE = 25;
+const TITLE_LIMIT = 80;
+// How much of an answer is kept as its text. A reply nobody would read to the end is
+// still bounded, the way a run's output is.
+const ANSWER_LIMIT = 100_000;
+// Events handed out per read. A stream that falls behind catches up over several reads
+// instead of loading everything an agent has said in one go.
+const EVENT_PAGE = 500;
+
+// The statuses an answer can still be worked on in: a runner claims either, and only
+// these take events, heartbeats and a result.
+const LIVE_STATUSES = ['pending', 'streaming'];
+
+// The caller's conversations with one external agent, newest first.
+export async function listThreads(userId: string, agentId: number): Promise<ChatThreadSummary[]> {
+ const rows = await db
+ .select()
+ .from(agentChatThread)
+ .where(and(eq(agentChatThread.agentId, agentId), eq(agentChatThread.userId, userId)))
+ .orderBy(desc(agentChatThread.updatedAt));
+ return rows.map((r) => ({
+ id: r.id,
+ title: r.title && r.title.length > 0 ? r.title : null,
+ cliSessionId: r.cliSessionId,
+ createdAt: iso(r.createdAt),
+ updatedAt: iso(r.updatedAt),
+ }));
+}
+
+// One page of a thread's transcript, oldest first within the page, page 0 being the
+// newest — the shape the chat history loads backwards from. Null when the thread is not
+// the caller's, which the route maps to a 404.
+export async function getThreadMessages(
+ threadId: string,
+ userId: string,
+ page = 0,
+): Promise<ChatMessagePage | null> {
+ if (!(await ownsThread(threadId, userId))) return null;
+ const rows = await db
+ .select()
+ .from(agentChatMessage)
+ .where(eq(agentChatMessage.threadId, threadId))
+ .orderBy(desc(agentChatMessage.id))
+ .limit(PAGE_SIZE + 1)
+ .offset(page * PAGE_SIZE);
+ const hasMore = rows.length > PAGE_SIZE;
+ const turns = (hasMore ? rows.slice(0, PAGE_SIZE) : rows).reverse();
+ const answers = await readAnswerParts(
+ turns.filter((r) => r.role === 'assistant').map((r) => r.id),
+ );
+ const items = turns
+ .map((r) => ({
+ id: String(r.id),
+ role: r.role as 'user' | 'assistant',
+ parts:
+ r.role === 'assistant'
+ ? (answers.get(r.id) ?? [])
+ : [{ type: 'text' as const, text: r.content }],
+ createdAt: iso(r.createdAt),
+ }))
+ // An answer whose runner has reported nothing yet has nothing to show; the browser
+ // is streaming it.
+ .filter((m) => m.parts.length > 0);
+ return { items, nextPage: hasMore ? page + 1 : null };
+}
+
+// The event types a transcript is made of: the answer's text, and the tool calls with
+// what each was given and answered. The lifecycle events say nothing the reader sees.
+const TRANSCRIPT_EVENTS = [
+ 'TEXT_MESSAGE_CONTENT',
+ 'TOOL_CALL_START',
+ 'TOOL_CALL_ARGS',
+ 'TOOL_CALL_RESULT',
+];
+
+// Rebuilds each answer's parts from the events its runner reported. A call's start is
+// what puts it between the stretches of text around it; its arguments and result are
+// filled in afterwards, and stay unset for a runner that reports neither.
+async function readAnswerParts(messageIds: number[]): Promise<Map<number, ChatPart[]>> {
+ const parts = new Map<number, ChatPart[]>();
+ if (messageIds.length === 0) return parts;
+ const rows = await db
+ .select({
+ messageId: agentChatEvent.messageId,
+ type: sql<string>`${agentChatEvent.payload}->>'type'`,
+ delta: sql<string | null>`${agentChatEvent.payload}->>'delta'`,
+ content: sql<string | null>`${agentChatEvent.payload}->>'content'`,
+ toolCallId: sql<string | null>`${agentChatEvent.payload}->>'toolCallId'`,
+ toolCallName: sql<string | null>`${agentChatEvent.payload}->>'toolCallName'`,
+ })
+ .from(agentChatEvent)
+ .where(
+ and(
+ inArray(agentChatEvent.messageId, messageIds),
+ inArray(sql`${agentChatEvent.payload}->>'type'`, TRANSCRIPT_EVENTS),
+ ),
+ )
+ .orderBy(asc(agentChatEvent.id));
+ // The call an answer's arguments and result belong to, by the id the runner gave it.
+ const calls = new Map<string, Extract<ChatPart, { type: 'tool' }>>();
+ for (const row of rows) {
+ const message = parts.get(row.messageId) ?? [];
+ parts.set(row.messageId, message);
+ const callKey = `${row.messageId}:${row.toolCallId}`;
+ switch (row.type) {
+ case 'TEXT_MESSAGE_CONTENT':
+ appendTextPart(message, row.delta ?? '');
+ break;
+ case 'TOOL_CALL_START': {
+ const started = {
+ type: 'tool' as const,
+ toolCallId: row.toolCallId ?? '',
+ toolName: row.toolCallName ?? '',
+ };
+ message.push(started);
+ calls.set(callKey, started);
+ break;
+ }
+ case 'TOOL_CALL_ARGS': {
+ const call = calls.get(callKey);
+ if (call && row.delta) call.args = (call.args ?? '') + row.delta;
+ break;
+ }
+ case 'TOOL_CALL_RESULT': {
+ const call = calls.get(callKey);
+ if (call && row.content) call.result = row.content;
+ break;
+ }
+ }
+ }
+ return parts;
+}
+
+export async function deleteThread(threadId: string, userId: string): Promise<boolean> {
+ const rows = await db
+ .delete(agentChatThread)
+ .where(and(eq(agentChatThread.id, threadId), eq(agentChatThread.userId, userId)))
+ .returning({ id: agentChatThread.id });
+ return rows.length > 0;
+}
+
+async function ownsThread(threadId: string, userId: string): Promise<boolean> {
+ const rows = await db
+ .select({ id: agentChatThread.id })
+ .from(agentChatThread)
+ .where(and(eq(agentChatThread.id, threadId), eq(agentChatThread.userId, userId)))
+ .limit(1);
+ return rows.length > 0;
+}
+
+// Stores the member's message and queues the answer next to it. A thread id continues
+// that conversation; without one a thread is created, titled after the message. Null
+// when the thread named is not the caller's.
+export async function sendMessage(input: {
+ agentId: number;
+ userId: string;
+ prompt: string;
+ threadId?: string;
+}): Promise<{ threadId: string; messageId: number } | null> {
+ const { agentId, userId, prompt } = input;
+ return db.transaction(async (tx) => {
+ let threadId = input.threadId;
+ if (threadId) {
+ const rows = await tx
+ .select({ id: agentChatThread.id })
+ .from(agentChatThread)
+ .where(
+ and(
+ eq(agentChatThread.id, threadId),
+ eq(agentChatThread.agentId, agentId),
+ eq(agentChatThread.userId, userId),
+ ),
+ )
+ .limit(1);
+ if (!rows[0]) return null;
+ await tx
+ .update(agentChatThread)
+ .set({ updatedAt: new Date() })
+ .where(eq(agentChatThread.id, threadId));
+ } else {
+ threadId = newChatThreadId(agentId, userId);
+ await tx
+ .insert(agentChatThread)
+ .values({ id: threadId, agentId, userId, title: prompt.slice(0, TITLE_LIMIT) });
+ }
+ await tx
+ .insert(agentChatMessage)
+ .values({ threadId, agentId, role: 'user', content: prompt, status: 'success' });
+ const answer = await tx
+ .insert(agentChatMessage)
+ .values({ threadId, agentId, role: 'assistant' })
+ .returning({ id: agentChatMessage.id });
+ return { threadId, messageId: answer[0].id };
+ });
+}
+
+export interface ClaimedChat {
+ id: number;
+ threadId: string;
+ prompt: string;
+ systemPrompt: string;
+ attempts: number;
+ sessionId: string | null;
+}
+
+// The claim's raw row: the answer plus what the prompts are built from.
+interface ClaimedRow {
+ id: number;
+ threadId: string;
+ attempts: number;
+ requesterUserId: string;
+ requesterName: string | null;
+ sessionId: string | null;
+}
+
+// Fails answers handed out too many times without a result, so a chat whose runner
+// keeps dying ends visibly instead of being served forever. Called once per claim, not
+// once per look at the feed: a claim waits for work and looks many times.
+async function expireExhausted(agentId: number): Promise<void> {
+ await db
+ .update(agentChatMessage)
+ .set({
+ status: 'failed',
+ lastError: 'Runner did not report a result',
+ finishedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(agentChatMessage.agentId, agentId),
+ inArray(agentChatMessage.status, LIVE_STATUSES),
+ sql`${agentChatMessage.attempts} >= ${agentChatConfig.maxAttempts()}`,
+ sql`${agentChatMessage.nextAttemptAt} <= now()`,
+ ),
+ );
+}
+
+// Waits for the agent's next answer to produce and hands it over under a lease, or null
+// when none turns up in time. Waiting instead of polling is what makes an answer start
+// the moment it is sent.
+export async function claimNextMessage(agent: RunnerAgent): Promise<ClaimedChat | null> {
+ await touchRunner(agent.id);
+ await expireExhausted(agent.id);
+ const deadline = Date.now() + agentChatConfig.claimWaitMs();
+ for (;;) {
+ const message = await claimMessage(agent);
+ if (message) return message;
+ if (Date.now() >= deadline) return null;
+ await sleep(agentChatConfig.claimPollMs());
+ }
+}
+
+// Takes the agent's next due answer, or null when it has none. Claiming clears whatever
+// a previous attempt produced: the answer is generated again from the start, and the
+// browser would otherwise read the abandoned half twice.
+async function claimMessage(agent: RunnerAgent): Promise<ClaimedChat | null> {
+ const rows = await db.execute(sql`
+ UPDATE agent_chat_message m
+ SET attempts = m.attempts + 1,
+ status = 'streaming',
+ content = '',
+ started_at = coalesce(m.started_at, now()),
+ next_attempt_at = now() + make_interval(secs => ${agentChatConfig.leaseSeconds()})
+ WHERE m.id = (
+ SELECT id FROM agent_chat_message q
+ WHERE q.agent_id = ${agent.id}
+ AND q.role = 'assistant'
+ AND q.status IN ('pending', 'streaming')
+ AND q.next_attempt_at <= now()
+ ORDER BY q.next_attempt_at, q.id
+ FOR UPDATE SKIP LOCKED
+ LIMIT 1
+ )
+ RETURNING
+ m.id,
+ m.thread_id AS "threadId",
+ m.attempts,
+ (SELECT user_id FROM agent_chat_thread t WHERE t.id = m.thread_id) AS "requesterUserId",
+ (SELECT u.name FROM agent_chat_thread t JOIN "user" u ON u.id = t.user_id
+ WHERE t.id = m.thread_id) AS "requesterName",
+ (SELECT cli_session_id FROM agent_chat_thread t WHERE t.id = m.thread_id) AS "sessionId"
+ `);
+ const row = (rows as unknown as ClaimedRow[])[0];
+ if (!row) return null;
+ await db.delete(agentChatEvent).where(eq(agentChatEvent.messageId, row.id));
+ // A thread bound to a live session on the runner's machine needs neither the earlier
+ // turns nor the system prompt again: that session already holds both, in fuller form
+ // than the transcript here keeps them.
+ const resumed = row.sessionId !== null;
+ const history = await readHistory(row.threadId, row.id, resumed);
+ const question = history.pop()?.content ?? '';
+ return {
+ id: row.id,
+ threadId: row.threadId,
+ prompt: resumed ? question : frameChatPrompt(history, question),
+ systemPrompt: resumed
+ ? ''
+ : buildSystemPrompt(agent, {
+ name: row.requesterName ?? 'the member',
+ userId: row.requesterUserId,
+ }),
+ attempts: row.attempts,
+ sessionId: row.sessionId,
+ };
+}
+
+// Binds a thread to the session its runner started, addressed through the answer being
+// produced so the runner needs no separate lookup. The first report wins: a retry of the
+// same answer starts a new session, and rebinding would strand the one already recorded.
+export async function setThreadSession(
+ agentId: number,
+ messageId: number,
+ sessionId: string,
+): Promise<void> {
+ await db
+ .update(agentChatThread)
+ .set({ cliSessionId: sessionId })
+ .where(
+ and(
+ sql`${agentChatThread.cliSessionId} IS NULL`,
+ inArray(
+ agentChatThread.id,
+ db
+ .select({ id: agentChatMessage.threadId })
+ .from(agentChatMessage)
+ .where(and(eq(agentChatMessage.id, messageId), eq(agentChatMessage.agentId, agentId))),
+ ),
+ ),
+ );
+}
+
+// The turns before the claimed answer, oldest last, capped at the configured depth. The
+// last of them is the message being answered. `questionOnly` takes just that one, for a
+// thread whose session already remembers everything before it.
+async function readHistory(
+ threadId: string,
+ beforeMessageId: number,
+ questionOnly: boolean,
+): Promise<{ role: string; content: string }[]> {
+ const rows = await db
+ .select({ role: agentChatMessage.role, content: agentChatMessage.content })
+ .from(agentChatMessage)
+ .where(
+ and(
+ eq(agentChatMessage.threadId, threadId),
+ sql`${agentChatMessage.id} < ${beforeMessageId}`,
+ sql`length(${agentChatMessage.content}) > 0`,
+ ),
+ )
+ .orderBy(desc(agentChatMessage.id))
+ .limit(questionOnly ? 1 : agentChatConfig.historyMessages());
+ return rows.reverse();
+}
+
+// What the agent is told before the task: the project, that a person is waiting in a
+// chat, who that person is, and last the operator's own instructions, which therefore
+// win over the generic parts.
+function buildSystemPrompt(
+ agent: RunnerAgent,
+ requester: { name: string; userId: string },
+): string {
+ const instructions = agent.instructions?.trim();
+ return (
+ projectPreamble({ key: agent.projectKey, name: agent.projectName }) +
+ chatModePreamble() +
+ peoplePreamble({ requester }) +
+ (instructions ? `## Instructions\n${instructions}\n` : '')
+ );
+}
+
+// The counterpart of runModePreamble for a chat: here a human is present, so the
+// autonomous-run rule about never asking questions does not apply.
+function chatModePreamble(): string {
+ return [
+ '## Run mode',
+ 'You are in a chat with a person who is waiting for your reply in the app. What you',
+ 'print is what they read, so answer them directly and keep it short. Ask a clarifying',
+ 'question when you genuinely need one — unlike an autonomous run, someone is there to',
+ 'answer it.',
+ '',
+ '',
+ ].join('\n');
+}
+
+function frameChatPrompt(history: { role: string; content: string }[], prompt: string): string {
+ const lines: string[] = [];
+ if (history.length > 0) {
+ lines.push('Earlier in this conversation:', '');
+ for (const m of history) {
+ lines.push(`${m.role === 'user' ? 'Person' : 'You'}: ${m.content}`, '');
+ }
+ }
+ lines.push('The person writes:', '', prompt);
+ return lines.join('\n');
+}
+
+// When a claimed answer falls back to the feed unless the runner reports again.
+function leaseUntil() {
+ return sql`now() + make_interval(secs => ${agentChatConfig.leaseSeconds()})`;
+}
+
+// The answer a runner call addresses: this agent's, and not finished yet.
+function liveAnswer(agentId: number, messageId: number) {
+ return and(
+ eq(agentChatMessage.id, messageId),
+ eq(agentChatMessage.agentId, agentId),
+ inArray(agentChatMessage.status, LIVE_STATUSES),
+ );
+}
+
+// Records what the runner reported. Text deltas also grow the answer's own text, so the
+// transcript reads correctly even if the browser never watched the stream. False when
+// the answer is not this agent's or is already finished.
+export async function appendEvents(
+ agentId: number,
+ messageId: number,
+ events: AgUiEventBody[],
+): Promise<boolean> {
+ const claimed = await db
+ .update(agentChatMessage)
+ .set({
+ content: sql`left(${agentChatMessage.content} || ${textOf(events)}, ${ANSWER_LIMIT})`,
+ nextAttemptAt: leaseUntil(),
+ })
+ .where(liveAnswer(agentId, messageId))
+ .returning({ id: agentChatMessage.id });
+ if (!claimed[0]) return false;
+ await db.insert(agentChatEvent).values(events.map((event) => ({ messageId, payload: event })));
+ return true;
+}
+
+function textOf(events: AgUiEventBody[]): string {
+ return events.map((e) => (e.type === 'TEXT_MESSAGE_CONTENT' ? e.delta : '')).join('');
+}
+
+export async function heartbeatMessage(agentId: number, messageId: number): Promise<boolean> {
+ await touchRunner(agentId);
+ const rows = await db
+ .update(agentChatMessage)
+ .set({ nextAttemptAt: leaseUntil() })
+ .where(liveAnswer(agentId, messageId))
+ .returning({ id: agentChatMessage.id });
+ return rows.length > 0;
+}
+
+// Closes the answer. A failure is terminal: the runner ran the command and it failed,
+// so serving the same answer again would only repeat it.
+export async function finishMessage(
+ agentId: number,
+ messageId: number,
+ result: { status: 'success' | 'failed'; error?: string | null },
+): Promise<boolean> {
+ await touchRunner(agentId);
+ const rows = await db
+ .update(agentChatMessage)
+ .set({
+ status: result.status,
+ lastError:
+ result.status === 'failed' ? (result.error?.slice(0, 500) ?? 'Answer failed') : null,
+ finishedAt: new Date(),
+ })
+ .where(liveAnswer(agentId, messageId))
+ .returning({ id: agentChatMessage.id });
+ return rows.length > 0;
+}
+
+export interface ChatEventPage {
+ items: { id: number; event: AgUiEventBody }[];
+ status: ChatMessageStatus;
+ error: string | null;
+ nextCursor: number | null;
+ // Whether reading again from nextCursor returns more of what is already stored, as
+ // opposed to waiting for the agent to say something new.
+ hasMore: boolean;
+}
+
+// The answer's events after the given cursor, with the answer's own state so a reader
+// knows whether more are coming. Null when the answer is not the caller's.
+export async function readEvents(
+ messageId: number,
+ agentId: number,
+ userId: string,
+ after = 0,
+): Promise<ChatEventPage | null> {
+ const rows = await db
+ .select({
+ status: agentChatMessage.status,
+ lastError: agentChatMessage.lastError,
+ })
+ .from(agentChatMessage)
+ .innerJoin(agentChatThread, eq(agentChatThread.id, agentChatMessage.threadId))
+ .where(
+ and(
+ eq(agentChatMessage.id, messageId),
+ eq(agentChatMessage.agentId, agentId),
+ eq(agentChatThread.userId, userId),
+ ),
+ )
+ .limit(1);
+ const message = rows[0];
+ if (!message) return null;
+ const eventRows = await db
+ .select({ id: agentChatEvent.id, payload: agentChatEvent.payload })
+ .from(agentChatEvent)
+ .where(and(eq(agentChatEvent.messageId, messageId), gt(agentChatEvent.id, after)))
+ .orderBy(asc(agentChatEvent.id))
+ .limit(EVENT_PAGE + 1);
+ const hasMore = eventRows.length > EVENT_PAGE;
+ const events = hasMore ? eventRows.slice(0, EVENT_PAGE) : eventRows;
+ return {
+ items: events.map((e) => ({ id: e.id, event: e.payload as AgUiEventBody })),
+ status: message.status as ChatMessageStatus,
+ error: message.lastError,
+ nextCursor: events.at(-1)?.id ?? null,
+ hasMore,
+ };
+}
diff --git a/apps/api/src/modules/agents/core/__tests__/integration/agent-threads.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/agent-threads.test.ts
index 5d319370..864b7f9a 100644
--- a/apps/api/src/modules/agents/core/__tests__/integration/agent-threads.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/integration/agent-threads.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach } from 'bun:test';
+import type { MastraMessagePart } from '@mastra/core/agent/message-list';
import { authedApi, type Api } from '#tests/helpers/app';
import { signUpTestUser } from '#tests/helpers/auth';
import { resetDb } from '#tests/helpers/db';
@@ -40,7 +41,7 @@ async function seedThread(
resourceId: string,
agent: { id: number; projectId: number },
title: string,
- turns: Array<{ role: 'user' | 'assistant'; text: string }> = [],
+ turns: Array<{ role: 'user' | 'assistant'; text: string; parts?: MastraMessagePart[] }> = [],
) {
await ensureThread(
threadId,
@@ -61,13 +62,17 @@ async function seedThread(
createdAt: new Date(t++),
content: {
format: 2 as const,
- parts: [{ type: 'text' as const, text: turn.text }],
+ parts: turn.parts ?? [{ type: 'text' as const, text: turn.text }],
content: turn.text,
},
})),
});
}
+function textOf(message: { parts: Array<{ type: string; text?: string }> }): string {
+ return message.parts.map((part) => (part.type === 'text' ? part.text : '')).join('');
+}
+
// Moves a seeded thread a minute into the past. Threads seeded one after another are
// stamped with the same millisecond, and the history list orders by updatedAt, so
// without this the expected order is not the only one the endpoint may return.
@@ -167,9 +172,9 @@ describe('agent chat history', () => {
.threads({ threadId: 't1' })
.messages.get();
expect(res.status).toBe(200);
- expect(res.data!.items.map((m) => ({ role: m.role, text: m.text }))).toEqual([
- { role: 'user', text: 'list 5 posts' },
- { role: 'assistant', text: 'here they are' },
+ expect(res.data!.items.map((m) => ({ role: m.role, parts: m.parts }))).toEqual([
+ { role: 'user', parts: [{ type: 'text', text: 'list 5 posts' }] },
+ { role: 'assistant', parts: [{ type: 'text', text: 'here they are' }] },
]);
expect(res.data!.items.every((message) => !Number.isNaN(Date.parse(message.createdAt)))).toBe(
true,
@@ -177,6 +182,48 @@ describe('agent chat history', () => {
expect(res.data!.nextPage).toBeNull();
});
+ it('keeps a tool call between the stretches of text around it', async () => {
+ const { owner, asOwner } = await setup();
+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');
+ await seedThread('t-tools', owner.userId, agent, 'tools', [
+ { role: 'user', text: 'what is left?' },
+ {
+ role: 'assistant',
+ text: 'Looking.Two things.',
+ parts: [
+ { type: 'text', text: 'Looking.' },
+ {
+ type: 'tool-invocation',
+ toolInvocation: {
+ toolCallId: 'call-1',
+ toolName: 'list_issues',
+ args: { status: 'open', __mastraMetadata: { runId: 'r1' } },
+ state: 'result',
+ result: 'two',
+ },
+ },
+ { type: 'text', text: 'Two things.' },
+ ],
+ },
+ ]);
+
+ const res = await agents(asOwner)({ agentId: agent.id })
+ .threads({ threadId: 't-tools' })
+ .messages.get();
+ expect(res.status).toBe(200);
+ expect(res.data!.items[1]!.parts).toEqual([
+ { type: 'text', text: 'Looking.' },
+ {
+ type: 'tool',
+ toolCallId: 'call-1',
+ toolName: 'list_issues',
+ args: '{"status":"open"}',
+ result: 'two',
+ },
+ { type: 'text', text: 'Two things.' },
+ ]);
+ });
+
it('returns an empty transcript for an owned thread with no messages', async () => {
const { owner, asOwner } = await setup();
const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');
@@ -203,15 +250,15 @@ describe('agent chat history', () => {
.messages.get();
expect(latest.status).toBe(200);
expect(latest.data!.items).toHaveLength(25);
- expect(latest.data!.items[0]!.text).toBe('message 2');
- expect(latest.data!.items[24]!.text).toBe('message 26');
+ expect(textOf(latest.data!.items[0]!)).toBe('message 2');
+ expect(textOf(latest.data!.items[24]!)).toBe('message 26');
expect(latest.data!.nextPage).toBe(1);
const earlier = await agents(asOwner)({ agentId: agent.id })
.threads({ threadId: 'long' })
.messages.get({ query: { page: 1 } });
expect(earlier.status).toBe(200);
- expect(earlier.data!.items.map((message) => message.text)).toEqual(['message 0', 'message 1']);
+ expect(earlier.data!.items.map(textOf)).toEqual(['message 0', 'message 1']);
expect(earlier.data!.nextPage).toBeNull();
});
diff --git a/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts
index df1f0f2e..d3735ab4 100644
--- a/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts
+++ b/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts
@@ -544,6 +544,9 @@ describe('ai agents', () => {
'GET /projects/:projectKey/ai-agents/:agentId/threads',
'GET /projects/:projectKey/ai-agents/:agentId/threads/:threadId/messages',
'DELETE /projects/:projectKey/ai-agents/:agentId/threads/:threadId',
+ 'POST /projects/:projectKey/ai-agents/:agentId/chat',
+ 'GET /projects/:projectKey/ai-agents/:agentId/chat/:messageId/events',
+ 'GET /projects/:projectKey/ai-agents/:agentId/chat/:messageId/stream',
]);
});
});
diff --git a/apps/api/src/modules/agents/core/index.ts b/apps/api/src/modules/agents/core/index.ts
index b54648d5..1c819be4 100644
--- a/apps/api/src/modules/agents/core/index.ts
+++ b/apps/api/src/modules/agents/core/index.ts
@@ -1,5 +1,5 @@
import { Elysia, t } from 'elysia';
-import { noContent } from '#shared/http';
+import { noContent, sseFrame, sseResponse } from '#shared/http';
import { guards } from '#shared/guards';
import { authContext } from '#shared/auth-context';
import { requireUser } from '#shared/access';
@@ -13,6 +13,7 @@ import {
deleteAgent,
regenerateKey,
getAgentById,
+ type AgentKind,
} from './service';
import {
AgentRunPageResponse,
@@ -31,12 +32,17 @@ import {
threadParams,
updateAgentBody,
} from './model';
-import { runAgent, streamAgent, type RunOpts } from './runtime';
+import { runAgent, streamAgent, type AgentRunEvent, type RunOpts } from './runtime';
import { peoplePreamble } from './prompt/run-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';
+import {
+ listThreads as listExternalThreads,
+ getThreadMessages as getExternalThreadMessages,
+ deleteThread as deleteExternalThread,
+} from '../chat/service';
// 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
@@ -56,6 +62,23 @@ function chatRunOpts(user: SessionUser | null, agentId: number, threadId?: strin
};
}
+async function* runFrames(events: AsyncIterable<AgentRunEvent>): AsyncGenerator<string> {
+ for await (const event of events) yield sseFrame(event);
+}
+
+// Where a thread of this agent is kept: an external agent's conversations are held by
+// the chat feed its runner drains, an internal agent's by the runtime memory. The routes
+// below serve both through the same shapes.
+function threadStore(kind: AgentKind) {
+ return kind === 'external'
+ ? {
+ list: listExternalThreads,
+ messages: getExternalThreadMessages,
+ remove: deleteExternalThread,
+ }
+ : { list: listChatThreads, messages: getChatThreadMessages, remove: deleteChatThread };
+}
+
export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['AI Agents'] } })
.use(authContext)
.use(guards)
@@ -228,33 +251,17 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
// agent is doing as it happens. Errors mid-stream arrive as an `error` event.
.post(
'/projects/:projectKey/ai-agents/:agentId/run/stream',
- ({ params, project, body, user }) => {
- const events = streamAgent(
- params.agentId,
- project.id,
- body.prompt,
- chatRunOpts(user, params.agentId, body.threadId),
- );
- const encoder = new TextEncoder();
- const stream = new ReadableStream<Uint8Array>({
- async start(controller) {
- for await (const event of events) {
- // The consumer cancelled (e.g. closed the chat): stop consuming the
- // agent stream instead of enqueuing onto a closed controller.
- if (controller.desiredSize === null) return;
- controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
- }
- controller.close();
- },
- });
- return new Response(stream, {
- headers: {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- Connection: 'keep-alive',
- },
- });
- },
+ ({ params, project, body, user }) =>
+ sseResponse(
+ runFrames(
+ streamAgent(
+ params.agentId,
+ project.id,
+ body.prompt,
+ chatRunOpts(user, params.agentId, body.threadId),
+ ),
+ ),
+ ),
{
body: runBody,
params: agentParams,
@@ -280,7 +287,7 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
const caller = requireUser(user);
const agent = await getAgentById(params.agentId, project.id);
if (!agent) throw new HttpError(404, 'Agent not found');
- return listChatThreads(caller.id, params.agentId);
+ return threadStore(agent.kind).list(caller.id, params.agentId);
},
{
params: agentParams,
@@ -298,7 +305,11 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
const caller = requireUser(user);
const agent = await getAgentById(params.agentId, project.id);
if (!agent) throw new HttpError(404, 'Agent not found');
- const messages = await getChatThreadMessages(params.threadId, caller.id, query.page ?? 0);
+ const messages = await threadStore(agent.kind).messages(
+ params.threadId,
+ caller.id,
+ query.page,
+ );
if (messages === null) throw new HttpError(404, 'Thread not found');
return messages;
},
@@ -319,9 +330,8 @@ export const aiAgentRoutes = new Elysia({ name: 'ai-agents', detail: { tags: ['A
const caller = requireUser(user);
const agent = await getAgentById(params.agentId, project.id);
if (!agent) throw new HttpError(404, 'Agent not found');
- if (!(await deleteChatThread(params.threadId, caller.id))) {
- throw new HttpError(404, 'Thread not found');
- }
+ const deleted = await threadStore(agent.kind).remove(params.threadId, caller.id);
+ if (!deleted) throw new HttpError(404, 'Thread not found');
return noContent();
},
{
diff --git a/apps/api/src/modules/agents/core/model.ts b/apps/api/src/modules/agents/core/model.ts
index cf4a3bf3..778e3c44 100644
--- a/apps/api/src/modules/agents/core/model.ts
+++ b/apps/api/src/modules/agents/core/model.ts
@@ -164,17 +164,38 @@ export const AgentRunPageResponse = t.Object({
export const ChatThreadResponse = t.Object({
id: t.String(),
title: t.Nullable(t.String()),
+ cliSessionId: t.Nullable(
+ t.String({
+ description:
+ "The coding agent session an external agent's runner keeps for this thread on its " +
+ 'own machine. Always null for an internal agent, which runs in this process.',
+ }),
+ ),
createdAt: t.String(),
updatedAt: t.String(),
});
+// One piece of a message (ChatPart): a stretch of text, or a tool the agent called
+// between two of them, with what it was given and what it answered where the agent
+// reported them.
+const ChatPartResponse = t.Union([
+ t.Object({ type: t.Literal('text'), text: t.String() }),
+ t.Object({
+ type: t.Literal('tool'),
+ toolCallId: t.String(),
+ toolName: t.String(),
+ args: t.Optional(t.String()),
+ result: t.Optional(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(),
+ parts: t.Array(ChatPartResponse),
createdAt: t.String(),
}),
),
diff --git a/apps/api/src/modules/agents/core/runtime/index.ts b/apps/api/src/modules/agents/core/runtime/index.ts
index 1bd5dbf3..bbde8174 100644
--- a/apps/api/src/modules/agents/core/runtime/index.ts
+++ b/apps/api/src/modules/agents/core/runtime/index.ts
@@ -9,6 +9,7 @@ import { buildRouteTools } from './tools/route-tools';
import { buildLocalTools } from './tools/local';
import { buildSkillTool, skillsPreamble } from './skill-runtime';
import { buildMemory, ensureThread, DEFAULT_LAST_MESSAGES } from './memory';
+import { toolArgsText, toolText } from '../../chat-parts';
import { isChatThreadId, newChatThreadId } from './thread-ids';
import { errorMessage } from '../helpers/errors';
import { projectPreamble } from '../prompt/framing';
@@ -65,8 +66,8 @@ async function resolveModel(row: AiAgentRow): Promise<ModelConfig> {
// and carries the conversation thread id; `error` reports a failure mid-stream.
export type AgentRunEvent =
| { type: 'text'; value: string }
- | { type: 'tool-start'; toolCallId: string; toolName: string }
- | { type: 'tool-end'; toolCallId: string; toolName: string }
+ | { type: 'tool-start'; toolCallId: string; toolName: string; args?: string }
+ | { type: 'tool-end'; toolCallId: string; toolName: string; result?: string }
| { type: 'done'; threadId: string | null }
| { type: 'error'; message: string };
@@ -147,6 +148,7 @@ export async function* streamAgent(
type: 'tool-start',
toolCallId: chunk.payload.toolCallId,
toolName: chunk.payload.toolName,
+ args: toolArgsText(chunk.payload.args),
};
break;
case 'tool-result':
@@ -154,6 +156,7 @@ export async function* streamAgent(
type: 'tool-end',
toolCallId: chunk.payload.toolCallId,
toolName: chunk.payload.toolName,
+ result: toolText(chunk.payload.result),
};
break;
case 'error':
diff --git a/apps/api/src/modules/agents/core/runtime/memory.ts b/apps/api/src/modules/agents/core/runtime/memory.ts
index 16c61e62..61834e83 100644
--- a/apps/api/src/modules/agents/core/runtime/memory.ts
+++ b/apps/api/src/modules/agents/core/runtime/memory.ts
@@ -1,6 +1,8 @@
import { Memory } from '@mastra/memory';
import { PostgresStore } from '@mastra/pg';
import { toIso } from '../helpers/dates';
+import { appendTextPart, toolArgsText, toolText } from '../../chat-parts';
+import type { ChatMessageDTO, ChatMessagePage, ChatPart, ChatThreadSummary } from '../../model';
// Conversation memory for internal agents. Threads and their messages are
// persisted in a Postgres-backed store (Mastra manages its own tables), reusing
@@ -100,14 +102,6 @@ export async function deleteThreadsWhere(
return threads.length;
}
-// One chat thread in the history list.
-export type ChatThreadSummary = {
- id: string;
- title: string | null;
- createdAt: string;
- updatedAt: string;
-};
-
// Lists a user's chat threads with one agent, newest first. Scoped by resourceId
// (the caller) and the agent binding in metadata, so a caller only ever sees their
// own conversations with that agent.
@@ -123,26 +117,12 @@ export async function listChatThreads(
return res.threads.map((t) => ({
id: t.id,
title: t.title && t.title.length > 0 ? t.title : null,
+ cliSessionId: null,
createdAt: toIso(t.createdAt),
updatedAt: toIso(t.updatedAt),
}));
}
-// One message in a restored conversation. Only user and assistant turns are
-// returned; tool and system messages are omitted (the UI shows text, not the raw
-// tool traffic).
-export type ChatMessageDTO = {
- id: string;
- role: 'user' | 'assistant';
- text: string;
- createdAt: string;
-};
-
-export type ChatMessagePage = {
- items: ChatMessageDTO[];
- nextPage: number | null;
-};
-
// Loads the transcript of one chat thread for the given owner. Returns null when
// the thread does not exist or is not owned by resourceId (so the caller maps it to
// a 404). Messages come back oldest first.
@@ -165,32 +145,43 @@ export async function getChatThreadMessages(
const out: ChatMessageDTO[] = [];
for (const m of messages) {
if (m.role !== 'user' && m.role !== 'assistant') continue;
- const text = messageText(m.content);
- if (text) out.push({ id: m.id, role: m.role, text, createdAt: toIso(m.createdAt) });
+ const parts = messageParts(m.content);
+ if (parts.length > 0) {
+ out.push({ id: m.id, role: m.role, parts, createdAt: toIso(m.createdAt) });
+ }
}
return { items: out, nextPage: hasMore ? page + 1 : null };
}
-// Extracts the plain text of a Mastra v2 message: the concatenation of its text
-// parts, falling back to the flat content string.
-function messageText(content: unknown): string {
- if (content && typeof content === 'object') {
- const parts = (content as { parts?: unknown }).parts;
- if (Array.isArray(parts)) {
- const text = parts
- .filter(
- (p): p is { type: string; text: string } =>
- !!p &&
- typeof p === 'object' &&
- (p as { type?: unknown }).type === 'text' &&
- typeof (p as { text?: unknown }).text === 'string',
- )
- .map((p) => p.text)
- .join('');
- if (text) return text;
+// As much of a stored Mastra v2 message part as the chat reads.
+type StoredPart = {
+ type?: unknown;
+ text?: unknown;
+ toolInvocation?: { toolCallId?: unknown; toolName?: unknown; args?: unknown; result?: unknown };
+};
+
+// Reads a Mastra v2 message into the parts the chat shows: its text and the tool calls
+// it made, in the order they are stored. Falls back to the flat content string of a
+// message kept without parts.
+function messageParts(content: unknown): ChatPart[] {
+ if (!content || typeof content !== 'object') return [];
+ const { parts, content: flat } = content as { parts?: unknown; content?: unknown };
+ const out: ChatPart[] = [];
+ for (const part of Array.isArray(parts) ? parts : []) {
+ if (!part || typeof part !== 'object') continue;
+ const { type, text, toolInvocation } = part as StoredPart;
+ if (type === 'text' && typeof text === 'string') {
+ appendTextPart(out, text);
+ } else if (type === 'tool-invocation' && typeof toolInvocation?.toolName === 'string') {
+ out.push({
+ type: 'tool',
+ toolCallId: String(toolInvocation.toolCallId ?? ''),
+ toolName: toolInvocation.toolName,
+ args: toolArgsText(toolInvocation.args),
+ result: toolText(toolInvocation.result),
+ });
}
- const flat = (content as { content?: unknown }).content;
- if (typeof flat === 'string') return flat;
}
- return '';
+ if (out.length > 0) return out;
+ return typeof flat === 'string' && flat ? [{ type: 'text', text: flat }] : [];
}
diff --git a/apps/api/src/modules/agents/model.ts b/apps/api/src/modules/agents/model.ts
index 9fea0656..3b0a5ec8 100644
--- a/apps/api/src/modules/agents/model.ts
+++ b/apps/api/src/modules/agents/model.ts
@@ -15,3 +15,45 @@ export const agentRunTrigger = t.Union([
]);
export type AgentRunTrigger = typeof agentRunTrigger.static;
+
+// The transcript of a chat, shared by both kinds of agent: an internal agent's
+// conversations are held by the runtime's memory, an external agent's by the feed its
+// runner drains, and the routes serving them return these shapes either way.
+
+// One chat thread in the history list. `cliSessionId` belongs to an external agent's
+// threads, where a runner keeps the session; an internal agent runs here and has none.
+export type ChatThreadSummary = {
+ id: string;
+ title: string | null;
+ cliSessionId: string | null;
+ createdAt: string;
+ updatedAt: string;
+};
+
+// One piece of a message, in the order the agent produced it: what it wrote, and the
+// tools it called between one stretch of text and the next. A call carries what it was
+// given and what it answered where those are known — an agent that reports neither
+// leaves both unset.
+export type ChatPart =
+ | { type: 'text'; text: string }
+ | {
+ type: 'tool';
+ toolCallId: string;
+ toolName: string;
+ args?: string;
+ result?: string;
+ };
+
+// One message of a conversation. Only user and assistant turns are returned; a tool
+// turn is folded into the parts of the turn that called it.
+export type ChatMessageDTO = {
+ id: string;
+ role: 'user' | 'assistant';
+ parts: ChatPart[];
+ createdAt: string;
+};
+
+export type ChatMessagePage = {
+ items: ChatMessageDTO[];
+ nextPage: number | null;
+};
diff --git a/apps/api/src/modules/agents/runner-auth.ts b/apps/api/src/modules/agents/runner-auth.ts
new file mode 100644
index 00000000..e02aa4e4
--- /dev/null
+++ b/apps/api/src/modules/agents/runner-auth.ts
@@ -0,0 +1,21 @@
+import { Elysia } from 'elysia';
+import { requireUser } from '#shared/access';
+import { authContext } from '#shared/auth-context';
+import { HttpError } from '#shared/lib';
+import { getRunnerAgent } from './runner/service';
+
+// Resolves the agent from the caller's API key, so a runner can only ever reach its own
+// work. Used by both feeds it drains — the run queue and the chat. Set
+// `runnerAgent: true` in the route options and read `agent` in the handler.
+export const runnerAuth = new Elysia({ name: 'runner-auth' }).use(authContext).macro({
+ runnerAgent(_enabled: boolean) {
+ return {
+ async resolve({ user }) {
+ const agent = await getRunnerAgent(requireUser(user).id);
+ if (!agent) throw new HttpError(403, 'Only an agent key can drain an agent feed');
+ if (agent.kind !== 'external') throw new HttpError(403, 'Internal agents run in-process');
+ return { agent };
+ },
+ };
+ },
+});
diff --git a/apps/api/src/modules/agents/runner/index.ts b/apps/api/src/modules/agents/runner/index.ts
index 27e7366b..0b81e545 100644
--- a/apps/api/src/modules/agents/runner/index.ts
+++ b/apps/api/src/modules/agents/runner/index.ts
@@ -1,11 +1,10 @@
import { Elysia, t } from 'elysia';
-import { authContext } from '#shared/auth-context';
-import { requireUser } from '#shared/access';
import { noContent } from '#shared/http';
import { HttpError } from '#shared/lib';
import { commonErrors, errors } from '#shared/responses';
+import { runnerAuth } from '../runner-auth';
import { ClaimResponse, resultBody, runParams } from './model';
-import { claimRunnerRun, finishRun, getRunnerAgent, heartbeatRun } from './service';
+import { claimRunnerRun, finishRun, heartbeatRun } from './service';
// The queue an external agent's runner drains, authenticated with the agent's own
// API key.
@@ -13,21 +12,7 @@ export const agentRunnerRoutes = new Elysia({
name: 'agent-runner',
detail: { tags: ['Agent Runner'] },
})
- .use(authContext)
- // Resolves the agent from the caller's key, so a runner can only ever reach its own
- // runs. Set `runnerAgent: true` in the route options and read `agent` in the handler.
- .macro({
- runnerAgent(_enabled: boolean) {
- return {
- async resolve({ user }) {
- const agent = await getRunnerAgent(requireUser(user).id);
- if (!agent) throw new HttpError(403, 'Only an agent key can claim runs');
- if (agent.kind !== 'external') throw new HttpError(403, 'Internal agents run in-process');
- return { agent };
- },
- };
- },
- })
+ .use(runnerAuth)
.post('/agent-runs/claim', async ({ agent }) => ({ run: await claimRunnerRun(agent) }), {
runnerAgent: true,
diff --git a/apps/api/src/modules/agents/runner/service.ts b/apps/api/src/modules/agents/runner/service.ts
index b1418f9f..81d4094c 100644
--- a/apps/api/src/modules/agents/runner/service.ts
+++ b/apps/api/src/modules/agents/runner/service.ts
@@ -82,7 +82,8 @@ type ClaimedRow = Omit<RunnerRun, 'systemPrompt'> & {
};
// Records that a runner polled, which is what the UI shows as the agent's presence.
-async function touchRunner(agentId: number): Promise<void> {
+// The chat feed calls it too: both queues are drained by the same runner.
+export async function touchRunner(agentId: number): Promise<void> {
await db.update(aiAgent).set({ lastSeenAt: new Date() }).where(eq(aiAgent.id, agentId));
}
diff --git a/apps/api/src/planner.ts b/apps/api/src/planner.ts
index 34b79026..6fea32c6 100644
--- a/apps/api/src/planner.ts
+++ b/apps/api/src/planner.ts
@@ -30,6 +30,7 @@ import { settingsRoutes } from './settings/routes';
import { godRoutes } from './god/routes';
import { agentScheduleRoutes } from './modules/agents/schedules';
import { agentRunnerRoutes } from './modules/agents/runner';
+import { agentChatRoutes } from './modules/agents/chat';
import { notificationRoutes } from './notifications/routes';
import { notificationSettingsRoutes } from './notification-settings/routes';
import { notificationPreferenceRoutes } from './notification-preferences/routes';
@@ -98,6 +99,7 @@ export const planner = new Elysia({ name: 'planner' })
.use(githubSettingsRoutes)
.use(agentScheduleRoutes)
.use(agentRunnerRoutes)
+ .use(agentChatRoutes)
.use(dashboardRoutes)
.use(noteBoardRoutes)
.use(analyticsRoutes)
diff --git a/apps/api/src/shared/http.ts b/apps/api/src/shared/http.ts
index 013960bb..7b05ec91 100644
--- a/apps/api/src/shared/http.ts
+++ b/apps/api/src/shared/http.ts
@@ -1,3 +1,37 @@
// A 204 No Content response. Elysia serializes returned values, so deletes return
// this explicit empty response instead of a body.
export const noContent = () => new Response(null, { status: 204 });
+
+// One Server-Sent Events frame: the JSON-encoded value, with the event id a client
+// passes back to resume from where it stopped when the caller numbers its events.
+export function sseFrame(data: unknown, id?: number): string {
+ const idLine = id === undefined ? '' : `id: ${id}\n`;
+ return `${idLine}data: ${JSON.stringify(data)}\n\n`;
+}
+
+// Streams frames as Server-Sent Events. Returned as a raw Response, so a route serving
+// one declares `200: t.Any()` — it is not a JSON shape the validator can describe.
+export function sseResponse(frames: AsyncIterable<string>): Response {
+ const encoder = new TextEncoder();
+ const stream = new ReadableStream<Uint8Array>({
+ async start(controller) {
+ for await (const frame of frames) {
+ // The consumer cancelled (e.g. closed the chat): stop consuming the source
+ // instead of enqueuing onto a closed controller.
+ if (controller.desiredSize === null) return;
+ controller.enqueue(encoder.encode(frame));
+ }
+ controller.close();
+ },
+ });
+ return new Response(stream, {
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ Connection: 'keep-alive',
+ // A proxy that buffers the response would hold it back until it ends, which is
+ // the one thing an event stream exists to avoid.
+ 'X-Accel-Buffering': 'no',
+ },
+ });
+}
diff --git a/apps/web/messages/ar/aiChat.json b/apps/web/messages/ar/aiChat.json
index c47ce06b..e83cca20 100644
--- a/apps/web/messages/ar/aiChat.json
+++ b/apps/web/messages/ar/aiChat.json
@@ -1,7 +1,7 @@
{
"noAccess": "مالكش صلاحية توصل لوكلاء الذكاء الاصطناعي في المشروع ده.",
"emptyTitle": "لا يوجد وكلاء للمحادثة",
- "emptyDescription": "الوكلاء الداخليين بس هما اللي تقدر تتكلم معاهم هنا، في وضع الاختبار.",
+ "emptyDescription": "اتكلم مع وكيل من وكلاء المشروع: وكيل داخلي، أو وكيل خارجي من خلال الرانر بتاعه.",
"createAgent": "إنشاء وكيل",
"agents": "الوكلاء",
"agentsAvailable": "{count, plural, zero {مفيش وكلاء متاحين} one {وكيل واحد متاح} two {وكيلين متاحين} few {# وكلاء متاحين} many {# وكيل متاح} other {# وكيل متاح}}",
@@ -9,8 +9,8 @@
"newChat": "محادثة جديدة",
"memoryOff": "الذاكرة معطّلة",
"noAgents": "لا يوجد وكلاء",
- "addInternalAgent": "إضافة وكيل داخلي",
- "noInternalAgents": "لا يوجد وكلاء داخليون للمحادثة بعد.",
+ "addAgent": "إضافة وكيل",
+ "noAgentsYet": "لا يوجد وكلاء للمحادثة بعد.",
"history": "السجلّ",
"backToChat": "العودة إلى المحادثة",
"minimize": "تصغير",
@@ -21,5 +21,8 @@
"deleteThread": "حذف المحادثة",
"deleteThreadConfirm": "سيُحذف «{title}» ورسائله نهائيًا.",
"noThreads": "مفيش محادثات لسه. ابعت رسالة عشان تبدأ واحدة.",
- "noModel": "لم يُحدَّد نموذج"
+ "noModel": "لم يُحدَّد نموذج",
+ "copySession": "نسخ معرّف الجلسة",
+ "sessionLabel": "معرّف الجلسة المحلية",
+ "sessionHint": "الجلسة اللي منفّذ الوكيل بيحتفظ بيها على جهازه. كمّلها هناك عشان تقرأ السجل الكامل بكل استدعاءات الأدوات."
}
diff --git a/apps/web/messages/ar/common.json b/apps/web/messages/ar/common.json
index 70dbf170..d2ba9ecd 100644
--- a/apps/web/messages/ar/common.json
+++ b/apps/web/messages/ar/common.json
@@ -80,9 +80,16 @@
"loadingEarlier": "جارٍ تحميل الرسائل السابقة…",
"messages": "رسائل المحادثة",
"usingTool": "يستخدم {tool}…",
+ "usedTool": "تم استخدام {tool}",
+ "usedTools": "{count, plural, zero {لم تُستخدم أدوات} one {تم استخدام أداة واحدة} two {تم استخدام أداتين} few {تم استخدام # أدوات} many {تم استخدام # أداة} other {تم استخدام # أداة}}",
+ "toolInput": "المدخلات",
+ "toolOutput": "المخرجات",
"thinking": "جارٍ التفكير…",
+ "waitingForRunner": "مستني الرانر…",
"title": "محادثة مع {agent}",
- "unreachable": "تعذّر الوصول إلى الوكيل. حاول مرة أخرى."
+ "unreachable": "تعذّر الوصول إلى الوكيل. حاول مرة أخرى.",
+ "runnerOffline": "المنفّذ (runner) مش متصل",
+ "runnerOfflineHint": "شغّل المنفّذ على جهازك عشان تقدر تكلّم الوكيل ده."
},
"share": {
"createFailed": "تعذّر إنشاء الرابط. حاول مرة أخرى.",
diff --git a/apps/web/messages/ar/settings.json b/apps/web/messages/ar/settings.json
index c8c63d46..6844f02f 100644
--- a/apps/web/messages/ar/settings.json
+++ b/apps/web/messages/ar/settings.json
@@ -163,6 +163,8 @@
"runnerHelpTitle": "إزاي تشغّل منفّذ",
"runnerHelpKey": "انسخ مفتاح واجهة البرمجة (API key) بتاع الوكيل",
"runnerHelpKeyHint": "بيظهر مرة واحدة بس، وقت الإنشاء أو وقت ما تعمل مفتاح جديد.",
+ "runnerHelpMcp": "فعّل MCP للمشروع",
+ "runnerHelpMcpHint": "الإعدادات، خادم MCP. مقفول افتراضيًا، ومن خلاله الوكيل بيقرأ المهام ويكتب النتيجة.",
"runnerHelpTool": "نزّل وكيل البرمجة وسجّل دخوله",
"runnerHelpToolHint": "على الجهاز اللي هيشغّل المنفّذ. المنفّذ مش هيقدر يسجّل دخولك بدالك.",
"runnerHelpRun": "احفظ الملفات في المكان اللي الوكيل هيشتغل فيه",
diff --git a/apps/web/messages/en/aiChat.json b/apps/web/messages/en/aiChat.json
index 5f733585..0327617c 100644
--- a/apps/web/messages/en/aiChat.json
+++ b/apps/web/messages/en/aiChat.json
@@ -1,7 +1,7 @@
{
"noAccess": "You do not have access to AI agents in this project.",
"emptyTitle": "No agents to chat with",
- "emptyDescription": "Only internal agents can chat here, in test mode.",
+ "emptyDescription": "Chat with an agent of this project: an internal one, or an external one through its runner.",
"createAgent": "Create an agent",
"agents": "Agents",
"agentsAvailable": "{count, plural, one {# agent} other {# agents}} available",
@@ -9,8 +9,8 @@
"newChat": "New chat",
"memoryOff": "Memory off",
"noAgents": "No agents",
- "addInternalAgent": "Add an internal agent",
- "noInternalAgents": "No internal agents to chat with yet.",
+ "addAgent": "Add an agent",
+ "noAgentsYet": "No agents to chat with yet.",
"history": "History",
"backToChat": "Back to chat",
"minimize": "Minimize",
@@ -21,5 +21,8 @@
"deleteThread": "Delete conversation",
"deleteThreadConfirm": "“{title}” and its messages are deleted permanently.",
"noThreads": "No conversations yet. Send a message to start one.",
- "noModel": "No model set"
+ "noModel": "No model set",
+ "copySession": "Copy session id",
+ "sessionLabel": "Local session id",
+ "sessionHint": "The session the agent's runner keeps on its own machine. Resume it there to read the full transcript with its tool calls."
}
diff --git a/apps/web/messages/en/common.json b/apps/web/messages/en/common.json
index 9d96bf48..44805386 100644
--- a/apps/web/messages/en/common.json
+++ b/apps/web/messages/en/common.json
@@ -80,9 +80,16 @@
"loadingEarlier": "Loading earlier messages…",
"messages": "Conversation messages",
"usingTool": "Using {tool}…",
+ "usedTool": "Used {tool}",
+ "usedTools": "{count, plural, one {Used # tool} other {Used # tools}}",
+ "toolInput": "Input",
+ "toolOutput": "Output",
"thinking": "Thinking…",
+ "waitingForRunner": "Waiting for the runner…",
"title": "Chat with {agent}",
- "unreachable": "Could not reach the agent. Try again."
+ "unreachable": "Could not reach the agent. Try again.",
+ "runnerOffline": "Runner offline",
+ "runnerOfflineHint": "Start the runner on your machine to chat with this agent."
},
"share": {
"createFailed": "Could not create the link. Try again.",
diff --git a/apps/web/messages/en/settings.json b/apps/web/messages/en/settings.json
index c4b9a10a..585c1dd7 100644
--- a/apps/web/messages/en/settings.json
+++ b/apps/web/messages/en/settings.json
@@ -163,6 +163,8 @@
"runnerHelpTitle": "How to start a runner",
"runnerHelpKey": "Copy the agent's API key",
"runnerHelpKeyHint": "Shown once, at creation or key regeneration.",
+ "runnerHelpMcp": "Turn MCP on for the project",
+ "runnerHelpMcpHint": "Settings, MCP Server. Off by default, and it is how the agent reads issues and posts results.",
"runnerHelpTool": "Install the coding agent and sign in",
"runnerHelpToolHint": "On the machine that will run the runner. The runner cannot sign in for you.",
"runnerHelpRun": "Save the files where the agent should work",
diff --git a/apps/web/messages/ru/aiChat.json b/apps/web/messages/ru/aiChat.json
index f02b4c21..4cb6ae9f 100644
--- a/apps/web/messages/ru/aiChat.json
+++ b/apps/web/messages/ru/aiChat.json
@@ -1,7 +1,7 @@
{
"noAccess": "У вас нет доступа к AI-агентам в этом проекте.",
"emptyTitle": "Нет агентов для чата",
- "emptyDescription": "Здесь могут общаться только внутренние агенты, в тестовом режиме.",
+ "emptyDescription": "Общайтесь с агентом проекта: внутренним или внешним через его раннер.",
"createAgent": "Создать агента",
"agents": "Агенты",
"agentsAvailable": "Доступно: {count, plural, one {# агент} few {# агента} many {# агентов} other {# агента}}",
@@ -9,8 +9,8 @@
"newChat": "Новый чат",
"memoryOff": "Память выключена",
"noAgents": "Нет агентов",
- "addInternalAgent": "Добавьте внутреннего агента",
- "noInternalAgents": "Внутренних агентов для чата пока нет.",
+ "addAgent": "Добавьте агента",
+ "noAgentsYet": "Агентов для чата пока нет.",
"history": "История",
"backToChat": "Назад к чату",
"minimize": "Свернуть",
@@ -21,5 +21,8 @@
"deleteThread": "Удалить разговор",
"deleteThreadConfirm": "«{title}» и его сообщения будут удалены навсегда.",
"noThreads": "Разговоров пока нет. Отправьте сообщение, чтобы начать.",
- "noModel": "Модель не задана"
+ "noModel": "Модель не задана",
+ "copySession": "Скопировать идентификатор сессии",
+ "sessionLabel": "Идентификатор локальной сессии",
+ "sessionHint": "Сессия, которую раннер агента держит на своей машине. Возобновите её там, чтобы прочитать полный лог с вызовами инструментов."
}
diff --git a/apps/web/messages/ru/common.json b/apps/web/messages/ru/common.json
index af9e973a..f105a68f 100644
--- a/apps/web/messages/ru/common.json
+++ b/apps/web/messages/ru/common.json
@@ -80,9 +80,16 @@
"loadingEarlier": "Загрузка предыдущих сообщений…",
"messages": "Сообщения разговора",
"usingTool": "Использует {tool}…",
+ "usedTool": "Использован {tool}",
+ "usedTools": "{count, plural, one {Использован # инструмент} few {Использовано # инструмента} many {Использовано # инструментов} other {Использовано # инструмента}}",
+ "toolInput": "Запрос",
+ "toolOutput": "Ответ",
"thinking": "Думает…",
+ "waitingForRunner": "Ждём раннер…",
"title": "Чат с {agent}",
- "unreachable": "Не удалось связаться с агентом. Попробуйте ещё раз."
+ "unreachable": "Не удалось связаться с агентом. Попробуйте ещё раз.",
+ "runnerOffline": "Раннер не на связи",
+ "runnerOfflineHint": "Запустите раннер на своей машине, чтобы писать этому агенту."
},
"share": {
"createFailed": "Не удалось создать ссылку. Попробуйте ещё раз.",
diff --git a/apps/web/messages/ru/settings.json b/apps/web/messages/ru/settings.json
index fc257d12..db7dec07 100644
--- a/apps/web/messages/ru/settings.json
+++ b/apps/web/messages/ru/settings.json
@@ -163,6 +163,8 @@
"runnerHelpTitle": "Как запустить раннер",
"runnerHelpKey": "Скопируйте API-ключ агента",
"runnerHelpKeyHint": "Показывается один раз — при создании или перевыпуске ключа.",
+ "runnerHelpMcp": "Включите MCP в проекте",
+ "runnerHelpMcpHint": "Настройки, MCP-сервер. По умолчанию выключен — через него агент читает задачи и пишет результат.",
"runnerHelpTool": "Установите CLI агента и войдите в аккаунт",
"runnerHelpToolHint": "На машине, где будет работать раннер. Сам он войти за вас не может.",
"runnerHelpRun": "Сохраните файлы там, где агент должен работать",
diff --git a/apps/web/messages/uk/aiChat.json b/apps/web/messages/uk/aiChat.json
index c706437c..f50107d1 100644
--- a/apps/web/messages/uk/aiChat.json
+++ b/apps/web/messages/uk/aiChat.json
@@ -1,7 +1,7 @@
{
"noAccess": "У вас немає доступу до AI-агентів у цьому проєкті.",
"emptyTitle": "Немає агентів для чату",
- "emptyDescription": "Тут можуть спілкуватися лише внутрішні агенти, у тестовому режимі.",
+ "emptyDescription": "Спілкуйтеся з агентом проєкту: внутрішнім або зовнішнім через його раннер.",
"createAgent": "Створити агента",
"agents": "Агенти",
"agentsAvailable": "Доступно: {count, plural, one {# агент} few {# агенти} many {# агентів} other {# агента}}",
@@ -9,8 +9,8 @@
"newChat": "Новий чат",
"memoryOff": "Памʼять вимкнена",
"noAgents": "Немає агентів",
- "addInternalAgent": "Додайте внутрішнього агента",
- "noInternalAgents": "Внутрішніх агентів для чату ще немає.",
+ "addAgent": "Додайте агента",
+ "noAgentsYet": "Агентів для чату ще немає.",
"history": "Історія",
"backToChat": "Назад до чату",
"minimize": "Згорнути",
@@ -21,5 +21,8 @@
"deleteThread": "Видалити розмову",
"deleteThreadConfirm": "«{title}» та її повідомлення буде видалено назавжди.",
"noThreads": "Розмов ще немає. Надішліть повідомлення, щоб почати.",
- "noModel": "Модель не задано"
+ "noModel": "Модель не задано",
+ "copySession": "Скопіювати ідентифікатор сесії",
+ "sessionLabel": "Ідентифікатор локальної сесії",
+ "sessionHint": "Сесія, яку раннер агента тримає на своїй машині. Відновіть її там, щоб прочитати повний лог із викликами інструментів."
}
diff --git a/apps/web/messages/uk/common.json b/apps/web/messages/uk/common.json
index bcd0145f..1b2c30b8 100644
--- a/apps/web/messages/uk/common.json
+++ b/apps/web/messages/uk/common.json
@@ -80,9 +80,16 @@
"loadingEarlier": "Завантаження попередніх повідомлень…",
"messages": "Повідомлення розмови",
"usingTool": "Використовує {tool}…",
+ "usedTool": "Використано {tool}",
+ "usedTools": "{count, plural, one {Використано # інструмент} few {Використано # інструменти} many {Використано # інструментів} other {Використано # інструмента}}",
+ "toolInput": "Запит",
+ "toolOutput": "Відповідь",
"thinking": "Думає…",
+ "waitingForRunner": "Чекаємо на раннер…",
"title": "Чат з {agent}",
- "unreachable": "Не вдалося зв'язатися з агентом. Спробуйте ще раз."
+ "unreachable": "Не вдалося зв'язатися з агентом. Спробуйте ще раз.",
+ "runnerOffline": "Раннер не на зв’язку",
+ "runnerOfflineHint": "Запустіть раннер на своїй машині, щоб писати цьому агенту."
},
"share": {
"createFailed": "Не вдалося створити посилання. Спробуйте ще раз.",
diff --git a/apps/web/messages/uk/settings.json b/apps/web/messages/uk/settings.json
index 3aefec72..73c6af59 100644
--- a/apps/web/messages/uk/settings.json
+++ b/apps/web/messages/uk/settings.json
@@ -163,6 +163,8 @@
"runnerHelpTitle": "Як запустити раннер",
"runnerHelpKey": "Скопіюйте API-ключ агента",
"runnerHelpKeyHint": "Показується один раз — при створенні або перевипуску ключа.",
+ "runnerHelpMcp": "Увімкніть MCP у проєкті",
+ "runnerHelpMcpHint": "Налаштування, MCP-сервер. Типово вимкнений — через нього агент читає задачі й пише результат.",
"runnerHelpTool": "Встановіть CLI агента та увійдіть в акаунт",
"runnerHelpToolHint": "На машині, де працюватиме раннер. Сам він увійти за вас не може.",
"runnerHelpRun": "Збережіть файли там, де агент має працювати",
diff --git a/apps/web/messages/zh-CN/aiChat.json b/apps/web/messages/zh-CN/aiChat.json
index f8f696bb..748a34d2 100644
--- a/apps/web/messages/zh-CN/aiChat.json
+++ b/apps/web/messages/zh-CN/aiChat.json
@@ -1,7 +1,7 @@
{
"noAccess": "你无权访问此项目的 AI 代理。",
"emptyTitle": "暂无可对话的代理",
- "emptyDescription": "这里只能以测试模式与内置代理对话。",
+ "emptyDescription": "与本项目的代理对话:内置代理,或通过运行器连接的外部代理。",
"createAgent": "新建代理",
"agents": "代理",
"agentsAvailable": "{count, plural, other {# 个代理可用}}",
@@ -9,8 +9,8 @@
"newChat": "新建对话",
"memoryOff": "记忆已关闭",
"noAgents": "暂无代理",
- "addInternalAgent": "添加内置代理",
- "noInternalAgents": "暂无可对话的内置代理。",
+ "addAgent": "添加代理",
+ "noAgentsYet": "暂无可对话的代理。",
"history": "历史记录",
"backToChat": "返回对话",
"minimize": "最小化",
@@ -21,5 +21,8 @@
"deleteThread": "删除对话",
"deleteThreadConfirm": "将永久删除“{title}”及其中的消息。",
"noThreads": "暂无对话。发送消息以开始对话。",
- "noModel": "未设置模型"
+ "noModel": "未设置模型",
+ "copySession": "复制会话 ID",
+ "sessionLabel": "本地会话 ID",
+ "sessionHint": "智能体运行器在自己机器上保留的会话。在那里恢复它,可查看包含工具调用的完整记录。"
}
diff --git a/apps/web/messages/zh-CN/common.json b/apps/web/messages/zh-CN/common.json
index e204ecd5..393fe7fa 100644
--- a/apps/web/messages/zh-CN/common.json
+++ b/apps/web/messages/zh-CN/common.json
@@ -80,9 +80,16 @@
"loadingEarlier": "正在加载更早的消息…",
"messages": "对话消息",
"usingTool": "正在使用 {tool}…",
+ "usedTool": "已使用 {tool}",
+ "usedTools": "{count, plural, other {已使用 # 个工具}}",
+ "toolInput": "输入",
+ "toolOutput": "输出",
"thinking": "正在思考…",
+ "waitingForRunner": "正在等待运行器…",
"title": "与 {agent} 对话",
- "unreachable": "无法连接代理,请重试。"
+ "unreachable": "无法连接代理,请重试。",
+ "runnerOffline": "运行器未连接",
+ "runnerOfflineHint": "在你的机器上启动运行器,才能与该智能体聊天。"
},
"share": {
"createFailed": "无法创建链接,请重试。",
diff --git a/apps/web/messages/zh-CN/settings.json b/apps/web/messages/zh-CN/settings.json
index 26092ed4..bfacd294 100644
--- a/apps/web/messages/zh-CN/settings.json
+++ b/apps/web/messages/zh-CN/settings.json
@@ -163,6 +163,8 @@
"runnerHelpTitle": "如何启动运行器",
"runnerHelpKey": "复制智能体的 API 密钥",
"runnerHelpKeyHint": "只显示一次——创建或重新生成密钥时。",
+ "runnerHelpMcp": "为项目开启 MCP",
+ "runnerHelpMcpHint": "设置、MCP 服务器。默认关闭,智能体通过它读取事项并写回结果。",
"runnerHelpTool": "安装智能体 CLI 并登录",
"runnerHelpToolHint": "在将要运行运行器的机器上。运行器无法替你登录。",
"runnerHelpRun": "把这些文件保存到智能体要工作的目录",
diff --git a/apps/web/package.json b/apps/web/package.json
index 69eba984..e8ffd121 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -51,6 +51,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^4.4.0",
+ "highlight.js": "~11.11.0",
"inter-ui": "^4.1.1",
"isomorphic-dompurify": "^3.22.0",
"lowlight": "^3.3.0",
diff --git a/apps/web/src/components/common/agent-chat/AgentChatMessage.tsx b/apps/web/src/components/common/agent-chat/AgentChatMessage.tsx
index a60b384a..69ff0cdf 100644
--- a/apps/web/src/components/common/agent-chat/AgentChatMessage.tsx
+++ b/apps/web/src/components/common/agent-chat/AgentChatMessage.tsx
@@ -1,12 +1,32 @@
'use client';
import type { ChatMessage } from '@/hooks/useAgentChat';
+import type { AiChatPart, AiChatToolPart } from '@/lib/api';
import { formatLongDate, formatTime } from '@/utils/dates';
import Markdown from '@/components/common/Markdown';
import { Bubble, BubbleContent } from '@/components/ui/bubble';
import { Marker, MarkerContent } from '@/components/ui/marker';
import { Message, MessageContent, MessageFooter } from '@/components/ui/message';
import { MessageScrollerItem } from '@/components/ui/message-scroller';
+import AgentChatToolCalls from './AgentChatToolCalls';
+
+type Block = { text: string } | { tools: AiChatToolPart[] };
+
+// Tool calls that follow one another are shown as one block, in the place between the
+// two stretches of text where they were made.
+function blocksOf(parts: AiChatPart[]): Block[] {
+ const blocks: Block[] = [];
+ for (const part of parts) {
+ if (part.type === 'text') {
+ blocks.push({ text: part.text });
+ continue;
+ }
+ const last = blocks[blocks.length - 1];
+ if (last && 'tools' in last) last.tools.push(part);
+ else blocks.push({ tools: [part] });
+ }
+ return blocks;
+}
export default function AgentChatMessage({
message,
@@ -30,14 +50,20 @@ export default function AgentChatMessage({
)}
<Message align={isUser ? 'end' : 'start'}>
<MessageContent>
- <Bubble variant={isUser ? 'muted' : 'ghost'}>
- <BubbleContent>
- {isUser ? (
- <span className="whitespace-pre-wrap">{message.text}</span>
+ <Bubble variant={isUser ? 'muted' : 'ghost'} className="gap-2">
+ {blocksOf(message.parts).map((block, index) =>
+ 'tools' in block ? (
+ <AgentChatToolCalls key={index} tools={block.tools} />
) : (
- <Markdown>{message.text}</Markdown>
- )}
- </BubbleContent>
+ <BubbleContent key={index}>
+ {isUser ? (
+ <span className="whitespace-pre-wrap">{block.text}</span>
+ ) : (
+ <Markdown>{block.text}</Markdown>
+ )}
+ </BubbleContent>
+ ),
+ )}
</Bubble>
<MessageFooter>{formatTime(message.createdAt)}</MessageFooter>
</MessageContent>
diff --git a/apps/web/src/components/common/agent-chat/AgentChatPanel.tsx b/apps/web/src/components/common/agent-chat/AgentChatPanel.tsx
index 94f2a171..2e22269a 100644
--- a/apps/web/src/components/common/agent-chat/AgentChatPanel.tsx
+++ b/apps/web/src/components/common/agent-chat/AgentChatPanel.tsx
@@ -5,6 +5,8 @@ import { ArrowUp, Bot, RotateCw } from 'lucide-react';
import type { AiAgent } from '@/lib/api';
import type { ChatMessage, ChatStatus } from '@/hooks/useAgentChat';
import { AgentChatTranscript } from './AgentChatTranscript';
+import { AgentRunnerStatus } from './AgentRunnerStatus';
+import { isRunnerOnline } from './runnerOnline';
import {
Empty,
EmptyDescription,
@@ -23,9 +25,7 @@ import { useTranslations } from 'next-intl';
// The running transcript and the composer for one agent conversation. The
// conversation state lives above this panel (in the agent chat host), so it is
-// presentational: it renders what it is given and reports sends. The agent's
-// replies stream in and render as markdown; the user's own turns render as plain
-// text.
+// presentational: it renders what it is given and reports sends.
export function AgentChatPanel({
agent,
messages,
@@ -49,20 +49,24 @@ export function AgentChatPanel({
}) {
const t = useTranslations('common.agentChat');
const [input, setInput] = useState('');
- const isStreaming = status === 'streaming';
+ // An external agent answers on its runner, so with none polling the message would sit
+ // in the queue with nothing to take it. The composer says so instead of accepting it.
+ const runnerOffline = agent.kind === 'external' && !isRunnerOnline(agent);
+ const isBusy = status !== 'ready';
+ const canWrite = !isBusy && !runnerOffline;
- // The textarea is disabled while a reply streams, which drops focus. Restore it
- // once streaming ends so the user can keep typing without clicking back in.
+ // The textarea is disabled while a reply is on its way, which drops focus. Restore
+ // it once the reply ends so the user can keep typing without clicking back in.
const textareaRef = useRef<HTMLTextAreaElement>(null);
- const wasStreaming = useRef(false);
+ const wasBusy = useRef(false);
useEffect(() => {
- if (wasStreaming.current && !isStreaming) textareaRef.current?.focus();
- wasStreaming.current = isStreaming;
- }, [isStreaming]);
+ if (wasBusy.current && !isBusy) textareaRef.current?.focus();
+ wasBusy.current = isBusy;
+ }, [isBusy]);
function submit() {
const text = input.trim();
- if (!text || isStreaming) return;
+ if (!text || !canWrite) return;
setInput('');
onSend(text);
}
@@ -84,7 +88,7 @@ export function AgentChatPanel({
) : (
<AgentChatTranscript
messages={messages}
- isStreaming={isStreaming}
+ status={status}
activeTool={activeTool}
hasEarlierMessages={hasEarlierMessages}
isLoadingEarlier={isLoadingEarlier}
@@ -94,6 +98,12 @@ export function AgentChatPanel({
</div>
<div className="p-4 pt-2">
+ {runnerOffline && (
+ <div className="mx-auto mb-2 flex w-full max-w-3xl flex-wrap items-center gap-x-2 gap-y-0.5">
+ <AgentRunnerStatus agent={agent} />
+ <span className="text-xs text-muted-foreground">{t('runnerOfflineHint')}</span>
+ </div>
+ )}
<form
className="mx-auto w-full max-w-3xl"
onSubmit={(e) => {
@@ -116,8 +126,12 @@ export function AgentChatPanel({
submit();
}
}}
- placeholder={t('messagePlaceholder', { agent: agent.name })}
- disabled={isStreaming}
+ placeholder={
+ runnerOffline
+ ? t('runnerOffline')
+ : t('messagePlaceholder', { agent: agent.name })
+ }
+ disabled={!canWrite}
rows={1}
/>
<InputGroupAddon align="block-end">
@@ -128,7 +142,7 @@ export function AgentChatPanel({
size="icon-sm"
className="rounded-lg text-muted-foreground hover:text-foreground"
title={t('reset')}
- disabled={isStreaming || messages.length === 0}
+ disabled={isBusy || messages.length === 0}
onClick={onReset}
>
<RotateCw />
@@ -140,7 +154,7 @@ export function AgentChatPanel({
variant="default"
size="icon-sm"
className="ml-auto rounded-lg"
- disabled={!input.trim() || isStreaming}
+ disabled={!input.trim() || !canWrite}
>
<ArrowUp />
<span className="sr-only">{t('send')}</span>
diff --git a/apps/web/src/components/common/agent-chat/AgentChatToolBlock.tsx b/apps/web/src/components/common/agent-chat/AgentChatToolBlock.tsx
new file mode 100644
index 00000000..cea0a13f
--- /dev/null
+++ b/apps/web/src/components/common/agent-chat/AgentChatToolBlock.tsx
@@ -0,0 +1,22 @@
+'use client';
+
+import { useMemo } from 'react';
+import { highlightJson } from '@/lib/highlight';
+
+// What a tool call was given or answered. `md-content` carries the highlighter's
+// colours, the fill behind the block, and the left-to-right direction a mirrored page
+// would otherwise impose on it.
+export default function AgentChatToolBlock({ label, text }: { label: string; text: string }) {
+ const highlighted = useMemo(() => highlightJson(text), [text]);
+
+ return (
+ <div className="min-w-0">
+ <span className="text-xs text-muted-foreground">{label}</span>
+ <div className="md-content mt-1">
+ <pre className="max-h-64 overflow-auto text-xs leading-relaxed wrap-break-word whitespace-pre-wrap">
+ <code>{highlighted ?? text}</code>
+ </pre>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/common/agent-chat/AgentChatToolCall.tsx b/apps/web/src/components/common/agent-chat/AgentChatToolCall.tsx
new file mode 100644
index 00000000..cbe19ee1
--- /dev/null
+++ b/apps/web/src/components/common/agent-chat/AgentChatToolCall.tsx
@@ -0,0 +1,43 @@
+'use client';
+
+import { Wrench } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import type { AiChatToolPart } from '@/lib/api';
+import { Marker, MarkerContent, MarkerIcon } from '@/components/ui/marker';
+import AgentChatToolBlock from './AgentChatToolBlock';
+import AgentChatToolDisclosure from './AgentChatToolDisclosure';
+
+// One tool call, opening to what it was given and what it answered.
+export default function AgentChatToolCall({
+ tool,
+ label,
+ withIcon = false,
+}: {
+ tool: AiChatToolPart;
+ label: string;
+ withIcon?: boolean;
+}) {
+ const t = useTranslations('common.agentChat');
+
+ if (!tool.args && !tool.result) {
+ return (
+ <Marker className="min-h-8">
+ {withIcon && (
+ <MarkerIcon className="size-3.5">
+ <Wrench className="size-3.5" />
+ </MarkerIcon>
+ )}
+ <MarkerContent>{label}</MarkerContent>
+ </Marker>
+ );
+ }
+
+ return (
+ <AgentChatToolDisclosure label={label} withIcon={withIcon}>
+ <div className="flex flex-col gap-2 pt-1 pb-2">
+ {tool.args && <AgentChatToolBlock label={t('toolInput')} text={tool.args} />}
+ {tool.result && <AgentChatToolBlock label={t('toolOutput')} text={tool.result} />}
+ </div>
+ </AgentChatToolDisclosure>
+ );
+}
diff --git a/apps/web/src/components/common/agent-chat/AgentChatToolCalls.tsx b/apps/web/src/components/common/agent-chat/AgentChatToolCalls.tsx
new file mode 100644
index 00000000..485fdcc0
--- /dev/null
+++ b/apps/web/src/components/common/agent-chat/AgentChatToolCalls.tsx
@@ -0,0 +1,31 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import type { AiChatToolPart } from '@/lib/api';
+import AgentChatToolCall from './AgentChatToolCall';
+import AgentChatToolDisclosure from './AgentChatToolDisclosure';
+
+// The tools the agent called in one stretch of its answer. Several are folded behind a
+// single row so they do not push the answer itself out of view.
+export default function AgentChatToolCalls({ tools }: { tools: AiChatToolPart[] }) {
+ const t = useTranslations('common.agentChat');
+
+ if (tools.length === 1) {
+ const only = tools[0]!;
+ return (
+ <AgentChatToolCall tool={only} label={t('usedTool', { tool: only.toolName })} withIcon />
+ );
+ }
+
+ return (
+ <AgentChatToolDisclosure label={t('usedTools', { count: tools.length })} withIcon>
+ <ul className="flex flex-col">
+ {tools.map((tool, index) => (
+ <li key={tool.toolCallId || index}>
+ <AgentChatToolCall tool={tool} label={tool.toolName} />
+ </li>
+ ))}
+ </ul>
+ </AgentChatToolDisclosure>
+ );
+}
diff --git a/apps/web/src/components/common/agent-chat/AgentChatToolDisclosure.tsx b/apps/web/src/components/common/agent-chat/AgentChatToolDisclosure.tsx
new file mode 100644
index 00000000..f843ddb7
--- /dev/null
+++ b/apps/web/src/components/common/agent-chat/AgentChatToolDisclosure.tsx
@@ -0,0 +1,32 @@
+'use client';
+
+import type { ReactNode } from 'react';
+import { ChevronRight, Wrench } from 'lucide-react';
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
+
+// A row in the transcript that opens to show more of a tool call. `withIcon` is for a
+// row that stands on its own in the answer; a call listed under such a row is named in
+// code instead.
+export default function AgentChatToolDisclosure({
+ label,
+ withIcon = false,
+ children,
+}: {
+ label: string;
+ withIcon?: boolean;
+ children: ReactNode;
+}) {
+ return (
+ <Collapsible>
+ <CollapsibleTrigger className="group flex min-h-8 w-fit max-w-full items-center gap-1.5 rounded-md text-sm text-muted-foreground transition-colors outline-none hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50">
+ <ChevronRight className="size-3.5 shrink-0 transition-transform duration-150 group-data-[state=open]:rotate-90 rtl:group-data-[state=closed]:rotate-180" />
+ {withIcon && <Wrench className="size-3.5 shrink-0" />}
+ <span className={`min-w-0 truncate ${withIcon ? '' : 'font-mono text-xs'}`}>{label}</span>
+ </CollapsibleTrigger>
+ {/* Indented to the trigger's label column, past the chevron. */}
+ <CollapsibleContent className="overflow-hidden ps-5 motion-safe:data-[state=closed]:animate-collapsible-up motion-safe:data-[state=open]:animate-collapsible-down">
+ {children}
+ </CollapsibleContent>
+ </Collapsible>
+ );
+}
diff --git a/apps/web/src/components/common/agent-chat/AgentChatTranscript.tsx b/apps/web/src/components/common/agent-chat/AgentChatTranscript.tsx
index 5e1e5450..60e61547 100644
--- a/apps/web/src/components/common/agent-chat/AgentChatTranscript.tsx
+++ b/apps/web/src/components/common/agent-chat/AgentChatTranscript.tsx
@@ -2,7 +2,7 @@
import { useEffect, useRef } from 'react';
import type { UIEvent, WheelEvent } from 'react';
-import type { ChatMessage } from '@/hooks/useAgentChat';
+import type { ChatMessage, ChatStatus } from '@/hooks/useAgentChat';
import { dayKey } from '@/utils/dates';
import AgentChatMessage from './AgentChatMessage';
import InitialScrollToEnd from './InitialScrollToEnd';
@@ -20,20 +20,26 @@ const loadThreshold = 48;
export function AgentChatTranscript({
messages,
- isStreaming,
+ status,
activeTool,
hasEarlierMessages = false,
isLoadingEarlier = false,
onLoadEarlier,
}: {
messages: ChatMessage[];
- isStreaming: boolean;
+ status: ChatStatus;
activeTool: string | null;
hasEarlierMessages?: boolean;
isLoadingEarlier?: boolean;
onLoadEarlier?: () => void;
}) {
const t = useTranslations('common.agentChat');
+
+ let statusLabel: string;
+ if (status === 'queued') statusLabel = t('waitingForRunner');
+ else if (activeTool) statusLabel = t('usingTool', { tool: activeTool });
+ else statusLabel = t('thinking');
+
const loadLocked = useRef(false);
const hasLeftStart = useRef(false);
@@ -77,7 +83,7 @@ export function AgentChatTranscript({
onWheel={handleWheel}
>
<MessageScrollerContent
- aria-busy={isStreaming || isLoadingEarlier}
+ aria-busy={status !== 'ready' || isLoadingEarlier}
className="mx-auto w-full max-w-3xl gap-6 p-4"
>
{messages.map((message, index) => {
@@ -91,12 +97,10 @@ export function AgentChatTranscript({
);
})}
- {isStreaming && (
+ {status !== 'ready' && (
<MessageScrollerItem messageId="stream-status">
<Marker role="status">
- <MarkerContent className="shimmer">
- {activeTool ? t('usingTool', { tool: activeTool }) : t('thinking')}
- </MarkerContent>
+ <MarkerContent className="shimmer">{statusLabel}</MarkerContent>
</Marker>
</MessageScrollerItem>
)}
diff --git a/apps/web/src/features/settings/components/ai-agents/AgentRunnerStatus.tsx b/apps/web/src/components/common/agent-chat/AgentRunnerStatus.tsx
similarity index 85%
rename from apps/web/src/features/settings/components/ai-agents/AgentRunnerStatus.tsx
rename to apps/web/src/components/common/agent-chat/AgentRunnerStatus.tsx
index 60f82e9d..c851f145 100644
--- a/apps/web/src/features/settings/components/ai-agents/AgentRunnerStatus.tsx
+++ b/apps/web/src/components/common/agent-chat/AgentRunnerStatus.tsx
@@ -3,15 +3,15 @@ import { useTranslations } from 'next-intl';
import type { AiAgent } from '@/lib/api';
import { cn } from '@/lib/utils';
import { formatDurationShort } from '@/utils/dates';
-
-// A runner is considered online while it keeps polling; the reference runner polls
-// every few seconds, so a gap this long means it is gone rather than between polls.
-const ONLINE_WINDOW_MS = 90_000;
+import { isRunnerOnline } from './runnerOnline';
// Whether an external agent's runner is connected right now. The agent has no runner
// until someone starts one, so "never connected" is a normal state and reads
// differently from "went offline". `compact` drops to the bare state for places that
// already say what it is about, such as a section header.
+//
+// The strings sit in the settings namespace, where the runner is set up; the chat shows
+// the same three states rather than wording its own.
export function AgentRunnerStatus({
agent,
compact = false,
@@ -22,7 +22,7 @@ export function AgentRunnerStatus({
}) {
const t = useTranslations('settings.agents');
const lastSeen = agent?.lastSeenAt ?? null;
- const online = lastSeen != null && Date.now() - new Date(lastSeen).getTime() < ONLINE_WINDOW_MS;
+ const online = isRunnerOnline(agent);
let label: string;
if (online) label = compact ? t('runnerStateOnline') : t('runnerOnline');
diff --git a/apps/web/src/components/common/agent-chat/runnerOnline.ts b/apps/web/src/components/common/agent-chat/runnerOnline.ts
new file mode 100644
index 00000000..9c9b15f9
--- /dev/null
+++ b/apps/web/src/components/common/agent-chat/runnerOnline.ts
@@ -0,0 +1,9 @@
+// A runner is considered online while it keeps polling; the reference runner polls
+// every few seconds, so a gap this long means it is gone rather than between polls.
+const ONLINE_WINDOW_MS = 90_000;
+
+// Only an external agent has a runner; an internal one runs on the instance itself.
+export function isRunnerOnline(agent: { lastSeenAt: string | null } | null): boolean {
+ const lastSeen = agent?.lastSeenAt ?? null;
+ return lastSeen != null && Date.now() - new Date(lastSeen).getTime() < ONLINE_WINDOW_MS;
+}
diff --git a/apps/web/src/features/ai-chat/components/floating/FloatingChat.tsx b/apps/web/src/features/ai-chat/components/floating/FloatingChat.tsx
index d7c77f5d..c3162b36 100644
--- a/apps/web/src/features/ai-chat/components/floating/FloatingChat.tsx
+++ b/apps/web/src/features/ai-chat/components/floating/FloatingChat.tsx
@@ -66,14 +66,16 @@ export function FloatingChat({
<div className="fixed right-4 bottom-4 z-40 flex flex-col items-end gap-3">
<div
className={cn(
- 'relative flex h-[32rem] max-h-[calc(100vh-7rem)] w-[calc(100vw-2rem)] max-w-96 flex-col overflow-hidden rounded-xl border bg-background shadow-xl',
+ 'relative flex h-[32rem] max-h-[calc(100vh-7rem)] w-[calc(100vw-2rem)] max-w-96 flex-col overflow-hidden rounded-xl border bg-background shadow-[var(--modal-shadow)]',
!open && 'hidden',
)}
>
<FloatingChatHeader
agents={agents}
providerLabel={providerLabel}
+ projectKey={project.project.key}
selected={selected}
+ threadId={selectedThreadId}
onSelectAgent={handleSelectAgent}
onShowHistory={() => setView('history')}
onNewChat={handleNewChat}
@@ -93,7 +95,7 @@ export function FloatingChat({
/>
) : (
<div className="flex h-full items-center justify-center px-6 text-center text-sm text-muted-foreground">
- {t('noInternalAgents')}
+ {t('noAgentsYet')}
</div>
)}
@@ -116,7 +118,7 @@ export function FloatingChat({
<Button
size="icon"
- className="size-12 shrink-0 rounded-full shadow-lg"
+ className="size-12 shrink-0 rounded-full shadow-[var(--overlay-shadow)]"
title={open ? t('hideChat') : t('openChat')}
aria-expanded={open}
onClick={() => onOpenChange(!open)}
diff --git a/apps/web/src/features/ai-chat/components/floating/FloatingChatHeader.tsx b/apps/web/src/features/ai-chat/components/floating/FloatingChatHeader.tsx
index 2fda8f5b..4c878be5 100644
--- a/apps/web/src/features/ai-chat/components/floating/FloatingChatHeader.tsx
+++ b/apps/web/src/features/ai-chat/components/floating/FloatingChatHeader.tsx
@@ -12,15 +12,20 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
+import { AgentRunnerStatus } from '@/components/common/agent-chat/AgentRunnerStatus';
+import { AiChatSessionBadge } from '../shared/AiChatSessionBadge';
+import { useThreadSessionId } from '../../hooks/useThreadSessionId';
import { agentModelLabel } from '../../utils/agentModelLabel';
-// The top bar of the floating chat: the agent picker plus the history, new-chat and
-// minimize actions. `selected` is null when the project has no internal agents, which
-// disables everything but minimize.
+// The top bar of the floating chat: the agent picker plus the session, history, new-chat
+// and minimize actions. `selected` is null when the project has no agents, which disables
+// everything but minimize.
export function FloatingChatHeader({
agents,
providerLabel,
+ projectKey,
selected,
+ threadId,
onSelectAgent,
onShowHistory,
onNewChat,
@@ -28,13 +33,16 @@ export function FloatingChatHeader({
}: {
agents: AiAgent[];
providerLabel: (key: string) => string;
+ projectKey: string;
selected: AiAgent | null;
+ threadId: string | null;
onSelectAgent: (id: number) => void;
onShowHistory: () => void;
onNewChat: () => void;
onMinimize: () => void;
}) {
const t = useTranslations('aiChat');
+ const sessionId = useThreadSessionId(projectKey, selected?.id ?? null, threadId);
return (
<div className="flex items-center gap-1 border-b px-2.5 py-2">
@@ -52,7 +60,7 @@ export function FloatingChatHeader({
{selected?.name ?? t('noAgents')}
</div>
<div className="truncate text-xs leading-tight text-muted-foreground">
- {selected ? `@${selected.username}` : t('addInternalAgent')}
+ {selected ? `@${selected.username}` : t('addAgent')}
</div>
</div>
{selected && <ChevronDown className="size-4 shrink-0 text-muted-foreground" />}
@@ -71,7 +79,11 @@ export function FloatingChatHeader({
<div className="min-w-0 flex-1">
<div className="truncate text-sm">{agent.name}</div>
<div className="truncate text-xs text-muted-foreground">
- {agentModelLabel(agent, providerLabel, t('noModel'))}
+ {agent.kind === 'external' ? (
+ <AgentRunnerStatus agent={agent} compact />
+ ) : (
+ agentModelLabel(agent, providerLabel, t('noModel'))
+ )}
</div>
</div>
{agent.id === selected?.id && <Check className="size-4 shrink-0" />}
@@ -80,6 +92,7 @@ export function FloatingChatHeader({
</DropdownMenuContent>
</DropdownMenu>
+ {sessionId && <AiChatSessionBadge compact sessionId={sessionId} />}
<Button
variant="ghost"
size="icon"
diff --git a/apps/web/src/features/ai-chat/components/page/AiChatAgentRail.tsx b/apps/web/src/features/ai-chat/components/page/AiChatAgentRail.tsx
index e60493cb..44fb59aa 100644
--- a/apps/web/src/features/ai-chat/components/page/AiChatAgentRail.tsx
+++ b/apps/web/src/features/ai-chat/components/page/AiChatAgentRail.tsx
@@ -4,9 +4,11 @@ import { Bot, Sparkles } from 'lucide-react';
import { useTranslations } from 'next-intl';
import type { AiAgent } from '@/lib/api';
import { cn } from '@/lib/utils';
+import { AgentRunnerStatus } from '@/components/common/agent-chat/AgentRunnerStatus';
import { agentModelLabel } from '../../utils/agentModelLabel';
-// The left rail of the AI Chat page: the internal agents to chat with.
+// The left rail of the AI Chat page: the agents to chat with. An internal agent shows
+// the model it runs on, an external one whether its runner is connected.
export function AiChatAgentRail({
agents,
selectedId,
@@ -56,10 +58,16 @@ export function AiChatAgentRail({
<div className="truncate text-sm font-medium">{agent.name}</div>
<div className="truncate text-xs text-muted-foreground">@{agent.username}</div>
<div className="mt-1 flex items-center gap-1 text-xs text-muted-foreground/80">
- <Sparkles className="size-3 shrink-0" />
- <span className="truncate">
- {agentModelLabel(agent, providerLabel, t('noModel'))}
- </span>
+ {agent.kind === 'external' ? (
+ <AgentRunnerStatus agent={agent} compact />
+ ) : (
+ <>
+ <Sparkles className="size-3 shrink-0" />
+ <span className="truncate">
+ {agentModelLabel(agent, providerLabel, t('noModel'))}
+ </span>
+ </>
+ )}
</div>
</div>
</button>
diff --git a/apps/web/src/features/ai-chat/components/page/AiChatConversation.tsx b/apps/web/src/features/ai-chat/components/page/AiChatConversation.tsx
index a95e857a..4a63248a 100644
--- a/apps/web/src/features/ai-chat/components/page/AiChatConversation.tsx
+++ b/apps/web/src/features/ai-chat/components/page/AiChatConversation.tsx
@@ -4,7 +4,10 @@ import { Bot } from 'lucide-react';
import { useTranslations } from 'next-intl';
import type { AiAgent } from '@/lib/api';
import { Badge } from '@/components/ui/badge';
+import { AgentRunnerStatus } from '@/components/common/agent-chat/AgentRunnerStatus';
import { AiChatThread } from '../shared/AiChatThread';
+import { AiChatSessionBadge } from '../shared/AiChatSessionBadge';
+import { useThreadSessionId } from '../../hooks/useThreadSessionId';
import { agentModelLabel } from '../../utils/agentModelLabel';
// One agent's conversation on the AI Chat page: a header identifying the agent, and the
@@ -23,6 +26,7 @@ export function AiChatConversation({
onThreadCreated: (threadId: string) => void;
}) {
const t = useTranslations('aiChat');
+ const sessionId = useThreadSessionId(projectKey, agent.id, threadId);
return (
<div className="flex h-full min-h-0 flex-col">
@@ -33,16 +37,27 @@ export function AiChatConversation({
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-medium">{agent.name}</span>
- {!agent.memoryEnabled && (
+ {/* Memory is a setting of the built-in runtime. An external agent's memory is
+ its runner's session, whose id the header shows instead. */}
+ {agent.kind === 'internal' && !agent.memoryEnabled && (
<Badge variant="secondary" className="shrink-0">
{t('memoryOff')}
</Badge>
)}
</div>
- <div className="truncate text-xs text-muted-foreground">
- @{agent.username} · {agentModelLabel(agent, providerLabel, t('noModel'))}
+ <div className="flex items-center gap-1.5 truncate text-xs text-muted-foreground">
+ <span className="truncate">@{agent.username}</span>
+ <span aria-hidden>·</span>
+ {agent.kind === 'external' ? (
+ <AgentRunnerStatus agent={agent} compact />
+ ) : (
+ <span className="truncate">
+ {agentModelLabel(agent, providerLabel, t('noModel'))}
+ </span>
+ )}
</div>
</div>
+ {sessionId && <AiChatSessionBadge sessionId={sessionId} />}
</div>
<div className="min-h-0 flex-1">
diff --git a/apps/web/src/features/ai-chat/components/shared/AiChatSessionBadge.tsx b/apps/web/src/features/ai-chat/components/shared/AiChatSessionBadge.tsx
new file mode 100644
index 00000000..b08d1f0f
--- /dev/null
+++ b/apps/web/src/features/ai-chat/components/shared/AiChatSessionBadge.tsx
@@ -0,0 +1,73 @@
+'use client';
+
+import { Check, Copy, Terminal } from 'lucide-react';
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Button } from '@/components/ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+
+// The coding agent session the agent's runner keeps for this conversation on its own
+// machine. It is what the operator resumes to read the full transcript — `claude
+// --resume <id>` in the runner's working directory. `compact` drops the id from the
+// trigger, for the floating window, where the header has no room for it.
+export function AiChatSessionBadge({
+ sessionId,
+ compact = false,
+}: {
+ sessionId: string;
+ compact?: boolean;
+}) {
+ const t = useTranslations('aiChat');
+ const [copied, setCopied] = useState(false);
+
+ const copy = async () => {
+ await navigator.clipboard.writeText(sessionId);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1500);
+ };
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="ghost"
+ size={compact ? 'icon' : 'sm'}
+ title={t('sessionLabel')}
+ className={
+ compact
+ ? 'size-7 shrink-0 text-muted-foreground hover:text-foreground'
+ : 'h-7 min-w-0 gap-1.5 px-2 text-muted-foreground hover:text-foreground'
+ }
+ >
+ <Terminal className="size-3.5 shrink-0" />
+ {compact ? (
+ <span className="sr-only">{t('sessionLabel')}</span>
+ ) : (
+ <span className="max-w-56 truncate font-mono text-xs" dir="ltr">
+ {sessionId}
+ </span>
+ )}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-96 space-y-2">
+ <p className="text-sm font-medium">{t('sessionLabel')}</p>
+ <p className="text-xs text-muted-foreground">{t('sessionHint')}</p>
+ <div className="flex items-start gap-1">
+ <span className="min-w-0 flex-1 font-mono text-xs break-all" dir="ltr">
+ {sessionId}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon"
+ title={t('copySession')}
+ onClick={() => void copy()}
+ className="size-6 shrink-0 text-muted-foreground"
+ >
+ {copied ? <Check className="size-3" /> : <Copy className="size-3" />}
+ <span className="sr-only">{t('copySession')}</span>
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/apps/web/src/features/ai-chat/components/shared/AiChatThread.tsx b/apps/web/src/features/ai-chat/components/shared/AiChatThread.tsx
index 4b4bb048..b0b9b2cd 100644
--- a/apps/web/src/features/ai-chat/components/shared/AiChatThread.tsx
+++ b/apps/web/src/features/ai-chat/components/shared/AiChatThread.tsx
@@ -1,9 +1,11 @@
'use client';
import { useEffect, useRef } from 'react';
+import { useQueryClient } from '@tanstack/react-query';
import type { AiAgent } from '@/lib/api';
import { useAgentChat } from '@/hooks/useAgentChat';
import { useAgentThreadMessagesQuery } from '@/services/aiAgents.service';
+import { qk } from '@/services/queryKeys';
import { AgentChatPanel } from '@/components/common/agent-chat/AgentChatPanel';
import { AiChatThreadSkeleton } from './AiChatThreadSkeleton';
@@ -34,8 +36,17 @@ export function AiChatThread({
send,
loadThread,
prependHistory,
- } = useAgentChat(projectKey, agent.id);
+ } = useAgentChat(projectKey, agent.id, agent.kind === 'external');
const messagesQuery = useAgentThreadMessagesQuery(projectKey, agent.id, threadId);
+ const qc = useQueryClient();
+
+ // An answer that just ended may have bound the thread to a session on the runner, and
+ // the thread list is what carries that. Refetching once per answer is what makes the
+ // session appear without a reload.
+ useEffect(() => {
+ if (status !== 'ready') return;
+ void qc.invalidateQueries({ queryKey: qk.agentThreads(projectKey, agent.id) });
+ }, [status, qc, projectKey, agent.id]);
// How many transcript pages of the active thread are already in the conversation.
// Page 0 counts as merged from the start: for a restored thread it is what
diff --git a/apps/web/src/features/ai-chat/hooks/useAiChatSelection.ts b/apps/web/src/features/ai-chat/hooks/useAiChatSelection.ts
index c5769a32..440125bd 100644
--- a/apps/web/src/features/ai-chat/hooks/useAiChatSelection.ts
+++ b/apps/web/src/features/ai-chat/hooks/useAiChatSelection.ts
@@ -7,9 +7,8 @@ import { useIntegrationCatalogQuery } from '@/services/integrations.service';
import { qk } from '@/services/queryKeys';
// The agents available for chat and which conversation is shown, shared by the AI Chat
-// page and the floating chat. Only internal agents appear, since they are the ones the
-// built-in runtime can run; external agents are driven through the API and have no test
-// chat.
+// page and the floating chat. Both kinds appear: an internal agent answers in the API
+// process, an external one through the runner its operator runs.
//
// `selectedThreadId` is a past thread, or null for a fresh chat. `newChatNonce` bumps on
// "New chat" so the host can key the conversation by it and remount into a fresh session
@@ -17,7 +16,7 @@ import { qk } from '@/services/queryKeys';
export function useAiChatSelection(projectKey: string | null) {
const qc = useQueryClient();
const agentsQuery = useAiAgentsQuery(projectKey);
- const agents = (agentsQuery.data ?? []).filter((agent) => agent.kind === 'internal');
+ const agents = agentsQuery.data ?? [];
const catalog = useIntegrationCatalogQuery(projectKey).data ?? [];
const providerLabel = (key: string) => catalog.find((entry) => entry.key === key)?.label ?? key;
diff --git a/apps/web/src/features/ai-chat/hooks/useThreadSessionId.ts b/apps/web/src/features/ai-chat/hooks/useThreadSessionId.ts
new file mode 100644
index 00000000..4dacc7aa
--- /dev/null
+++ b/apps/web/src/features/ai-chat/hooks/useThreadSessionId.ts
@@ -0,0 +1,15 @@
+'use client';
+
+import { useAgentThreadsQuery } from '@/services/aiAgents.service';
+
+// The coding agent session an external agent's runner keeps for the shown thread, which
+// the thread list is what carries. Null until a runner has reported one.
+export function useThreadSessionId(
+ projectKey: string,
+ agentId: number | null,
+ threadId: string | null,
+): string | null {
+ const threadsQuery = useAgentThreadsQuery(projectKey, agentId);
+ if (!threadId) return null;
+ return threadsQuery.data?.find((thread) => thread.id === threadId)?.cliSessionId ?? null;
+}
diff --git a/apps/web/src/features/settings/components/ai-agents/AgentRunnerHelpSheet.tsx b/apps/web/src/features/settings/components/ai-agents/AgentRunnerHelpSheet.tsx
index 88152ab6..59e17415 100644
--- a/apps/web/src/features/settings/components/ai-agents/AgentRunnerHelpSheet.tsx
+++ b/apps/web/src/features/settings/components/ai-agents/AgentRunnerHelpSheet.tsx
@@ -13,9 +13,10 @@ import { AgentRunnerHelpStep } from './AgentRunnerHelpStep';
//
// One tab per coding agent, each holding the files to copy as they stand: the MCP
// server this instance exposes, the runner config, and the line that starts it. The
-// only difference between the tabs is the command being started. YOUR_KEY rather
-// than <key>: next-intl parses angle brackets in a message as rich-text tags, and
-// step 1 quotes the placeholder.
+// runner knows how to invoke each of these CLIs, so the config only names one; a tab
+// differs from the next in where that CLI reads its MCP server from. Where the key
+// itself has to be written out, the placeholder is `the-agent-key` rather than
+// `$ITSAPLAN_API_KEY`, which on the same screen means the variable the runner sets.
// The MCP server for a client that takes a JSON config file. The key comes from the
// environment the runner sets, so it is not duplicated in a second file.
@@ -35,14 +36,14 @@ const CODEX_TOML = `[mcp_servers.itsaplan]
url = "${API_URL}/mcp"
bearer_token_env_var = "ITSAPLAN_API_KEY"`;
-// Copilot CLI reads a project's servers from .mcp.json; its headers take no variable
-// interpolation, so the key is written in as it stands.
+// Copilot CLI reads the same .mcp.json as Claude Code, but its headers take no
+// variable interpolation, so the key is written in as it stands.
const COPILOT_MCP = `{
"mcpServers": {
"itsaplan": {
"type": "http",
"url": "${API_URL}/mcp",
- "headers": { "Authorization": "Bearer YOUR_KEY" },
+ "headers": { "Authorization": "Bearer the-agent-key" },
"tools": ["*"]
}
}
@@ -81,52 +82,43 @@ const AGENTS = [
{
id: 'claude',
label: 'Claude Code',
- // --mcp-config adds this instance's server to whatever the machine already has;
- // the operator's own servers, skills and memory stay in the run. A headless run
- // has nobody to answer a permission prompt, so it goes to auto mode, where a
- // classifier reviews each action instead — including the MCP tool calls, which
- // therefore need no allow list of their own.
- command:
- 'claude -p --mcp-config ./mcp.json ' +
- '--append-system-prompt "$ITSAPLAN_SYSTEM_PROMPT" ' +
- '--permission-mode auto --output-format text',
- files: [{ name: 'mcp.json', code: MCP_JSON }],
+ // Claude Code picks up .mcp.json from the directory it runs in, which is `cwd`,
+ // so the runner config needs nothing for it. The instance's server lands on top
+ // of what the machine already has, so the operator's own servers, skills and
+ // memory stay in the run.
+ agent: 'claude',
+ files: [{ name: '.mcp.json', code: MCP_JSON }],
},
{
id: 'codex',
label: 'Codex',
- // Codex has no system-prompt flag, so the run's system prompt is prepended to
- // the task; "-" is codex's own marker for "read the prompt from stdin".
- command:
- 'printf \'%s\\n\\n%s\' "$ITSAPLAN_SYSTEM_PROMPT" "$(cat)" | ' +
- 'codex exec --sandbox workspace-write --skip-git-repo-check -',
+ // Codex reads its servers from ~/.codex/config.toml only — no project file — so
+ // this one is written once per machine. --skip-git-repo-check is what lets the
+ // working directory be something other than a git repository.
+ agent: 'codex',
+ args: ['--skip-git-repo-check'],
files: [{ name: '~/.codex/config.toml', code: CODEX_TOML }],
},
{
id: 'gemini',
label: 'Gemini CLI',
- // Same as Codex: no system-prompt flag, so it goes in front of the task. Gemini
- // reads a piped prompt on stdin.
- command:
- 'printf \'%s\\n\\n%s\' "$ITSAPLAN_SYSTEM_PROMPT" "$(cat)" | gemini --approval-mode yolo',
+ agent: 'gemini',
files: [{ name: '.gemini/settings.json', code: GEMINI_SETTINGS }],
},
{
id: 'copilot',
label: 'Copilot CLI',
- // No system-prompt flag and no stdin prompt: both go in as one -p argument.
- command:
- 'copilot -p "$(printf \'%s\\n\\n%s\' "$ITSAPLAN_SYSTEM_PROMPT" "$(cat)")" ' +
- '--allow-all-tools --no-ask-user',
+ agent: 'copilot',
files: [{ name: '.mcp.json', code: COPILOT_MCP }],
},
{
id: 'opencode',
label: 'Opencode',
- // opencode run takes the prompt as an argument only, never on stdin.
- command: 'opencode run "$(printf \'%s\\n\\n%s\' "$ITSAPLAN_SYSTEM_PROMPT" "$(cat)")"',
+ agent: 'opencode',
files: [{ name: 'opencode.json', code: OPENCODE_JSON }],
},
+ // A command of its own turns the preset off: the runner then knows nothing about
+ // what it runs, keeps no session for it, and hands it the task on stdin.
{
id: 'custom',
label: '',
@@ -135,16 +127,25 @@ const AGENTS = [
},
] as const;
-function configFile(command: string): string {
- return `{
- "url": "${API_URL}",
- "apiKey": "YOUR_KEY",
- "command": ${JSON.stringify(command)},
- "cwd": "/path/to/working-dir",
- "concurrency": 1,
- "pollIntervalMs": 3000,
- "timeoutMs": 1800000
-}`;
+// Only what the runner cannot work out on its own. `cwd` is where the agent's files
+// and the MCP config above are read from; concurrency, poll interval and timeout keep
+// their defaults.
+function configFile(preset: {
+ agent?: string;
+ args?: readonly string[];
+ command?: string;
+}): string {
+ return JSON.stringify(
+ {
+ url: API_URL,
+ apiKey: 'the-agent-key',
+ ...(preset.agent ? { agent: preset.agent } : { command: preset.command }),
+ cwd: '/path/to/working-dir',
+ ...(preset.args ? { args: preset.args } : {}),
+ },
+ null,
+ 2,
+ );
}
export const RUN_COMMAND = 'npx -y @itsaplan/runner';
@@ -160,10 +161,10 @@ export function AgentRunnerHelpSheet() {
{t('runnerHelpOpen')}
</Button>
</SheetTrigger>
- {/* Fixed height with the scroll inside: the tabs hold snippets of different
+ {/* Full height with the scroll inside: the tabs hold snippets of different
lengths, and a sheet that resized to each of them would jump under the
pointer. */}
- <SheetContent side="bottom" className="flex h-[90vh] flex-col">
+ <SheetContent side="bottom" className="flex h-dvh flex-col">
<SheetHeader>
<SheetTitle>{t('runnerHelpTitle')}</SheetTitle>
</SheetHeader>
@@ -172,11 +173,15 @@ export function AgentRunnerHelpSheet() {
<p className="text-xs text-muted-foreground">{t('runnerHelpKeyHint')}</p>
</AgentRunnerHelpStep>
- <AgentRunnerHelpStep n={2} title={t('runnerHelpTool')}>
+ <AgentRunnerHelpStep n={2} title={t('runnerHelpMcp')}>
+ <p className="text-xs text-muted-foreground">{t('runnerHelpMcpHint')}</p>
+ </AgentRunnerHelpStep>
+
+ <AgentRunnerHelpStep n={3} title={t('runnerHelpTool')}>
<p className="text-xs text-muted-foreground">{t('runnerHelpToolHint')}</p>
</AgentRunnerHelpStep>
- <AgentRunnerHelpStep n={3} title={t('runnerHelpRun')}>
+ <AgentRunnerHelpStep n={4} title={t('runnerHelpRun')}>
<Tabs defaultValue="claude">
<TabsList variant="line">
{AGENTS.map((a) => (
@@ -195,7 +200,7 @@ export function AgentRunnerHelpSheet() {
))}
<div className="space-y-1.5">
<p className="font-mono text-xs text-muted-foreground">itsaplan-runner.json</p>
- <AgentRunnerCodeBlock code={configFile(a.command)} />
+ <AgentRunnerCodeBlock code={configFile(a)} />
</div>
<AgentRunnerCodeBlock code={RUN_COMMAND} />
</TabsContent>
@@ -203,7 +208,7 @@ export function AgentRunnerHelpSheet() {
</Tabs>
</AgentRunnerHelpStep>
- <AgentRunnerHelpStep n={4} title={t('runnerHelpCheck')}>
+ <AgentRunnerHelpStep n={5} title={t('runnerHelpCheck')}>
<p className="text-xs text-muted-foreground">{t('runnerHelpCheckHint')}</p>
</AgentRunnerHelpStep>
</div>
diff --git a/apps/web/src/features/settings/components/ai-agents/AgentRunnerSection.tsx b/apps/web/src/features/settings/components/ai-agents/AgentRunnerSection.tsx
index 185fdfe1..305a731f 100644
--- a/apps/web/src/features/settings/components/ai-agents/AgentRunnerSection.tsx
+++ b/apps/web/src/features/settings/components/ai-agents/AgentRunnerSection.tsx
@@ -1,10 +1,10 @@
import { Code2, Package, Terminal } from 'lucide-react';
import { useTranslations } from 'next-intl';
import type { AiAgent } from '@/lib/api';
+import { AgentRunnerStatus } from '@/components/common/agent-chat/AgentRunnerStatus';
import { AgentFormSection } from './AgentFormSection';
import { AgentRunnerCodeBlock } from './AgentRunnerCodeBlock';
import { AgentRunnerHelpSheet, RUN_COMMAND } from './AgentRunnerHelpSheet';
-import { AgentRunnerStatus } from './AgentRunnerStatus';
// The Runner section of an external agent: whether its runner is connected right
// now, and how to start one. Who may give the agent work is an access question and
diff --git a/apps/web/src/features/settings/components/ai-agents/AgentSheetForm.tsx b/apps/web/src/features/settings/components/ai-agents/AgentSheetForm.tsx
index 83d29a92..623907c3 100644
--- a/apps/web/src/features/settings/components/ai-agents/AgentSheetForm.tsx
+++ b/apps/web/src/features/settings/components/ai-agents/AgentSheetForm.tsx
@@ -247,11 +247,14 @@ export function AgentSheetForm({
revealedKey !== null ? <AgentKeyBanner apiKey={revealedKey} onDismiss={onDismissKey} /> : null;
// The full-width internal editor owns its scroll container (it holds the section
- // nav's scroll spy). Every other case stacks in a single readable column here.
+ // nav's scroll spy). Every other case stacks in a single column here. Once the
+ // agent exists the chat takes the other half of the sheet and the form fills its
+ // column; while creating there is no chat and it stands alone at full width, which
+ // needs a readable cap.
const ownsScroll = expanded && value.kind === 'internal';
let contentWidth = '';
if (ownsScroll) contentWidth = AGENT_EXPANDED_WIDTH;
- else if (expanded) contentWidth = 'max-w-2xl';
+ else if (expanded && isCreate) contentWidth = 'max-w-2xl';
const fields = (
<SettingsAiAgentFields
@@ -285,7 +288,7 @@ export function AgentSheetForm({
{ownsScroll ? (
fields
) : (
- <div className="min-h-0 flex-1 overflow-y-auto px-4 pt-5 pb-6">
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 pt-5 pb-6 sm:px-6">
<div className={`mx-auto w-full space-y-6 ${contentWidth}`}>
{banner}
{fields}
diff --git a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentRow.tsx b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentRow.tsx
index d06077b7..c74a3285 100644
--- a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentRow.tsx
+++ b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentRow.tsx
@@ -9,6 +9,7 @@ import {
} from 'lucide-react';
import type { AiAgent } from '@/lib/api';
import { formatShortDate } from '@/utils/dates';
+import { AgentRunnerStatus } from '@/components/common/agent-chat/AgentRunnerStatus';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
@@ -22,7 +23,6 @@ import { TableCell, TableRow } from '@/components/ui/table';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useSettingsCan } from '../../context/settingsPermission';
import { AgentMetaRow, AgentTriggers } from './AgentMetaRow';
-import { AgentRunnerStatus } from './AgentRunnerStatus';
import { useTranslations } from 'next-intl';
// One agent as a table row: the Agent cell holds the name, @username, kind badge,
@@ -51,11 +51,8 @@ export function SettingsAiAgentRow({
const t = useTranslations('settings.agents');
const can = useSettingsCan();
const canHistory = can('read');
- // Only an internal agent runs in the built-in runtime, which is what the test chat
- // drives.
- const canChat = agent.kind === 'internal' && canHistory;
const canRegenerate = agent.kind === 'external' && can('edit');
- const hasMenu = canChat || canRegenerate || can('delete');
+ const hasMenu = canHistory || canRegenerate || can('delete');
return (
<TableRow className="group/item">
@@ -125,7 +122,7 @@ export function SettingsAiAgentRow({
<TooltipContent>{t('moreActions')}</TooltipContent>
</Tooltip>
<DropdownMenuContent align="end">
- {canChat && (
+ {canHistory && (
<DropdownMenuItem className="min-h-11 sm:min-h-8" onSelect={onChat}>
<MessageSquare />
{t('testChat')}
@@ -137,7 +134,7 @@ export function SettingsAiAgentRow({
{t('regenerateConfirm')}
</DropdownMenuItem>
)}
- {can('delete') && (canChat || canRegenerate) && <DropdownMenuSeparator />}
+ {can('delete') && (canHistory || canRegenerate) && <DropdownMenuSeparator />}
{can('delete') && (
<DropdownMenuItem
className="min-h-11 sm:min-h-8"
diff --git a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentSheet.tsx b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentSheet.tsx
index 3d79e438..dd9421a3 100644
--- a/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentSheet.tsx
+++ b/apps/web/src/features/settings/components/ai-agents/SettingsAiAgentSheet.tsx
@@ -68,19 +68,19 @@ function SheetBody({
const [revealedKey, setRevealedKey] = useState<string | null>(null);
const agent = initialAgent ?? createdAgent;
- const canTest = agent?.kind === 'internal';
// Held here so the transcript and thread survive re-renders. No agent yet during
// create → id 0; the chat is only reachable once the agent exists.
- const chat = useAgentChat(projectKey, agent?.id ?? 0);
+ const chat = useAgentChat(projectKey, agent?.id ?? 0, agent?.kind === 'external');
function onCreated(created: AiAgent, apiKey: string | null) {
setCreatedAgent(created);
setRevealedKey(apiKey);
}
- // The sheet is always full width: a testable agent shows the form and the chat side
- // by side; otherwise the form takes the full width on its own.
- const split = canTest && !!agent;
+ // The sheet is always full width: an existing agent shows the form and the chat side
+ // by side; while creating one there is nothing to chat with, so the form takes the
+ // full width on its own.
+ const split = !!agent;
return (
<div className="flex h-full min-h-0 flex-col">
diff --git a/apps/web/src/features/settings/components/schedules/SettingsScheduleDialog.tsx b/apps/web/src/features/settings/components/schedules/SettingsScheduleDialog.tsx
index ff5161a7..ff931e95 100644
--- a/apps/web/src/features/settings/components/schedules/SettingsScheduleDialog.tsx
+++ b/apps/web/src/features/settings/components/schedules/SettingsScheduleDialog.tsx
@@ -1,6 +1,7 @@
import { useState } from 'react';
import { Terminal } from 'lucide-react';
import type { AgentSchedule, AgentScheduleInput, AiAgent } from '@/lib/api';
+import { AgentRunnerStatus } from '@/components/common/agent-chat/AgentRunnerStatus';
import Modal from '@/components/common/overlay/Modal';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -14,7 +15,6 @@ import {
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { parseScheduleInput } from '../../utils/cronSchedule';
-import { AgentRunnerStatus } from '../ai-agents/AgentRunnerStatus';
import { SettingsScheduleInput } from './SettingsScheduleInput';
import { useTranslations } from 'next-intl';
diff --git a/apps/web/src/hooks/useAgentChat.ts b/apps/web/src/hooks/useAgentChat.ts
index 5d97c538..cbb81ef7 100644
--- a/apps/web/src/hooks/useAgentChat.ts
+++ b/apps/web/src/hooks/useAgentChat.ts
@@ -2,24 +2,49 @@
import { useCallback, useRef, useState } from 'react';
import { toast } from 'sonner';
-import { ApiError, streamAiAgentRun } from '@/lib/api';
-import type { AiChatMessage } from '@/lib/api';
+import { ApiError, streamAiAgentChat, streamAiAgentRun } from '@/lib/api';
+import type { AiChatMessage, AiChatPart, AiChatToolPart } from '@/lib/api';
import { useTranslations } from 'next-intl';
export type ChatMessage = AiChatMessage;
-export type ChatStatus = 'ready' | 'streaming';
+// Only a tool call between two chunks of the answer starts a new text part.
+function appendText(parts: AiChatPart[], chunk: string): AiChatPart[] {
+ const last = parts[parts.length - 1];
+ if (last?.type !== 'text') return [...parts, { type: 'text', text: chunk }];
+ return [...parts.slice(0, -1), { type: 'text', text: last.text + chunk }];
+}
+
+// What a call was given or answered arrives after the call itself.
+function updateToolPart(
+ parts: AiChatPart[],
+ toolCallId: string,
+ update: (part: AiChatToolPart) => AiChatToolPart,
+): AiChatPart[] {
+ return parts.map((part) =>
+ part.type === 'tool' && part.toolCallId === toolCallId ? update(part) : part,
+ );
+}
-// Drives one conversation with an internal agent. Sends a prompt, streams the
-// response over SSE (see streamAiAgentRun), and exposes the running transcript, the
-// stream status, and the tool the agent is currently using (for the status marker).
+// 'queued' is the wait an external agent's message goes through: it is on the feed and
+// no runner has taken it yet, so nothing is being written.
+export type ChatStatus = 'ready' | 'queued' | 'streaming';
+
+// Drives one conversation with an agent. Sends a prompt, streams the response over
+// SSE, and exposes the running transcript, the stream status, and the tool the agent
+// is currently using (for the status marker).
+//
+// An internal agent answers in the API process (streamAiAgentRun); an external one is
+// answered by its runner on the operator's machine (streamAiAgentChat), which is why
+// its answer starts only once that runner picks the message up. Both produce the same
+// events, so everything below is the same for either.
//
// When the agent has memory enabled, the run belongs to a conversation thread: the
// thread id returned by the first message is kept so follow-up messages continue it,
// and it is surfaced as `threadId` so the host can reflect the new thread in the
// history list. loadThread() restores a past conversation; newChat() starts a fresh
// one. threadId is null while a new conversation has not produced its first reply.
-export function useAgentChat(projectKey: string, agentId: number) {
+export function useAgentChat(projectKey: string, agentId: number, external: boolean) {
const t = useTranslations('common.agentChat');
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [status, setStatus] = useState<ChatStatus>('ready');
@@ -32,37 +57,70 @@ export function useAgentChat(projectKey: string, agentId: number) {
const send = useCallback(
async (prompt: string) => {
const text = prompt.trim();
- if (!text || status === 'streaming') return;
+ if (!text || status !== 'ready') return;
const assistantId = crypto.randomUUID();
const createdAt = new Date().toISOString();
setMessages((m) => [
...m,
- { id: crypto.randomUUID(), role: 'user', text, createdAt },
- { id: assistantId, role: 'assistant', text: '', createdAt },
+ { id: crypto.randomUUID(), role: 'user', parts: [{ type: 'text', text }], createdAt },
+ { id: assistantId, role: 'assistant', parts: [], createdAt },
]);
- setStatus('streaming');
+ setStatus(external ? 'queued' : 'streaming');
setActiveTool(null);
- const appendToAssistant = (chunk: string) =>
+ const growAssistant = (grow: (parts: AiChatPart[]) => AiChatPart[]) =>
setMessages((m) =>
- m.map((msg) => (msg.id === assistantId ? { ...msg, text: msg.text + chunk } : msg)),
+ m.map((msg) => (msg.id === assistantId ? { ...msg, parts: grow(msg.parts) } : msg)),
);
+ const stream = external ? streamAiAgentChat : streamAiAgentRun;
try {
- for await (const event of streamAiAgentRun(projectKey, agentId, {
+ for await (const event of stream(projectKey, agentId, {
prompt: text,
threadId: threadRef.current,
})) {
switch (event.type) {
case 'text':
- appendToAssistant(event.value);
+ // The first thing the agent produces is what says a runner took the
+ // message, so the wait ends here rather than on a status of its own.
+ setStatus('streaming');
+ // Writing the answer means the tool it was using is behind it, which is
+ // the only end some CLIs report at all.
+ setActiveTool(null);
+ growAssistant((parts) => appendText(parts, event.value));
break;
case 'tool-start':
+ setStatus('streaming');
setActiveTool(event.toolName);
+ growAssistant((parts) => [
+ ...parts,
+ {
+ type: 'tool',
+ toolCallId: event.toolCallId,
+ toolName: event.toolName,
+ args: event.args,
+ },
+ ]);
+ break;
+ case 'tool-args':
+ growAssistant((parts) =>
+ updateToolPart(parts, event.toolCallId, (tool) => ({
+ ...tool,
+ args: (tool.args ?? '') + event.delta,
+ })),
+ );
break;
case 'tool-end':
setActiveTool(null);
+ if (event.result) {
+ growAssistant((parts) =>
+ updateToolPart(parts, event.toolCallId, (tool) => ({
+ ...tool,
+ result: event.result,
+ })),
+ );
+ }
break;
case 'done':
threadRef.current = event.threadId;
@@ -78,12 +136,12 @@ export function useAgentChat(projectKey: string, agentId: number) {
} finally {
setStatus('ready');
setActiveTool(null);
- // Drop the assistant placeholder if it never received any text (an error
+ // Drop the assistant placeholder if the agent never produced anything (an error
// before the first chunk), so an empty bubble is not left behind.
- setMessages((m) => m.filter((msg) => !(msg.id === assistantId && msg.text === '')));
+ setMessages((m) => m.filter((msg) => !(msg.id === assistantId && msg.parts.length === 0)));
}
},
- [projectKey, agentId, status, t],
+ [projectKey, agentId, status, external, t],
);
// Restores a past conversation: shows its transcript and continues its thread.
@@ -103,7 +161,6 @@ export function useAgentChat(projectKey: string, agentId: number) {
});
}, []);
- // Starts a fresh conversation (no thread yet).
const newChat = useCallback(() => {
threadRef.current = null;
setThreadId(null);
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 037640e0..b302621c 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -452,25 +452,44 @@ export interface NewConfiguredToolInput {
// conversation thread id; `error` reports a failure that happened mid-run.
export type AgentRunEvent =
| { type: 'text'; value: string }
- | { type: 'tool-start'; toolCallId: string; toolName: string }
- | { type: 'tool-end'; toolCallId: string; toolName: string }
+ | { type: 'tool-start'; toolCallId: string; toolName: string; args?: string }
+ // An external agent's runner sends a call's arguments after the call itself, in
+ // pieces; an internal agent has them all at its start.
+ | { type: 'tool-args'; toolCallId: string; delta: string }
+ | { type: 'tool-end'; toolCallId: string; result?: string }
| { type: 'done'; threadId: string | null }
| { type: 'error'; message: string };
// One of the caller's saved chat conversations with an agent. `title` is the first
-// prompt (truncated); null when it was never set.
+// prompt (truncated); null when it was never set. `cliSessionId` is the coding agent
+// session an external agent's runner keeps for the thread on its own machine — null
+// before the runner has reported one, and always null for an internal agent.
export interface AiChatThread {
id: string;
title: string | null;
+ cliSessionId: string | null;
createdAt: string;
updatedAt: string;
}
+// One piece of a message, in the order the agent produced it: what it wrote, and the
+// tools it called between one stretch of text and the next. A call carries what it was
+// given and what it answered where the agent reported them.
+export interface AiChatToolPart {
+ type: 'tool';
+ toolCallId: string;
+ toolName: string;
+ args?: string;
+ result?: string;
+}
+
+export type AiChatPart = { type: 'text'; text: string } | AiChatToolPart;
+
// One restored message of a chat thread's transcript.
export interface AiChatMessage {
id: string;
role: 'user' | 'assistant';
- text: string;
+ parts: AiChatPart[];
createdAt: string;
}
@@ -497,6 +516,15 @@ export async function* streamAiAgentRun(
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
+ for await (const frame of readSseFrames(res)) {
+ yield JSON.parse(frame.data) as AgentRunEvent;
+ }
+}
+
+// The frames of one SSE connection: separated by a blank line, each carrying a single
+// JSON-encoded event on its `data:` line and, on a resumable stream, the `id:` a
+// reconnect resumes from. Throws ApiError when the request failed before the stream.
+async function* readSseFrames(res: Response): AsyncGenerator<{ id: number | null; data: string }> {
if (!res.ok || !res.body) {
const err = await res.json().catch(() => null);
throw new ApiError(res.status, err?.error ?? `${res.status} ${res.statusText}`);
@@ -505,20 +533,107 @@ export async function* streamAiAgentRun(
let buffer = '';
for (;;) {
const { done, value } = await reader.read();
- if (done) break;
+ if (done) return;
buffer += value;
- // SSE frames are separated by a blank line; each frame here is a single
- // `data:` line carrying one JSON-encoded event.
let sep: number;
while ((sep = buffer.indexOf('\n\n')) !== -1) {
- const frame = buffer.slice(0, sep);
+ const lines = buffer.slice(0, sep).split('\n');
buffer = buffer.slice(sep + 2);
- const line = frame.split('\n').find((l) => l.startsWith('data:'));
- if (line) yield JSON.parse(line.slice(5).trim()) as AgentRunEvent;
+ const dataLine = lines.find((l) => l.startsWith('data:'));
+ if (!dataLine) continue;
+ const idLine = lines.find((l) => l.startsWith('id:'));
+ yield {
+ id: idLine ? Number(idLine.slice(3).trim()) : null,
+ data: dataLine.slice(5).trim(),
+ };
}
}
}
+// What an external agent's runner reports while it answers, as AG-UI events
+// (https://docs.ag-ui.com). Only the ones the chat renders are named; the rest of the
+// protocol passes through and is ignored here.
+interface AgUiEvent {
+ type: string;
+ delta?: string;
+ content?: string;
+ message?: string;
+ toolCallId?: string;
+ toolCallName?: string;
+}
+
+// How many times a dropped stream is picked up again. The answer keeps being produced
+// on the operator's machine either way; this only decides how long the browser follows it.
+const CHAT_STREAM_RETRIES = 3;
+
+// Sends a message to an external agent and streams the answer its runner produces,
+// yielding the same events as an internal agent's run so the chat consumes one shape.
+// The answer starts only once a runner takes the message: until then the stream is open
+// with nothing on it.
+export async function* streamAiAgentChat(
+ projectKey: string,
+ agentId: number,
+ input: { prompt: string; threadId?: string | null },
+): AsyncGenerator<AgentRunEvent> {
+ const body = input.threadId
+ ? { prompt: input.prompt, threadId: input.threadId }
+ : { prompt: input.prompt };
+ const sent = await request<{ threadId: string; messageId: number }>(
+ `/projects/${projectKey}/ai-agents/${agentId}/chat`,
+ { method: 'POST', body: JSON.stringify(body) },
+ );
+ const base = `${API_URL}/projects/${projectKey}/ai-agents/${agentId}/chat/${sent.messageId}/stream`;
+ let after = 0;
+ // The answer always ends on a terminal event, so a stream that closed without one was
+ // cut: pick it up again from the last event already shown.
+ for (let attempt = 0; attempt <= CHAT_STREAM_RETRIES; attempt++) {
+ let ended = false;
+ try {
+ const res = await fetch(`${base}?after=${after}`, { credentials: 'include' });
+ for await (const frame of readSseFrames(res)) {
+ after = frame.id ?? after;
+ const event = JSON.parse(frame.data) as AgUiEvent;
+ if (event.type === 'RUN_FINISHED') {
+ ended = true;
+ break;
+ }
+ if (event.type === 'RUN_ERROR') {
+ ended = true;
+ yield { type: 'error', message: event.message ?? 'The agent stopped answering' };
+ break;
+ }
+ const mapped = toRunEvent(event);
+ if (mapped) yield mapped;
+ }
+ } catch (err) {
+ if (attempt === CHAT_STREAM_RETRIES) throw err;
+ }
+ if (ended) break;
+ }
+ yield { type: 'done', threadId: sent.threadId };
+}
+
+function toRunEvent(event: AgUiEvent): AgentRunEvent | null {
+ switch (event.type) {
+ case 'TEXT_MESSAGE_CONTENT':
+ return { type: 'text', value: event.delta ?? '' };
+ case 'TOOL_CALL_START':
+ return {
+ type: 'tool-start',
+ toolCallId: event.toolCallId ?? '',
+ toolName: event.toolCallName ?? '',
+ };
+ case 'TOOL_CALL_ARGS':
+ return { type: 'tool-args', toolCallId: event.toolCallId ?? '', delta: event.delta ?? '' };
+ // TOOL_CALL_END closes the call's arguments, which the runner reports in the same
+ // batch as the call itself. The tool is done when its result arrives.
+ case 'TOOL_CALL_RESULT':
+ return { type: 'tool-end', toolCallId: event.toolCallId ?? '', result: event.content };
+ default:
+ return null;
+ }
+}
+
export type CustomFieldType =
| 'text'
| 'markdown'
diff --git a/apps/web/src/lib/highlight.tsx b/apps/web/src/lib/highlight.tsx
new file mode 100644
index 00000000..b4a1fca8
--- /dev/null
+++ b/apps/web/src/lib/highlight.tsx
@@ -0,0 +1,39 @@
+import json from 'highlight.js/lib/languages/json';
+import { createLowlight } from 'lowlight';
+import type { ReactNode } from 'react';
+
+// Highlighting for the JSON a chat shows. Registering the one grammar keeps the rest of
+// highlight.js out of the bundle; the `hljs-*` class names it emits are coloured by the
+// `.md-content` palette in globals.css, so a block has to be rendered inside it.
+
+const lowlight = createLowlight({ json });
+
+// What lowlight returns: a highlighted block is made of text and of spans carrying the
+// `hljs-*` classes, nothing else.
+type HastNode =
+ | { type: 'text'; value: string }
+ | { type: 'element'; properties?: { className?: string[] }; children: HastNode[] };
+
+// The value indented and highlighted, or null when it is not JSON — a tool that
+// answered in plain text is shown as it wrote it.
+export function highlightJson(value: string): ReactNode | null {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ return null;
+ }
+ const tree = lowlight.highlight('json', JSON.stringify(parsed, null, 2));
+ return toNodes(tree.children as HastNode[]);
+}
+
+function toNodes(nodes: HastNode[]): ReactNode {
+ return nodes.map((node, index) => {
+ if (node.type === 'text') return node.value;
+ return (
+ <span key={index} className={node.properties?.className?.join(' ')}>
+ {toNodes(node.children)}
+ </span>
+ );
+ });
+}
diff --git a/bun.lock b/bun.lock
index 9ab6c58b..67c9d3b8 100644
--- a/bun.lock
+++ b/bun.lock
@@ -100,6 +100,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^4.4.0",
+ "highlight.js": "~11.11.0",
"inter-ui": "^4.1.1",
"isomorphic-dompurify": "^3.22.0",
"lowlight": "^3.3.0",
@@ -239,12 +240,13 @@
},
"packages/runner": {
"name": "@itsaplan/runner",
- "version": "0.1.0",
+ "version": "0.2.0",
"bin": {
"itsaplan-runner": "./dist/cli.js",
},
"devDependencies": {
"@repo/eslint-config": "workspace:*",
+ "@types/bun": "latest",
"@types/node": "^26.2.0",
"eslint": "^9.39.0",
"typescript": "^6.0.3",
diff --git a/docs/runner.md b/docs/runner.md
new file mode 100644
index 00000000..13e82a0b
--- /dev/null
+++ b/docs/runner.md
@@ -0,0 +1,192 @@
+# Coding agent setup
+
+[`@itsaplan/runner`](https://www.npmjs.com/package/@itsaplan/runner) runs an external agent
+on your own machine. It has a preset for each of five coding agent CLIs. A preset builds
+the command itself: the flags for an unattended run, and the session resume.
+
+Each preset needs two files in the working directory:
+
+- the CLI's own config, which points it at the MCP server of your instance,
+- `itsaplan-runner.json`, which points the runner at your instance.
+
+This page holds both files for each preset, and the notes that apply to that CLI. The
+runner's own settings are in its
+[README](https://github.com/croffasia/itsaplan/blob/main/packages/runner/README.md).
+
+Enable MCP for the project first, in Settings, MCP Server. It is off by default.
+
+## Claude Code
+
+Claude Code reads `.mcp.json` from the working directory:
+
+```json
+{
+ "mcpServers": {
+ "itsaplan": {
+ "type": "http",
+ "url": "http://localhost:3000/mcp",
+ "headers": { "Authorization": "Bearer ${ITSAPLAN_API_KEY}" }
+ }
+ }
+}
+```
+
+`itsaplan-runner.json`:
+
+```json
+{
+ "url": "http://localhost:3000",
+ "apiKey": "the key you copied on creation",
+ "agent": "claude",
+ "cwd": "/Users/me/work/my-repo"
+}
+```
+
+- Claude Code uses this server in addition to the servers that the machine already has.
+ Your own MCP servers, skills and memory stay available in the run. For a file in a
+ different location, set `"args": ["--mcp-config", "/path/to/mcp.json"]`.
+- The preset passes `--permission-mode auto`. No person is available to approve an action.
+ A classifier thus examines each action, MCP tool calls included. Repeat the flag in
+ `args` to select a different mode.
+- The preset also passes `--output-format stream-json --include-partial-messages`. This
+ stream gives the chat answer word by word, and includes the tool calls.
+ `--append-system-prompt` gives Claude Code the context of the run.
+
+## Codex
+
+Codex reads its MCP servers from `~/.codex/config.toml`. `bearer_token_env_var` takes the
+key from the environment that the runner sets:
+
+```toml
+[mcp_servers.itsaplan]
+url = "http://localhost:3000/mcp"
+bearer_token_env_var = "ITSAPLAN_API_KEY"
+```
+
+`itsaplan-runner.json`:
+
+```json
+{
+ "url": "http://localhost:3000",
+ "apiKey": "the key you copied on creation",
+ "agent": "codex",
+ "cwd": "/path/to/working-dir",
+ "args": ["--skip-git-repo-check"]
+}
+```
+
+- Codex has no system-prompt flag. The preset puts the context of the run before the task.
+ The preset sends both on stdin.
+- The preset passes `-c sandbox_mode="workspace-write"`. Codex then writes only in the
+ working directory. The preset uses a config override and not `--sandbox`, because
+ `codex exec resume` does not accept that flag. `codex exec resume` runs each message
+ after the first one. Each argument that you add must thus be applicable to `codex exec`
+ and to `codex exec resume`.
+- Add `--skip-git-repo-check` only if the working directory is not a git repository.
+
+## Gemini CLI
+
+Gemini CLI reads `.gemini/settings.json` from the working directory. It expands `$VARS`.
+The key thus comes from the environment. `trust` removes the tool confirmation, which a
+headless run cannot answer:
+
+```json
+{
+ "mcpServers": {
+ "itsaplan": {
+ "httpUrl": "http://localhost:3000/mcp",
+ "headers": { "Authorization": "Bearer $ITSAPLAN_API_KEY" },
+ "trust": true
+ }
+ }
+}
+```
+
+`itsaplan-runner.json`:
+
+```json
+{
+ "url": "http://localhost:3000",
+ "apiKey": "the key you copied on creation",
+ "agent": "gemini",
+ "cwd": "/path/to/working-dir"
+}
+```
+
+- Gemini CLI also has no system-prompt flag. The preset puts the context of the run before
+ the task, and sends both in one `-p` argument.
+- The preset passes `--approval-mode yolo`, which approves each tool call. Repeat the flag
+ in `args` for `auto_edit`, which approves only file changes.
+- Gemini CLI keeps no session. Each chat message thus includes the conversation.
+
+## GitHub Copilot CLI
+
+GitHub Copilot CLI reads `.mcp.json` from the working directory. Its headers accept no
+variables. You thus write the key in the file:
+
+```json
+{
+ "mcpServers": {
+ "itsaplan": {
+ "type": "http",
+ "url": "http://localhost:3000/mcp",
+ "headers": { "Authorization": "Bearer the-agent-key" },
+ "tools": ["*"]
+ }
+ }
+}
+```
+
+`itsaplan-runner.json`:
+
+```json
+{
+ "url": "http://localhost:3000",
+ "apiKey": "the key you copied on creation",
+ "agent": "copilot",
+ "cwd": "/path/to/working-dir"
+}
+```
+
+- Copilot CLI has no system-prompt flag, and it does not read stdin. The preset thus sends
+ the context of the run and the task in one `-p` argument.
+- The preset passes `--allow-all-tools` and `--no-ask-user`. Copilot CLI then does not
+ wait for an approval.
+- Copilot CLI keeps no session. Each chat message thus includes the conversation.
+
+## opencode
+
+opencode reads `opencode.json` from the working directory. It expands `{env:VAR}`. The key
+thus stays out of the file:
+
+```json
+{
+ "$schema": "https://opencode.ai/config.json",
+ "model": "anthropic/claude-sonnet-5",
+ "mcp": {
+ "itsaplan": {
+ "type": "remote",
+ "url": "http://localhost:3000/mcp",
+ "enabled": true,
+ "headers": { "Authorization": "Bearer {env:ITSAPLAN_API_KEY}" }
+ }
+ }
+}
+```
+
+`itsaplan-runner.json`:
+
+```json
+{
+ "url": "http://localhost:3000",
+ "apiKey": "the key you copied on creation",
+ "agent": "opencode",
+ "cwd": "/path/to/working-dir"
+}
+```
+
+- `opencode run` takes the prompt as an argument and does not read stdin. The preset thus
+ sends the context of the run and the task in one argument.
+- Set `model` as `provider/model`. opencode supports many providers. Without this key, a
+ run uses the model of the last interactive session. Run `opencode auth login` to make a
+ provider available.
diff --git a/packages/db/drizzle/0083_ambitious_wendell_rand.sql b/packages/db/drizzle/0083_ambitious_wendell_rand.sql
new file mode 100644
index 00000000..d2b6f48f
--- /dev/null
+++ b/packages/db/drizzle/0083_ambitious_wendell_rand.sql
@@ -0,0 +1,42 @@
+CREATE TABLE "agent_chat_event" (
+ "id" bigserial PRIMARY KEY NOT NULL,
+ "message_id" integer NOT NULL,
+ "payload" jsonb NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "agent_chat_message" (
+ "id" serial PRIMARY KEY NOT NULL,
+ "thread_id" text NOT NULL,
+ "agent_id" integer NOT NULL,
+ "role" text NOT NULL,
+ "content" text DEFAULT '' NOT NULL,
+ "status" text DEFAULT 'pending' NOT NULL,
+ "attempts" integer DEFAULT 0 NOT NULL,
+ "next_attempt_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "last_error" text,
+ "started_at" timestamp with time zone,
+ "finished_at" timestamp with time zone,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "agent_chat_message_role_check" CHECK ("agent_chat_message"."role" IN ('user', 'assistant')),
+ CONSTRAINT "agent_chat_message_status_check" CHECK ("agent_chat_message"."status" IN ('pending', 'streaming', 'success', 'failed'))
+);
+--> statement-breakpoint
+CREATE TABLE "agent_chat_thread" (
+ "id" text PRIMARY KEY NOT NULL,
+ "agent_id" integer NOT NULL,
+ "user_id" text NOT NULL,
+ "title" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+ALTER TABLE "agent_chat_event" ADD CONSTRAINT "agent_chat_event_message_id_agent_chat_message_id_fk" FOREIGN KEY ("message_id") REFERENCES "public"."agent_chat_message"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_chat_message" ADD CONSTRAINT "agent_chat_message_thread_id_agent_chat_thread_id_fk" FOREIGN KEY ("thread_id") REFERENCES "public"."agent_chat_thread"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_chat_message" ADD CONSTRAINT "agent_chat_message_agent_id_ai_agent_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."ai_agent"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_chat_thread" ADD CONSTRAINT "agent_chat_thread_agent_id_ai_agent_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."ai_agent"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_chat_thread" ADD CONSTRAINT "agent_chat_thread_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+CREATE INDEX "agent_chat_event_message_idx" ON "agent_chat_event" USING btree ("message_id","id");--> statement-breakpoint
+CREATE INDEX "agent_chat_message_thread_idx" ON "agent_chat_message" USING btree ("thread_id","id");--> statement-breakpoint
+CREATE INDEX "agent_chat_message_due_idx" ON "agent_chat_message" USING btree ("agent_id","next_attempt_at") WHERE "agent_chat_message"."status" IN ('pending', 'streaming');--> statement-breakpoint
+CREATE INDEX "agent_chat_thread_agent_user_idx" ON "agent_chat_thread" USING btree ("agent_id","user_id","updated_at" DESC NULLS LAST);
\ No newline at end of file
diff --git a/packages/db/drizzle/0084_busy_speed_demon.sql b/packages/db/drizzle/0084_busy_speed_demon.sql
new file mode 100644
index 00000000..f131b383
--- /dev/null
+++ b/packages/db/drizzle/0084_busy_speed_demon.sql
@@ -0,0 +1 @@
+ALTER TABLE "agent_chat_thread" ADD COLUMN "cli_session_id" text;
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0083_snapshot.json b/packages/db/drizzle/meta/0083_snapshot.json
new file mode 100644
index 00000000..4878b6e4
--- /dev/null
+++ b/packages/db/drizzle/meta/0083_snapshot.json
@@ -0,0 +1,6525 @@
+{
+ "id": "328596c3-0865-4b0a-a57a-fd5034f031cb",
+ "prevId": "ed8f4570-7b18-4fb8-a7ae-3f0518ecfb9b",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "account_userId_idx": {
+ "name": "account_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.apikey": {
+ "name": "apikey",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "config_id": {
+ "name": "config_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'default'"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start": {
+ "name": "start",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reference_id": {
+ "name": "reference_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prefix": {
+ "name": "prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refill_interval": {
+ "name": "refill_interval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refill_amount": {
+ "name": "refill_amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_refill_at": {
+ "name": "last_refill_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "rate_limit_enabled": {
+ "name": "rate_limit_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "rate_limit_time_window": {
+ "name": "rate_limit_time_window",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 1000
+ },
+ "rate_limit_max": {
+ "name": "rate_limit_max",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 100
+ },
+ "request_count": {
+ "name": "request_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "remaining": {
+ "name": "remaining",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_request": {
+ "name": "last_request",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "apikey_configId_idx": {
+ "name": "apikey_configId_idx",
+ "columns": [
+ {
+ "expression": "config_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "apikey_referenceId_idx": {
+ "name": "apikey_referenceId_idx",
+ "columns": [
+ {
+ "expression": "reference_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "apikey_key_idx": {
+ "name": "apikey_key_idx",
+ "columns": [
+ {
+ "expression": "key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.passkey": {
+ "name": "passkey",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "public_key": {
+ "name": "public_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credential_id": {
+ "name": "credential_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "counter": {
+ "name": "counter",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "device_type": {
+ "name": "device_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "backed_up": {
+ "name": "backed_up",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "transports": {
+ "name": "transports",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "aaguid": {
+ "name": "aaguid",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "passkey_userId_idx": {
+ "name": "passkey_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "passkey_credentialID_idx": {
+ "name": "passkey_credentialID_idx",
+ "columns": [
+ {
+ "expression": "credential_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "passkey_user_id_user_id_fk": {
+ "name": "passkey_user_id_user_id_fk",
+ "tableFrom": "passkey",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "session_userId_idx": {
+ "name": "session_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'user'"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "verification_identifier_idx": {
+ "name": "verification_identifier_idx",
+ "columns": [
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_chat_event": {
+ "name": "agent_chat_event",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigserial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_chat_event_message_idx": {
+ "name": "agent_chat_event_message_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_chat_event_message_id_agent_chat_message_id_fk": {
+ "name": "agent_chat_event_message_id_agent_chat_message_id_fk",
+ "tableFrom": "agent_chat_event",
+ "tableTo": "agent_chat_message",
+ "columnsFrom": [
+ "message_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_chat_message": {
+ "name": "agent_chat_message",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_chat_message_thread_idx": {
+ "name": "agent_chat_message_thread_idx",
+ "columns": [
+ {
+ "expression": "thread_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_chat_message_due_idx": {
+ "name": "agent_chat_message_due_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "next_attempt_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"agent_chat_message\".\"status\" IN ('pending', 'streaming')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_chat_message_thread_id_agent_chat_thread_id_fk": {
+ "name": "agent_chat_message_thread_id_agent_chat_thread_id_fk",
+ "tableFrom": "agent_chat_message",
+ "tableTo": "agent_chat_thread",
+ "columnsFrom": [
+ "thread_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_chat_message_agent_id_ai_agent_id_fk": {
+ "name": "agent_chat_message_agent_id_ai_agent_id_fk",
+ "tableFrom": "agent_chat_message",
+ "tableTo": "ai_agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "agent_chat_message_role_check": {
+ "name": "agent_chat_message_role_check",
+ "value": "\"agent_chat_message\".\"role\" IN ('user', 'assistant')"
+ },
+ "agent_chat_message_status_check": {
+ "name": "agent_chat_message_status_check",
+ "value": "\"agent_chat_message\".\"status\" IN ('pending', 'streaming', 'success', 'failed')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_chat_thread": {
+ "name": "agent_chat_thread",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_chat_thread_agent_user_idx": {
+ "name": "agent_chat_thread_agent_user_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_chat_thread_agent_id_ai_agent_id_fk": {
+ "name": "agent_chat_thread_agent_id_ai_agent_id_fk",
+ "tableFrom": "agent_chat_thread",
+ "tableTo": "ai_agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_chat_thread_user_id_user_id_fk": {
+ "name": "agent_chat_thread_user_id_user_id_fk",
+ "tableFrom": "agent_chat_thread",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_run": {
+ "name": "agent_run",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "schedule_id": {
+ "name": "schedule_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'delegation'"
+ },
+ "scheduled_for": {
+ "name": "scheduled_for",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_activity_id": {
+ "name": "source_activity_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "output": {
+ "name": "output",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_run_schedule_fire_uq": {
+ "name": "agent_run_schedule_fire_uq",
+ "columns": [
+ {
+ "expression": "schedule_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scheduled_for",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_run_due_idx": {
+ "name": "agent_run_due_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "next_attempt_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_run_schedule_idx": {
+ "name": "agent_run_schedule_idx",
+ "columns": [
+ {
+ "expression": "schedule_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_run_agent_id_ai_agent_id_fk": {
+ "name": "agent_run_agent_id_ai_agent_id_fk",
+ "tableFrom": "agent_run",
+ "tableTo": "ai_agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_run_issue_id_issue_id_fk": {
+ "name": "agent_run_issue_id_issue_id_fk",
+ "tableFrom": "agent_run",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_run_schedule_id_agent_schedule_id_fk": {
+ "name": "agent_run_schedule_id_agent_schedule_id_fk",
+ "tableFrom": "agent_run",
+ "tableTo": "agent_schedule",
+ "columnsFrom": [
+ "schedule_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_run_source_activity_id_issue_activity_id_fk": {
+ "name": "agent_run_source_activity_id_issue_activity_id_fk",
+ "tableFrom": "agent_run",
+ "tableTo": "issue_activity",
+ "columnsFrom": [
+ "source_activity_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "agent_run_status_check": {
+ "name": "agent_run_status_check",
+ "value": "\"agent_run\".\"status\" IN ('pending', 'success', 'failed', 'canceled')"
+ },
+ "agent_run_trigger_check": {
+ "name": "agent_run_trigger_check",
+ "value": "\"agent_run\".\"trigger\" IN ('mention', 'delegation', 'schedule', 'manual')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_schedule": {
+ "name": "agent_schedule",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cron": {
+ "name": "cron",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "next_run_at": {
+ "name": "next_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "last_run_at": {
+ "name": "last_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_schedule_due_idx": {
+ "name": "agent_schedule_due_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "next_run_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_schedule_agent_idx": {
+ "name": "agent_schedule_agent_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_schedule_agent_id_ai_agent_id_fk": {
+ "name": "agent_schedule_agent_id_ai_agent_id_fk",
+ "tableFrom": "agent_schedule",
+ "tableTo": "ai_agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "agent_schedule_agent_id_name_unique": {
+ "name": "agent_schedule_agent_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "agent_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "agent_schedule_status_check": {
+ "name": "agent_schedule_status_check",
+ "value": "\"agent_schedule\".\"status\" IN ('active', 'paused')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_skill": {
+ "name": "agent_skill",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_url": {
+ "name": "source_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "s3_prefix": {
+ "name": "s3_prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "files": {
+ "name": "files",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_skill_project_idx": {
+ "name": "agent_skill_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_skill_project_id_project_id_fk": {
+ "name": "agent_skill_project_id_project_id_fk",
+ "tableFrom": "agent_skill",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "agent_skill_project_id_name_unique": {
+ "name": "agent_skill_project_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "agent_skill_source_check": {
+ "name": "agent_skill_source_check",
+ "value": "\"agent_skill\".\"source\" IN ('upload', 'inline', 'github')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_skill_link": {
+ "name": "agent_skill_link",
+ "schema": "",
+ "columns": {
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "skill_id": {
+ "name": "skill_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "agent_skill_link_skill_idx": {
+ "name": "agent_skill_link_skill_idx",
+ "columns": [
+ {
+ "expression": "skill_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_skill_link_agent_id_ai_agent_id_fk": {
+ "name": "agent_skill_link_agent_id_ai_agent_id_fk",
+ "tableFrom": "agent_skill_link",
+ "tableTo": "ai_agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_skill_link_skill_id_agent_skill_id_fk": {
+ "name": "agent_skill_link_skill_id_agent_skill_id_fk",
+ "tableFrom": "agent_skill_link",
+ "tableTo": "agent_skill",
+ "columnsFrom": [
+ "skill_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "agent_skill_link_agent_id_skill_id_pk": {
+ "name": "agent_skill_link_agent_id_skill_id_pk",
+ "columns": [
+ "agent_id",
+ "skill_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_tool": {
+ "name": "agent_tool",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool_key": {
+ "name": "tool_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credential_id": {
+ "name": "credential_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_tool_project_idx": {
+ "name": "agent_tool_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_tool_credential_idx": {
+ "name": "agent_tool_credential_idx",
+ "columns": [
+ {
+ "expression": "credential_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_tool_project_id_project_id_fk": {
+ "name": "agent_tool_project_id_project_id_fk",
+ "tableFrom": "agent_tool",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_tool_credential_id_integration_credential_id_fk": {
+ "name": "agent_tool_credential_id_integration_credential_id_fk",
+ "tableFrom": "agent_tool",
+ "tableTo": "integration_credential",
+ "columnsFrom": [
+ "credential_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "agent_tool_project_id_tool_key_credential_id_unique": {
+ "name": "agent_tool_project_id_tool_key_credential_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "tool_key",
+ "credential_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_tool_link": {
+ "name": "agent_tool_link",
+ "schema": "",
+ "columns": {
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_tool_id": {
+ "name": "agent_tool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "agent_tool_link_tool_idx": {
+ "name": "agent_tool_link_tool_idx",
+ "columns": [
+ {
+ "expression": "agent_tool_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_tool_link_agent_id_ai_agent_id_fk": {
+ "name": "agent_tool_link_agent_id_ai_agent_id_fk",
+ "tableFrom": "agent_tool_link",
+ "tableTo": "ai_agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_tool_link_agent_tool_id_agent_tool_id_fk": {
+ "name": "agent_tool_link_agent_tool_id_agent_tool_id_fk",
+ "tableFrom": "agent_tool_link",
+ "tableTo": "agent_tool",
+ "columnsFrom": [
+ "agent_tool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "agent_tool_link_agent_id_agent_tool_id_pk": {
+ "name": "agent_tool_link_agent_id_agent_tool_id_pk",
+ "columns": [
+ "agent_id",
+ "agent_tool_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_agent": {
+ "name": "ai_agent",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "username": {
+ "name": "username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "model_credential_id": {
+ "name": "model_credential_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "instructions": {
+ "name": "instructions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tools": {
+ "name": "tools",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "temperature": {
+ "name": "temperature",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "max_steps": {
+ "name": "max_steps",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trigger_on_mention": {
+ "name": "trigger_on_mention",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "trigger_on_assign": {
+ "name": "trigger_on_assign",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "delegation_delay_sec": {
+ "name": "delegation_delay_sec",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 120
+ },
+ "role_id": {
+ "name": "role_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "api_key_ciphertext": {
+ "name": "api_key_ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "api_key_iv": {
+ "name": "api_key_iv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "api_key_auth_tag": {
+ "name": "api_key_auth_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "memory_enabled": {
+ "name": "memory_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "memory_last_messages": {
+ "name": "memory_last_messages",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "owner_user_id": {
+ "name": "owner_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "runner_scope": {
+ "name": "runner_scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'project'"
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "ai_agent_project_idx": {
+ "name": "ai_agent_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "ai_agent_project_id_project_id_fk": {
+ "name": "ai_agent_project_id_project_id_fk",
+ "tableFrom": "ai_agent",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_agent_user_id_user_id_fk": {
+ "name": "ai_agent_user_id_user_id_fk",
+ "tableFrom": "ai_agent",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_agent_model_credential_id_integration_credential_id_fk": {
+ "name": "ai_agent_model_credential_id_integration_credential_id_fk",
+ "tableFrom": "ai_agent",
+ "tableTo": "integration_credential",
+ "columnsFrom": [
+ "model_credential_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "ai_agent_role_id_project_role_id_fk": {
+ "name": "ai_agent_role_id_project_role_id_fk",
+ "tableFrom": "ai_agent",
+ "tableTo": "project_role",
+ "columnsFrom": [
+ "role_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "ai_agent_owner_user_id_user_id_fk": {
+ "name": "ai_agent_owner_user_id_user_id_fk",
+ "tableFrom": "ai_agent",
+ "tableTo": "user",
+ "columnsFrom": [
+ "owner_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "ai_agent_project_id_username_unique": {
+ "name": "ai_agent_project_id_username_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "username"
+ ]
+ },
+ "ai_agent_user_id_unique": {
+ "name": "ai_agent_user_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "ai_agent_kind_check": {
+ "name": "ai_agent_kind_check",
+ "value": "\"ai_agent\".\"kind\" IN ('external', 'internal')"
+ },
+ "ai_agent_runner_scope_check": {
+ "name": "ai_agent_runner_scope_check",
+ "value": "\"ai_agent\".\"runner_scope\" IN ('owner', 'project')"
+ },
+ "ai_agent_delegation_delay_check": {
+ "name": "ai_agent_delegation_delay_check",
+ "value": "\"ai_agent\".\"delegation_delay_sec\" >= 0 AND \"ai_agent\".\"delegation_delay_sec\" <= 86400"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.app_secret": {
+ "name": "app_secret",
+ "schema": "",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "ciphertext": {
+ "name": "ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "iv": {
+ "name": "iv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "auth_tag": {
+ "name": "auth_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redacted": {
+ "name": "redacted",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.app_setting": {
+ "name": "app_setting",
+ "schema": "",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.custom_field": {
+ "name": "custom_field",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_type_id": {
+ "name": "issue_type_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "field_type": {
+ "name": "field_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "show_in_body": {
+ "name": "show_in_body",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "custom_field_project_id_project_id_fk": {
+ "name": "custom_field_project_id_project_id_fk",
+ "tableFrom": "custom_field",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "custom_field_issue_type_id_issue_type_id_fk": {
+ "name": "custom_field_issue_type_id_issue_type_id_fk",
+ "tableFrom": "custom_field",
+ "tableTo": "issue_type",
+ "columnsFrom": [
+ "issue_type_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "custom_field_field_type_check": {
+ "name": "custom_field_field_type_check",
+ "value": "\"custom_field\".\"field_type\" IN ('text', 'markdown', 'url', 'number', 'boolean', 'date', 'datetime', 'datetime_range', 'select', 'multi_select')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.custom_field_option": {
+ "name": "custom_field_option",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "field_id": {
+ "name": "field_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'#6b7280'"
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "custom_field_option_field_id_custom_field_id_fk": {
+ "name": "custom_field_option_field_id_custom_field_id_fk",
+ "tableFrom": "custom_field_option",
+ "tableTo": "custom_field",
+ "columnsFrom": [
+ "field_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "custom_field_option_field_id_value_unique": {
+ "name": "custom_field_option_field_id_value_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "field_id",
+ "value"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.cycle": {
+ "name": "cycle",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "goal": {
+ "name": "goal",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "start_date": {
+ "name": "start_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "end_date": {
+ "name": "end_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "cycle_project_idx": {
+ "name": "cycle_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "start_date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "cycle_project_id_project_id_fk": {
+ "name": "cycle_project_id_project_id_fk",
+ "tableFrom": "cycle",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "cycle_dates_check": {
+ "name": "cycle_dates_check",
+ "value": "\"cycle\".\"end_date\" >= \"cycle\".\"start_date\""
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.initiative": {
+ "name": "initiative",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'planned'"
+ },
+ "owner_user_id": {
+ "name": "owner_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "priority": {
+ "name": "priority",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start_date": {
+ "name": "start_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "target_date": {
+ "name": "target_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "initiative_project_idx": {
+ "name": "initiative_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "initiative_project_id_project_id_fk": {
+ "name": "initiative_project_id_project_id_fk",
+ "tableFrom": "initiative",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "initiative_owner_user_id_user_id_fk": {
+ "name": "initiative_owner_user_id_user_id_fk",
+ "tableFrom": "initiative",
+ "tableTo": "user",
+ "columnsFrom": [
+ "owner_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "initiative_status_check": {
+ "name": "initiative_status_check",
+ "value": "\"initiative\".\"status\" IN ('proposed', 'planned', 'active', 'completed', 'canceled')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.initiative_label": {
+ "name": "initiative_label",
+ "schema": "",
+ "columns": {
+ "initiative_id": {
+ "name": "initiative_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "label_id": {
+ "name": "label_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "initiative_label_initiative_id_initiative_id_fk": {
+ "name": "initiative_label_initiative_id_initiative_id_fk",
+ "tableFrom": "initiative_label",
+ "tableTo": "initiative",
+ "columnsFrom": [
+ "initiative_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "initiative_label_label_id_label_id_fk": {
+ "name": "initiative_label_label_id_label_id_fk",
+ "tableFrom": "initiative_label",
+ "tableTo": "label",
+ "columnsFrom": [
+ "label_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "initiative_label_initiative_id_label_id_pk": {
+ "name": "initiative_label_initiative_id_label_id_pk",
+ "columns": [
+ "initiative_id",
+ "label_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.integration_credential": {
+ "name": "integration_credential",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "integration_key": {
+ "name": "integration_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ciphertext": {
+ "name": "ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "iv": {
+ "name": "iv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "auth_tag": {
+ "name": "auth_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redacted": {
+ "name": "redacted",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "integration_credential_project_idx": {
+ "name": "integration_credential_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "integration_credential_project_id_project_id_fk": {
+ "name": "integration_credential_project_id_project_id_fk",
+ "tableFrom": "integration_credential",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue": {
+ "name": "issue",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sequence_number": {
+ "name": "sequence_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type_id": {
+ "name": "type_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "initiative_id": {
+ "name": "initiative_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cycle_id": {
+ "name": "cycle_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "column_id": {
+ "name": "column_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "parent_id": {
+ "name": "parent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "assignee_user_id": {
+ "name": "assignee_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "delegate_user_id": {
+ "name": "delegate_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "priority": {
+ "name": "priority",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start_date": {
+ "name": "start_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "due_date": {
+ "name": "due_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "share_token": {
+ "name": "share_token",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "share_extended": {
+ "name": "share_extended",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_project_active_idx": {
+ "name": "issue_project_active_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "column_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"issue\".\"archived_at\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_parent_idx": {
+ "name": "issue_parent_idx",
+ "columns": [
+ {
+ "expression": "parent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"issue\".\"parent_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_cycle_idx": {
+ "name": "issue_cycle_idx",
+ "columns": [
+ {
+ "expression": "cycle_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"issue\".\"cycle_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_project_id_project_id_fk": {
+ "name": "issue_project_id_project_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_type_id_issue_type_id_fk": {
+ "name": "issue_type_id_issue_type_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "issue_type",
+ "columnsFrom": [
+ "type_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_initiative_id_initiative_id_fk": {
+ "name": "issue_initiative_id_initiative_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "initiative",
+ "columnsFrom": [
+ "initiative_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_cycle_id_cycle_id_fk": {
+ "name": "issue_cycle_id_cycle_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "cycle",
+ "columnsFrom": [
+ "cycle_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_column_id_project_column_id_fk": {
+ "name": "issue_column_id_project_column_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "project_column",
+ "columnsFrom": [
+ "column_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_parent_id_issue_id_fk": {
+ "name": "issue_parent_id_issue_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "parent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_assignee_user_id_user_id_fk": {
+ "name": "issue_assignee_user_id_user_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "user",
+ "columnsFrom": [
+ "assignee_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_delegate_user_id_user_id_fk": {
+ "name": "issue_delegate_user_id_user_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "user",
+ "columnsFrom": [
+ "delegate_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "issue_share_token_unique": {
+ "name": "issue_share_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "share_token"
+ ]
+ },
+ "issue_project_id_sequence_number_unique": {
+ "name": "issue_project_id_sequence_number_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "sequence_number"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_activity": {
+ "name": "issue_activity",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "initiative_id": {
+ "name": "initiative_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "actor_name": {
+ "name": "actor_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subject": {
+ "name": "subject",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "from_text": {
+ "name": "from_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "to_text": {
+ "name": "to_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_activity_issue_idx": {
+ "name": "issue_activity_issue_idx",
+ "columns": [
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_activity_initiative_idx": {
+ "name": "issue_activity_initiative_idx",
+ "columns": [
+ {
+ "expression": "initiative_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_activity_issue_id_issue_id_fk": {
+ "name": "issue_activity_issue_id_issue_id_fk",
+ "tableFrom": "issue_activity",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_activity_initiative_id_initiative_id_fk": {
+ "name": "issue_activity_initiative_id_initiative_id_fk",
+ "tableFrom": "issue_activity",
+ "tableTo": "initiative",
+ "columnsFrom": [
+ "initiative_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_activity_actor_user_id_user_id_fk": {
+ "name": "issue_activity_actor_user_id_user_id_fk",
+ "tableFrom": "issue_activity",
+ "tableTo": "user",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "issue_activity_kind_check": {
+ "name": "issue_activity_kind_check",
+ "value": "\"issue_activity\".\"kind\" IN ('comment', 'activity')"
+ },
+ "issue_activity_owner_check": {
+ "name": "issue_activity_owner_check",
+ "value": "(\"issue_activity\".\"issue_id\" IS NOT NULL) <> (\"issue_activity\".\"initiative_id\" IS NOT NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.issue_attachment": {
+ "name": "issue_attachment",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "public_id": {
+ "name": "public_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "s3_key": {
+ "name": "s3_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "filename": {
+ "name": "filename",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content_type": {
+ "name": "content_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "size_bytes": {
+ "name": "size_bytes",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_attachment_issue_idx": {
+ "name": "issue_attachment_issue_idx",
+ "columns": [
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_attachment_issue_id_issue_id_fk": {
+ "name": "issue_attachment_issue_id_issue_id_fk",
+ "tableFrom": "issue_attachment",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "issue_attachment_public_id_unique": {
+ "name": "issue_attachment_public_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "public_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_checklist": {
+ "name": "issue_checklist",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_checklist_issue_idx": {
+ "name": "issue_checklist_issue_idx",
+ "columns": [
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_checklist_issue_id_issue_id_fk": {
+ "name": "issue_checklist_issue_id_issue_id_fk",
+ "tableFrom": "issue_checklist",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_checklist_item": {
+ "name": "issue_checklist_item",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "checklist_id": {
+ "name": "checklist_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "done": {
+ "name": "done",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_checklist_item_checklist_idx": {
+ "name": "issue_checklist_item_checklist_idx",
+ "columns": [
+ {
+ "expression": "checklist_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_checklist_item_checklist_id_issue_checklist_id_fk": {
+ "name": "issue_checklist_item_checklist_id_issue_checklist_id_fk",
+ "tableFrom": "issue_checklist_item",
+ "tableTo": "issue_checklist",
+ "columnsFrom": [
+ "checklist_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_field_option": {
+ "name": "issue_field_option",
+ "schema": "",
+ "columns": {
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "field_id": {
+ "name": "field_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "option_id": {
+ "name": "option_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "issue_field_option_issue_id_issue_id_fk": {
+ "name": "issue_field_option_issue_id_issue_id_fk",
+ "tableFrom": "issue_field_option",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_field_option_field_id_custom_field_id_fk": {
+ "name": "issue_field_option_field_id_custom_field_id_fk",
+ "tableFrom": "issue_field_option",
+ "tableTo": "custom_field",
+ "columnsFrom": [
+ "field_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_field_option_option_id_custom_field_option_id_fk": {
+ "name": "issue_field_option_option_id_custom_field_option_id_fk",
+ "tableFrom": "issue_field_option",
+ "tableTo": "custom_field_option",
+ "columnsFrom": [
+ "option_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "issue_field_option_issue_id_field_id_option_id_pk": {
+ "name": "issue_field_option_issue_id_field_id_option_id_pk",
+ "columns": [
+ "issue_id",
+ "field_id",
+ "option_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_field_value": {
+ "name": "issue_field_value",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "field_id": {
+ "name": "field_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value_text": {
+ "name": "value_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "value_number": {
+ "name": "value_number",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "value_bool": {
+ "name": "value_bool",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "value_date": {
+ "name": "value_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "value_datetime": {
+ "name": "value_datetime",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "value_datetime_end": {
+ "name": "value_datetime_end",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "issue_field_value_issue_id_issue_id_fk": {
+ "name": "issue_field_value_issue_id_issue_id_fk",
+ "tableFrom": "issue_field_value",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_field_value_field_id_custom_field_id_fk": {
+ "name": "issue_field_value_field_id_custom_field_id_fk",
+ "tableFrom": "issue_field_value",
+ "tableTo": "custom_field",
+ "columnsFrom": [
+ "field_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "issue_field_value_issue_id_field_id_unique": {
+ "name": "issue_field_value_issue_id_field_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "issue_id",
+ "field_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_label": {
+ "name": "issue_label",
+ "schema": "",
+ "columns": {
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "label_id": {
+ "name": "label_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "issue_label_issue_id_issue_id_fk": {
+ "name": "issue_label_issue_id_issue_id_fk",
+ "tableFrom": "issue_label",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_label_label_id_label_id_fk": {
+ "name": "issue_label_label_id_label_id_fk",
+ "tableFrom": "issue_label",
+ "tableTo": "label",
+ "columnsFrom": [
+ "label_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "issue_label_issue_id_label_id_pk": {
+ "name": "issue_label_issue_id_label_id_pk",
+ "columns": [
+ "issue_id",
+ "label_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_link": {
+ "name": "issue_link",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "source_issue_id": {
+ "name": "source_issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_issue_id": {
+ "name": "target_issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_link_pair_kind_idx": {
+ "name": "issue_link_pair_kind_idx",
+ "columns": [
+ {
+ "expression": "least(\"source_issue_id\", \"target_issue_id\")",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "greatest(\"source_issue_id\", \"target_issue_id\")",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_link_source_idx": {
+ "name": "issue_link_source_idx",
+ "columns": [
+ {
+ "expression": "source_issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_link_target_idx": {
+ "name": "issue_link_target_idx",
+ "columns": [
+ {
+ "expression": "target_issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_link_source_issue_id_issue_id_fk": {
+ "name": "issue_link_source_issue_id_issue_id_fk",
+ "tableFrom": "issue_link",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "source_issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_link_target_issue_id_issue_id_fk": {
+ "name": "issue_link_target_issue_id_issue_id_fk",
+ "tableFrom": "issue_link",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "target_issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "issue_link_kind_check": {
+ "name": "issue_link_kind_check",
+ "value": "\"issue_link\".\"kind\" IN ('blocks', 'relates', 'duplicates')"
+ },
+ "issue_link_self_check": {
+ "name": "issue_link_self_check",
+ "value": "\"issue_link\".\"source_issue_id\" <> \"issue_link\".\"target_issue_id\""
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.issue_type": {
+ "name": "issue_type",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'#6b7280'"
+ },
+ "is_default": {
+ "name": "is_default",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "issue_type_project_id_project_id_fk": {
+ "name": "issue_type_project_id_project_id_fk",
+ "tableFrom": "issue_type",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "issue_type_project_id_name_unique": {
+ "name": "issue_type_project_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_watcher": {
+ "name": "issue_watcher",
+ "schema": "",
+ "columns": {
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "subscribed": {
+ "name": "subscribed",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "issue_watcher_issue_id_issue_id_fk": {
+ "name": "issue_watcher_issue_id_issue_id_fk",
+ "tableFrom": "issue_watcher",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_watcher_user_id_user_id_fk": {
+ "name": "issue_watcher_user_id_user_id_fk",
+ "tableFrom": "issue_watcher",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "issue_watcher_issue_id_user_id_pk": {
+ "name": "issue_watcher_issue_id_user_id_pk",
+ "columns": [
+ "issue_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.label": {
+ "name": "label",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'#6b7280'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "label_project_id_project_id_fk": {
+ "name": "label_project_id_project_id_fk",
+ "tableFrom": "label",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "label_group_id_label_group_id_fk": {
+ "name": "label_group_id_label_group_id_fk",
+ "tableFrom": "label",
+ "tableTo": "label_group",
+ "columnsFrom": [
+ "group_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "label_project_id_name_unique": {
+ "name": "label_project_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.label_group": {
+ "name": "label_group",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'#6b7280'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "label_group_project_id_project_id_fk": {
+ "name": "label_group_project_id_project_id_fk",
+ "tableFrom": "label_group",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "label_group_project_id_name_unique": {
+ "name": "label_group_project_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.note_board": {
+ "name": "note_board",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "owner_user_id": {
+ "name": "owner_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "canvas": {
+ "name": "canvas",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "note_board_project_idx": {
+ "name": "note_board_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "note_board_project_id_project_id_fk": {
+ "name": "note_board_project_id_project_id_fk",
+ "tableFrom": "note_board",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "note_board_owner_user_id_user_id_fk": {
+ "name": "note_board_owner_user_id_user_id_fk",
+ "tableFrom": "note_board",
+ "tableTo": "user",
+ "columnsFrom": [
+ "owner_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "note_board_created_by_user_id_user_id_fk": {
+ "name": "note_board_created_by_user_id_user_id_fk",
+ "tableFrom": "note_board",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.note_board_member": {
+ "name": "note_board_member",
+ "schema": "",
+ "columns": {
+ "board_id": {
+ "name": "board_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "note_board_member_user_idx": {
+ "name": "note_board_member_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "note_board_member_board_id_note_board_id_fk": {
+ "name": "note_board_member_board_id_note_board_id_fk",
+ "tableFrom": "note_board_member",
+ "tableTo": "note_board",
+ "columnsFrom": [
+ "board_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "note_board_member_user_id_user_id_fk": {
+ "name": "note_board_member_user_id_user_id_fk",
+ "tableFrom": "note_board_member",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "note_board_member_board_id_user_id_pk": {
+ "name": "note_board_member_board_id_user_id_pk",
+ "columns": [
+ "board_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.notification": {
+ "name": "notification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_activity_id": {
+ "name": "source_activity_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "actor_name": {
+ "name": "actor_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "read_at": {
+ "name": "read_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "snoozed_until": {
+ "name": "snoozed_until",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "notification_user_idx": {
+ "name": "notification_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notification_user_unread_idx": {
+ "name": "notification_user_unread_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"notification\".\"read_at\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "notification_user_id_user_id_fk": {
+ "name": "notification_user_id_user_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notification_project_id_project_id_fk": {
+ "name": "notification_project_id_project_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notification_issue_id_issue_id_fk": {
+ "name": "notification_issue_id_issue_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notification_source_activity_id_issue_activity_id_fk": {
+ "name": "notification_source_activity_id_issue_activity_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "issue_activity",
+ "columnsFrom": [
+ "source_activity_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "notification_actor_user_id_user_id_fk": {
+ "name": "notification_actor_user_id_user_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "user",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "notification_type_check": {
+ "name": "notification_type_check",
+ "value": "\"notification\".\"type\" IN ('assigned', 'mentioned', 'commented', 'state_changed')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.notification_delivery": {
+ "name": "notification_delivery",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "recipient": {
+ "name": "recipient",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "notification_delivery_due_idx": {
+ "name": "notification_delivery_due_idx",
+ "columns": [
+ {
+ "expression": "next_attempt_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"notification_delivery\".\"status\" = 'pending'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "notification_delivery_project_id_project_id_fk": {
+ "name": "notification_delivery_project_id_project_id_fk",
+ "tableFrom": "notification_delivery",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "notification_delivery_channel_check": {
+ "name": "notification_delivery_channel_check",
+ "value": "\"notification_delivery\".\"channel\" IN ('email', 'telegram')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.project": {
+ "name": "project",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "next_sequence": {
+ "name": "next_sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "mcp_enabled": {
+ "name": "mcp_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "initiatives_enabled": {
+ "name": "initiatives_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "dashboards_enabled": {
+ "name": "dashboards_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "notes_enabled": {
+ "name": "notes_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "cycles_enabled": {
+ "name": "cycles_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "subtasks_enabled": {
+ "name": "subtasks_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "checklists_enabled": {
+ "name": "checklists_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "issue_stats_enabled": {
+ "name": "issue_stats_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "project_key_unique": {
+ "name": "project_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_action": {
+ "name": "project_action",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "condition": {
+ "name": "condition",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "effect": {
+ "name": "effect",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_action_project_idx": {
+ "name": "project_action_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_action_project_id_project_id_fk": {
+ "name": "project_action_project_id_project_id_fk",
+ "tableFrom": "project_action",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_column": {
+ "name": "project_column",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "state_type": {
+ "name": "state_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'unstarted'"
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'#6b7280'"
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "wip_limit": {
+ "name": "wip_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "wip_mode": {
+ "name": "wip_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'soft'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_column_project_id_project_id_fk": {
+ "name": "project_column_project_id_project_id_fk",
+ "tableFrom": "project_column",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "project_column_project_id_position_unique": {
+ "name": "project_column_project_id_position_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "position"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "project_column_state_type_check": {
+ "name": "project_column_state_type_check",
+ "value": "\"project_column\".\"state_type\" IN ('backlog', 'unstarted', 'started', 'completed', 'canceled')"
+ },
+ "project_column_wip_mode_check": {
+ "name": "project_column_wip_mode_check",
+ "value": "\"project_column\".\"wip_mode\" IN ('soft', 'hard')"
+ },
+ "project_column_wip_limit_check": {
+ "name": "project_column_wip_limit_check",
+ "value": "\"project_column\".\"wip_limit\" IS NULL OR \"project_column\".\"wip_limit\" > 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.project_dashboard": {
+ "name": "project_dashboard",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "layout": {
+ "name": "layout",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_dashboard_project_idx": {
+ "name": "project_dashboard_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_dashboard_project_id_project_id_fk": {
+ "name": "project_dashboard_project_id_project_id_fk",
+ "tableFrom": "project_dashboard",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_invite": {
+ "name": "project_invite",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'member'"
+ },
+ "role_id": {
+ "name": "role_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "invited_by_user_id": {
+ "name": "invited_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accepted_by_user_id": {
+ "name": "accepted_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "responded_at": {
+ "name": "responded_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "project_invite_pending_uq": {
+ "name": "project_invite_pending_uq",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"project_invite\".\"status\" = 'pending'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_invite_project_idx": {
+ "name": "project_invite_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_invite_project_id_project_id_fk": {
+ "name": "project_invite_project_id_project_id_fk",
+ "tableFrom": "project_invite",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_invite_role_id_project_role_id_fk": {
+ "name": "project_invite_role_id_project_role_id_fk",
+ "tableFrom": "project_invite",
+ "tableTo": "project_role",
+ "columnsFrom": [
+ "role_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_invite_invited_by_user_id_user_id_fk": {
+ "name": "project_invite_invited_by_user_id_user_id_fk",
+ "tableFrom": "project_invite",
+ "tableTo": "user",
+ "columnsFrom": [
+ "invited_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_invite_accepted_by_user_id_user_id_fk": {
+ "name": "project_invite_accepted_by_user_id_user_id_fk",
+ "tableFrom": "project_invite",
+ "tableTo": "user",
+ "columnsFrom": [
+ "accepted_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "project_invite_token_unique": {
+ "name": "project_invite_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "project_invite_role_check": {
+ "name": "project_invite_role_check",
+ "value": "\"project_invite\".\"role\" IN ('owner', 'member')"
+ },
+ "project_invite_status_check": {
+ "name": "project_invite_status_check",
+ "value": "\"project_invite\".\"status\" IN ('pending', 'accepted', 'rejected')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.project_member": {
+ "name": "project_member",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'member'"
+ },
+ "role_id": {
+ "name": "role_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_member_user_idx": {
+ "name": "project_member_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_member_project_id_project_id_fk": {
+ "name": "project_member_project_id_project_id_fk",
+ "tableFrom": "project_member",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_member_user_id_user_id_fk": {
+ "name": "project_member_user_id_user_id_fk",
+ "tableFrom": "project_member",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_member_role_id_project_role_id_fk": {
+ "name": "project_member_role_id_project_role_id_fk",
+ "tableFrom": "project_member",
+ "tableTo": "project_role",
+ "columnsFrom": [
+ "role_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_member_project_id_user_id_pk": {
+ "name": "project_member_project_id_user_id_pk",
+ "columns": [
+ "project_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "project_member_role_check": {
+ "name": "project_member_role_check",
+ "value": "\"project_member\".\"role\" IN ('owner', 'member')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.project_notification_setting": {
+ "name": "project_notification_setting",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "ciphertext": {
+ "name": "ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "iv": {
+ "name": "iv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "auth_tag": {
+ "name": "auth_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redacted": {
+ "name": "redacted",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_notification_setting_project_id_project_id_fk": {
+ "name": "project_notification_setting_project_id_project_id_fk",
+ "tableFrom": "project_notification_setting",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_role": {
+ "name": "project_role",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "is_default": {
+ "name": "is_default",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_role_default_uq": {
+ "name": "project_role_default_uq",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"project_role\".\"is_default\"",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_role_project_idx": {
+ "name": "project_role_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_role_project_id_project_id_fk": {
+ "name": "project_role_project_id_project_id_fk",
+ "tableFrom": "project_role",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "project_role_project_id_name_unique": {
+ "name": "project_role_project_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_setting": {
+ "name": "project_setting",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_setting_project_id_project_id_fk": {
+ "name": "project_setting_project_id_project_id_fk",
+ "tableFrom": "project_setting",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_setting_project_id_key_pk": {
+ "name": "project_setting_project_id_key_pk",
+ "columns": [
+ "project_id",
+ "key"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_view": {
+ "name": "project_view",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "filters": {
+ "name": "filters",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "display": {
+ "name": "display",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "share_token": {
+ "name": "share_token",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "share_extended": {
+ "name": "share_extended",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_view_project_idx": {
+ "name": "project_view_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_view_project_id_project_id_fk": {
+ "name": "project_view_project_id_project_id_fk",
+ "tableFrom": "project_view",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "project_view_share_token_unique": {
+ "name": "project_view_share_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "share_token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_view_favorite": {
+ "name": "project_view_favorite",
+ "schema": "",
+ "columns": {
+ "view_id": {
+ "name": "view_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_view_favorite_view_id_project_view_id_fk": {
+ "name": "project_view_favorite_view_id_project_view_id_fk",
+ "tableFrom": "project_view_favorite",
+ "tableTo": "project_view",
+ "columnsFrom": [
+ "view_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_view_favorite_user_id_user_id_fk": {
+ "name": "project_view_favorite_user_id_user_id_fk",
+ "tableFrom": "project_view_favorite",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_view_favorite_view_id_user_id_pk": {
+ "name": "project_view_favorite_view_id_user_id_pk",
+ "columns": [
+ "view_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.revision": {
+ "name": "revision",
+ "schema": "",
+ "columns": {
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "rev": {
+ "name": "rev",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "revision_project_idx": {
+ "name": "revision_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_notification_preference": {
+ "name": "user_notification_preference",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_events": {
+ "name": "email_events",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "telegram_events": {
+ "name": "telegram_events",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_notification_preference_user_id_user_id_fk": {
+ "name": "user_notification_preference_user_id_user_id_fk",
+ "tableFrom": "user_notification_preference",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_notification_preference_project_id_project_id_fk": {
+ "name": "user_notification_preference_project_id_project_id_fk",
+ "tableFrom": "user_notification_preference",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_notification_pref_user_project_unique": {
+ "name": "user_notification_pref_user_project_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user_id",
+ "project_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_preference": {
+ "name": "user_preference",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'UTC'"
+ },
+ "locale": {
+ "name": "locale",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'en'"
+ },
+ "theme": {
+ "name": "theme",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'system'"
+ },
+ "issue_open_mode": {
+ "name": "issue_open_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'panel'"
+ },
+ "start_page": {
+ "name": "start_page",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'work-items'"
+ },
+ "show_chat_by_default": {
+ "name": "show_chat_by_default",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "issue_stats_open": {
+ "name": "issue_stats_open",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "issue_stats_view": {
+ "name": "issue_stats_view",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'compact'"
+ },
+ "issue_activity_view": {
+ "name": "issue_activity_view",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'flat'"
+ },
+ "auto_watch": {
+ "name": "auto_watch",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "hotkeys": {
+ "name": "hotkeys",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_project_id": {
+ "name": "last_project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_preference_user_id_user_id_fk": {
+ "name": "user_preference_user_id_user_id_fk",
+ "tableFrom": "user_preference",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_preference_last_project_id_project_id_fk": {
+ "name": "user_preference_last_project_id_project_id_fk",
+ "tableFrom": "user_preference",
+ "tableTo": "project",
+ "columnsFrom": [
+ "last_project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "user_preference_theme_check": {
+ "name": "user_preference_theme_check",
+ "value": "\"user_preference\".\"theme\" IN ('light', 'dark', 'system')"
+ },
+ "user_preference_issue_open_mode_check": {
+ "name": "user_preference_issue_open_mode_check",
+ "value": "\"user_preference\".\"issue_open_mode\" IN ('panel', 'page')"
+ },
+ "user_preference_start_page_check": {
+ "name": "user_preference_start_page_check",
+ "value": "\"user_preference\".\"start_page\" IN ('inbox', 'dashboard', 'work-items', 'initiatives', 'ai-chat')"
+ },
+ "user_preference_issue_stats_view_check": {
+ "name": "user_preference_issue_stats_view_check",
+ "value": "\"user_preference\".\"issue_stats_view\" IN ('compact', 'timeline')"
+ },
+ "user_preference_issue_activity_view_check": {
+ "name": "user_preference_issue_activity_view_check",
+ "value": "\"user_preference\".\"issue_activity_view\" IN ('flat', 'grouped')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.user_telegram_account": {
+ "name": "user_telegram_account",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "username": {
+ "name": "username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "first_name": {
+ "name": "first_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "link_code": {
+ "name": "link_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "link_code_expires_at": {
+ "name": "link_code_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "linked_at": {
+ "name": "linked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_telegram_account_chat_id_unique": {
+ "name": "user_telegram_account_chat_id_unique",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"user_telegram_account\".\"chat_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_telegram_account_link_code_unique": {
+ "name": "user_telegram_account_link_code_unique",
+ "columns": [
+ {
+ "expression": "link_code",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"user_telegram_account\".\"link_code\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_telegram_account_user_id_user_id_fk": {
+ "name": "user_telegram_account_user_id_user_id_fk",
+ "tableFrom": "user_telegram_account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.webhook": {
+ "name": "webhook",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "secret": {
+ "name": "secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "events": {
+ "name": "events",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "consecutive_failures": {
+ "name": "consecutive_failures",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "webhook_project_idx": {
+ "name": "webhook_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "webhook_project_id_project_id_fk": {
+ "name": "webhook_project_id_project_id_fk",
+ "tableFrom": "webhook",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.webhook_delivery": {
+ "name": "webhook_delivery",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "webhook_id": {
+ "name": "webhook_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event_id": {
+ "name": "event_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "response_status": {
+ "name": "response_status",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "response_body": {
+ "name": "response_body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "webhook_delivery_due_idx": {
+ "name": "webhook_delivery_due_idx",
+ "columns": [
+ {
+ "expression": "next_attempt_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"webhook_delivery\".\"status\" = 'pending'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "webhook_delivery_webhook_idx": {
+ "name": "webhook_delivery_webhook_idx",
+ "columns": [
+ {
+ "expression": "webhook_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "webhook_delivery_webhook_id_webhook_id_fk": {
+ "name": "webhook_delivery_webhook_id_webhook_id_fk",
+ "tableFrom": "webhook_delivery",
+ "tableTo": "webhook",
+ "columnsFrom": [
+ "webhook_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0084_snapshot.json b/packages/db/drizzle/meta/0084_snapshot.json
new file mode 100644
index 00000000..735741c7
--- /dev/null
+++ b/packages/db/drizzle/meta/0084_snapshot.json
@@ -0,0 +1,6531 @@
+{
+ "id": "bcf474e9-9f83-4de8-9863-3d319ac18a53",
+ "prevId": "328596c3-0865-4b0a-a57a-fd5034f031cb",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "account_userId_idx": {
+ "name": "account_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.apikey": {
+ "name": "apikey",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "config_id": {
+ "name": "config_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'default'"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start": {
+ "name": "start",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reference_id": {
+ "name": "reference_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prefix": {
+ "name": "prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refill_interval": {
+ "name": "refill_interval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refill_amount": {
+ "name": "refill_amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_refill_at": {
+ "name": "last_refill_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "rate_limit_enabled": {
+ "name": "rate_limit_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "rate_limit_time_window": {
+ "name": "rate_limit_time_window",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 1000
+ },
+ "rate_limit_max": {
+ "name": "rate_limit_max",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 100
+ },
+ "request_count": {
+ "name": "request_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "remaining": {
+ "name": "remaining",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_request": {
+ "name": "last_request",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "apikey_configId_idx": {
+ "name": "apikey_configId_idx",
+ "columns": [
+ {
+ "expression": "config_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "apikey_referenceId_idx": {
+ "name": "apikey_referenceId_idx",
+ "columns": [
+ {
+ "expression": "reference_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "apikey_key_idx": {
+ "name": "apikey_key_idx",
+ "columns": [
+ {
+ "expression": "key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.passkey": {
+ "name": "passkey",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "public_key": {
+ "name": "public_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credential_id": {
+ "name": "credential_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "counter": {
+ "name": "counter",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "device_type": {
+ "name": "device_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "backed_up": {
+ "name": "backed_up",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "transports": {
+ "name": "transports",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "aaguid": {
+ "name": "aaguid",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "passkey_userId_idx": {
+ "name": "passkey_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "passkey_credentialID_idx": {
+ "name": "passkey_credentialID_idx",
+ "columns": [
+ {
+ "expression": "credential_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "passkey_user_id_user_id_fk": {
+ "name": "passkey_user_id_user_id_fk",
+ "tableFrom": "passkey",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "session_userId_idx": {
+ "name": "session_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'user'"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "verification_identifier_idx": {
+ "name": "verification_identifier_idx",
+ "columns": [
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_chat_event": {
+ "name": "agent_chat_event",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "bigserial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_chat_event_message_idx": {
+ "name": "agent_chat_event_message_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_chat_event_message_id_agent_chat_message_id_fk": {
+ "name": "agent_chat_event_message_id_agent_chat_message_id_fk",
+ "tableFrom": "agent_chat_event",
+ "tableTo": "agent_chat_message",
+ "columnsFrom": [
+ "message_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_chat_message": {
+ "name": "agent_chat_message",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "thread_id": {
+ "name": "thread_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_chat_message_thread_idx": {
+ "name": "agent_chat_message_thread_idx",
+ "columns": [
+ {
+ "expression": "thread_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_chat_message_due_idx": {
+ "name": "agent_chat_message_due_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "next_attempt_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"agent_chat_message\".\"status\" IN ('pending', 'streaming')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_chat_message_thread_id_agent_chat_thread_id_fk": {
+ "name": "agent_chat_message_thread_id_agent_chat_thread_id_fk",
+ "tableFrom": "agent_chat_message",
+ "tableTo": "agent_chat_thread",
+ "columnsFrom": [
+ "thread_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_chat_message_agent_id_ai_agent_id_fk": {
+ "name": "agent_chat_message_agent_id_ai_agent_id_fk",
+ "tableFrom": "agent_chat_message",
+ "tableTo": "ai_agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "agent_chat_message_role_check": {
+ "name": "agent_chat_message_role_check",
+ "value": "\"agent_chat_message\".\"role\" IN ('user', 'assistant')"
+ },
+ "agent_chat_message_status_check": {
+ "name": "agent_chat_message_status_check",
+ "value": "\"agent_chat_message\".\"status\" IN ('pending', 'streaming', 'success', 'failed')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_chat_thread": {
+ "name": "agent_chat_thread",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cli_session_id": {
+ "name": "cli_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_chat_thread_agent_user_idx": {
+ "name": "agent_chat_thread_agent_user_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_chat_thread_agent_id_ai_agent_id_fk": {
+ "name": "agent_chat_thread_agent_id_ai_agent_id_fk",
+ "tableFrom": "agent_chat_thread",
+ "tableTo": "ai_agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_chat_thread_user_id_user_id_fk": {
+ "name": "agent_chat_thread_user_id_user_id_fk",
+ "tableFrom": "agent_chat_thread",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_run": {
+ "name": "agent_run",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "schedule_id": {
+ "name": "schedule_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'delegation'"
+ },
+ "scheduled_for": {
+ "name": "scheduled_for",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_activity_id": {
+ "name": "source_activity_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "output": {
+ "name": "output",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_run_schedule_fire_uq": {
+ "name": "agent_run_schedule_fire_uq",
+ "columns": [
+ {
+ "expression": "schedule_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "scheduled_for",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_run_due_idx": {
+ "name": "agent_run_due_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "next_attempt_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_run_schedule_idx": {
+ "name": "agent_run_schedule_idx",
+ "columns": [
+ {
+ "expression": "schedule_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_run_agent_id_ai_agent_id_fk": {
+ "name": "agent_run_agent_id_ai_agent_id_fk",
+ "tableFrom": "agent_run",
+ "tableTo": "ai_agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_run_issue_id_issue_id_fk": {
+ "name": "agent_run_issue_id_issue_id_fk",
+ "tableFrom": "agent_run",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_run_schedule_id_agent_schedule_id_fk": {
+ "name": "agent_run_schedule_id_agent_schedule_id_fk",
+ "tableFrom": "agent_run",
+ "tableTo": "agent_schedule",
+ "columnsFrom": [
+ "schedule_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_run_source_activity_id_issue_activity_id_fk": {
+ "name": "agent_run_source_activity_id_issue_activity_id_fk",
+ "tableFrom": "agent_run",
+ "tableTo": "issue_activity",
+ "columnsFrom": [
+ "source_activity_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "agent_run_status_check": {
+ "name": "agent_run_status_check",
+ "value": "\"agent_run\".\"status\" IN ('pending', 'success', 'failed', 'canceled')"
+ },
+ "agent_run_trigger_check": {
+ "name": "agent_run_trigger_check",
+ "value": "\"agent_run\".\"trigger\" IN ('mention', 'delegation', 'schedule', 'manual')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_schedule": {
+ "name": "agent_schedule",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cron": {
+ "name": "cron",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "next_run_at": {
+ "name": "next_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "last_run_at": {
+ "name": "last_run_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_schedule_due_idx": {
+ "name": "agent_schedule_due_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "next_run_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_schedule_agent_idx": {
+ "name": "agent_schedule_agent_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_schedule_agent_id_ai_agent_id_fk": {
+ "name": "agent_schedule_agent_id_ai_agent_id_fk",
+ "tableFrom": "agent_schedule",
+ "tableTo": "ai_agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "agent_schedule_agent_id_name_unique": {
+ "name": "agent_schedule_agent_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "agent_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "agent_schedule_status_check": {
+ "name": "agent_schedule_status_check",
+ "value": "\"agent_schedule\".\"status\" IN ('active', 'paused')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_skill": {
+ "name": "agent_skill",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_url": {
+ "name": "source_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "s3_prefix": {
+ "name": "s3_prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "files": {
+ "name": "files",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_skill_project_idx": {
+ "name": "agent_skill_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_skill_project_id_project_id_fk": {
+ "name": "agent_skill_project_id_project_id_fk",
+ "tableFrom": "agent_skill",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "agent_skill_project_id_name_unique": {
+ "name": "agent_skill_project_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "agent_skill_source_check": {
+ "name": "agent_skill_source_check",
+ "value": "\"agent_skill\".\"source\" IN ('upload', 'inline', 'github')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_skill_link": {
+ "name": "agent_skill_link",
+ "schema": "",
+ "columns": {
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "skill_id": {
+ "name": "skill_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "agent_skill_link_skill_idx": {
+ "name": "agent_skill_link_skill_idx",
+ "columns": [
+ {
+ "expression": "skill_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_skill_link_agent_id_ai_agent_id_fk": {
+ "name": "agent_skill_link_agent_id_ai_agent_id_fk",
+ "tableFrom": "agent_skill_link",
+ "tableTo": "ai_agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_skill_link_skill_id_agent_skill_id_fk": {
+ "name": "agent_skill_link_skill_id_agent_skill_id_fk",
+ "tableFrom": "agent_skill_link",
+ "tableTo": "agent_skill",
+ "columnsFrom": [
+ "skill_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "agent_skill_link_agent_id_skill_id_pk": {
+ "name": "agent_skill_link_agent_id_skill_id_pk",
+ "columns": [
+ "agent_id",
+ "skill_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_tool": {
+ "name": "agent_tool",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool_key": {
+ "name": "tool_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credential_id": {
+ "name": "credential_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_tool_project_idx": {
+ "name": "agent_tool_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_tool_credential_idx": {
+ "name": "agent_tool_credential_idx",
+ "columns": [
+ {
+ "expression": "credential_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_tool_project_id_project_id_fk": {
+ "name": "agent_tool_project_id_project_id_fk",
+ "tableFrom": "agent_tool",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_tool_credential_id_integration_credential_id_fk": {
+ "name": "agent_tool_credential_id_integration_credential_id_fk",
+ "tableFrom": "agent_tool",
+ "tableTo": "integration_credential",
+ "columnsFrom": [
+ "credential_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "agent_tool_project_id_tool_key_credential_id_unique": {
+ "name": "agent_tool_project_id_tool_key_credential_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "tool_key",
+ "credential_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_tool_link": {
+ "name": "agent_tool_link",
+ "schema": "",
+ "columns": {
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_tool_id": {
+ "name": "agent_tool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "agent_tool_link_tool_idx": {
+ "name": "agent_tool_link_tool_idx",
+ "columns": [
+ {
+ "expression": "agent_tool_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_tool_link_agent_id_ai_agent_id_fk": {
+ "name": "agent_tool_link_agent_id_ai_agent_id_fk",
+ "tableFrom": "agent_tool_link",
+ "tableTo": "ai_agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_tool_link_agent_tool_id_agent_tool_id_fk": {
+ "name": "agent_tool_link_agent_tool_id_agent_tool_id_fk",
+ "tableFrom": "agent_tool_link",
+ "tableTo": "agent_tool",
+ "columnsFrom": [
+ "agent_tool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "agent_tool_link_agent_id_agent_tool_id_pk": {
+ "name": "agent_tool_link_agent_id_agent_tool_id_pk",
+ "columns": [
+ "agent_id",
+ "agent_tool_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_agent": {
+ "name": "ai_agent",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "username": {
+ "name": "username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "model_credential_id": {
+ "name": "model_credential_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "instructions": {
+ "name": "instructions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tools": {
+ "name": "tools",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "temperature": {
+ "name": "temperature",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "max_steps": {
+ "name": "max_steps",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trigger_on_mention": {
+ "name": "trigger_on_mention",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "trigger_on_assign": {
+ "name": "trigger_on_assign",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "delegation_delay_sec": {
+ "name": "delegation_delay_sec",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 120
+ },
+ "role_id": {
+ "name": "role_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "api_key_ciphertext": {
+ "name": "api_key_ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "api_key_iv": {
+ "name": "api_key_iv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "api_key_auth_tag": {
+ "name": "api_key_auth_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "memory_enabled": {
+ "name": "memory_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "memory_last_messages": {
+ "name": "memory_last_messages",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "owner_user_id": {
+ "name": "owner_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "runner_scope": {
+ "name": "runner_scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'project'"
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "ai_agent_project_idx": {
+ "name": "ai_agent_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "ai_agent_project_id_project_id_fk": {
+ "name": "ai_agent_project_id_project_id_fk",
+ "tableFrom": "ai_agent",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_agent_user_id_user_id_fk": {
+ "name": "ai_agent_user_id_user_id_fk",
+ "tableFrom": "ai_agent",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "ai_agent_model_credential_id_integration_credential_id_fk": {
+ "name": "ai_agent_model_credential_id_integration_credential_id_fk",
+ "tableFrom": "ai_agent",
+ "tableTo": "integration_credential",
+ "columnsFrom": [
+ "model_credential_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "ai_agent_role_id_project_role_id_fk": {
+ "name": "ai_agent_role_id_project_role_id_fk",
+ "tableFrom": "ai_agent",
+ "tableTo": "project_role",
+ "columnsFrom": [
+ "role_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "ai_agent_owner_user_id_user_id_fk": {
+ "name": "ai_agent_owner_user_id_user_id_fk",
+ "tableFrom": "ai_agent",
+ "tableTo": "user",
+ "columnsFrom": [
+ "owner_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "ai_agent_project_id_username_unique": {
+ "name": "ai_agent_project_id_username_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "username"
+ ]
+ },
+ "ai_agent_user_id_unique": {
+ "name": "ai_agent_user_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "ai_agent_kind_check": {
+ "name": "ai_agent_kind_check",
+ "value": "\"ai_agent\".\"kind\" IN ('external', 'internal')"
+ },
+ "ai_agent_runner_scope_check": {
+ "name": "ai_agent_runner_scope_check",
+ "value": "\"ai_agent\".\"runner_scope\" IN ('owner', 'project')"
+ },
+ "ai_agent_delegation_delay_check": {
+ "name": "ai_agent_delegation_delay_check",
+ "value": "\"ai_agent\".\"delegation_delay_sec\" >= 0 AND \"ai_agent\".\"delegation_delay_sec\" <= 86400"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.app_secret": {
+ "name": "app_secret",
+ "schema": "",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "ciphertext": {
+ "name": "ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "iv": {
+ "name": "iv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "auth_tag": {
+ "name": "auth_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redacted": {
+ "name": "redacted",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.app_setting": {
+ "name": "app_setting",
+ "schema": "",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.custom_field": {
+ "name": "custom_field",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_type_id": {
+ "name": "issue_type_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "field_type": {
+ "name": "field_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "show_in_body": {
+ "name": "show_in_body",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "custom_field_project_id_project_id_fk": {
+ "name": "custom_field_project_id_project_id_fk",
+ "tableFrom": "custom_field",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "custom_field_issue_type_id_issue_type_id_fk": {
+ "name": "custom_field_issue_type_id_issue_type_id_fk",
+ "tableFrom": "custom_field",
+ "tableTo": "issue_type",
+ "columnsFrom": [
+ "issue_type_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "custom_field_field_type_check": {
+ "name": "custom_field_field_type_check",
+ "value": "\"custom_field\".\"field_type\" IN ('text', 'markdown', 'url', 'number', 'boolean', 'date', 'datetime', 'datetime_range', 'select', 'multi_select')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.custom_field_option": {
+ "name": "custom_field_option",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "field_id": {
+ "name": "field_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'#6b7280'"
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "custom_field_option_field_id_custom_field_id_fk": {
+ "name": "custom_field_option_field_id_custom_field_id_fk",
+ "tableFrom": "custom_field_option",
+ "tableTo": "custom_field",
+ "columnsFrom": [
+ "field_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "custom_field_option_field_id_value_unique": {
+ "name": "custom_field_option_field_id_value_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "field_id",
+ "value"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.cycle": {
+ "name": "cycle",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "goal": {
+ "name": "goal",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "start_date": {
+ "name": "start_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "end_date": {
+ "name": "end_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "cycle_project_idx": {
+ "name": "cycle_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "start_date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "cycle_project_id_project_id_fk": {
+ "name": "cycle_project_id_project_id_fk",
+ "tableFrom": "cycle",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "cycle_dates_check": {
+ "name": "cycle_dates_check",
+ "value": "\"cycle\".\"end_date\" >= \"cycle\".\"start_date\""
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.initiative": {
+ "name": "initiative",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'planned'"
+ },
+ "owner_user_id": {
+ "name": "owner_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "priority": {
+ "name": "priority",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start_date": {
+ "name": "start_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "target_date": {
+ "name": "target_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "initiative_project_idx": {
+ "name": "initiative_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "initiative_project_id_project_id_fk": {
+ "name": "initiative_project_id_project_id_fk",
+ "tableFrom": "initiative",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "initiative_owner_user_id_user_id_fk": {
+ "name": "initiative_owner_user_id_user_id_fk",
+ "tableFrom": "initiative",
+ "tableTo": "user",
+ "columnsFrom": [
+ "owner_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "initiative_status_check": {
+ "name": "initiative_status_check",
+ "value": "\"initiative\".\"status\" IN ('proposed', 'planned', 'active', 'completed', 'canceled')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.initiative_label": {
+ "name": "initiative_label",
+ "schema": "",
+ "columns": {
+ "initiative_id": {
+ "name": "initiative_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "label_id": {
+ "name": "label_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "initiative_label_initiative_id_initiative_id_fk": {
+ "name": "initiative_label_initiative_id_initiative_id_fk",
+ "tableFrom": "initiative_label",
+ "tableTo": "initiative",
+ "columnsFrom": [
+ "initiative_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "initiative_label_label_id_label_id_fk": {
+ "name": "initiative_label_label_id_label_id_fk",
+ "tableFrom": "initiative_label",
+ "tableTo": "label",
+ "columnsFrom": [
+ "label_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "initiative_label_initiative_id_label_id_pk": {
+ "name": "initiative_label_initiative_id_label_id_pk",
+ "columns": [
+ "initiative_id",
+ "label_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.integration_credential": {
+ "name": "integration_credential",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "integration_key": {
+ "name": "integration_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ciphertext": {
+ "name": "ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "iv": {
+ "name": "iv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "auth_tag": {
+ "name": "auth_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redacted": {
+ "name": "redacted",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "integration_credential_project_idx": {
+ "name": "integration_credential_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "integration_credential_project_id_project_id_fk": {
+ "name": "integration_credential_project_id_project_id_fk",
+ "tableFrom": "integration_credential",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue": {
+ "name": "issue",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sequence_number": {
+ "name": "sequence_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type_id": {
+ "name": "type_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "initiative_id": {
+ "name": "initiative_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cycle_id": {
+ "name": "cycle_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "column_id": {
+ "name": "column_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "parent_id": {
+ "name": "parent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "assignee_user_id": {
+ "name": "assignee_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "delegate_user_id": {
+ "name": "delegate_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "priority": {
+ "name": "priority",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start_date": {
+ "name": "start_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "due_date": {
+ "name": "due_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "share_token": {
+ "name": "share_token",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "share_extended": {
+ "name": "share_extended",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_project_active_idx": {
+ "name": "issue_project_active_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "column_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"issue\".\"archived_at\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_parent_idx": {
+ "name": "issue_parent_idx",
+ "columns": [
+ {
+ "expression": "parent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"issue\".\"parent_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_cycle_idx": {
+ "name": "issue_cycle_idx",
+ "columns": [
+ {
+ "expression": "cycle_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"issue\".\"cycle_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_project_id_project_id_fk": {
+ "name": "issue_project_id_project_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_type_id_issue_type_id_fk": {
+ "name": "issue_type_id_issue_type_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "issue_type",
+ "columnsFrom": [
+ "type_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_initiative_id_initiative_id_fk": {
+ "name": "issue_initiative_id_initiative_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "initiative",
+ "columnsFrom": [
+ "initiative_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_cycle_id_cycle_id_fk": {
+ "name": "issue_cycle_id_cycle_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "cycle",
+ "columnsFrom": [
+ "cycle_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_column_id_project_column_id_fk": {
+ "name": "issue_column_id_project_column_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "project_column",
+ "columnsFrom": [
+ "column_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "issue_parent_id_issue_id_fk": {
+ "name": "issue_parent_id_issue_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "parent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_assignee_user_id_user_id_fk": {
+ "name": "issue_assignee_user_id_user_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "user",
+ "columnsFrom": [
+ "assignee_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "issue_delegate_user_id_user_id_fk": {
+ "name": "issue_delegate_user_id_user_id_fk",
+ "tableFrom": "issue",
+ "tableTo": "user",
+ "columnsFrom": [
+ "delegate_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "issue_share_token_unique": {
+ "name": "issue_share_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "share_token"
+ ]
+ },
+ "issue_project_id_sequence_number_unique": {
+ "name": "issue_project_id_sequence_number_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "sequence_number"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_activity": {
+ "name": "issue_activity",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "initiative_id": {
+ "name": "initiative_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "actor_name": {
+ "name": "actor_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subject": {
+ "name": "subject",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "from_text": {
+ "name": "from_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "to_text": {
+ "name": "to_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_activity_issue_idx": {
+ "name": "issue_activity_issue_idx",
+ "columns": [
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_activity_initiative_idx": {
+ "name": "issue_activity_initiative_idx",
+ "columns": [
+ {
+ "expression": "initiative_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_activity_issue_id_issue_id_fk": {
+ "name": "issue_activity_issue_id_issue_id_fk",
+ "tableFrom": "issue_activity",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_activity_initiative_id_initiative_id_fk": {
+ "name": "issue_activity_initiative_id_initiative_id_fk",
+ "tableFrom": "issue_activity",
+ "tableTo": "initiative",
+ "columnsFrom": [
+ "initiative_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_activity_actor_user_id_user_id_fk": {
+ "name": "issue_activity_actor_user_id_user_id_fk",
+ "tableFrom": "issue_activity",
+ "tableTo": "user",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "issue_activity_kind_check": {
+ "name": "issue_activity_kind_check",
+ "value": "\"issue_activity\".\"kind\" IN ('comment', 'activity')"
+ },
+ "issue_activity_owner_check": {
+ "name": "issue_activity_owner_check",
+ "value": "(\"issue_activity\".\"issue_id\" IS NOT NULL) <> (\"issue_activity\".\"initiative_id\" IS NOT NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.issue_attachment": {
+ "name": "issue_attachment",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "public_id": {
+ "name": "public_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "s3_key": {
+ "name": "s3_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "filename": {
+ "name": "filename",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content_type": {
+ "name": "content_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "size_bytes": {
+ "name": "size_bytes",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_attachment_issue_idx": {
+ "name": "issue_attachment_issue_idx",
+ "columns": [
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_attachment_issue_id_issue_id_fk": {
+ "name": "issue_attachment_issue_id_issue_id_fk",
+ "tableFrom": "issue_attachment",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "issue_attachment_public_id_unique": {
+ "name": "issue_attachment_public_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "public_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_checklist": {
+ "name": "issue_checklist",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_checklist_issue_idx": {
+ "name": "issue_checklist_issue_idx",
+ "columns": [
+ {
+ "expression": "issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_checklist_issue_id_issue_id_fk": {
+ "name": "issue_checklist_issue_id_issue_id_fk",
+ "tableFrom": "issue_checklist",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_checklist_item": {
+ "name": "issue_checklist_item",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "checklist_id": {
+ "name": "checklist_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "done": {
+ "name": "done",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_checklist_item_checklist_idx": {
+ "name": "issue_checklist_item_checklist_idx",
+ "columns": [
+ {
+ "expression": "checklist_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_checklist_item_checklist_id_issue_checklist_id_fk": {
+ "name": "issue_checklist_item_checklist_id_issue_checklist_id_fk",
+ "tableFrom": "issue_checklist_item",
+ "tableTo": "issue_checklist",
+ "columnsFrom": [
+ "checklist_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_field_option": {
+ "name": "issue_field_option",
+ "schema": "",
+ "columns": {
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "field_id": {
+ "name": "field_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "option_id": {
+ "name": "option_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "issue_field_option_issue_id_issue_id_fk": {
+ "name": "issue_field_option_issue_id_issue_id_fk",
+ "tableFrom": "issue_field_option",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_field_option_field_id_custom_field_id_fk": {
+ "name": "issue_field_option_field_id_custom_field_id_fk",
+ "tableFrom": "issue_field_option",
+ "tableTo": "custom_field",
+ "columnsFrom": [
+ "field_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_field_option_option_id_custom_field_option_id_fk": {
+ "name": "issue_field_option_option_id_custom_field_option_id_fk",
+ "tableFrom": "issue_field_option",
+ "tableTo": "custom_field_option",
+ "columnsFrom": [
+ "option_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "issue_field_option_issue_id_field_id_option_id_pk": {
+ "name": "issue_field_option_issue_id_field_id_option_id_pk",
+ "columns": [
+ "issue_id",
+ "field_id",
+ "option_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_field_value": {
+ "name": "issue_field_value",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "field_id": {
+ "name": "field_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value_text": {
+ "name": "value_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "value_number": {
+ "name": "value_number",
+ "type": "numeric",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "value_bool": {
+ "name": "value_bool",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "value_date": {
+ "name": "value_date",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "value_datetime": {
+ "name": "value_datetime",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "value_datetime_end": {
+ "name": "value_datetime_end",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "issue_field_value_issue_id_issue_id_fk": {
+ "name": "issue_field_value_issue_id_issue_id_fk",
+ "tableFrom": "issue_field_value",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_field_value_field_id_custom_field_id_fk": {
+ "name": "issue_field_value_field_id_custom_field_id_fk",
+ "tableFrom": "issue_field_value",
+ "tableTo": "custom_field",
+ "columnsFrom": [
+ "field_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "issue_field_value_issue_id_field_id_unique": {
+ "name": "issue_field_value_issue_id_field_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "issue_id",
+ "field_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_label": {
+ "name": "issue_label",
+ "schema": "",
+ "columns": {
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "label_id": {
+ "name": "label_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "issue_label_issue_id_issue_id_fk": {
+ "name": "issue_label_issue_id_issue_id_fk",
+ "tableFrom": "issue_label",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_label_label_id_label_id_fk": {
+ "name": "issue_label_label_id_label_id_fk",
+ "tableFrom": "issue_label",
+ "tableTo": "label",
+ "columnsFrom": [
+ "label_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "issue_label_issue_id_label_id_pk": {
+ "name": "issue_label_issue_id_label_id_pk",
+ "columns": [
+ "issue_id",
+ "label_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_link": {
+ "name": "issue_link",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "source_issue_id": {
+ "name": "source_issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_issue_id": {
+ "name": "target_issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "issue_link_pair_kind_idx": {
+ "name": "issue_link_pair_kind_idx",
+ "columns": [
+ {
+ "expression": "least(\"source_issue_id\", \"target_issue_id\")",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "greatest(\"source_issue_id\", \"target_issue_id\")",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_link_source_idx": {
+ "name": "issue_link_source_idx",
+ "columns": [
+ {
+ "expression": "source_issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "issue_link_target_idx": {
+ "name": "issue_link_target_idx",
+ "columns": [
+ {
+ "expression": "target_issue_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "issue_link_source_issue_id_issue_id_fk": {
+ "name": "issue_link_source_issue_id_issue_id_fk",
+ "tableFrom": "issue_link",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "source_issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_link_target_issue_id_issue_id_fk": {
+ "name": "issue_link_target_issue_id_issue_id_fk",
+ "tableFrom": "issue_link",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "target_issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "issue_link_kind_check": {
+ "name": "issue_link_kind_check",
+ "value": "\"issue_link\".\"kind\" IN ('blocks', 'relates', 'duplicates')"
+ },
+ "issue_link_self_check": {
+ "name": "issue_link_self_check",
+ "value": "\"issue_link\".\"source_issue_id\" <> \"issue_link\".\"target_issue_id\""
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.issue_type": {
+ "name": "issue_type",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'#6b7280'"
+ },
+ "is_default": {
+ "name": "is_default",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "issue_type_project_id_project_id_fk": {
+ "name": "issue_type_project_id_project_id_fk",
+ "tableFrom": "issue_type",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "issue_type_project_id_name_unique": {
+ "name": "issue_type_project_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.issue_watcher": {
+ "name": "issue_watcher",
+ "schema": "",
+ "columns": {
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "subscribed": {
+ "name": "subscribed",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "issue_watcher_issue_id_issue_id_fk": {
+ "name": "issue_watcher_issue_id_issue_id_fk",
+ "tableFrom": "issue_watcher",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "issue_watcher_user_id_user_id_fk": {
+ "name": "issue_watcher_user_id_user_id_fk",
+ "tableFrom": "issue_watcher",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "issue_watcher_issue_id_user_id_pk": {
+ "name": "issue_watcher_issue_id_user_id_pk",
+ "columns": [
+ "issue_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.label": {
+ "name": "label",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "group_id": {
+ "name": "group_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'#6b7280'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "label_project_id_project_id_fk": {
+ "name": "label_project_id_project_id_fk",
+ "tableFrom": "label",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "label_group_id_label_group_id_fk": {
+ "name": "label_group_id_label_group_id_fk",
+ "tableFrom": "label",
+ "tableTo": "label_group",
+ "columnsFrom": [
+ "group_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "label_project_id_name_unique": {
+ "name": "label_project_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.label_group": {
+ "name": "label_group",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'#6b7280'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "label_group_project_id_project_id_fk": {
+ "name": "label_group_project_id_project_id_fk",
+ "tableFrom": "label_group",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "label_group_project_id_name_unique": {
+ "name": "label_group_project_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.note_board": {
+ "name": "note_board",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "owner_user_id": {
+ "name": "owner_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "canvas": {
+ "name": "canvas",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "note_board_project_idx": {
+ "name": "note_board_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "note_board_project_id_project_id_fk": {
+ "name": "note_board_project_id_project_id_fk",
+ "tableFrom": "note_board",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "note_board_owner_user_id_user_id_fk": {
+ "name": "note_board_owner_user_id_user_id_fk",
+ "tableFrom": "note_board",
+ "tableTo": "user",
+ "columnsFrom": [
+ "owner_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "note_board_created_by_user_id_user_id_fk": {
+ "name": "note_board_created_by_user_id_user_id_fk",
+ "tableFrom": "note_board",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.note_board_member": {
+ "name": "note_board_member",
+ "schema": "",
+ "columns": {
+ "board_id": {
+ "name": "board_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "note_board_member_user_idx": {
+ "name": "note_board_member_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "note_board_member_board_id_note_board_id_fk": {
+ "name": "note_board_member_board_id_note_board_id_fk",
+ "tableFrom": "note_board_member",
+ "tableTo": "note_board",
+ "columnsFrom": [
+ "board_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "note_board_member_user_id_user_id_fk": {
+ "name": "note_board_member_user_id_user_id_fk",
+ "tableFrom": "note_board_member",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "note_board_member_board_id_user_id_pk": {
+ "name": "note_board_member_board_id_user_id_pk",
+ "columns": [
+ "board_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.notification": {
+ "name": "notification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "issue_id": {
+ "name": "issue_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_activity_id": {
+ "name": "source_activity_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "actor_name": {
+ "name": "actor_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "read_at": {
+ "name": "read_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "snoozed_until": {
+ "name": "snoozed_until",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "notification_user_idx": {
+ "name": "notification_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notification_user_unread_idx": {
+ "name": "notification_user_unread_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"notification\".\"read_at\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "notification_user_id_user_id_fk": {
+ "name": "notification_user_id_user_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notification_project_id_project_id_fk": {
+ "name": "notification_project_id_project_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notification_issue_id_issue_id_fk": {
+ "name": "notification_issue_id_issue_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "issue",
+ "columnsFrom": [
+ "issue_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notification_source_activity_id_issue_activity_id_fk": {
+ "name": "notification_source_activity_id_issue_activity_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "issue_activity",
+ "columnsFrom": [
+ "source_activity_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "notification_actor_user_id_user_id_fk": {
+ "name": "notification_actor_user_id_user_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "user",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "notification_type_check": {
+ "name": "notification_type_check",
+ "value": "\"notification\".\"type\" IN ('assigned', 'mentioned', 'commented', 'state_changed')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.notification_delivery": {
+ "name": "notification_delivery",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "channel": {
+ "name": "channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "recipient": {
+ "name": "recipient",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "notification_delivery_due_idx": {
+ "name": "notification_delivery_due_idx",
+ "columns": [
+ {
+ "expression": "next_attempt_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"notification_delivery\".\"status\" = 'pending'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "notification_delivery_project_id_project_id_fk": {
+ "name": "notification_delivery_project_id_project_id_fk",
+ "tableFrom": "notification_delivery",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "notification_delivery_channel_check": {
+ "name": "notification_delivery_channel_check",
+ "value": "\"notification_delivery\".\"channel\" IN ('email', 'telegram')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.project": {
+ "name": "project",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "next_sequence": {
+ "name": "next_sequence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "mcp_enabled": {
+ "name": "mcp_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "initiatives_enabled": {
+ "name": "initiatives_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "dashboards_enabled": {
+ "name": "dashboards_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "notes_enabled": {
+ "name": "notes_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "cycles_enabled": {
+ "name": "cycles_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "subtasks_enabled": {
+ "name": "subtasks_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "checklists_enabled": {
+ "name": "checklists_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "issue_stats_enabled": {
+ "name": "issue_stats_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "project_key_unique": {
+ "name": "project_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_action": {
+ "name": "project_action",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "condition": {
+ "name": "condition",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "effect": {
+ "name": "effect",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_action_project_idx": {
+ "name": "project_action_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_action_project_id_project_id_fk": {
+ "name": "project_action_project_id_project_id_fk",
+ "tableFrom": "project_action",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_column": {
+ "name": "project_column",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "state_type": {
+ "name": "state_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'unstarted'"
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'#6b7280'"
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "wip_limit": {
+ "name": "wip_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "wip_mode": {
+ "name": "wip_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'soft'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_column_project_id_project_id_fk": {
+ "name": "project_column_project_id_project_id_fk",
+ "tableFrom": "project_column",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "project_column_project_id_position_unique": {
+ "name": "project_column_project_id_position_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "position"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "project_column_state_type_check": {
+ "name": "project_column_state_type_check",
+ "value": "\"project_column\".\"state_type\" IN ('backlog', 'unstarted', 'started', 'completed', 'canceled')"
+ },
+ "project_column_wip_mode_check": {
+ "name": "project_column_wip_mode_check",
+ "value": "\"project_column\".\"wip_mode\" IN ('soft', 'hard')"
+ },
+ "project_column_wip_limit_check": {
+ "name": "project_column_wip_limit_check",
+ "value": "\"project_column\".\"wip_limit\" IS NULL OR \"project_column\".\"wip_limit\" > 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.project_dashboard": {
+ "name": "project_dashboard",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "layout": {
+ "name": "layout",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_dashboard_project_idx": {
+ "name": "project_dashboard_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_dashboard_project_id_project_id_fk": {
+ "name": "project_dashboard_project_id_project_id_fk",
+ "tableFrom": "project_dashboard",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_invite": {
+ "name": "project_invite",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'member'"
+ },
+ "role_id": {
+ "name": "role_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "invited_by_user_id": {
+ "name": "invited_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accepted_by_user_id": {
+ "name": "accepted_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "responded_at": {
+ "name": "responded_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "project_invite_pending_uq": {
+ "name": "project_invite_pending_uq",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"project_invite\".\"status\" = 'pending'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_invite_project_idx": {
+ "name": "project_invite_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_invite_project_id_project_id_fk": {
+ "name": "project_invite_project_id_project_id_fk",
+ "tableFrom": "project_invite",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_invite_role_id_project_role_id_fk": {
+ "name": "project_invite_role_id_project_role_id_fk",
+ "tableFrom": "project_invite",
+ "tableTo": "project_role",
+ "columnsFrom": [
+ "role_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_invite_invited_by_user_id_user_id_fk": {
+ "name": "project_invite_invited_by_user_id_user_id_fk",
+ "tableFrom": "project_invite",
+ "tableTo": "user",
+ "columnsFrom": [
+ "invited_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_invite_accepted_by_user_id_user_id_fk": {
+ "name": "project_invite_accepted_by_user_id_user_id_fk",
+ "tableFrom": "project_invite",
+ "tableTo": "user",
+ "columnsFrom": [
+ "accepted_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "project_invite_token_unique": {
+ "name": "project_invite_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "project_invite_role_check": {
+ "name": "project_invite_role_check",
+ "value": "\"project_invite\".\"role\" IN ('owner', 'member')"
+ },
+ "project_invite_status_check": {
+ "name": "project_invite_status_check",
+ "value": "\"project_invite\".\"status\" IN ('pending', 'accepted', 'rejected')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.project_member": {
+ "name": "project_member",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'member'"
+ },
+ "role_id": {
+ "name": "role_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_member_user_idx": {
+ "name": "project_member_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_member_project_id_project_id_fk": {
+ "name": "project_member_project_id_project_id_fk",
+ "tableFrom": "project_member",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_member_user_id_user_id_fk": {
+ "name": "project_member_user_id_user_id_fk",
+ "tableFrom": "project_member",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_member_role_id_project_role_id_fk": {
+ "name": "project_member_role_id_project_role_id_fk",
+ "tableFrom": "project_member",
+ "tableTo": "project_role",
+ "columnsFrom": [
+ "role_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_member_project_id_user_id_pk": {
+ "name": "project_member_project_id_user_id_pk",
+ "columns": [
+ "project_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "project_member_role_check": {
+ "name": "project_member_role_check",
+ "value": "\"project_member\".\"role\" IN ('owner', 'member')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.project_notification_setting": {
+ "name": "project_notification_setting",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "ciphertext": {
+ "name": "ciphertext",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "iv": {
+ "name": "iv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "auth_tag": {
+ "name": "auth_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redacted": {
+ "name": "redacted",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_notification_setting_project_id_project_id_fk": {
+ "name": "project_notification_setting_project_id_project_id_fk",
+ "tableFrom": "project_notification_setting",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_role": {
+ "name": "project_role",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "is_default": {
+ "name": "is_default",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_role_default_uq": {
+ "name": "project_role_default_uq",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"project_role\".\"is_default\"",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "project_role_project_idx": {
+ "name": "project_role_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_role_project_id_project_id_fk": {
+ "name": "project_role_project_id_project_id_fk",
+ "tableFrom": "project_role",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "project_role_project_id_name_unique": {
+ "name": "project_role_project_id_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_setting": {
+ "name": "project_setting",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_setting_project_id_project_id_fk": {
+ "name": "project_setting_project_id_project_id_fk",
+ "tableFrom": "project_setting",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_setting_project_id_key_pk": {
+ "name": "project_setting_project_id_key_pk",
+ "columns": [
+ "project_id",
+ "key"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_view": {
+ "name": "project_view",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "filters": {
+ "name": "filters",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "display": {
+ "name": "display",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "position": {
+ "name": "position",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "share_token": {
+ "name": "share_token",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "share_extended": {
+ "name": "share_extended",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "project_view_project_idx": {
+ "name": "project_view_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "project_view_project_id_project_id_fk": {
+ "name": "project_view_project_id_project_id_fk",
+ "tableFrom": "project_view",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "project_view_share_token_unique": {
+ "name": "project_view_share_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "share_token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_view_favorite": {
+ "name": "project_view_favorite",
+ "schema": "",
+ "columns": {
+ "view_id": {
+ "name": "view_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_view_favorite_view_id_project_view_id_fk": {
+ "name": "project_view_favorite_view_id_project_view_id_fk",
+ "tableFrom": "project_view_favorite",
+ "tableTo": "project_view",
+ "columnsFrom": [
+ "view_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_view_favorite_user_id_user_id_fk": {
+ "name": "project_view_favorite_user_id_user_id_fk",
+ "tableFrom": "project_view_favorite",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_view_favorite_view_id_user_id_pk": {
+ "name": "project_view_favorite_view_id_user_id_pk",
+ "columns": [
+ "view_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.revision": {
+ "name": "revision",
+ "schema": "",
+ "columns": {
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "rev": {
+ "name": "rev",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "revision_project_idx": {
+ "name": "revision_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_notification_preference": {
+ "name": "user_notification_preference",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_events": {
+ "name": "email_events",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "telegram_events": {
+ "name": "telegram_events",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_notification_preference_user_id_user_id_fk": {
+ "name": "user_notification_preference_user_id_user_id_fk",
+ "tableFrom": "user_notification_preference",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_notification_preference_project_id_project_id_fk": {
+ "name": "user_notification_preference_project_id_project_id_fk",
+ "tableFrom": "user_notification_preference",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_notification_pref_user_project_unique": {
+ "name": "user_notification_pref_user_project_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user_id",
+ "project_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_preference": {
+ "name": "user_preference",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'UTC'"
+ },
+ "locale": {
+ "name": "locale",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'en'"
+ },
+ "theme": {
+ "name": "theme",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'system'"
+ },
+ "issue_open_mode": {
+ "name": "issue_open_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'panel'"
+ },
+ "start_page": {
+ "name": "start_page",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'work-items'"
+ },
+ "show_chat_by_default": {
+ "name": "show_chat_by_default",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "issue_stats_open": {
+ "name": "issue_stats_open",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "issue_stats_view": {
+ "name": "issue_stats_view",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'compact'"
+ },
+ "issue_activity_view": {
+ "name": "issue_activity_view",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'flat'"
+ },
+ "auto_watch": {
+ "name": "auto_watch",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "hotkeys": {
+ "name": "hotkeys",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_project_id": {
+ "name": "last_project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_preference_user_id_user_id_fk": {
+ "name": "user_preference_user_id_user_id_fk",
+ "tableFrom": "user_preference",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_preference_last_project_id_project_id_fk": {
+ "name": "user_preference_last_project_id_project_id_fk",
+ "tableFrom": "user_preference",
+ "tableTo": "project",
+ "columnsFrom": [
+ "last_project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "user_preference_theme_check": {
+ "name": "user_preference_theme_check",
+ "value": "\"user_preference\".\"theme\" IN ('light', 'dark', 'system')"
+ },
+ "user_preference_issue_open_mode_check": {
+ "name": "user_preference_issue_open_mode_check",
+ "value": "\"user_preference\".\"issue_open_mode\" IN ('panel', 'page')"
+ },
+ "user_preference_start_page_check": {
+ "name": "user_preference_start_page_check",
+ "value": "\"user_preference\".\"start_page\" IN ('inbox', 'dashboard', 'work-items', 'initiatives', 'ai-chat')"
+ },
+ "user_preference_issue_stats_view_check": {
+ "name": "user_preference_issue_stats_view_check",
+ "value": "\"user_preference\".\"issue_stats_view\" IN ('compact', 'timeline')"
+ },
+ "user_preference_issue_activity_view_check": {
+ "name": "user_preference_issue_activity_view_check",
+ "value": "\"user_preference\".\"issue_activity_view\" IN ('flat', 'grouped')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.user_telegram_account": {
+ "name": "user_telegram_account",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "username": {
+ "name": "username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "first_name": {
+ "name": "first_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "link_code": {
+ "name": "link_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "link_code_expires_at": {
+ "name": "link_code_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "linked_at": {
+ "name": "linked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_telegram_account_chat_id_unique": {
+ "name": "user_telegram_account_chat_id_unique",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"user_telegram_account\".\"chat_id\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_telegram_account_link_code_unique": {
+ "name": "user_telegram_account_link_code_unique",
+ "columns": [
+ {
+ "expression": "link_code",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"user_telegram_account\".\"link_code\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_telegram_account_user_id_user_id_fk": {
+ "name": "user_telegram_account_user_id_user_id_fk",
+ "tableFrom": "user_telegram_account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.webhook": {
+ "name": "webhook",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "secret": {
+ "name": "secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "events": {
+ "name": "events",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "consecutive_failures": {
+ "name": "consecutive_failures",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "webhook_project_idx": {
+ "name": "webhook_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "webhook_project_id_project_id_fk": {
+ "name": "webhook_project_id_project_id_fk",
+ "tableFrom": "webhook",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.webhook_delivery": {
+ "name": "webhook_delivery",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "webhook_id": {
+ "name": "webhook_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event_id": {
+ "name": "event_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "response_status": {
+ "name": "response_status",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "response_body": {
+ "name": "response_body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "webhook_delivery_due_idx": {
+ "name": "webhook_delivery_due_idx",
+ "columns": [
+ {
+ "expression": "next_attempt_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"webhook_delivery\".\"status\" = 'pending'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "webhook_delivery_webhook_idx": {
+ "name": "webhook_delivery_webhook_idx",
+ "columns": [
+ {
+ "expression": "webhook_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "webhook_delivery_webhook_id_webhook_id_fk": {
+ "name": "webhook_delivery_webhook_id_webhook_id_fk",
+ "tableFrom": "webhook_delivery",
+ "tableTo": "webhook",
+ "columnsFrom": [
+ "webhook_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index 6eaa6c8c..6cfc3189 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -582,6 +582,20 @@
"when": 1786805381958,
"tag": "0082_yellow_proudstar",
"breakpoints": true
+ },
+ {
+ "idx": 83,
+ "version": "7",
+ "when": 1786911699600,
+ "tag": "0083_ambitious_wendell_rand",
+ "breakpoints": true
+ },
+ {
+ "idx": 84,
+ "version": "7",
+ "when": 1786919228260,
+ "tag": "0084_busy_speed_demon",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema/app.ts b/packages/db/src/schema/app.ts
index 1d9ecbaf..05006487 100644
--- a/packages/db/src/schema/app.ts
+++ b/packages/db/src/schema/app.ts
@@ -4,6 +4,7 @@
import { sql } from 'drizzle-orm';
import {
bigint,
+ bigserial,
boolean,
check,
type AnyPgColumn,
@@ -502,6 +503,91 @@ export const agentRun = pgTable(
],
);
+// A conversation between one member and one external agent. The internal agents'
+// threads are held by Mastra's own store; an external agent is driven by a runner on
+// its operator's machine, which has no memory of its own, so the conversation lives
+// here. The id carries the same shape as a Mastra chat thread id (see
+// runtime/thread-ids), which is what lets the chat UI address both kinds the same way.
+export const agentChatThread = pgTable(
+ 'agent_chat_thread',
+ {
+ id: text('id').primaryKey(),
+ agentId: integer('agent_id')
+ .notNull()
+ .references(() => aiAgent.id, { onDelete: 'cascade' }),
+ userId: text('user_id')
+ .notNull()
+ .references(() => user.id, { onDelete: 'cascade' }),
+ title: text('title'),
+ // The session the runner's coding agent keeps for this thread on its own machine.
+ // Set once the runner reports the session it started; null means the next message
+ // starts a fresh one and is sent with the conversation framed into its prompt.
+ cliSessionId: text('cli_session_id'),
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
+ },
+ (t) => [index('agent_chat_thread_agent_user_idx').on(t.agentId, t.userId, t.updatedAt.desc())],
+);
+
+// One turn of a chat thread, and for an agent turn also the queue row the runner
+// drains. A member's message is written 'success' with its text; the agent's answer is
+// inserted empty and 'pending', goes 'streaming' when a runner claims it, and is filled
+// in from the events that runner reports. A claim pushes next_attempt_at forward by a
+// lease, so an answer whose runner dies is claimable again once the lease expires —
+// which is why the due index covers both live states. agent_id repeats the thread's
+// agent so a runner finds its due turns with one index.
+export const agentChatMessage = pgTable(
+ 'agent_chat_message',
+ {
+ id: serial('id').primaryKey(),
+ threadId: text('thread_id')
+ .notNull()
+ .references(() => agentChatThread.id, { onDelete: 'cascade' }),
+ agentId: integer('agent_id')
+ .notNull()
+ .references(() => aiAgent.id, { onDelete: 'cascade' }),
+ role: text('role').notNull(),
+ // The turn's text: what the member wrote, or what the agent has said so far. It is
+ // appended to as text events arrive, so the transcript reads correctly mid-answer.
+ content: text('content').notNull().default(''),
+ status: text('status').notNull().default('pending'),
+ attempts: integer('attempts').notNull().default(0),
+ nextAttemptAt: timestamp('next_attempt_at', { withTimezone: true }).notNull().defaultNow(),
+ lastError: text('last_error'),
+ startedAt: timestamp('started_at', { withTimezone: true }),
+ finishedAt: timestamp('finished_at', { withTimezone: true }),
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
+ },
+ (t) => [
+ check('agent_chat_message_role_check', sql`${t.role} IN ('user', 'assistant')`),
+ check(
+ 'agent_chat_message_status_check',
+ sql`${t.status} IN ('pending', 'streaming', 'success', 'failed')`,
+ ),
+ index('agent_chat_message_thread_idx').on(t.threadId, t.id),
+ index('agent_chat_message_due_idx')
+ .on(t.agentId, t.nextAttemptAt)
+ .where(sql`${t.status} IN ('pending', 'streaming')`),
+ ],
+);
+
+// What the runner reported while producing one agent turn, as AG-UI events (text
+// deltas, tool calls, the run's lifecycle). Append-only: the id is the cursor a reader
+// resumes from, which is what lets the browser reconnect mid-answer without replaying
+// what it already has.
+export const agentChatEvent = pgTable(
+ 'agent_chat_event',
+ {
+ id: bigserial('id', { mode: 'number' }).primaryKey(),
+ messageId: integer('message_id')
+ .notNull()
+ .references(() => agentChatMessage.id, { onDelete: 'cascade' }),
+ payload: jsonb('payload').notNull(),
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
+ },
+ (t) => [index('agent_chat_event_message_idx').on(t.messageId, t.id)],
+);
+
// Stored credentials for a project's integrations. One store for every secret: the
// API keys of LLM providers (kind 'llm', addressed by an internal agent's model) and
// the credentials of tool integrations (kind 'tool', bound to configured tools).
diff --git a/packages/runner/README.md b/packages/runner/README.md
index 38f5cb2d..ede3af7e 100644
--- a/packages/runner/README.md
+++ b/packages/runner/README.md
@@ -1,267 +1,218 @@
# @itsaplan/runner
-[It's a Plan](https://itsaplan.dev) is self-hosted, open-source project management and
-issue tracking where AI agents work like teammates: they have a role, permissions, and
-issues assigned to them.
+[It's a Plan](https://itsaplan.dev) is a self-hosted, open-source issue tracker. An AI
+agent in it is a project member: it has a role, permissions, and its own issues.
-This package runs the tasks of one such agent on your own machine. It takes one queued
-task at a time, passes it to a command you choose, and sends the result back. The
-command is yours: Claude Code, Codex, a shell script, anything that reads stdin.
+This package runs one such agent on your own machine.
+
+- Polls your instance for the agent's queued runs. Runs each one with a coding agent CLI.
+ Reports the result.
+- Has presets for Claude Code, Codex, opencode, Gemini CLI and GitHub Copilot CLI. Each
+ preset sets the unattended flags and the session resume.
+- Runs your own `command` instead, if you prefer. The command takes the task on stdin.
+- Answers the agent's chat. Sends the text and the tool calls while the CLI prints them.
## Quick start
-**1. Get the agent's key.** In your project: Settings, AI agents, create one of kind
-External. The key is shown once, at creation.
+**1. Get the agent's key.** In your project, go to Settings, AI agents. Create an agent
+of kind External. The key appears one time only, at creation.
+
+**2. Enable MCP** for the project, in Settings, MCP Server. MCP is off by default. The
+agent reads the issue and writes its result through it.
-**2. Write `itsaplan-runner.json`** in the folder you want the agent to work in:
+**3. Give the coding agent the address of that server.** Claude Code reads `.mcp.json`
+from the folder it runs in. For the other four CLIs, see
+[Coding agent setup](https://github.com/croffasia/itsaplan/blob/main/docs/runner.md).
```json
{
- "url": "http://localhost:3000",
- "apiKey": "the key you just copied",
- "command": "claude -p"
+ "mcpServers": {
+ "itsaplan": {
+ "type": "http",
+ "url": "http://localhost:3000/mcp",
+ "headers": { "Authorization": "Bearer ${ITSAPLAN_API_KEY}" }
+ }
+ }
}
```
-**3. Start it:**
-
-```bash
-npx -y @itsaplan/runner
-```
+The runner sets `ITSAPLAN_API_KEY` for the command that it starts. The key thus stays in
+one file.
-The agent goes online in the project within a few seconds. Delegate an issue to it or
-mention it in a comment, and the task lands in your terminal.
+**4. Write `itsaplan-runner.json`** in the same folder:
-`Ctrl-C` stops the runner once the tasks in flight are done. Anything still queued
-waits for the next runner.
-
-## Settings
-
-The runner reads `./itsaplan-runner.json`, or the path you give it as an argument or in
-`ITSAPLAN_RUNNER_CONFIG`:
-
-```bash
-npx -y @itsaplan/runner /path/to/config.json
+```json
+{
+ "url": "http://localhost:3000",
+ "apiKey": "the key you just copied",
+ "agent": "claude"
+}
```
-Environment variables win over the file:
-
-| Field | Environment variable | Default | What it does |
-| ---------------- | --------------------------- | ------------------ | ----------------------------------- |
-| `url` | `ITSAPLAN_URL` | required | Your Itsaplan instance |
-| `apiKey` | `ITSAPLAN_API_KEY` | required | The external agent's key |
-| `command` | `ITSAPLAN_COMMAND` | required | The command that handles one task |
-| `cwd` | `ITSAPLAN_CWD` | where you start it | Working directory for the command |
-| `env` | | `{}` | Extra variables for the command |
-| `concurrency` | `ITSAPLAN_CONCURRENCY` | `1` | How many tasks may run at once |
-| `pollIntervalMs` | `ITSAPLAN_POLL_INTERVAL_MS` | `3000` | Wait after an empty queue, at least 1000 |
-| `timeoutMs` | `ITSAPLAN_TIMEOUT_MS` | `1800000` | When a task is killed as stuck |
-
-Which is how the key stays out of any file:
+**5. Start it:**
```bash
-export ITSAPLAN_API_KEY=…
npx -y @itsaplan/runner
```
-## What your command receives
-
-The task text arrives on **stdin**. The rest of the run arrives in the environment:
+The project shows the agent as online in a few seconds. Delegate an issue to the agent,
+or mention it in a comment. The task then starts in your terminal.
-| Variable | What it holds |
-| ------------------------ | ------------------------------------------------------ |
-| `ITSAPLAN_URL` | the instance the task came from |
-| `ITSAPLAN_API_KEY` | the agent's key, for the API and the MCP server |
-| `ITSAPLAN_RUN_ID` | the run's id |
-| `ITSAPLAN_TRIGGER` | `mention`, `delegation`, `schedule`, or `manual` |
-| `ITSAPLAN_SYSTEM_PROMPT` | context about the run, for commands that take a system prompt |
-| `ITSAPLAN_ISSUE` | the issue key, e.g. `MKT-42` (empty when there is none) |
-| `ITSAPLAN_ISSUE_ID` | the issue's numeric id |
+## Which coding agent
-The task on stdin is written by the server: what happened, what to do, and to post the
-result as a comment on the issue. The agent reads everything else through the MCP
-server at `$ITSAPLAN_URL/mcp`, with `$ITSAPLAN_API_KEY` as a bearer token, acting as
-its own user under its role. Enable MCP in the project settings.
+`agent` names a CLI that the runner knows. The runner then builds the command itself: the
+flags for an unattended run, and the session resume.
-Exit code `0` is a success, anything else a failure with the tail of stderr as the
-error. Stdout becomes the run's output either way.
+| Agent | Runs | Keeps a chat session |
+| ---------- | ------------------------ | -------------------- |
+| `claude` | Claude Code | yes |
+| `codex` | Codex CLI | yes |
+| `opencode` | opencode | yes |
+| `gemini` | Gemini CLI | no |
+| `copilot` | GitHub Copilot CLI | no |
-## Claude Code
+Each preset needs the CLI's own MCP config.
+[Coding agent setup](https://github.com/croffasia/itsaplan/blob/main/docs/runner.md) holds
+that file, and the notes for each CLI.
-`mcp.json`, next to the runner config:
+`--agent` on the command line has priority over the file. The runner appends the
+arguments after `--` to the ones from the preset:
-```json
-{
- "mcpServers": {
- "itsaplan": {
- "type": "http",
- "url": "http://localhost:3000/mcp",
- "headers": { "Authorization": "Bearer ${ITSAPLAN_API_KEY}" }
- }
- }
-}
+```bash
+npx -y @itsaplan/runner --agent claude -- --model opus
```
-`itsaplan-runner.json`:
+Write the same arguments in the file if a service manager starts the runner:
```json
{
"url": "http://localhost:3000",
"apiKey": "the key you copied on creation",
- "command": "claude -p --mcp-config ./mcp.json --append-system-prompt \"$ITSAPLAN_SYSTEM_PROMPT\" --permission-mode auto --output-format text",
- "cwd": "/Users/me/work/my-repo"
+ "agent": "claude",
+ "cwd": "/Users/me/work/my-repo",
+ "args": ["--model", "opus"]
}
```
-- `--mcp-config` adds this instance's server on top of what the machine already has,
- so your own MCP servers, skills, and memory stay in the run. Drop it if the server is
- already in the repository's `.mcp.json` or was added with `claude mcp add`.
-- `--permission-mode auto` covers permissions: nobody is there to answer a prompt, so a
- classifier reviews each action instead, MCP tool calls included.
+Your arguments come after the preset's own. A repeated flag thus replaces its value.
-## Codex
+`command` replaces the preset with your own shell command. The command receives the task
+on stdin. The runner keeps no session for it, because it does not know how to resume one.
-Codex reads its MCP servers from `~/.codex/config.toml`, and `bearer_token_env_var`
-takes the key from the environment the runner already sets:
+## Settings
+
+The runner reads `./itsaplan-runner.json`. For a different file, give the path as an
+argument or in `ITSAPLAN_RUNNER_CONFIG`:
-```toml
-[mcp_servers.itsaplan]
-url = "http://localhost:3000/mcp"
-bearer_token_env_var = "ITSAPLAN_API_KEY"
+```bash
+npx -y @itsaplan/runner /path/to/config.json
```
-`itsaplan-runner.json`:
+The environment variables have priority over the file. The command-line options have
+priority over both.
-```json
-{
- "url": "http://localhost:3000",
- "apiKey": "the key you copied on creation",
- "command": "printf '%s\\n\\n%s' \"$ITSAPLAN_SYSTEM_PROMPT\" \"$(cat)\" | codex exec --sandbox workspace-write --skip-git-repo-check -",
- "cwd": "/path/to/working-dir"
-}
+| Field | Environment variable | Default | What it does |
+| ---------------- | --------------------------- | ------------------ | ----------------------------------- |
+| `url` | `ITSAPLAN_URL` | required | Your Itsaplan instance |
+| `apiKey` | `ITSAPLAN_API_KEY` | required | The external agent's key |
+| `agent` | `ITSAPLAN_AGENT` | — | The coding agent to run |
+| `args` | | `[]` | Arguments added after the preset's |
+| `command` | `ITSAPLAN_COMMAND` | — | Your own command, instead of `agent` |
+| `cwd` | `ITSAPLAN_CWD` | where you start it | Working directory for the command |
+| `env` | | `{}` | Extra variables for the command |
+| `concurrency` | `ITSAPLAN_CONCURRENCY` | `1` | Tasks at once. Queued runs and chat answers count apart |
+| `pollIntervalMs` | `ITSAPLAN_POLL_INTERVAL_MS` | `3000` | Wait after an empty queue. Minimum 1000 |
+| `timeoutMs` | `ITSAPLAN_TIMEOUT_MS` | `1800000` | Time before the runner stops a task |
+| `outputFormat` | `ITSAPLAN_OUTPUT_FORMAT` | the preset's | How the runner reads a chat answer |
+
+Set `agent` or `command`. With the environment you need no file at all:
+
+```bash
+export ITSAPLAN_API_KEY=…
+npx -y @itsaplan/runner --agent claude
```
-- Codex has no system-prompt flag, so `printf` puts the system prompt in front of the
- task, and the trailing `-` tells Codex to read all of it from stdin.
-- `--sandbox workspace-write` bounds what it may change: writes stay inside the working
- directory.
-- `--skip-git-repo-check` is only needed when that directory is not a git repository.
+## What the coding agent receives
-## Gemini CLI
+### The task text
-`.gemini/settings.json` in the working directory. Gemini expands `$VARS` in it, so the
-key comes from the environment, and `trust` skips the tool confirmation a headless run
-cannot answer:
+The server writes the task text. The text states what occurred, what to do, and to post
+the result as a comment on the issue. Your own `command` receives the text on **stdin**. A
+preset gives it to its CLI in the way that CLI accepts it: on stdin for `claude` and
+`codex`, as an argument for `gemini`, `copilot` and `opencode`.
-```json
-{
- "mcpServers": {
- "itsaplan": {
- "httpUrl": "http://localhost:3000/mcp",
- "headers": { "Authorization": "Bearer $ITSAPLAN_API_KEY" },
- "trust": true
- }
- }
-}
-```
+The agent reads all other data through the MCP server at `$ITSAPLAN_URL/mcp`. The agent
+sends `$ITSAPLAN_API_KEY` as a bearer token, and acts as its own user with its role.
-`itsaplan-runner.json`:
+### The environment
-```json
-{
- "url": "http://localhost:3000",
- "apiKey": "the key you copied on creation",
- "command": "printf '%s\\n\\n%s' \"$ITSAPLAN_SYSTEM_PROMPT\" \"$(cat)\" | gemini --approval-mode yolo",
- "cwd": "/path/to/working-dir"
-}
-```
+Every run holds these variables:
-- Gemini has no system-prompt flag either, and reads the piped prompt on stdin, so the
- command is shaped like the Codex one.
-- `--approval-mode yolo` approves every tool call, which a headless run needs.
- `auto_edit` is the narrower option: file edits only.
+| Variable | What it holds |
+| ------------------------ | ---------------------------------------------------------------- |
+| `ITSAPLAN_URL` | the instance that sent the task |
+| `ITSAPLAN_API_KEY` | the agent's key, for the API and the MCP server |
+| `ITSAPLAN_TRIGGER` | `mention`, `delegation`, `schedule`, `manual`, or `chat` |
+| `ITSAPLAN_SYSTEM_PROMPT` | the context of the run, for a command that takes a system prompt |
-## GitHub Copilot CLI
+A queued run adds three more:
-`.mcp.json` in the working directory. Copilot's headers take no variable
-interpolation, so the key goes in as it stands:
+| Variable | What it holds |
+| ------------------- | --------------------------------------------------------------- |
+| `ITSAPLAN_RUN_ID` | the run's id |
+| `ITSAPLAN_ISSUE` | the issue key, for example `MKT-42`. Empty if there is no issue |
+| `ITSAPLAN_ISSUE_ID` | the numeric id of the issue. Empty if there is no issue |
-```json
-{
- "mcpServers": {
- "itsaplan": {
- "type": "http",
- "url": "http://localhost:3000/mcp",
- "headers": { "Authorization": "Bearer the-agent-key" },
- "tools": ["*"]
- }
- }
-}
-```
+A chat message adds three others in their place, and `ITSAPLAN_TRIGGER` is `chat`:
-`itsaplan-runner.json`:
+| Variable | What it holds |
+| ---------------------- | ---------------------------------------------------------------- |
+| `ITSAPLAN_THREAD_ID` | the conversation's id |
+| `ITSAPLAN_MESSAGE_ID` | the id of the message to answer |
+| `ITSAPLAN_SESSION_ID` | the coding agent's session to resume. Empty for the first message |
-```json
-{
- "url": "http://localhost:3000",
- "apiKey": "the key you copied on creation",
- "command": "copilot -p \"$(printf '%s\\n\\n%s' \"$ITSAPLAN_SYSTEM_PROMPT\" \"$(cat)\")\" --allow-all-tools --no-ask-user",
- "cwd": "/path/to/working-dir"
-}
-```
+The task text of a chat message includes the conversation, unless a session holds it. See
+Sessions below.
-- Copilot takes neither a system-prompt flag nor a prompt on stdin, so both go in as
- one `-p` argument.
-- `--allow-all-tools` and `--no-ask-user` keep it from waiting for an approval it
- cannot get.
+### The result
-## opencode
+Exit code `0` is a success. Any other code is a failure. The end of stderr then becomes
+the error. Stdout becomes the run's output in both cases.
-`opencode.json` in the working directory. opencode interpolates `{env:VAR}`, so the key
-stays out of the file:
+## Chat
-```json
-{
- "$schema": "https://opencode.ai/config.json",
- "model": "anthropic/claude-sonnet-5",
- "mcp": {
- "itsaplan": {
- "type": "remote",
- "url": "http://localhost:3000/mcp",
- "enabled": true,
- "headers": { "Authorization": "Bearer {env:ITSAPLAN_API_KEY}" }
- }
- }
-}
-```
+The runner streams the answer to the chat while the command runs. It reports the tool
+calls with the answer. `outputFormat` tells the runner how to read the output:
-`itsaplan-runner.json`:
+- `text` — all the output is the answer.
+- `claude-stream-json`, `codex-jsonl`, `opencode-json` — the event stream of that CLI.
-```json
-{
- "url": "http://localhost:3000",
- "apiKey": "the key you copied on creation",
- "command": "opencode run \"$(printf '%s\\n\\n%s' \"$ITSAPLAN_SYSTEM_PROMPT\" \"$(cat)\")\"",
- "cwd": "/path/to/working-dir"
-}
-```
+A preset sets `outputFormat` for you. Set it yourself only with your own `command`. If the
+output does not agree with the format, the runner sends the output as plain text.
-- `opencode run` takes the prompt as an argument and never reads stdin, so the task is
- passed the same way as with Copilot.
-- Pin `model` as `provider/model`. opencode is provider agnostic, and without that key
- a run falls back to whatever model was picked interactively last. `opencode auth
- login` is what makes a provider available in the first place.
+### Sessions
-## Requirements
+Each conversation resumes one session of the coding agent, which keeps its full context.
+Without a session the server sends the last 20 messages of the conversation as plain text.
+
+- The chat header shows the session id. Run `claude --resume <id>` in the runner's working
+ directory to open the same session in your terminal.
+- `gemini` and `copilot` keep no session: neither one reports the id of a session that
+ starts non-interactively.
+- A session stays on the machine that started it. If you delete its files or move the
+ runner, the answers fail. Start a new chat then.
-Node 20 or newer, an It's a Plan instance on 0.10.0 or newer, and an **external** agent in
-your project. Its API key is what the runner authenticates with.
+## Requirements
-The coding agent you point the runner at has to be installed and signed in on the same
-machine — the runner starts it as you and cannot sign in for you.
+- **Node 20 or later.**
+- **An It's a Plan instance 0.10.0 or later.** The chat needs 0.11.0. An older instance
+ gives the runner only the queued runs.
+- **An external agent in your project.** The runner authenticates with its API key.
+- **The coding agent, installed and signed in on the same machine.** The runner starts the
+ CLI as you, but it cannot sign in for you.
-On macOS and Linux there is nothing else to it. The runner hands every task to `sh -c`,
-so the commands in this file are POSIX shell.
+macOS and Linux need nothing else. The runner starts a preset directly, so its arguments
+need no quotes. Your own `command` goes to `sh -c`, so write it as POSIX shell.
Windows needs WSL2, because `cmd.exe` and PowerShell have no `sh`:
@@ -269,13 +220,11 @@ Windows needs WSL2, because `cmd.exe` and PowerShell have no `sh`:
wsl --install # installs Ubuntu, then reboot
```
-Everything after that happens inside WSL: Node, the coding agent, the config file, and
-`npx -y @itsaplan/runner`. Two things worth knowing there:
+Do everything else in WSL: Node, the coding agent, the config file, and the runner.
-- Keep the working directory in the WSL file system (`~/work/repo`) rather than under
- `/mnt/c/...`. File access across that boundary is slow enough to notice on a repo.
-- An instance running on the Windows host is reachable from WSL2 as
- `http://localhost:3000`.
+- Keep the working directory in the WSL file system (`~/work/repo`), not under
+ `/mnt/c/...`. Access between the two file systems is slow.
+- An instance on the Windows host is available at `http://localhost:3000`.
## License
diff --git a/packages/runner/package.json b/packages/runner/package.json
index a4768efb..ac61d5a6 100644
--- a/packages/runner/package.json
+++ b/packages/runner/package.json
@@ -1,7 +1,7 @@
{
"name": "@itsaplan/runner",
- "version": "0.1.0",
- "description": "Runs an Itsaplan external agent's queued tasks on your own machine",
+ "version": "0.2.0",
+ "description": "Runs an Itsaplan external agent's queued tasks and answers its chat on your own machine",
"keywords": [
"itsaplan",
"ai-agents",
@@ -45,10 +45,12 @@
"build": "bun build src/cli.ts --target=node --outfile dist/cli.js",
"prepublishOnly": "bun run build",
"lint": "eslint .",
- "typecheck": "tsc --noEmit"
+ "test": "bun test",
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json"
},
"devDependencies": {
"@repo/eslint-config": "workspace:*",
+ "@types/bun": "latest",
"@types/node": "^26.2.0",
"eslint": "^9.39.0",
"typescript": "^6.0.3"
diff --git a/packages/runner/src/__tests__/agui.test.ts b/packages/runner/src/__tests__/agui.test.ts
new file mode 100644
index 00000000..f53536dd
--- /dev/null
+++ b/packages/runner/src/__tests__/agui.test.ts
@@ -0,0 +1,299 @@
+import { describe, it, expect } from 'bun:test';
+import { AnswerStream, type AgUiEvent } from '../agui';
+
+// The adapter is what a chat answer is read through, and the coding agents it reads
+// print several shapes of the same thing, so the mapping is pinned here.
+
+function collect() {
+ const events: AgUiEvent[] = [];
+ return {
+ events,
+ send: async (batch: AgUiEvent[]) => {
+ events.push(...batch);
+ },
+ };
+}
+
+const types = (events: AgUiEvent[]) => events.map((e) => e.type);
+const text = (events: AgUiEvent[]) =>
+ events
+ .filter((e) => e.type === 'TEXT_MESSAGE_CONTENT')
+ .map((e) => (e as { delta: string }).delta)
+ .join('');
+
+describe('answer stream', () => {
+ it('reports plain output as one message', async () => {
+ const sink = collect();
+ const stream = new AnswerStream('text', 'chat:1:u:x', '7', sink.send);
+
+ stream.write('Two things ');
+ stream.write('are left.');
+ await stream.finish('');
+
+ expect(types(sink.events)).toEqual([
+ 'RUN_STARTED',
+ 'TEXT_MESSAGE_START',
+ 'TEXT_MESSAGE_CONTENT',
+ 'TEXT_MESSAGE_END',
+ 'RUN_FINISHED',
+ ]);
+ expect(text(sink.events)).toBe('Two things are left.');
+ });
+
+ it('ends a failed answer with what went wrong, keeping what was said', async () => {
+ const sink = collect();
+ const stream = new AnswerStream('text', 'chat:1:u:x', '7', sink.send);
+
+ stream.write('Started, then ');
+ await stream.fail('Command exited with 1');
+
+ expect(types(sink.events).at(-1)).toBe('RUN_ERROR');
+ expect(text(sink.events)).toBe('Started, then ');
+ });
+
+ it("reads Claude's stream as text and tool calls", async () => {
+ const sink = collect();
+ const stream = new AnswerStream('claude-stream-json', 'chat:1:u:x', '7', sink.send);
+
+ stream.write(
+ [
+ JSON.stringify({ type: 'system', subtype: 'init' }),
+ JSON.stringify({
+ type: 'stream_event',
+ event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'Check' } },
+ }),
+ JSON.stringify({
+ type: 'assistant',
+ message: {
+ content: [{ type: 'tool_use', id: 'tool-1', name: 'Bash', input: { command: 'ls' } }],
+ },
+ }),
+ JSON.stringify({
+ type: 'user',
+ message: {
+ content: [{ type: 'tool_result', tool_use_id: 'tool-1', content: 'README.md' }],
+ },
+ }),
+ JSON.stringify({
+ type: 'stream_event',
+ event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'ing done.' } },
+ }),
+ '',
+ ].join('\n'),
+ );
+ await stream.finish('Checking done.');
+
+ expect(types(sink.events)).toEqual([
+ 'RUN_STARTED',
+ 'TEXT_MESSAGE_START',
+ 'TEXT_MESSAGE_CONTENT',
+ 'TOOL_CALL_START',
+ 'TOOL_CALL_ARGS',
+ 'TOOL_CALL_END',
+ 'TOOL_CALL_RESULT',
+ 'TEXT_MESSAGE_CONTENT',
+ 'TEXT_MESSAGE_END',
+ 'RUN_FINISHED',
+ ]);
+ // The final text repeats the partials, so it is not appended a second time.
+ expect(text(sink.events)).toBe('Checking done.');
+ });
+
+ it('takes the final message when the command reported no partials', async () => {
+ const sink = collect();
+ const stream = new AnswerStream('claude-stream-json', 'chat:1:u:x', '7', sink.send);
+
+ stream.write(
+ `${JSON.stringify({ type: 'result', subtype: 'success', result: 'All done.' })}\n`,
+ );
+ await stream.finish('All done.');
+
+ expect(text(sink.events)).toBe('All done.');
+ });
+
+ it('shows output that is not the configured format as text', async () => {
+ const sink = collect();
+ const stream = new AnswerStream('claude-stream-json', 'chat:1:u:x', '7', sink.send);
+
+ stream.write('not json at all\n');
+ await stream.finish('');
+
+ expect(text(sink.events)).toBe('not json at all\n');
+ });
+
+ it("reads Codex's jsonl as text and shell calls", async () => {
+ const sink = collect();
+ const stream = new AnswerStream('codex-jsonl', 'chat:1:u:x', '7', sink.send);
+
+ stream.write(
+ [
+ JSON.stringify({ type: 'thread.started', thread_id: '01a00c82' }),
+ JSON.stringify({ type: 'turn.started' }),
+ JSON.stringify({
+ type: 'item.completed',
+ item: {
+ id: 'item_0',
+ type: 'command_execution',
+ command: 'ls',
+ aggregated_output: 'README.md',
+ },
+ }),
+ JSON.stringify({
+ type: 'item.completed',
+ item: { id: 'item_1', type: 'agent_message', text: 'Checked.' },
+ }),
+ '',
+ ].join('\n'),
+ );
+ await stream.finish('Checked.');
+
+ expect(types(sink.events)).toEqual([
+ 'RUN_STARTED',
+ 'TOOL_CALL_START',
+ 'TOOL_CALL_ARGS',
+ 'TOOL_CALL_END',
+ 'TOOL_CALL_RESULT',
+ 'TEXT_MESSAGE_START',
+ 'TEXT_MESSAGE_CONTENT',
+ 'TEXT_MESSAGE_END',
+ 'RUN_FINISHED',
+ ]);
+ expect(text(sink.events)).toBe('Checked.');
+ });
+
+ it("reads opencode's json, adding only what a re-sent part grew by", async () => {
+ const sink = collect();
+ const stream = new AnswerStream('opencode-json', 'chat:1:u:x', '7', sink.send);
+
+ stream.write(
+ [
+ JSON.stringify({
+ type: 'message.part.updated',
+ sessionID: 'ses_1',
+ part: { type: 'text', text: 'Look' },
+ }),
+ JSON.stringify({
+ type: 'message.part.updated',
+ sessionID: 'ses_1',
+ part: { type: 'text', text: 'Looking at it.' },
+ }),
+ '',
+ ].join('\n'),
+ );
+ await stream.finish('Looking at it.');
+
+ expect(text(sink.events)).toBe('Looking at it.');
+ });
+
+ it('reports what an opencode tool call ended with', async () => {
+ const sink = collect();
+ const stream = new AnswerStream('opencode-json', 'chat:1:u:x', '7', sink.send);
+
+ stream.write(
+ [
+ JSON.stringify({
+ sessionID: 'ses_1',
+ part: {
+ type: 'tool',
+ callID: 'c1',
+ tool: 'bash',
+ state: { status: 'running', input: { command: 'ls' } },
+ },
+ }),
+ JSON.stringify({
+ sessionID: 'ses_1',
+ part: {
+ type: 'tool',
+ callID: 'c1',
+ tool: 'bash',
+ state: { status: 'completed', input: { command: 'ls' }, output: 'README.md' },
+ },
+ }),
+ '',
+ ].join('\n'),
+ );
+ await stream.finish('');
+
+ expect(types(sink.events)).toEqual([
+ 'RUN_STARTED',
+ 'TOOL_CALL_START',
+ 'TOOL_CALL_ARGS',
+ 'TOOL_CALL_END',
+ 'TOOL_CALL_RESULT',
+ 'RUN_FINISHED',
+ ]);
+ const result = sink.events.find((e) => e.type === 'TOOL_CALL_RESULT');
+ expect((result as { content: string }).content).toBe('README.md');
+ });
+
+ it('reports what a failed opencode tool call said, once', async () => {
+ const sink = collect();
+ const stream = new AnswerStream('opencode-json', 'chat:1:u:x', '7', sink.send);
+
+ const failed = JSON.stringify({
+ sessionID: 'ses_1',
+ part: {
+ type: 'tool',
+ callID: 'c1',
+ tool: 'bash',
+ state: { status: 'error', input: {}, error: 'exit 1' },
+ },
+ });
+ stream.write([failed, failed, ''].join('\n'));
+ await stream.finish('');
+
+ const results = sink.events.filter((e) => e.type === 'TOOL_CALL_RESULT');
+ expect(results).toHaveLength(1);
+ expect((results[0] as { content: string }).content).toBe('exit 1');
+ });
+
+ it('ignores a line that parses to something other than an object', async () => {
+ for (const format of ['claude-stream-json', 'codex-jsonl', 'opencode-json'] as const) {
+ const sink = collect();
+ const stream = new AnswerStream(format, 'chat:1:u:x', '7', sink.send);
+
+ stream.write('null\n42\n');
+ await stream.finish('');
+
+ expect(types(sink.events)).toEqual(['RUN_STARTED', 'RUN_FINISHED']);
+ }
+ });
+
+ it('reports the session each format names, from its first line', async () => {
+ const claude = collect();
+ const claudeStream = new AnswerStream('claude-stream-json', 'chat:1:u:x', '7', claude.send);
+ claudeStream.write(
+ `${JSON.stringify({ type: 'system', subtype: 'init', session_id: 'abc' })}\n`,
+ );
+ expect(claudeStream.startedSession()).toBe('abc');
+
+ const codex = collect();
+ const codexStream = new AnswerStream('codex-jsonl', 'chat:1:u:x', '7', codex.send);
+ codexStream.write(`${JSON.stringify({ type: 'thread.started', thread_id: '01a0' })}\n`);
+ expect(codexStream.startedSession()).toBe('01a0');
+
+ const opencode = collect();
+ const opencodeStream = new AnswerStream('opencode-json', 'chat:1:u:x', '7', opencode.send);
+ opencodeStream.write(`${JSON.stringify({ type: 'step.started', sessionID: 'ses_9' })}\n`);
+ expect(opencodeStream.startedSession()).toBe('ses_9');
+ });
+
+ it('keeps the first session it saw when later lines name another', async () => {
+ const sink = collect();
+ const stream = new AnswerStream('claude-stream-json', 'chat:1:u:x', '7', sink.send);
+
+ stream.write(`${JSON.stringify({ type: 'system', session_id: 'first' })}\n`);
+ stream.write(`${JSON.stringify({ type: 'assistant', session_id: 'second' })}\n`);
+
+ expect(stream.startedSession()).toBe('first');
+ });
+
+ it('reports no session for a format that names none', async () => {
+ const sink = collect();
+ const stream = new AnswerStream('text', 'chat:1:u:x', '7', sink.send);
+
+ stream.write('done\n');
+
+ expect(stream.startedSession()).toBeNull();
+ });
+});
diff --git a/packages/runner/src/__tests__/presets.test.ts b/packages/runner/src/__tests__/presets.test.ts
new file mode 100644
index 00000000..dcdd2051
--- /dev/null
+++ b/packages/runner/src/__tests__/presets.test.ts
@@ -0,0 +1,69 @@
+import { describe, it, expect } from 'bun:test';
+import { PRESETS, presetArgv, presetPrompt } from '../presets';
+
+// The preset is what makes a session survive between messages, so the argument it builds
+// for each CLI is pinned here: getting the resume spelling wrong is silent — the command
+// runs, it just starts over every time.
+
+describe('preset arguments', () => {
+ it('starts Claude Code without a session and resumes the one it is given', () => {
+ const fresh = presetArgv(PRESETS.claude, null, 'context', [], 'do it');
+ expect(fresh).not.toContain('--resume');
+ expect(fresh).toContain('--output-format');
+
+ const resumed = presetArgv(PRESETS.claude, 'abc-123', 'context', [], 'do it');
+ expect(resumed.slice(0, 3)).toEqual(['-p', '--resume', 'abc-123']);
+ });
+
+ it("puts Codex's resume in front, as the subcommand it is, and keeps the stdin marker last", () => {
+ const fresh = presetArgv(PRESETS.codex, null, '', [], 'do it');
+ expect(fresh[0]).toBe('exec');
+ expect(fresh.at(-1)).toBe('-');
+
+ const resumed = presetArgv(PRESETS.codex, '01a0', '', ['--model', 'gpt-5'], 'do it');
+ expect(resumed.slice(0, 3)).toEqual(['exec', 'resume', '01a0']);
+ expect(resumed.at(-1)).toBe('-');
+ // The operator's own arguments sit before the marker, never after it.
+ expect(resumed.indexOf('--model')).toBeLessThan(resumed.length - 1);
+ });
+
+ it('gives opencode the task as the last argument, after the session flag', () => {
+ const argv = presetArgv(PRESETS.opencode, 'ses_1', '', [], 'do it');
+ expect(argv).toContain('--session');
+ expect(argv.at(-1)).toBe('do it');
+ });
+
+ it('ignores a session for a CLI that cannot resume one', () => {
+ const argv = presetArgv(PRESETS.gemini, 'whatever', '', [], 'do it');
+ expect(argv).not.toContain('whatever');
+ expect(argv.at(-2)).toBe('-p');
+ expect(argv.at(-1)).toBe('do it');
+ });
+
+ it("appends the operator's arguments after the preset's, so a repeated flag wins", () => {
+ const argv = presetArgv(PRESETS.claude, null, '', ['--permission-mode', 'plan'], 'do it');
+ expect(argv.lastIndexOf('--permission-mode')).toBeGreaterThan(
+ argv.indexOf('--permission-mode'),
+ );
+ expect(argv.at(-1)).toBe('plan');
+ });
+
+ it('passes the system prompt by flag where there is one and in front of the task otherwise', () => {
+ const claude = presetArgv(PRESETS.claude, null, 'context', [], 'do it');
+ expect(claude).toContain('--append-system-prompt');
+ expect(claude).toContain('context');
+ expect(presetPrompt(PRESETS.claude, 'context', 'do it')).toBe('do it');
+
+ expect(presetPrompt(PRESETS.codex, 'context', 'do it')).toBe('context\n\ndo it');
+ expect(presetArgv(PRESETS.opencode, null, 'context', [], 'do it').at(-1)).toBe(
+ 'context\n\ndo it',
+ );
+ });
+
+ it('leaves the task alone on a resumed session, where the context is already held', () => {
+ expect(presetPrompt(PRESETS.codex, '', 'do it')).toBe('do it');
+ expect(presetArgv(PRESETS.claude, 'abc', '', [], 'do it')).not.toContain(
+ '--append-system-prompt',
+ );
+ });
+});
diff --git a/packages/runner/src/agui.ts b/packages/runner/src/agui.ts
new file mode 100644
index 00000000..878521a2
--- /dev/null
+++ b/packages/runner/src/agui.ts
@@ -0,0 +1,362 @@
+import type { OutputFormat } from './config';
+
+// Turns what the command prints into AG-UI events (https://docs.ag-ui.com), which is what
+// the server stores and the chat reads. A CLI that reports its own stream also carries the
+// tool calls it makes, and those become tool events rather than text.
+
+export type AgUiEvent =
+ | { type: 'RUN_STARTED'; threadId: string; runId: string }
+ | { type: 'RUN_FINISHED'; threadId: string; runId: string }
+ | { type: 'RUN_ERROR'; message: string }
+ | { type: 'TEXT_MESSAGE_START'; messageId: string; role: 'assistant' }
+ | { type: 'TEXT_MESSAGE_CONTENT'; messageId: string; delta: string }
+ | { type: 'TEXT_MESSAGE_END'; messageId: string }
+ | { type: 'TOOL_CALL_START'; toolCallId: string; toolCallName: string; parentMessageId: string }
+ | { type: 'TOOL_CALL_ARGS'; toolCallId: string; delta: string }
+ | { type: 'TOOL_CALL_END'; toolCallId: string }
+ | { type: 'TOOL_CALL_RESULT'; messageId: string; toolCallId: string; content: string };
+
+// Text is sent in batches rather than per chunk: a token at a time would be a request
+// per token, and the reader cannot tell the difference at this size anyway.
+const FLUSH_CHARS = 1500;
+// The server's own cap on one text event. Longer output is split across events.
+const DELTA_LIMIT = 12_000;
+// A tool's arguments and result are reported whole: cutting one breaks the JSON the chat
+// indents and highlights. An outsized one is cut from the front, where a long output says
+// least.
+const TOOL_TEXT_LIMIT = 32_000;
+
+// Produces the events of one answer and hands them to `send` in batches. The caller
+// writes the command's output as it arrives and calls flush on a timer, so a long
+// answer reaches the chat while it is still being written.
+export class AnswerStream {
+ private readonly messageId: string;
+ private queued: AgUiEvent[] = [];
+ private text = '';
+ private started = false;
+ private line = '';
+ // Every event-stream format names its session before the model has produced anything,
+ // so it is known in time for the first batch of events.
+ private sessionId: string | null = null;
+ // opencode re-sends a growing part rather than the delta, so the last text seen says
+ // how much of the next one is new. Tool parts are re-sent the same way, hence the sets:
+ // one for the call already reported, one for the result it ended with.
+ private openTextPart = '';
+ private readonly openToolCalls = new Set<string>();
+ private readonly closedToolCalls = new Set<string>();
+ // Whether the command reported partial text of its own. Its final message repeats
+ // that text, and emitting both would say everything twice.
+ private sawPartialText = false;
+ private sawAnyText = false;
+ // The flush in flight, so the next one waits for it instead of racing it.
+ private sending: Promise<void> = Promise.resolve();
+
+ constructor(
+ private readonly format: OutputFormat,
+ private readonly threadId: string,
+ private readonly runId: string,
+ private readonly send: (events: AgUiEvent[]) => Promise<void>,
+ ) {
+ this.messageId = `msg-${runId}`;
+ this.queued.push({ type: 'RUN_STARTED', threadId, runId });
+ }
+
+ write(chunk: string): void {
+ if (this.format === 'text') {
+ this.appendText(chunk);
+ return;
+ }
+ this.line += chunk;
+ const lines = this.line.split('\n');
+ this.line = lines.pop() ?? '';
+ for (const line of lines) this.readLine(line);
+ }
+
+ // Null for a format that reports no session, and for a run that printed nothing.
+ startedSession(): string | null {
+ return this.sessionId;
+ }
+
+ // Two flushes can overlap — the timer and the close — so they are chained to keep the
+ // events in the order they were produced. A batch that fails to send goes back to the
+ // front of the queue for the next flush to carry.
+ async flush(): Promise<void> {
+ const sending = this.sending.catch(() => {}).then(() => this.sendQueued());
+ this.sending = sending.catch(() => {});
+ return sending;
+ }
+
+ private async sendQueued(): Promise<void> {
+ this.drainText();
+ if (this.queued.length === 0) return;
+ const batch = this.queued;
+ this.queued = [];
+ try {
+ await this.send(batch);
+ } catch (err) {
+ this.queued.unshift(...batch);
+ throw err;
+ }
+ }
+
+ // `fallback` is the command's plain output, used when it printed nothing the adapter
+ // recognised as text — a stream-json that says only that it ran still has something to
+ // show.
+ async finish(fallback: string): Promise<void> {
+ this.closeText(fallback);
+ this.queued.push({ type: 'RUN_FINISHED', threadId: this.threadId, runId: this.runId });
+ await this.flush();
+ }
+
+ async fail(message: string, fallback = ''): Promise<void> {
+ this.closeText(fallback);
+ this.queued.push({ type: 'RUN_ERROR', message });
+ await this.flush();
+ }
+
+ private closeText(fallback: string): void {
+ if (this.line) {
+ this.readLine(this.line);
+ this.line = '';
+ }
+ if (!this.sawAnyText && fallback) this.appendText(fallback);
+ this.drainText();
+ if (this.started) this.queued.push({ type: 'TEXT_MESSAGE_END', messageId: this.messageId });
+ this.started = false;
+ }
+
+ private appendText(text: string): void {
+ if (!text) return;
+ this.sawAnyText = true;
+ this.text += text;
+ if (this.text.length >= FLUSH_CHARS) this.drainText();
+ }
+
+ private drainText(): void {
+ if (this.text.length === 0) return;
+ if (!this.started) {
+ this.started = true;
+ this.queued.push({
+ type: 'TEXT_MESSAGE_START',
+ messageId: this.messageId,
+ role: 'assistant',
+ });
+ }
+ while (this.text.length > 0) {
+ const delta = this.text.slice(0, DELTA_LIMIT);
+ this.text = this.text.slice(DELTA_LIMIT);
+ this.queued.push({ type: 'TEXT_MESSAGE_CONTENT', messageId: this.messageId, delta });
+ }
+ }
+
+ // Anything unrecognised is ignored: these formats carry more than a chat needs, and a
+ // new message type is not an error.
+ private readLine(line: string): void {
+ const trimmed = line.trim();
+ if (!trimmed) return;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(trimmed);
+ } catch {
+ // Output that is not the format it was configured with still has something to say.
+ // A CLI writing its own diagnostics to stdout alongside the stream lands here too.
+ this.appendText(`${trimmed}\n`);
+ return;
+ }
+ // A line that parses to null, a number or a string carries none of the fields below,
+ // and reading them off it would end the run with a type error.
+ if (!parsed || typeof parsed !== 'object') return;
+ switch (this.format) {
+ case 'claude-stream-json':
+ this.readClaudeLine(parsed as StreamJsonLine);
+ break;
+ case 'codex-jsonl':
+ this.readCodexLine(parsed as CodexLine);
+ break;
+ case 'opencode-json':
+ this.readOpencodeLine(parsed as OpencodeLine);
+ break;
+ }
+ }
+
+ // `thread.started` names the session; the answer arrives as a completed item of type
+ // agent_message, and the commands it ran as items of their own.
+ private readCodexLine(message: CodexLine): void {
+ if (message.type === 'thread.started' && message.thread_id) {
+ this.sessionId ??= message.thread_id;
+ return;
+ }
+ const item = message.item;
+ if (message.type !== 'item.completed' || !item) return;
+ if (item.type === 'agent_message' && item.text) {
+ this.appendText(item.text);
+ return;
+ }
+ if (item.type === 'command_execution' && item.id) {
+ this.pushToolCall(item.id, 'shell', item.command ?? '');
+ this.pushToolResult(item.id, item.aggregated_output ?? '');
+ }
+ }
+
+ // opencode names the session on every event, and text arrives as parts of an assistant
+ // message rather than as deltas of its own.
+ private readOpencodeLine(message: OpencodeLine): void {
+ if (message.sessionID) this.sessionId ??= message.sessionID;
+ const part = message.part;
+ if (!part) return;
+ if (part.type === 'text' && part.text) {
+ const grown = part.text.startsWith(this.openTextPart)
+ ? part.text.slice(this.openTextPart.length)
+ : part.text;
+ this.openTextPart = part.text;
+ this.appendText(grown);
+ return;
+ }
+ if (part.type !== 'tool' || !part.callID) return;
+ if (!this.openToolCalls.has(part.callID)) {
+ this.openToolCalls.add(part.callID);
+ this.pushToolCall(part.callID, part.tool ?? 'tool', JSON.stringify(part.state?.input ?? {}));
+ }
+ if (this.closedToolCalls.has(part.callID)) return;
+ const state = part.state;
+ const result =
+ state?.status === 'completed' ? state.output : state?.status === 'error' ? state.error : null;
+ if (typeof result !== 'string') return;
+ this.closedToolCalls.add(part.callID);
+ this.pushToolResult(part.callID, result);
+ }
+
+ private readClaudeLine(message: StreamJsonLine): void {
+ if (message.session_id) this.sessionId ??= message.session_id;
+ switch (message.type) {
+ case 'stream_event':
+ this.readPartial(message.event);
+ break;
+ case 'assistant':
+ this.readAssistant(message.message?.content ?? []);
+ break;
+ case 'user':
+ this.readToolResults(message.message?.content ?? []);
+ break;
+ case 'result':
+ // The final text repeats what was already streamed; it is the fallback for a
+ // command that reported no partials.
+ if (!this.sawAnyText && typeof message.result === 'string') this.appendText(message.result);
+ break;
+ }
+ }
+
+ private readPartial(event: StreamEvent | undefined): void {
+ if (event?.type !== 'content_block_delta') return;
+ if (event.delta?.type === 'text_delta' && event.delta.text) {
+ this.sawPartialText = true;
+ this.appendText(event.delta.text);
+ }
+ }
+
+ private readAssistant(content: ContentBlock[]): void {
+ for (const block of content) {
+ if (block.type === 'text' && block.text && !this.sawPartialText) {
+ this.appendText(block.text);
+ }
+ if (block.type === 'tool_use' && block.id) {
+ this.pushToolCall(block.id, block.name ?? 'tool', JSON.stringify(block.input ?? {}));
+ }
+ }
+ }
+
+ private readToolResults(content: ContentBlock[]): void {
+ for (const block of content) {
+ if (block.type !== 'tool_result' || !block.tool_use_id) continue;
+ this.pushToolResult(block.tool_use_id, textOfResult(block.content));
+ }
+ }
+
+ // The text so far is drained first, so a tool call lands between the words said before
+ // it and the words said after it.
+ private pushToolCall(toolCallId: string, toolCallName: string, args: string): void {
+ this.drainText();
+ this.queued.push(
+ { type: 'TOOL_CALL_START', toolCallId, toolCallName, parentMessageId: this.messageId },
+ { type: 'TOOL_CALL_ARGS', toolCallId, delta: tail(args, TOOL_TEXT_LIMIT) },
+ { type: 'TOOL_CALL_END', toolCallId },
+ );
+ }
+
+ private pushToolResult(toolCallId: string, content: string): void {
+ this.drainText();
+ this.queued.push({
+ type: 'TOOL_CALL_RESULT',
+ messageId: this.messageId,
+ toolCallId,
+ content: tail(content, TOOL_TEXT_LIMIT),
+ });
+ }
+}
+
+function tail(text: string, limit: number): string {
+ return text.length <= limit ? text : `…${text.slice(-limit)}`;
+}
+
+// A tool result is either a string or the block list the model was shown.
+function textOfResult(content: unknown): string {
+ if (typeof content === 'string') return content;
+ if (Array.isArray(content)) {
+ return content
+ .map((part) => (typeof part === 'object' && part && 'text' in part ? String(part.text) : ''))
+ .join('');
+ }
+ return '';
+}
+
+// The parts of Claude Code's stream-json this adapter reads. `session_id` rides on every
+// line, including the first.
+interface StreamJsonLine {
+ type?: string;
+ session_id?: string;
+ event?: StreamEvent;
+ message?: { content?: ContentBlock[] };
+ result?: unknown;
+}
+
+// The parts of Codex's --json output this adapter reads.
+interface CodexLine {
+ type?: string;
+ thread_id?: string;
+ item?: {
+ id?: string;
+ type?: string;
+ text?: string;
+ command?: string;
+ aggregated_output?: string;
+ };
+}
+
+// The parts of opencode's --format json output this adapter reads.
+interface OpencodeLine {
+ type?: string;
+ sessionID?: string;
+ part?: {
+ type?: string;
+ text?: string;
+ callID?: string;
+ tool?: string;
+ // A call ends 'completed' with its output, or 'error' with what went wrong.
+ state?: { status?: string; input?: unknown; output?: string; error?: string };
+ };
+}
+
+interface StreamEvent {
+ type?: string;
+ delta?: { type?: string; text?: string };
+}
+
+interface ContentBlock {
+ type?: string;
+ text?: string;
+ id?: string;
+ name?: string;
+ input?: unknown;
+ tool_use_id?: string;
+ content?: unknown;
+}
diff --git a/packages/runner/src/chat.ts b/packages/runner/src/chat.ts
new file mode 100644
index 00000000..dbf174f3
--- /dev/null
+++ b/packages/runner/src/chat.ts
@@ -0,0 +1,62 @@
+import { AnswerStream } from './agui';
+import type { ChatMessage, Client } from './client';
+import type { RunnerConfig } from './config';
+import { execute } from './execute';
+
+// The command is the same one that handles a queued run; what differs is that its output
+// is reported while it is still being written, so the person waiting in the chat reads the
+// answer as it appears.
+//
+// A thread with no session yet is answered by a command started without one, and the
+// session it reports is sent with the first batch of events, which binds the thread.
+
+// Often enough to read as typing, rarely enough that a chatty command does not become a
+// request per line.
+const FLUSH_MS = 500;
+
+export async function answer(
+ config: RunnerConfig,
+ client: Client,
+ message: ChatMessage,
+): Promise<void> {
+ // Reported once: repeating it on every batch is a field the server has to ignore.
+ let reported = message.sessionId !== null;
+ const stream: AnswerStream = new AnswerStream(
+ config.outputFormat,
+ message.threadId,
+ String(message.id),
+ (events) => {
+ const started = reported ? undefined : (stream.startedSession() ?? undefined);
+ if (started) reported = true;
+ return client.chatEvents(message.id, events, started);
+ },
+ );
+ // A flush that fails is not fatal: the next one carries what it left behind.
+ const flushing = setInterval(() => {
+ void stream.flush().catch(() => {});
+ }, FLUSH_MS);
+ const outcome = await execute(
+ config,
+ {
+ prompt: message.prompt,
+ systemPrompt: message.systemPrompt,
+ sessionId: message.sessionId,
+ env: {
+ ITSAPLAN_TRIGGER: 'chat',
+ ITSAPLAN_SYSTEM_PROMPT: message.systemPrompt,
+ ITSAPLAN_THREAD_ID: message.threadId,
+ ITSAPLAN_MESSAGE_ID: String(message.id),
+ ITSAPLAN_SESSION_ID: message.sessionId ?? '',
+ },
+ },
+ (chunk) => stream.write(chunk),
+ ).finally(() => clearInterval(flushing));
+ if (outcome.status === 'success') {
+ await stream.finish(outcome.output);
+ await client.chatResult(message.id, { status: 'success' });
+ return;
+ }
+ const error = outcome.error ?? 'The command failed';
+ await stream.fail(error, outcome.output);
+ await client.chatResult(message.id, { status: 'failed', error });
+}
diff --git a/packages/runner/src/cli.ts b/packages/runner/src/cli.ts
index 99662aec..b8f76078 100755
--- a/packages/runner/src/cli.ts
+++ b/packages/runner/src/cli.ts
@@ -1,24 +1,28 @@
#!/usr/bin/env node
import { setTimeout as sleep } from 'node:timers/promises';
-import { Client, RequestError, type Run } from './client';
+import { answer } from './chat';
+import { Client, RequestError, type ChatMessage, type Run } from './client';
import { loadConfig, type RunnerConfig } from './config';
import { execute } from './execute';
-// The runner: claim a task, run the configured command, report the result, repeat.
-// It holds no state — the queue is the server's — so stopping it mid-task only means
-// that task's lease expires and another runner (or this one, restarted) picks it up.
+// The runner holds no state — the queue is the server's — so stopping it mid-task only
+// means that task's lease expires and another runner picks it up.
+//
+// Two feeds are drained side by side: triggered runs, polled, and chat messages, claimed
+// by a call that waits on the server for one.
const HEARTBEAT_MS = 60_000;
+const ERROR_BACKOFF_MS = 5_000;
function log(message: string): void {
console.log(`[itsaplan-runner] ${message}`);
}
-// Keeps the lease alive while the command runs; a task can take much longer than the
-// server's lease, and without this it would be handed out again mid-flight.
-async function withHeartbeat<T>(client: Client, runId: number, work: Promise<T>): Promise<T> {
+// A task can take much longer than the server's lease; without this it would be handed
+// out again mid-flight.
+async function withHeartbeat<T>(beat: () => Promise<void>, work: Promise<T>): Promise<T> {
const timer = setInterval(() => {
- client.heartbeat(runId).catch((err) => log(`heartbeat failed: ${String(err)}`));
+ beat().catch((err) => log(`heartbeat failed: ${String(err)}`));
}, HEARTBEAT_MS);
try {
return await work;
@@ -27,11 +31,28 @@ async function withHeartbeat<T>(client: Client, runId: number, work: Promise<T>)
}
}
+function taskOf(run: Run) {
+ return {
+ prompt: run.prompt,
+ systemPrompt: run.systemPrompt,
+ env: {
+ ITSAPLAN_RUN_ID: String(run.id),
+ ITSAPLAN_TRIGGER: run.trigger,
+ ITSAPLAN_SYSTEM_PROMPT: run.systemPrompt,
+ ITSAPLAN_ISSUE: run.issueIdentifier ?? '',
+ ITSAPLAN_ISSUE_ID: run.issueId == null ? '' : String(run.issueId),
+ },
+ };
+}
+
async function handle(config: RunnerConfig, client: Client, run: Run): Promise<void> {
const label = run.issueIdentifier ?? `run ${run.id}`;
log(`${label}: started (${run.trigger})`);
try {
- const outcome = await withHeartbeat(client, run.id, execute(config, run));
+ const outcome = await withHeartbeat(
+ () => client.heartbeat(run.id),
+ execute(config, taskOf(run)),
+ );
await client.report(run.id, outcome);
log(`${label}: ${outcome.status}${outcome.error ? ` — ${outcome.error}` : ''}`);
} catch (err) {
@@ -43,55 +64,149 @@ async function handle(config: RunnerConfig, client: Client, run: Run): Promise<v
}
}
-async function main(): Promise<void> {
- const configPath =
- process.argv[2] ?? process.env.ITSAPLAN_RUNNER_CONFIG ?? './itsaplan-runner.json';
- const config = await loadConfig(configPath);
- const client = new Client(config);
- const active = new Set<Promise<void>>();
- let stopping = false;
-
- for (const signal of ['SIGINT', 'SIGTERM'] as const) {
- process.on(signal, () => {
- // The commands run in their own process groups, so quitting now leaves them
- // running with nobody to report their result: the lease expires and the run is
- // handed out again.
- if (stopping) {
- log('quitting now — the commands in flight keep running, their runs are retried');
- process.exit(1);
- }
- stopping = true;
- log('stopping — finishing the tasks in flight, press again to quit now');
- });
+async function handleChat(
+ config: RunnerConfig,
+ client: Client,
+ message: ChatMessage,
+): Promise<void> {
+ log(`chat ${message.id}: answering`);
+ try {
+ await withHeartbeat(() => client.chatHeartbeat(message.id), answer(config, client, message));
+ log(`chat ${message.id}: answered`);
+ } catch (err) {
+ // Without a reported failure the chat waits for an answer that is no longer coming.
+ const text = err instanceof Error ? err.message : String(err);
+ log(`chat ${message.id}: runner error — ${text}`);
+ await client.chatResult(message.id, { status: 'failed', error: text }).catch(() => {});
}
+}
- log(
- `polling ${config.url} every ${config.pollIntervalMs}ms, up to ${config.concurrency} at once`,
- );
- while (!stopping) {
- if (active.size >= config.concurrency) {
+// Both feeds are drained the same way; they differ in what asking for work means — a poll
+// for runs, a waiting claim for chat. `onEmpty` waits before asking again, and returns
+// false to give the feed up entirely.
+async function drain<T>(
+ state: { stopping: boolean },
+ concurrency: number,
+ take: () => Promise<T | null>,
+ run: (item: T) => Promise<void>,
+ onEmpty: () => Promise<boolean>,
+): Promise<void> {
+ const active = new Set<Promise<void>>();
+ let done = false;
+ while (!state.stopping && !done) {
+ if (active.size >= concurrency) {
await Promise.race(active);
continue;
}
- let run: Run | null = null;
+ let item: T | null = null;
try {
- run = await client.claim();
+ item = await take();
} catch (err) {
// A key the server refuses will be refused just as much on the next poll, so
// stop instead of hiding it in a log line every few seconds.
if (err instanceof RequestError && (err.status === 401 || err.status === 403)) throw err;
log(`claim failed: ${String(err)}`);
+ // Backing off here and not in onEmpty: a claim that waits on the server returns
+ // instantly when it fails, and retrying it at that rate would hammer both sides.
+ await sleep(ERROR_BACKOFF_MS);
+ continue;
}
- if (!run) {
- await sleep(config.pollIntervalMs);
+ if (!item) {
+ done = !(await onEmpty());
continue;
}
- const task = handle(config, client, run).finally(() => active.delete(task));
+ const task = run(item).finally(() => active.delete(task));
active.add(task);
}
await Promise.all(active);
}
+function parseArgv(argv: string[]): { configPath?: string; agent?: string; args: string[] } {
+ const parsed: { configPath?: string; agent?: string; args: string[] } = { args: [] };
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (arg === '--') {
+ parsed.args = argv.slice(i + 1);
+ break;
+ }
+ if (arg === '--agent') {
+ const value = argv[++i];
+ if (value === undefined) throw new Error('--agent needs a value');
+ parsed.agent = value;
+ continue;
+ }
+ if (arg.startsWith('--agent=')) {
+ parsed.agent = arg.slice('--agent='.length);
+ continue;
+ }
+ if (arg.startsWith('-')) throw new Error(`unknown option ${arg}`);
+ parsed.configPath ??= arg;
+ }
+ return parsed;
+}
+
+async function main(): Promise<void> {
+ const cli = parseArgv(process.argv.slice(2));
+ const configPath =
+ cli.configPath ?? process.env.ITSAPLAN_RUNNER_CONFIG ?? './itsaplan-runner.json';
+ const config = await loadConfig(configPath, { agent: cli.agent, args: cli.args });
+ const client = new Client(config);
+ const state = { stopping: false };
+
+ for (const signal of ['SIGINT', 'SIGTERM'] as const) {
+ process.on(signal, () => {
+ // The commands run in their own process groups, so quitting now leaves them running
+ // with nobody to report their result: the lease expires and the run is handed out
+ // again.
+ if (state.stopping) {
+ log('quitting now — the commands in flight keep running, their runs are retried');
+ process.exit(1);
+ }
+ state.stopping = true;
+ log('stopping — finishing the tasks in flight, press again to quit now');
+ });
+ }
+
+ log(
+ `running ${config.agent ?? 'the configured command'}, polling ${config.url} every ` +
+ `${config.pollIntervalMs}ms, up to ${config.concurrency} at once`,
+ );
+ let chatSupported = true;
+ await Promise.all([
+ drain<Run>(
+ state,
+ config.concurrency,
+ () => client.claim(),
+ (run) => handle(config, client, run),
+ async () => {
+ await sleep(config.pollIntervalMs);
+ return true;
+ },
+ ),
+ // The claim already waits on the server, so an empty one means the wait ran out and
+ // asking again is the whole delay there is. An instance too old to have the feed
+ // answers 404, and that loop ends rather than asking forever.
+ drain<ChatMessage>(
+ state,
+ config.concurrency,
+ async () => {
+ try {
+ return await client.claimChat();
+ } catch (err) {
+ if (err instanceof RequestError && err.status === 404) {
+ log('this instance has no chat feed — only queued runs will be answered');
+ chatSupported = false;
+ return null;
+ }
+ throw err;
+ }
+ },
+ (message) => handleChat(config, client, message),
+ () => Promise.resolve(chatSupported),
+ ),
+ ]);
+}
+
main().catch((err) => {
console.error(`[itsaplan-runner] ${err instanceof Error ? err.message : String(err)}`);
process.exit(1);
diff --git a/packages/runner/src/client.ts b/packages/runner/src/client.ts
index a66a5a89..0f9efaea 100644
--- a/packages/runner/src/client.ts
+++ b/packages/runner/src/client.ts
@@ -1,24 +1,39 @@
+import type { AgUiEvent } from './agui';
import type { RunnerConfig } from './config';
-// The three calls the runner makes. The agent's API key is the whole authorization:
-// it identifies the agent, and the server only ever hands back that agent's runs.
+// The agent's API key is the whole authorization: it identifies the agent, and the server
+// only ever hands back that agent's work.
export interface Run {
id: number;
trigger: 'mention' | 'delegation' | 'schedule' | 'manual';
prompt: string;
systemPrompt: string;
- attempts: number;
issueId: number | null;
issueIdentifier: string | null;
}
+// `prompt` carries the conversation so far framed into a task — unless `sessionId` is set,
+// where the coding agent session already holds it and only the new message is sent. Null
+// there means no session yet: start one and report the id it got.
+export interface ChatMessage {
+ id: number;
+ threadId: string;
+ prompt: string;
+ systemPrompt: string;
+ sessionId: string | null;
+}
+
// None of these calls does real work on the server, so a request that hangs is a dead
// connection. Without a deadline it would never settle and the runner would stop polling.
const REQUEST_TIMEOUT_MS = 30_000;
-// Carries the status, so the caller can tell a rejected key from a server that is
-// merely down.
+// Claiming a chat message is the one call that does wait: the server holds it until a
+// message turns up, so the answer starts the moment it is sent. The deadline has to
+// outlast that wait, or the runner would abort every idle claim.
+const CHAT_CLAIM_TIMEOUT_MS = 35_000;
+
+// The status is carried so the caller can tell a rejected key from a server that is down.
export class RequestError extends Error {
constructor(
readonly status: number,
@@ -31,7 +46,11 @@ export class RequestError extends Error {
export class Client {
constructor(private readonly config: RunnerConfig) {}
- private async post(path: string, body?: unknown): Promise<Response> {
+ private async post(
+ path: string,
+ body?: unknown,
+ timeoutMs = REQUEST_TIMEOUT_MS,
+ ): Promise<Response> {
const res = await fetch(`${this.config.url}${path}`, {
method: 'POST',
headers: {
@@ -39,7 +58,7 @@ export class Client {
...(body === undefined ? {} : { 'content-type': 'application/json' }),
},
body: body === undefined ? undefined : JSON.stringify(body),
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ signal: AbortSignal.timeout(timeoutMs),
});
if (!res.ok) {
throw new RequestError(
@@ -66,4 +85,29 @@ export class Client {
): Promise<void> {
await this.post(`/agent-runs/${runId}/result`, result);
}
+
+ async claimChat(): Promise<ChatMessage | null> {
+ const res = await this.post('/agent-chats/claim', undefined, CHAT_CLAIM_TIMEOUT_MS);
+ const body = (await res.json()) as { message: ChatMessage | null };
+ return body.message;
+ }
+
+ // `sessionId` binds the thread to that session for every later message in it.
+ async chatEvents(messageId: number, events: AgUiEvent[], sessionId?: string): Promise<void> {
+ await this.post(`/agent-chats/${messageId}/events`, {
+ events,
+ ...(sessionId && { sessionId }),
+ });
+ }
+
+ async chatHeartbeat(messageId: number): Promise<void> {
+ await this.post(`/agent-chats/${messageId}/heartbeat`);
+ }
+
+ async chatResult(
+ messageId: number,
+ result: { status: 'success' | 'failed'; error?: string },
+ ): Promise<void> {
+ await this.post(`/agent-chats/${messageId}/result`, result);
+ }
}
diff --git a/packages/runner/src/config.ts b/packages/runner/src/config.ts
index 4fcba02e..f52ab1e6 100644
--- a/packages/runner/src/config.ts
+++ b/packages/runner/src/config.ts
@@ -1,25 +1,43 @@
import { readFile } from 'node:fs/promises';
+import { PRESETS, PRESET_NAMES, isPresetName, type Preset, type PresetName } from './presets';
-// The runner's own settings, read from a JSON file and overridable by environment.
-// What to execute is entirely the operator's choice: the runner passes the task on
-// stdin and knows nothing about what the command does with it.
+// Two ways to say what to run. `agent` names a CLI the runner knows (see presets.ts) and
+// the runner builds the invocation, which is what lets it resume that CLI's sessions.
+// `command` is a shell command the operator writes themselves, and no session is kept for
+// it. `command` wins where both are set.
export interface RunnerConfig {
- // Where the instance lives and the external agent's API key.
url: string;
apiKey: string;
- // The shell command that handles one task. It receives the prompt on stdin.
- command: string;
- // Working directory for the command. Defaults to the process's own.
+ agent?: PresetName;
+ // Receives the prompt on stdin.
+ command?: string;
+ // Appended to what the preset builds. Ignored with `command`, which already spells out
+ // the whole invocation.
+ args: string[];
+ // Defaults to the process's own.
cwd?: string;
- // Extra environment for the command, on top of the runner's own.
+ // On top of the runner's own environment.
env: Record<string, string>;
- // How many tasks to run at once.
concurrency: number;
// How often to ask for work when the queue was empty.
pollIntervalMs: number;
// How long one task may take before it is killed and reported as failed.
timeoutMs: number;
+ // How the output is read when the command answers a chat message. 'text' takes whatever
+ // it prints; the others read one CLI's own event stream, which also carries the tool
+ // calls it makes and the session it started.
+ outputFormat: OutputFormat;
+}
+
+const OUTPUT_FORMATS = ['text', 'claude-stream-json', 'codex-jsonl', 'opencode-json'] as const;
+
+export type OutputFormat = (typeof OUTPUT_FORMATS)[number];
+
+// The preset a config resolves to, or undefined when it runs the operator's own command.
+export function presetOf(config: Pick<RunnerConfig, 'agent' | 'command'>): Preset | undefined {
+ if (config.command || !config.agent) return undefined;
+ return PRESETS[config.agent];
}
const DEFAULTS = {
@@ -28,9 +46,9 @@ const DEFAULTS = {
timeoutMs: 30 * 60 * 1000,
};
-// An empty poll is three writes on the server (the lease sweep, the presence stamp,
-// and the claim itself), so a runner asking faster than once a second costs the
-// instance more than it saves its operator: a task waits at most this long anyway.
+// An empty poll is three writes on the server (the lease sweep, the presence stamp, and
+// the claim itself), so asking faster than once a second costs the instance more than it
+// saves its operator.
const MIN_POLL_INTERVAL_MS = 1000;
function intFrom(value: unknown, fallback: number): number {
@@ -38,14 +56,41 @@ function intFrom(value: unknown, fallback: number): number {
return typeof parsed === 'number' && Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}
+// The preset's own format unless the operator names one.
+function outputFormatFrom(value: unknown, preset: Preset | undefined): OutputFormat {
+ const name = typeof value === 'string' ? value.trim() : '';
+ if (!name) return preset?.outputFormat ?? 'text';
+ const format = OUTPUT_FORMATS.find((candidate) => candidate === name);
+ if (!format) {
+ throw new Error(`outputFormat must be one of ${OUTPUT_FORMATS.join(', ')}`);
+ }
+ return format;
+}
+
+function agentFrom(value: unknown): PresetName | undefined {
+ const name = typeof value === 'string' ? value.trim() : '';
+ if (!name) return undefined;
+ if (!isPresetName(name)) {
+ throw new Error(`agent must be one of ${PRESET_NAMES.join(', ')}`);
+ }
+ return name;
+}
+
+function argsFrom(value: unknown): string[] {
+ if (value === undefined) return [];
+ if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {
+ throw new Error('args must be an array of strings');
+ }
+ return value as string[];
+}
+
function required(value: unknown, field: string): string {
const text = typeof value === 'string' ? value.trim() : '';
if (!text) throw new Error(`${field} is required — set it in the config file or the environment`);
return text;
}
-// The config file, or nothing when there is none — a runner configured entirely by
-// environment variables needs no file.
+// A runner configured entirely by environment variables needs no file.
async function readConfigFile(path: string): Promise<Record<string, unknown>> {
let text: string;
try {
@@ -61,15 +106,35 @@ async function readConfigFile(path: string): Promise<Record<string, unknown>> {
}
}
-// Reads the config file, then lets ITSAPLAN_* environment variables win over it, so
-// the key can stay out of the file.
-export async function loadConfig(path: string): Promise<RunnerConfig> {
+// What the command line contributed, which wins over both the file and the environment.
+export interface ConfigOverrides {
+ agent?: string;
+ // The arguments after `--`, appended to the ones the config file already gives.
+ args?: string[];
+}
+
+// ITSAPLAN_* environment variables win over the file, so the key can stay out of it, and
+// the command line wins over both.
+export async function loadConfig(
+ path: string,
+ overrides: ConfigOverrides = {},
+): Promise<RunnerConfig> {
const raw = await readConfigFile(path);
const env = process.env;
+ const agent = agentFrom(overrides.agent ?? env.ITSAPLAN_AGENT ?? raw.agent);
+ const command =
+ (env.ITSAPLAN_COMMAND ?? (raw.command as string | undefined))?.trim() || undefined;
+ if (!agent && !command) {
+ throw new Error(
+ `set either agent (one of ${PRESET_NAMES.join(', ')}) or command in the config file or the environment`,
+ );
+ }
return {
url: required(env.ITSAPLAN_URL ?? raw.url, 'url').replace(/\/+$/, ''),
apiKey: required(env.ITSAPLAN_API_KEY ?? raw.apiKey, 'apiKey'),
- command: required(env.ITSAPLAN_COMMAND ?? raw.command, 'command'),
+ agent,
+ command,
+ args: [...argsFrom(raw.args), ...(overrides.args ?? [])],
cwd: (env.ITSAPLAN_CWD ?? (raw.cwd as string | undefined))?.replace(/^~/, env.HOME ?? '~'),
env: (raw.env as Record<string, string> | undefined) ?? {},
concurrency: intFrom(env.ITSAPLAN_CONCURRENCY ?? raw.concurrency, DEFAULTS.concurrency),
@@ -78,5 +143,9 @@ export async function loadConfig(path: string): Promise<RunnerConfig> {
MIN_POLL_INTERVAL_MS,
),
timeoutMs: intFrom(env.ITSAPLAN_TIMEOUT_MS ?? raw.timeoutMs, DEFAULTS.timeoutMs),
+ outputFormat: outputFormatFrom(
+ env.ITSAPLAN_OUTPUT_FORMAT ?? raw.outputFormat,
+ presetOf({ agent, command }),
+ ),
};
}
diff --git a/packages/runner/src/execute.ts b/packages/runner/src/execute.ts
index afe99b05..006873d8 100644
--- a/packages/runner/src/execute.ts
+++ b/packages/runner/src/execute.ts
@@ -1,11 +1,22 @@
import { spawn } from 'node:child_process';
-import type { Run } from './client';
-import type { RunnerConfig } from './config';
+import { presetOf, type RunnerConfig } from './config';
+import { presetArgv, presetPrompt, type Preset } from './presets';
-// Runs one task: the configured command in a shell, with the task on stdin and the
-// run's context in the environment, including the server's system prompt for commands
-// that take one. Everything the agent needs beyond the task — the issue, its comments,
-// its fields — it reads itself through the API or MCP with the key handed to it here.
+// Runs one task: the command the preset builds, or the operator's own in a shell, with the
+// task on stdin and its context in the environment. Everything the agent needs beyond the
+// task — the issue, its comments, its fields — it reads itself through the API or MCP with
+// the key handed to it here.
+
+// A queued run and a chat message differ only in these.
+export interface Task {
+ prompt: string;
+ // A preset with no flag for it puts this in front of the prompt; the operator's own
+ // command reads it from the environment.
+ systemPrompt: string;
+ env: Record<string, string>;
+ // The coding agent session to resume, for a preset that keeps them.
+ sessionId?: string | null;
+}
export interface Outcome {
status: 'success' | 'failed';
@@ -13,28 +24,24 @@ export interface Outcome {
error?: string;
}
-// What is reported back: the tail of each stream, so a long transcript still shows its
-// ending — the part that says what the agent did — without sending megabytes back.
+// Only the tail of each stream is reported, so a long transcript still shows its ending —
+// the part that says what the agent did — without sending megabytes back.
const OUTPUT_LIMIT = 8000;
const ERROR_LIMIT = 400;
-// Applied as the output arrives, so a command that prints for half an hour does not
-// buffer all of it to have everything but the last few kilobytes thrown away.
+// Applied as the output arrives, so a command that prints for half an hour does not buffer
+// all of it to have everything but the last few kilobytes thrown away.
function tail(text: string, limit: number): string {
return text.length <= limit ? text : `…${text.slice(-limit)}`;
}
-function childEnv(config: RunnerConfig, run: Run): Record<string, string> {
+function childEnv(config: RunnerConfig, task: Task): Record<string, string> {
return {
...(process.env as Record<string, string>),
...config.env,
ITSAPLAN_URL: config.url,
ITSAPLAN_API_KEY: config.apiKey,
- ITSAPLAN_RUN_ID: String(run.id),
- ITSAPLAN_TRIGGER: run.trigger,
- ITSAPLAN_SYSTEM_PROMPT: run.systemPrompt,
- ITSAPLAN_ISSUE: run.issueIdentifier ?? '',
- ITSAPLAN_ISSUE_ID: run.issueId == null ? '' : String(run.issueId),
+ ...task.env,
};
}
@@ -49,10 +56,40 @@ function killGroup(pid: number): void {
}
}
-export async function execute(config: RunnerConfig, run: Run): Promise<Outcome> {
- const child = spawn('sh', ['-c', config.command], {
+// A preset is spawned directly, with no shell in between: the session id and the
+// operator's arguments reach the command as they are, with nothing to quote. The
+// operator's own command goes through a shell, which is what it was written for.
+function spawnArgs(
+ config: RunnerConfig,
+ preset: Preset | undefined,
+ task: Task,
+): [string, string[]] {
+ if (!preset) return ['sh', ['-c', config.command ?? '']];
+ return [
+ preset.bin,
+ presetArgv(preset, task.sessionId ?? null, task.systemPrompt, config.args, task.prompt),
+ ];
+}
+
+// A CLI that took the task as an argument would read it twice if it also arrived here.
+function stdinText(preset: Preset | undefined, task: Task): string {
+ if (!preset) return task.prompt;
+ if (preset.promptVia === 'arg') return '';
+ return presetPrompt(preset, task.systemPrompt, task.prompt);
+}
+
+// `onData` sees stdout as it arrives, for a caller that reports the output while the
+// command is still running.
+export async function execute(
+ config: RunnerConfig,
+ task: Task,
+ onData?: (chunk: string) => void,
+): Promise<Outcome> {
+ const preset = presetOf(config);
+ const [bin, args] = spawnArgs(config, preset, task);
+ const child = spawn(bin, args, {
cwd: config.cwd,
- env: childEnv(config, run),
+ env: childEnv(config, task),
detached: true,
});
@@ -68,14 +105,15 @@ export async function execute(config: RunnerConfig, run: Run): Promise<Outcome>
child.stderr.setEncoding('utf8');
child.stdout.on('data', (chunk: string) => {
stdout = tail(stdout + chunk, OUTPUT_LIMIT);
+ onData?.(chunk);
});
child.stderr.on('data', (chunk: string) => {
stderr = tail(stderr + chunk, ERROR_LIMIT);
});
- // A command that ignores stdin closes the pipe before the prompt is written, which
- // is an EPIPE the runner has no reason to fail on.
+ // A command that ignores stdin closes the pipe before the prompt is written, which is an
+ // EPIPE the runner has no reason to fail on.
child.stdin.on('error', () => {});
- child.stdin.end(run.prompt);
+ child.stdin.end(stdinText(preset, task));
const exited = new Promise<{ code: number | null; signal: string | null }>((resolve, reject) => {
child.on('error', reject);
diff --git a/packages/runner/src/presets.ts b/packages/runner/src/presets.ts
new file mode 100644
index 00000000..22d73e56
--- /dev/null
+++ b/packages/runner/src/presets.ts
@@ -0,0 +1,140 @@
+import type { OutputFormat } from './config';
+
+// A preset exists because several facts about a CLI have to agree: how its output is read,
+// where the session it started is named, how an existing one is resumed, how the task and
+// the system prompt reach it, and what it takes to run unattended. Wiring those into a
+// shell command by hand can produce a combination that runs but silently never reports a
+// session, or one that waits forever for an approval nobody is there to give.
+//
+// Anything else about the invocation — MCP servers, model, working directory — is the
+// operator's, passed through `args` and the `--` tail.
+
+export type PresetName = 'claude' | 'codex' | 'opencode' | 'gemini' | 'copilot';
+
+export interface Preset {
+ bin: string;
+ outputFormat: OutputFormat;
+ // False means the server keeps framing the conversation into every chat message.
+ sessions: boolean;
+ // A CLI that takes the prompt as an argument gets it after everything else, which is why
+ // `tail` exists.
+ promptVia: 'stdin' | 'arg';
+ // Only Claude Code has a flag for the run's context; the rest get it in front of the
+ // task.
+ systemPromptFlag?: string;
+ // The arguments before the operator's own, given null for a fresh session.
+ head: (sessionId: string | null) => string[];
+ // The arguments after the operator's own: a stdin marker, or the flag the prompt follows.
+ tail: string[];
+}
+
+export const PRESETS: Record<PresetName, Preset> = {
+ // stream-json carries the tool calls into the chat, and `session_id` rides on every line
+ // of it, including the first. --verbose is required for stream-json under --print, and
+ // --permission-mode auto has a classifier review each action, since nobody is there to
+ // answer a prompt.
+ claude: {
+ bin: 'claude',
+ outputFormat: 'claude-stream-json',
+ sessions: true,
+ promptVia: 'stdin',
+ systemPromptFlag: '--append-system-prompt',
+ head: (sessionId) => [
+ '-p',
+ ...(sessionId ? ['--resume', sessionId] : []),
+ '--output-format',
+ 'stream-json',
+ '--include-partial-messages',
+ '--verbose',
+ '--permission-mode',
+ 'auto',
+ ],
+ tail: [],
+ },
+
+ // Resuming is a subcommand, and it accepts a narrower set of options than plain `exec` —
+ // notably no --sandbox, --cd or --profile. An argument only `exec` takes would break
+ // every message after the first, so the sandbox is set through `-c sandbox_mode=…`,
+ // which both accept.
+ codex: {
+ bin: 'codex',
+ outputFormat: 'codex-jsonl',
+ sessions: true,
+ promptVia: 'stdin',
+ head: (sessionId) => [
+ ...(sessionId ? ['exec', 'resume', sessionId] : ['exec']),
+ '--json',
+ '-c',
+ 'sandbox_mode="workspace-write"',
+ ],
+ tail: ['-'],
+ },
+
+ opencode: {
+ bin: 'opencode',
+ outputFormat: 'opencode-json',
+ sessions: true,
+ promptVia: 'arg',
+ head: (sessionId) => [
+ 'run',
+ '--format',
+ 'json',
+ ...(sessionId ? ['--session', sessionId] : []),
+ ],
+ tail: [],
+ },
+
+ // Nothing here resumes Gemini or Copilot: neither documents a way to read the id of a
+ // session started non-interactively, nor states that its resume flag works alongside a
+ // one-shot prompt. Give either one a session-aware `head` and `sessions: true` once
+ // someone has checked it on a machine that has it.
+ gemini: {
+ bin: 'gemini',
+ outputFormat: 'text',
+ sessions: false,
+ promptVia: 'arg',
+ head: () => ['--approval-mode', 'yolo'],
+ tail: ['-p'],
+ },
+
+ copilot: {
+ bin: 'copilot',
+ outputFormat: 'text',
+ sessions: false,
+ promptVia: 'arg',
+ head: () => ['--allow-all-tools', '--no-ask-user'],
+ tail: ['-p'],
+ },
+};
+
+export const PRESET_NAMES = Object.keys(PRESETS) as PresetName[];
+
+export function isPresetName(value: string): value is PresetName {
+ return value in PRESETS;
+}
+
+// Without a flag for it, the run's context goes in front of the task. It is empty on a
+// resumed session, which already holds it.
+export function presetPrompt(preset: Preset, systemPrompt: string, prompt: string): string {
+ if (preset.systemPromptFlag || !systemPrompt) return prompt;
+ return `${systemPrompt}\n\n${prompt}`;
+}
+
+// The operator's own arguments sit between what the preset needs in front and what it
+// needs last, so a prompt passed as an argument stays at the end, a stdin marker is not
+// separated from its command, and a repeated flag overrides the preset's.
+export function presetArgv(
+ preset: Preset,
+ sessionId: string | null,
+ systemPrompt: string,
+ extraArgs: string[],
+ prompt: string,
+): string[] {
+ return [
+ ...preset.head(preset.sessions ? sessionId : null),
+ ...(preset.systemPromptFlag && systemPrompt ? [preset.systemPromptFlag, systemPrompt] : []),
+ ...extraArgs,
+ ...preset.tail,
+ ...(preset.promptVia === 'arg' ? [presetPrompt(preset, systemPrompt, prompt)] : []),
+ ];
+}
diff --git a/packages/runner/tsconfig.json b/packages/runner/tsconfig.json
index 374bac55..ed1878ca 100644
--- a/packages/runner/tsconfig.json
+++ b/packages/runner/tsconfig.json
@@ -1,7 +1,11 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
+ // Node types only: this is the one workspace member published to npm, and its
+ // source has to run on plain Node. The tests are checked with Bun's types by
+ // tsconfig.test.json instead.
"types": ["node"]
},
- "include": ["src"]
+ "include": ["src"],
+ "exclude": ["src/__tests__"]
}
diff --git a/packages/runner/tsconfig.test.json b/packages/runner/tsconfig.test.json
new file mode 100644
index 00000000..f8312298
--- /dev/null
+++ b/packages/runner/tsconfig.test.json
@@ -0,0 +1,7 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "types": ["node", "bun"]
+ },
+ "include": ["src"]
+}