Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 37 additions & 6 deletions src/app/api/v2/ai/agent-config/repos/[...fullName]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ function parseFullNameParams(segments: string[]): { fullName: string; isEffectiv
* /api/v2/ai/agent-config/repos/{owner}/{repo}:
* get:
* summary: Get repository AI agent config override
* description: Returns the per-repository AI agent configuration override.
* description: >
* Returns the raw per-repository AI agent configuration override (not merged
* with the global config). This shows only the fields that are explicitly
* overridden for this repository. Returns 404 if no override exists.
* tags:
* - AI Agent Config
* operationId: getRepoAIAgentConfig
Expand All @@ -65,12 +68,14 @@ function parseFullNameParams(segments: string[]): { fullName: string; isEffectiv
* schema:
* type: string
* description: The repository owner
* example: goodrx
* - in: path
* name: repo
* required: true
* schema:
* type: string
* description: The repository name
* example: lifecycle
* responses:
* '200':
* description: Repository AI agent config override
Expand All @@ -94,7 +99,15 @@ function parseFullNameParams(segments: string[]): { fullName: string; isEffectiv
* /api/v2/ai/agent-config/repos/{owner}/{repo}/effective:
* get:
* summary: Get effective (merged) AI agent config for repository
* description: Returns the fully merged global + repository AI agent configuration.
* description: >
* Returns the fully merged configuration for a repository. The merge applies
* the repository override on top of the global config using these rules:
* scalar fields (enabled, maxMessagesPerSession, sessionTTL, systemPromptOverride)
* are replaced by the repo value when present; array fields (additiveRules,
* excludedTools, excludedFilePatterns) are merged additively (union of global
* and repo arrays). Provider settings and performance tuning parameters are
* always taken from the global config (not overridable per-repo).
* If no repo override exists, this returns the global config unchanged.
* tags:
* - AI Agent Config
* operationId: getEffectiveAIAgentConfig
Expand All @@ -105,12 +118,14 @@ function parseFullNameParams(segments: string[]): { fullName: string; isEffectiv
* schema:
* type: string
* description: The repository owner
* example: goodrx
* - in: path
* name: repo
* required: true
* schema:
* type: string
* description: The repository name
* example: lifecycle
* responses:
* '200':
* description: Effective merged AI agent configuration
Expand Down Expand Up @@ -159,7 +174,13 @@ const getHandler = async (req: NextRequest, { params }: { params: { fullName: st
* /api/v2/ai/agent-config/repos/{owner}/{repo}:
* put:
* summary: Create or update repository AI agent config override
* description: Validates and creates or updates the per-repository AI agent configuration override.
* description: >
* Upserts a per-repository AI agent configuration override. Only include
* the fields you want to override — omitted fields will continue to inherit
* from the global config. Validation enforces the same limits as the global
* config (prompt length, pattern count, core tool restrictions). The request
* body is validated against the AIAgentRepoOverride schema.
* Changes take effect immediately and invalidate cached effective configs.
* tags:
* - AI Agent Config
* operationId: putRepoAIAgentConfig
Expand All @@ -170,12 +191,14 @@ const getHandler = async (req: NextRequest, { params }: { params: { fullName: st
* schema:
* type: string
* description: The repository owner
* example: goodrx
* - in: path
* name: repo
* required: true
* schema:
* type: string
* description: The repository name
* example: lifecycle
* requestBody:
* required: true
* content:
Expand All @@ -190,7 +213,10 @@ const getHandler = async (req: NextRequest, { params }: { params: { fullName: st
* schema:
* $ref: '#/components/schemas/GetRepoAIAgentConfigSuccessResponse'
* '400':
* description: Validation error
* description: >
* Validation error. Possible reasons: JSON schema violation,
* systemPromptOverride exceeds maximum length, excluded tool is a core tool,
* invalid exclusion pattern, overly broad file pattern.
* content:
* application/json:
* schema:
Expand Down Expand Up @@ -261,7 +287,10 @@ const putHandler = async (req: NextRequest, { params }: { params: { fullName: st
* /api/v2/ai/agent-config/repos/{owner}/{repo}:
* delete:
* summary: Delete repository AI agent config override
* description: Soft-deletes the per-repository AI agent configuration override.
* description: >
* Soft-deletes the per-repository AI agent configuration override.
* After deletion, the repository reverts to using the global config only.
* The override can be recreated later with a PUT request.
* tags:
* - AI Agent Config
* operationId: deleteRepoAIAgentConfig
Expand All @@ -272,12 +301,14 @@ const putHandler = async (req: NextRequest, { params }: { params: { fullName: st
* schema:
* type: string
* description: The repository owner
* example: goodrx
* - in: path
* name: repo
* required: true
* schema:
* type: string
* description: The repository name
* example: lifecycle
* responses:
* '200':
* description: Repository config override deleted
Expand All @@ -286,7 +317,7 @@ const putHandler = async (req: NextRequest, { params }: { params: { fullName: st
* schema:
* $ref: '#/components/schemas/SuccessApiResponse'
* '400':
* description: Invalid request
* description: Invalid request (e.g. cannot delete the /effective endpoint)
* content:
* application/json:
* schema:
Expand Down
6 changes: 5 additions & 1 deletion src/app/api/v2/ai/agent-config/repos/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ import AIAgentConfigService from 'server/services/aiAgentConfig';
* /api/v2/ai/agent-config/repos:
* get:
* summary: List all repository AI agent config overrides
* description: Returns an array of all repository-level AI agent configuration overrides.
* description: >
* Returns an array of all repository-level AI agent configuration overrides.
* These are partial configs that override specific fields of the global config.
* To see the fully merged config for a specific repo, use the /effective endpoint instead.
* Soft-deleted overrides are excluded from the response.
* tags:
* - AI Agent Config
* operationId: listRepoAIAgentConfigs
Expand Down
18 changes: 15 additions & 3 deletions src/app/api/v2/ai/agent-config/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ import { aiAgentConfigSchema } from 'server/lib/validation/aiAgentConfigSchemas'
* /api/v2/ai/agent-config:
* get:
* summary: Get global AI agent configuration
* description: Returns the current global AI agent configuration from the database.
* description: >
* Returns the current global AI agent configuration. This is the base configuration
* that applies to all repositories unless overridden by a per-repository config.
* The response includes provider settings, model definitions, session limits,
* tool exclusions, and performance tuning parameters.
* tags:
* - AI Agent Config
* operationId: getGlobalAIAgentConfig
Expand Down Expand Up @@ -57,7 +61,12 @@ const getHandler = async (req: NextRequest) => {
* /api/v2/ai/agent-config:
* put:
* summary: Update global AI agent configuration
* description: Validates and updates the global AI agent configuration.
* description: >
* Validates and replaces the global AI agent configuration. The full AIAgentConfig
* object must be provided (this is a full replacement, not a patch). Validation
* enforces limits on systemPromptOverride length (max 50,000 chars), excludedFilePatterns
* count, and prevents exclusion of core tools. The updated configuration is returned.
* Changes take effect immediately and invalidate cached effective configs.
* tags:
* - AI Agent Config
* operationId: updateGlobalAIAgentConfig
Expand All @@ -75,7 +84,10 @@ const getHandler = async (req: NextRequest) => {
* schema:
* $ref: '#/components/schemas/GetGlobalAIAgentConfigSuccessResponse'
* '400':
* description: Validation error
* description: >
* Validation error. Possible reasons: JSON schema violation,
* systemPromptOverride exceeds maximum length, excluded tool is a core tool,
* invalid exclusion pattern.
* content:
* application/json:
* schema:
Expand Down
9 changes: 7 additions & 2 deletions src/app/api/v2/ai/chat/[buildUuid]/messages/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ import AIAgentConversationService from 'server/services/ai/conversation/storage'
* /api/v2/ai/chat/{buildUuid}/messages:
* get:
* summary: Get conversation messages
* description: Returns the conversation messages for a given build UUID.
* description: >
* Returns the full conversation history for a given build UUID, including
* user and assistant messages. Assistant messages may include tool call
* activity history, evidence items, and debug data collected during streaming.
* Returns an empty array if no conversation exists for the build.
* tags:
* - AI Chat
* operationId: getAIChatMessages
Expand All @@ -36,9 +40,10 @@ import AIAgentConversationService from 'server/services/ai/conversation/storage'
* schema:
* type: string
* description: The UUID of the build to retrieve messages for.
* example: white-poetry-596195
* responses:
* '200':
* description: Conversation messages
* description: Conversation messages with optional activity history and debug data.
* content:
* application/json:
* schema:
Expand Down
124 changes: 119 additions & 5 deletions src/app/api/v2/ai/chat/[buildUuid]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,62 @@ export const dynamic = 'force-dynamic';
* post:
* summary: Stream AI chat response
* description: >
* Sends a message to the AI agent and streams the response as Server-Sent Events.
* Sends a message to the AI agent and streams the response as Server-Sent Events (SSE).
* The buildUuid identifies the ephemeral environment context.
*
*
* **Streaming protocol:**
* The response uses the `text/event-stream` content type. Each event is a JSON object
* sent as `data: {JSON}\n\n`. Clients should use the EventSource API or a streaming
* fetch with an AbortController. The connection is kept alive via the `Connection: keep-alive`
* header. Clients can cancel by aborting the request.
*
*
* **SSE event types (by `type` field):**
*
* - `chunk` — Streamed text fragment of the AI response. Concatenate all chunks to build
* the full response. See SSEChunkEvent schema.
*
* - `tool_call` — The AI is invoking a tool. Contains a `toolCallId` that correlates
* with a later `processing` event. See SSEToolCallEvent schema.
*
* - `processing` — A tool call has completed. Messages starting with a checkmark (✓)
* indicate success. See SSEProcessingEvent schema.
*
* - `thinking` — The AI is reasoning before producing output. See SSEThinkingEvent schema.
*
* - `error` — A non-fatal processing error during investigation. See SSEActivityErrorEvent schema.
*
* - `evidence_file` — A source file found as evidence. See SSEEvidenceFileEvent schema.
*
* - `evidence_commit` — A git commit found as evidence. See SSEEvidenceCommitEvent schema.
*
* - `evidence_resource` — A Kubernetes resource found as evidence. See SSEEvidenceResourceEvent schema.
*
* - `debug_context` — System prompt and model selection info. See SSEDebugContextEvent schema.
*
* - `debug_tool_call` — Raw tool invocation data. See SSEDebugToolCallEvent schema.
*
* - `debug_tool_result` — Raw tool result data. See SSEDebugToolResultEvent schema.
*
* - `debug_metrics` — Aggregate token/cost metrics. See SSEDebugMetricsEvent schema.
*
* - `complete_json` — Structured JSON response (e.g. investigation_complete).
* Sent before the `complete` event. See SSECompleteJsonEvent schema.
*
* - `complete` — Final event signaling end of stream. See SSECompleteEvent schema.
*
*
* **Error handling:**
* Because the HTTP 200 status is committed before streaming begins, errors during
* processing are delivered as SSE events with `error: true` instead of HTTP error codes.
* See the SSEErrorEvent schema for the error payload format, which includes a `category`
* field for classification and a `suggestedAction` field for client retry logic.
*
*
* **Typical event sequence:**
* `chunk*` → `tool_call` → `processing` → `chunk*` → ... → `complete_json`? → `complete`
*
* tags:
* - AI Chat
* operationId: streamAIChat
Expand All @@ -66,25 +120,85 @@ export const dynamic = 'force-dynamic';
* message:
* type: string
* description: The user message to send to the AI agent.
* example: Why is the web service CrashLoopBackOff?
* clearHistory:
* type: boolean
* description: Whether to clear conversation history before processing.
* default: false
* provider:
* type: string
* description: The LLM provider to use (e.g. anthropic, openai).
* description: >
* The LLM provider to use. When omitted the default provider from the
* effective configuration is used.
* example: anthropic
* modelId:
* type: string
* description: The specific model ID to use.
* description: >
* The specific model ID to use. Must belong to the given provider.
* When omitted the default model is used.
* example: claude-sonnet-4-20250514
* isSystemAction:
* type: boolean
* description: Whether this message is a system-initiated action.
* description: >
* Whether this message is a system-initiated action (e.g. automatic
* investigation triggered by a deployment event).
* default: false
* mode:
* type: string
* enum: [investigate, fix]
* description: >
* Operation mode. "investigate" (default) is read-only analysis.
* "fix" enables the agent to take corrective actions via tools.
* default: investigate
* responses:
* '200':
* description: SSE event stream
* description: >
* SSE event stream. Each line is formatted as `data: {JSON}\n\n`.
* Events use a `type` discriminator field — see the SSE event schemas
* (SSEChunkEvent, SSEToolCallEvent, SSEProcessingEvent, SSEThinkingEvent,
* SSEActivityErrorEvent, SSEEvidenceFileEvent, SSEEvidenceCommitEvent,
* SSEEvidenceResourceEvent, SSEDebugContextEvent, SSEDebugToolCallEvent,
* SSEDebugToolResultEvent, SSEDebugMetricsEvent, SSECompleteJsonEvent,
* SSECompleteEvent). Errors arrive as SSEErrorEvent with `error: true`.
* headers:
* Content-Type:
* schema:
* type: string
* example: text/event-stream; charset=utf-8
* Cache-Control:
* schema:
* type: string
* example: no-cache, no-transform
* Connection:
* schema:
* type: string
* example: keep-alive
* X-Accel-Buffering:
* schema:
* type: string
* example: 'no'
* content:
* text/event-stream:
* schema:
* type: string
* description: >
* Newline-delimited SSE events. Each event is `data: <JSON>\n\n`.
* examples:
* chunk:
* summary: Text chunk event
* value: 'data: {"type":"chunk","content":"The web service is failing because..."}\n\n'
* tool_call:
* summary: Tool invocation event
* value: 'data: {"type":"tool_call","message":"Reading pod logs...","toolCallId":"tc_1"}\n\n'
* processing:
* summary: Tool completion event
* value: 'data: {"type":"processing","message":"✓ Pod logs retrieved","toolCallId":"tc_1","details":{"toolDurationMs":1200}}\n\n'
* complete:
* summary: Stream completion event
* value: 'data: {"type":"complete","totalInvestigationTimeMs":8500}\n\n'
* error:
* summary: Stream error event
* value: 'data: {"error":true,"userMessage":"Rate limit exceeded","category":"rate-limited","suggestedAction":"retry","retryAfter":30,"modelName":"claude-sonnet-4-20250514"}\n\n'
* '400':
* description: Missing required fields or invalid JSON
* content:
Expand Down
7 changes: 6 additions & 1 deletion src/app/api/v2/ai/chat/[buildUuid]/session/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ import AIAgentConversationService from 'server/services/ai/conversation/storage'
* /api/v2/ai/chat/{buildUuid}/session:
* delete:
* summary: Clear conversation session
* description: Clears all conversation messages for a given build UUID.
* description: >
* Deletes all conversation messages for a given build UUID and resets the session.
* Sessions are stored in Redis and expire automatically after the configured
* sessionTTL (default 3600 seconds). Use this endpoint to force-clear a session
* before its TTL, for example when starting a fresh investigation.
* tags:
* - AI Chat
* operationId: deleteAIChatSession
Expand All @@ -36,6 +40,7 @@ import AIAgentConversationService from 'server/services/ai/conversation/storage'
* schema:
* type: string
* description: The UUID of the build whose session to clear.
* example: white-poetry-596195
* responses:
* '200':
* description: Session cleared successfully
Expand Down
Loading