(projectCwd: string, targetPort: number, isFresh?: () => boolean)
| 115 | * @param isFresh - Getter for whether the project is in creation mode |
| 116 | */ |
| 117 | export function createAgentRoute(projectCwd: string, targetPort: number, isFresh?: () => boolean) { |
| 118 | const agent = new Hono(); |
| 119 | |
| 120 | // ─── Model Catalog ─────────────────────────────────────── |
| 121 | |
| 122 | agent.get('/api/models', (c) => { |
| 123 | return c.json({ providers: getProviderCatalog() }); |
| 124 | }); |
| 125 | |
| 126 | // ─── Chat (trigger LLM) ───────────────────────────────── |
| 127 | |
| 128 | agent.post('/api/chat', async (c) => { |
| 129 | let body: unknown; |
| 130 | try { |
| 131 | body = await c.req.json(); |
| 132 | } catch { |
| 133 | return c.json({ success: false, error: 'Invalid request body' }, 400); |
| 134 | } |
| 135 | |
| 136 | const parsed = ChatRequestSchema.safeParse(body); |
| 137 | if (!parsed.success) { |
| 138 | const message = parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; '); |
| 139 | return c.json({ success: false, error: message }, 400); |
| 140 | } |
| 141 | |
| 142 | const { prompt, model, modelProvider, consoleEntries, images, pageContext, language } = parsed.data; |
| 143 | const modelId = model ?? DEFAULT_MODEL; |
| 144 | |
| 145 | // Prepend context blocks to the prompt |
| 146 | let augmentedPrompt = prompt; |
| 147 | if (pageContext) { |
| 148 | augmentedPrompt = formatPageContext(pageContext) + augmentedPrompt; |
| 149 | } |
| 150 | if (consoleEntries && consoleEntries.length > 0) { |
| 151 | const context = formatConsoleContext(consoleEntries); |
| 152 | if (context) { |
| 153 | augmentedPrompt = context + augmentedPrompt; |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | // Build user content — multipart if images are present |
| 158 | const hasImages = images && images.length > 0; |
| 159 | const userContent = hasImages |
| 160 | ? [ |
| 161 | { type: 'text' as const, text: augmentedPrompt }, |
| 162 | ...images.map(dataUrl => ({ type: 'image' as const, image: dataUrl })), |
| 163 | ] |
| 164 | : augmentedPrompt; |
| 165 | |
| 166 | // Cancel any in-flight stream before starting a new one |
| 167 | activeStreamAbort?.abort(); |
| 168 | const abortController = new AbortController(); |
| 169 | activeStreamAbort = abortController; |
| 170 | const { signal } = abortController; |
| 171 | |
| 172 | // Adapter stream that emits events through the bus |
| 173 | const adapter = { |
| 174 | writeSSE: async (msg: { event?: string; data: string; id?: string }) => { |
no test coverage detected