Skip to content

Commit 9e6ffd0

Browse files
authored
configurable agent (#102)
1 parent 6821b56 commit 9e6ffd0

21 files changed

Lines changed: 973 additions & 76 deletions

File tree

‎src/app/api/v2/ai/agent-config/repos/[...fullName]/route.ts‎

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,10 @@ function parseFullNameParams(segments: string[]): { fullName: string; isEffectiv
5454
* /api/v2/ai/agent-config/repos/{owner}/{repo}:
5555
* get:
5656
* summary: Get repository AI agent config override
57-
* description: Returns the per-repository AI agent configuration override.
57+
* description: >
58+
* Returns the raw per-repository AI agent configuration override (not merged
59+
* with the global config). This shows only the fields that are explicitly
60+
* overridden for this repository. Returns 404 if no override exists.
5861
* tags:
5962
* - AI Agent Config
6063
* operationId: getRepoAIAgentConfig
@@ -65,12 +68,14 @@ function parseFullNameParams(segments: string[]): { fullName: string; isEffectiv
6568
* schema:
6669
* type: string
6770
* description: The repository owner
71+
* example: goodrx
6872
* - in: path
6973
* name: repo
7074
* required: true
7175
* schema:
7276
* type: string
7377
* description: The repository name
78+
* example: lifecycle
7479
* responses:
7580
* '200':
7681
* description: Repository AI agent config override
@@ -94,7 +99,15 @@ function parseFullNameParams(segments: string[]): { fullName: string; isEffectiv
9499
* /api/v2/ai/agent-config/repos/{owner}/{repo}/effective:
95100
* get:
96101
* summary: Get effective (merged) AI agent config for repository
97-
* description: Returns the fully merged global + repository AI agent configuration.
102+
* description: >
103+
* Returns the fully merged configuration for a repository. The merge applies
104+
* the repository override on top of the global config using these rules:
105+
* scalar fields (enabled, maxMessagesPerSession, sessionTTL, systemPromptOverride)
106+
* are replaced by the repo value when present; array fields (additiveRules,
107+
* excludedTools, excludedFilePatterns) are merged additively (union of global
108+
* and repo arrays). Provider settings and performance tuning parameters are
109+
* always taken from the global config (not overridable per-repo).
110+
* If no repo override exists, this returns the global config unchanged.
98111
* tags:
99112
* - AI Agent Config
100113
* operationId: getEffectiveAIAgentConfig
@@ -105,12 +118,14 @@ function parseFullNameParams(segments: string[]): { fullName: string; isEffectiv
105118
* schema:
106119
* type: string
107120
* description: The repository owner
121+
* example: goodrx
108122
* - in: path
109123
* name: repo
110124
* required: true
111125
* schema:
112126
* type: string
113127
* description: The repository name
128+
* example: lifecycle
114129
* responses:
115130
* '200':
116131
* description: Effective merged AI agent configuration
@@ -159,7 +174,13 @@ const getHandler = async (req: NextRequest, { params }: { params: { fullName: st
159174
* /api/v2/ai/agent-config/repos/{owner}/{repo}:
160175
* put:
161176
* summary: Create or update repository AI agent config override
162-
* description: Validates and creates or updates the per-repository AI agent configuration override.
177+
* description: >
178+
* Upserts a per-repository AI agent configuration override. Only include
179+
* the fields you want to override — omitted fields will continue to inherit
180+
* from the global config. Validation enforces the same limits as the global
181+
* config (prompt length, pattern count, core tool restrictions). The request
182+
* body is validated against the AIAgentRepoOverride schema.
183+
* Changes take effect immediately and invalidate cached effective configs.
163184
* tags:
164185
* - AI Agent Config
165186
* operationId: putRepoAIAgentConfig
@@ -170,12 +191,14 @@ const getHandler = async (req: NextRequest, { params }: { params: { fullName: st
170191
* schema:
171192
* type: string
172193
* description: The repository owner
194+
* example: goodrx
173195
* - in: path
174196
* name: repo
175197
* required: true
176198
* schema:
177199
* type: string
178200
* description: The repository name
201+
* example: lifecycle
179202
* requestBody:
180203
* required: true
181204
* content:
@@ -190,7 +213,10 @@ const getHandler = async (req: NextRequest, { params }: { params: { fullName: st
190213
* schema:
191214
* $ref: '#/components/schemas/GetRepoAIAgentConfigSuccessResponse'
192215
* '400':
193-
* description: Validation error
216+
* description: >
217+
* Validation error. Possible reasons: JSON schema violation,
218+
* systemPromptOverride exceeds maximum length, excluded tool is a core tool,
219+
* invalid exclusion pattern, overly broad file pattern.
194220
* content:
195221
* application/json:
196222
* schema:
@@ -261,7 +287,10 @@ const putHandler = async (req: NextRequest, { params }: { params: { fullName: st
261287
* /api/v2/ai/agent-config/repos/{owner}/{repo}:
262288
* delete:
263289
* summary: Delete repository AI agent config override
264-
* description: Soft-deletes the per-repository AI agent configuration override.
290+
* description: >
291+
* Soft-deletes the per-repository AI agent configuration override.
292+
* After deletion, the repository reverts to using the global config only.
293+
* The override can be recreated later with a PUT request.
265294
* tags:
266295
* - AI Agent Config
267296
* operationId: deleteRepoAIAgentConfig
@@ -272,12 +301,14 @@ const putHandler = async (req: NextRequest, { params }: { params: { fullName: st
272301
* schema:
273302
* type: string
274303
* description: The repository owner
304+
* example: goodrx
275305
* - in: path
276306
* name: repo
277307
* required: true
278308
* schema:
279309
* type: string
280310
* description: The repository name
311+
* example: lifecycle
281312
* responses:
282313
* '200':
283314
* description: Repository config override deleted
@@ -286,7 +317,7 @@ const putHandler = async (req: NextRequest, { params }: { params: { fullName: st
286317
* schema:
287318
* $ref: '#/components/schemas/SuccessApiResponse'
288319
* '400':
289-
* description: Invalid request
320+
* description: Invalid request (e.g. cannot delete the /effective endpoint)
290321
* content:
291322
* application/json:
292323
* schema:

‎src/app/api/v2/ai/agent-config/repos/route.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,11 @@ import AIAgentConfigService from 'server/services/aiAgentConfig';
2525
* /api/v2/ai/agent-config/repos:
2626
* get:
2727
* summary: List all repository AI agent config overrides
28-
* description: Returns an array of all repository-level AI agent configuration overrides.
28+
* description: >
29+
* Returns an array of all repository-level AI agent configuration overrides.
30+
* These are partial configs that override specific fields of the global config.
31+
* To see the fully merged config for a specific repo, use the /effective endpoint instead.
32+
* Soft-deleted overrides are excluded from the response.
2933
* tags:
3034
* - AI Agent Config
3135
* operationId: listRepoAIAgentConfigs

‎src/app/api/v2/ai/agent-config/route.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,11 @@ import { aiAgentConfigSchema } from 'server/lib/validation/aiAgentConfigSchemas'
2727
* /api/v2/ai/agent-config:
2828
* get:
2929
* summary: Get global AI agent configuration
30-
* description: Returns the current global AI agent configuration from the database.
30+
* description: >
31+
* Returns the current global AI agent configuration. This is the base configuration
32+
* that applies to all repositories unless overridden by a per-repository config.
33+
* The response includes provider settings, model definitions, session limits,
34+
* tool exclusions, and performance tuning parameters.
3135
* tags:
3236
* - AI Agent Config
3337
* operationId: getGlobalAIAgentConfig
@@ -57,7 +61,12 @@ const getHandler = async (req: NextRequest) => {
5761
* /api/v2/ai/agent-config:
5862
* put:
5963
* summary: Update global AI agent configuration
60-
* description: Validates and updates the global AI agent configuration.
64+
* description: >
65+
* Validates and replaces the global AI agent configuration. The full AIAgentConfig
66+
* object must be provided (this is a full replacement, not a patch). Validation
67+
* enforces limits on systemPromptOverride length (max 50,000 chars), excludedFilePatterns
68+
* count, and prevents exclusion of core tools. The updated configuration is returned.
69+
* Changes take effect immediately and invalidate cached effective configs.
6170
* tags:
6271
* - AI Agent Config
6372
* operationId: updateGlobalAIAgentConfig
@@ -75,7 +84,10 @@ const getHandler = async (req: NextRequest) => {
7584
* schema:
7685
* $ref: '#/components/schemas/GetGlobalAIAgentConfigSuccessResponse'
7786
* '400':
78-
* description: Validation error
87+
* description: >
88+
* Validation error. Possible reasons: JSON schema violation,
89+
* systemPromptOverride exceeds maximum length, excluded tool is a core tool,
90+
* invalid exclusion pattern.
7991
* content:
8092
* application/json:
8193
* schema:

‎src/app/api/v2/ai/chat/[buildUuid]/messages/route.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,11 @@ import AIAgentConversationService from 'server/services/ai/conversation/storage'
2525
* /api/v2/ai/chat/{buildUuid}/messages:
2626
* get:
2727
* summary: Get conversation messages
28-
* description: Returns the conversation messages for a given build UUID.
28+
* description: >
29+
* Returns the full conversation history for a given build UUID, including
30+
* user and assistant messages. Assistant messages may include tool call
31+
* activity history, evidence items, and debug data collected during streaming.
32+
* Returns an empty array if no conversation exists for the build.
2933
* tags:
3034
* - AI Chat
3135
* operationId: getAIChatMessages
@@ -36,9 +40,10 @@ import AIAgentConversationService from 'server/services/ai/conversation/storage'
3640
* schema:
3741
* type: string
3842
* description: The UUID of the build to retrieve messages for.
43+
* example: white-poetry-596195
3944
* responses:
4045
* '200':
41-
* description: Conversation messages
46+
* description: Conversation messages with optional activity history and debug data.
4247
* content:
4348
* application/json:
4449
* schema:

‎src/app/api/v2/ai/chat/[buildUuid]/route.ts‎

Lines changed: 119 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,62 @@ export const dynamic = 'force-dynamic';
4242
* post:
4343
* summary: Stream AI chat response
4444
* description: >
45-
* Sends a message to the AI agent and streams the response as Server-Sent Events.
45+
* Sends a message to the AI agent and streams the response as Server-Sent Events (SSE).
4646
* The buildUuid identifies the ephemeral environment context.
47+
*
48+
*
49+
* **Streaming protocol:**
50+
* The response uses the `text/event-stream` content type. Each event is a JSON object
51+
* sent as `data: {JSON}\n\n`. Clients should use the EventSource API or a streaming
52+
* fetch with an AbortController. The connection is kept alive via the `Connection: keep-alive`
53+
* header. Clients can cancel by aborting the request.
54+
*
55+
*
56+
* **SSE event types (by `type` field):**
57+
*
58+
* - `chunk` — Streamed text fragment of the AI response. Concatenate all chunks to build
59+
* the full response. See SSEChunkEvent schema.
60+
*
61+
* - `tool_call` — The AI is invoking a tool. Contains a `toolCallId` that correlates
62+
* with a later `processing` event. See SSEToolCallEvent schema.
63+
*
64+
* - `processing` — A tool call has completed. Messages starting with a checkmark (✓)
65+
* indicate success. See SSEProcessingEvent schema.
66+
*
67+
* - `thinking` — The AI is reasoning before producing output. See SSEThinkingEvent schema.
68+
*
69+
* - `error` — A non-fatal processing error during investigation. See SSEActivityErrorEvent schema.
70+
*
71+
* - `evidence_file` — A source file found as evidence. See SSEEvidenceFileEvent schema.
72+
*
73+
* - `evidence_commit` — A git commit found as evidence. See SSEEvidenceCommitEvent schema.
74+
*
75+
* - `evidence_resource` — A Kubernetes resource found as evidence. See SSEEvidenceResourceEvent schema.
76+
*
77+
* - `debug_context` — System prompt and model selection info. See SSEDebugContextEvent schema.
78+
*
79+
* - `debug_tool_call` — Raw tool invocation data. See SSEDebugToolCallEvent schema.
80+
*
81+
* - `debug_tool_result` — Raw tool result data. See SSEDebugToolResultEvent schema.
82+
*
83+
* - `debug_metrics` — Aggregate token/cost metrics. See SSEDebugMetricsEvent schema.
84+
*
85+
* - `complete_json` — Structured JSON response (e.g. investigation_complete).
86+
* Sent before the `complete` event. See SSECompleteJsonEvent schema.
87+
*
88+
* - `complete` — Final event signaling end of stream. See SSECompleteEvent schema.
89+
*
90+
*
91+
* **Error handling:**
92+
* Because the HTTP 200 status is committed before streaming begins, errors during
93+
* processing are delivered as SSE events with `error: true` instead of HTTP error codes.
94+
* See the SSEErrorEvent schema for the error payload format, which includes a `category`
95+
* field for classification and a `suggestedAction` field for client retry logic.
96+
*
97+
*
98+
* **Typical event sequence:**
99+
* `chunk*` → `tool_call` → `processing` → `chunk*` → ... → `complete_json`? → `complete`
100+
*
47101
* tags:
48102
* - AI Chat
49103
* operationId: streamAIChat
@@ -66,25 +120,85 @@ export const dynamic = 'force-dynamic';
66120
* message:
67121
* type: string
68122
* description: The user message to send to the AI agent.
123+
* example: Why is the web service CrashLoopBackOff?
69124
* clearHistory:
70125
* type: boolean
71126
* description: Whether to clear conversation history before processing.
127+
* default: false
72128
* provider:
73129
* type: string
74-
* description: The LLM provider to use (e.g. anthropic, openai).
130+
* description: >
131+
* The LLM provider to use. When omitted the default provider from the
132+
* effective configuration is used.
133+
* example: anthropic
75134
* modelId:
76135
* type: string
77-
* description: The specific model ID to use.
136+
* description: >
137+
* The specific model ID to use. Must belong to the given provider.
138+
* When omitted the default model is used.
139+
* example: claude-sonnet-4-20250514
78140
* isSystemAction:
79141
* type: boolean
80-
* description: Whether this message is a system-initiated action.
142+
* description: >
143+
* Whether this message is a system-initiated action (e.g. automatic
144+
* investigation triggered by a deployment event).
145+
* default: false
146+
* mode:
147+
* type: string
148+
* enum: [investigate, fix]
149+
* description: >
150+
* Operation mode. "investigate" (default) is read-only analysis.
151+
* "fix" enables the agent to take corrective actions via tools.
152+
* default: investigate
81153
* responses:
82154
* '200':
83-
* description: SSE event stream
155+
* description: >
156+
* SSE event stream. Each line is formatted as `data: {JSON}\n\n`.
157+
* Events use a `type` discriminator field — see the SSE event schemas
158+
* (SSEChunkEvent, SSEToolCallEvent, SSEProcessingEvent, SSEThinkingEvent,
159+
* SSEActivityErrorEvent, SSEEvidenceFileEvent, SSEEvidenceCommitEvent,
160+
* SSEEvidenceResourceEvent, SSEDebugContextEvent, SSEDebugToolCallEvent,
161+
* SSEDebugToolResultEvent, SSEDebugMetricsEvent, SSECompleteJsonEvent,
162+
* SSECompleteEvent). Errors arrive as SSEErrorEvent with `error: true`.
163+
* headers:
164+
* Content-Type:
165+
* schema:
166+
* type: string
167+
* example: text/event-stream; charset=utf-8
168+
* Cache-Control:
169+
* schema:
170+
* type: string
171+
* example: no-cache, no-transform
172+
* Connection:
173+
* schema:
174+
* type: string
175+
* example: keep-alive
176+
* X-Accel-Buffering:
177+
* schema:
178+
* type: string
179+
* example: 'no'
84180
* content:
85181
* text/event-stream:
86182
* schema:
87183
* type: string
184+
* description: >
185+
* Newline-delimited SSE events. Each event is `data: <JSON>\n\n`.
186+
* examples:
187+
* chunk:
188+
* summary: Text chunk event
189+
* value: 'data: {"type":"chunk","content":"The web service is failing because..."}\n\n'
190+
* tool_call:
191+
* summary: Tool invocation event
192+
* value: 'data: {"type":"tool_call","message":"Reading pod logs...","toolCallId":"tc_1"}\n\n'
193+
* processing:
194+
* summary: Tool completion event
195+
* value: 'data: {"type":"processing","message":"✓ Pod logs retrieved","toolCallId":"tc_1","details":{"toolDurationMs":1200}}\n\n'
196+
* complete:
197+
* summary: Stream completion event
198+
* value: 'data: {"type":"complete","totalInvestigationTimeMs":8500}\n\n'
199+
* error:
200+
* summary: Stream error event
201+
* value: 'data: {"error":true,"userMessage":"Rate limit exceeded","category":"rate-limited","suggestedAction":"retry","retryAfter":30,"modelName":"claude-sonnet-4-20250514"}\n\n'
88202
* '400':
89203
* description: Missing required fields or invalid JSON
90204
* content:

‎src/app/api/v2/ai/chat/[buildUuid]/session/route.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,11 @@ import AIAgentConversationService from 'server/services/ai/conversation/storage'
2525
* /api/v2/ai/chat/{buildUuid}/session:
2626
* delete:
2727
* summary: Clear conversation session
28-
* description: Clears all conversation messages for a given build UUID.
28+
* description: >
29+
* Deletes all conversation messages for a given build UUID and resets the session.
30+
* Sessions are stored in Redis and expire automatically after the configured
31+
* sessionTTL (default 3600 seconds). Use this endpoint to force-clear a session
32+
* before its TTL, for example when starting a fresh investigation.
2933
* tags:
3034
* - AI Chat
3135
* operationId: deleteAIChatSession
@@ -36,6 +40,7 @@ import AIAgentConversationService from 'server/services/ai/conversation/storage'
3640
* schema:
3741
* type: string
3842
* description: The UUID of the build whose session to clear.
43+
* example: white-poetry-596195
3944
* responses:
4045
* '200':
4146
* description: Session cleared successfully

0 commit comments

Comments
 (0)