Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 | 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 22x 22x 22x 36x 13x 22x 22x 11x 11x 15x 15x 15x 22x 22x 36x 18x 18x 18x 18x 1x 18x 13x 13x 1x 18x 18x 12x 12x 12x 15x 14x 12x 16x 16x 14x 14x 14x 2x 2x 12x 1x 11x 1x 10x 12x 22x 22x 3x 3x 3x 3x 3x 3x | import { Injectable, Logger, Inject, forwardRef } from '@nestjs/common';
import {
LlmProvider,
LLM_PROVIDER,
LlmContent,
LlmGenerationConfig,
} from '../llm-provider/llm-provider.interface';
import { EventsGateway } from '../events/events.gateway';
import { LlmResponsesService } from '../llm-responses/llm-responses.service';
import { ApplicationStateService } from '../application-state/application-state.service';
import { MessageBusService } from '../message-bus/message-bus.service';
import { SessionsService } from '../sessions/sessions.service';
import { SystemPromptsService } from '../system-prompts/system-prompts.service';
import { ToolSchemaService } from '../llm-orchestration/tool-schema.service';
import { HistoryCompressionService } from '../llm-orchestration/history-compression.service';
import { SubAgentsService } from '../sub-agents/sub-agents.service';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { SessionInput } from '../core-entities/session-input.entity';
import { AIAction } from '../core-entities/ai-action.entity';
import { toShortId } from '../utils';
interface ActiveRequestState {
abortController: AbortController;
pendingInputId: string;
}
// Retry utility functions
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function isRetryableError(error: any, _retryAttempt: number): boolean {
const errorMessage = error.message?.toLowerCase() || '';
const errorCode = error.code;
const status = error.status;
// Never retry on abort
Iif (
error.name === 'AbortError' ||
error.code === 'ABORT_ERR' ||
error.message === 'This operation was aborted'
) {
return false;
}
// Retry on network errors
const networkErrors = [
'ECONNRESET',
'ETIMEDOUT',
'ENOTFOUND',
'ENETUNREACH',
'ECONNREFUSED',
];
Iif (errorCode && networkErrors.includes(errorCode)) {
return true;
}
// Retry on rate limiting
Iif (
status === 429 ||
errorMessage.includes('rate limit') ||
errorMessage.includes('too many requests')
) {
return true;
}
// Retry on server errors
Iif (status >= 500 && status < 600) {
return true;
}
// Retry on empty response errors
Iif (errorMessage.includes('empty response')) {
return true;
}
// Retry on timeout
Iif (errorMessage.includes('timeout')) {
return true;
}
return false;
}
@Injectable()
export class ChatService {
private readonly logger = new Logger(ChatService.name);
private activeRequests = new Map<string, ActiveRequestState>();
constructor(
@Inject(LLM_PROVIDER)
private readonly llmProvider: LlmProvider,
private readonly eventsGateway: EventsGateway,
@Inject(forwardRef(() => LlmResponsesService))
private readonly llmResponsesService: LlmResponsesService,
private readonly applicationStateService: ApplicationStateService,
private readonly messageBusService: MessageBusService,
@Inject(forwardRef(() => SessionsService))
private readonly sessionsService: SessionsService,
@Inject(forwardRef(() => SystemPromptsService))
private readonly systemPromptsService: SystemPromptsService,
private readonly toolSchemaService: ToolSchemaService,
private readonly historyCompressionService: HistoryCompressionService,
private readonly subAgentsService: SubAgentsService,
@Inject('ACTION_HANDLER_REGISTRY')
private readonly handlerRegistry: Map<string, any>,
@InjectRepository(SessionInput)
private readonly sessionInputsRepository: Repository<SessionInput>,
@InjectRepository(AIAction)
private readonly aiActionsRepository: Repository<AIAction>,
) {}
/**
* Helper to call LLM with exponential backoff retry.
*/
private async callWithRetry(
request: {
prompt: string;
systemInstruction: string;
history: LlmContent[];
modelId?: string;
generationConfig?: LlmGenerationConfig;
tools?: any[];
onToken?: (
token: string,
isFirst: boolean,
thoughtChunk?: string,
) => void;
abortController: AbortController;
},
sessionId: string,
pendingInputId: string,
): Promise<any> {
const retryEnabled =
await this.applicationStateService.getLlmRetryEnabled();
const maxAttempts =
await this.applicationStateService.getLlmRetryMaxAttempts();
let lastError: Error | undefined;
let attempt = 1;
while (attempt <= maxAttempts) {
try {
// Broadcast retry attempt if not first
Iif (attempt > 1) {
this.logger.log(
`Retry attempt ${attempt}/${maxAttempts} for session ${sessionId}`,
);
this.eventsGateway.sendToAll('llm-retry-attempt', {
sessionInputId: pendingInputId,
sessionId,
attempt,
maxAttempts,
});
}
return await this.llmProvider.generateContent(request);
} catch (error) {
lastError = error as Error;
// Check if we should retry
const shouldRetry =
retryEnabled &&
attempt < maxAttempts &&
isRetryableError(error, attempt);
Iif (!shouldRetry) {
throw error;
}
// Exponential backoff: 1s, 2s, 4s...
const backoffMs = Math.pow(2, attempt - 1) * 1000;
this.logger.log(
`LLM call failed (attempt ${attempt}/${maxAttempts}): ${error.message}. Retrying in ${backoffMs}ms...`,
);
await delay(backoffMs);
attempt++;
}
}
// Should not reach here, but throw last error if we do
throw lastError;
}
/**
* Reconstructs chat history from
* database for a given session.
* Orders by sequence_number to ensure correct conversation flow.
*/
private async getHistory(sessionId: string): Promise<LlmContent[]> {
const inputs = await this.sessionInputsRepository.find({
where: { session_id: sessionId, is_discarded: false },
order: { sequence_number: 'ASC' },
});
// Pre-identify model inputs that have tool_calls so we can batch-load their actions
const modelInputIdsWithToolCalls: string[] = [];
for (const input of inputs) {
if (input.role === 'model' && input.tool_calls) {
modelInputIdsWithToolCalls.push(input.id);
}
}
// Single batch query for ALL AIActions with executionLogs for all model turns
const actionsByInputId = new Map<string, AIAction[]>();
if (modelInputIdsWithToolCalls.length > 0) {
const allActions = await this.aiActionsRepository.find({
where: { input_id: In(modelInputIdsWithToolCalls) },
relations: ['executionLogs'],
});
for (const action of allActions) {
const existing = actionsByInputId.get(action.input_id) || [];
existing.push(action);
actionsByInputId.set(action.input_id, existing);
}
}
const history: LlmContent[] = [];
for (const input of inputs) {
if (input.role === 'user' && input.generated_context_string) {
history.push({
role: 'user',
parts: [{ text: input.generated_context_string }],
shortId: toShortId(input.id),
});
} else if (input.role === 'model') {
const content: LlmContent = {
role: 'model',
parts: [{ text: input.raw_llm_response || '' }],
shortId: toShortId(input.id),
};
// Attach thoughts if they exist in database
if (input.thoughts) {
content.thoughts = input.thoughts;
}
// Attach tool calls if they exist in database
if (input.tool_calls) {
try {
content.tool_calls = JSON.parse(input.tool_calls);
} catch (e) {
this.logger.error(
`Failed to parse tool_calls for input ${input.id}: ${e.message}`,
);
}
}
history.push(content);
// If this turn had tool calls, add tool results from pre-loaded batch
if (content.tool_calls && content.tool_calls.length > 0) {
const toolActions = actionsByInputId.get(input.id) || [];
// Build a map of tool_call_id -> action for O(1) lookup
const actionsByToolCallId = new Map<string, AIAction>();
for (const action of toolActions) {
if (action.tool_call_id) {
actionsByToolCallId.set(action.tool_call_id, action);
}
}
// Iterate over tool_calls in order and add matching tool results
// This ensures tool results are in the same order as tool_calls (critical for Ollama)
for (const toolCall of content.tool_calls) {
const action = actionsByToolCallId.get(toolCall.id);
if (!action) continue;
const output = action.executionLogs?.[0]?.output || '';
const errorMessage = action.executionLogs?.[0]?.error_message || '';
// Skip if no output and no error - nothing to report
if (!output && !errorMessage) {
this.logger.warn(
`Tool ${action.action_type} (tool_call_id: ${action.tool_call_id}) has no output or error. Skipping tool result.`,
);
continue;
}
// Determine what to send as tool result
let toolResult: string;
if (output && errorMessage) {
// Tool has both output and error
toolResult = `${output}\n\nError: ${errorMessage}`;
} else if (errorMessage) {
// Tool failed with error only
toolResult = `Error: ${errorMessage}`;
} else {
// Tool has output only
toolResult = output;
}
history.push({
role: 'tool',
tool_call_id: action.tool_call_id,
tool_name: action.action_type,
parts: [{ text: toolResult }],
});
}
}
}
}
this.logger.log(
`Reconstructed history for session ${sessionId} with ${history.length} turns.`,
);
// Compress history to redact older request_context results
return this.historyCompressionService.compress(history);
}
public async sendMessage(
sessionId: string,
message: string,
isManual: boolean,
existingInputId?: string,
): Promise<void> {
const history = await this.getHistory(sessionId);
if (isManual) {
this.messageBusService.submit({
event: 'llm-input-generated',
data: { prompt: message },
});
this.eventsGateway.sendToAll('llm-input-generated', { prompt: message });
this.eventsGateway.sendToAll('refresh-ui', { sessionId });
return;
}
try {
const session = await this.sessionsService.findOne(sessionId);
const isStreaming =
await this.applicationStateService.getStreamingEnabled();
// Check if this is a sub-agent session
const isSubAgentSession = !!session.sub_agent_id;
let subAgent = null;
let systemPromptToUse = session.systemPrompt;
let systemPromptId = '';
Iif (isSubAgentSession) {
subAgent = await this.subAgentsService.findOne(session.sub_agent_id);
Iif (subAgent && subAgent.systemPrompt) {
// Use sub-agent's system prompt
systemPromptToUse = subAgent.systemPrompt;
}
this.logger.log(
`Session ${sessionId} is a sub-agent session (agent: ${subAgent?.name})`,
);
}
// Lazy rendering: Fetch and render system prompt right before calling LLM
let finalSystemInstruction = '';
if (systemPromptToUse) {
systemPromptId = systemPromptToUse.id;
this.logger.log(
`Lazy rendering system prompt ${systemPromptId} for turn in session ${sessionId}`,
);
const rendered = await this.systemPromptsService.findOneWithSession(
systemPromptId,
session.id,
session.session_title,
);
finalSystemInstruction = rendered.prompt_content;
} else {
this.logger.log(
`No system prompt found for session ${sessionId}. Fetching default.`,
);
const defaultPrompt =
await this.systemPromptsService.findDefaultWithSession(
session.id,
session.session_title,
);
finalSystemInstruction = defaultPrompt?.prompt_content || '';
systemPromptId = defaultPrompt?.id || '';
}
const executionStrategy =
await this.applicationStateService.getExecutionStrategy();
// Generate tool definitions for native tool calling
// For sub-agents, only use the tools defined in their system prompt
// TODO: tool_capable should be queried from model registry
const isToolCapable = session.model_id?.includes('/');
let tools: any[] | undefined;
Iif (isToolCapable && systemPromptId) {
tools = await this.toolSchemaService.generateToolDefinitionsForPrompt(
this.handlerRegistry,
systemPromptId,
);
this.logger.log(
`Generated ${tools?.length || 0} tools for system prompt ${systemPromptId}`,
);
}
let pendingInput: SessionInput;
if (existingInputId) {
// Use existing input for regeneration
pendingInput = await this.sessionInputsRepository.findOneBy({
id: existingInputId,
});
Iif (!pendingInput) {
throw new Error(
`Existing SessionInput with ID "${existingInputId}" not found for regeneration.`,
);
}
// Clear AI response fields for regeneration
pendingInput.raw_llm_response = null;
pendingInput.thoughts = null;
pendingInput.tool_calls = null;
pendingInput.llm_response_explanation = null;
pendingInput.error_message = null;
pendingInput.input_token_count = null;
pendingInput.output_token_count = null;
pendingInput.cached_token_count = null;
pendingInput = await this.sessionInputsRepository.save(pendingInput);
} else {
pendingInput = await this.llmResponsesService.createPendingAiInput(
sessionId,
executionStrategy,
);
}
// BROADCAST: LLM Generation Started
this.eventsGateway.sendToAll('llm-generation-started', {
sessionInputId: pendingInput.id,
sessionId: session.id,
isStreaming: isStreaming,
});
const abortController = new AbortController();
this.activeRequests.set(sessionId, {
abortController,
pendingInputId: pendingInput.id,
});
const onToken = isStreaming
? (chunk: string, isFirst: boolean, thoughtChunk?: string) => {
Iif (isFirst) {
// BROADCAST: LLM Generation In Progress
this.eventsGateway.sendToAll('llm-generation-in-progress', {
sessionInputId: pendingInput.id,
});
}
Iif (chunk) {
this.eventsGateway.sendToAll('llm-stream-chunk', {
sessionInputId: pendingInput.id,
chunk,
isFirst,
});
}
Iif (thoughtChunk) {
this.eventsGateway.sendToAll('llm-thought-chunk', {
sessionInputId: pendingInput.id,
chunk: thoughtChunk,
isFirst,
});
}
}
: undefined;
const generationConfig: LlmGenerationConfig = {};
Iif (session.reasoning_effort) {
generationConfig.reasoning = { effort: session.reasoning_effort };
}
const llm_response = await this.callWithRetry(
{
prompt: message,
systemInstruction: finalSystemInstruction,
history: history,
modelId: session.model_id,
generationConfig,
tools,
onToken,
abortController,
},
sessionId,
pendingInput.id,
);
// Save response to database
await this.llmResponsesService.finalizePendingAiInput(pendingInput.id, {
raw_llm_response: llm_response.text,
execution_strategy: executionStrategy,
input_token_count: llm_response.usage?.inputTokens,
output_token_count: llm_response.usage?.outputTokens,
cached_token_count: llm_response.usage?.cachedTokens,
tool_calls: llm_response.tool_calls,
thoughts: llm_response.thoughts,
});
// BROADCAST: LLM Generation Ended (Success)
this.eventsGateway.sendToAll('llm-generation-ended', {
sessionInputId: pendingInput.id,
sessionId: session.id,
});
this.eventsGateway.sendToAll('refresh-ui', { sessionId });
// Cleanup state
this.activeRequests.delete(sessionId);
} catch (error) {
// Store pendingInputId before deleting from active requests
const pendingInputId =
this.activeRequests.get(sessionId)?.pendingInputId || 'unknown';
this.activeRequests.delete(sessionId);
// Check if this is an abort error (expected during cancellation)
const isAbortError =
error.name === 'AbortError' ||
error.code === 'ABORT_ERR' ||
error.message === 'This operation was aborted';
Iif (isAbortError) {
this.logger.log(
`Request aborted for session ${sessionId} (expected operation)`,
);
// BROADCAST: LLM Generation Ended (Aborted - no error)
this.eventsGateway.sendToAll('llm-generation-ended', {
sessionInputId: pendingInputId,
sessionId: sessionId,
});
// Don't throw - abort is expected behavior
return;
}
// Persist error to database
await this.llmResponsesService.updatePendingAiInputWithError(
pendingInputId,
error.message,
);
// BROADCAST: LLM Generation Ended (Error)
this.eventsGateway.sendToAll('llm-generation-ended', {
sessionInputId: pendingInputId,
sessionId: sessionId,
error: error.message,
});
this.logger.error(
`Error in sendMessage for session ${sessionId}: ${error.message}`,
error.stack,
);
// Refresh UI to display persisted error
this.eventsGateway.sendToAll('refresh-ui', { sessionId });
throw error;
}
}
public cancelRequest(sessionId: string): boolean {
const state = this.activeRequests.get(sessionId);
Iif (!state) {
this.logger.warn(`No active request to cancel for session ${sessionId}`);
return false;
}
try {
state.abortController.abort();
this.logger.log(`Request aborted for session ${sessionId}`);
this.activeRequests.delete(sessionId);
this.eventsGateway.sendToAll('refresh-ui', { sessionId });
return true;
} catch (error) {
this.logger.error(
`Failed to cancel request for session ${sessionId}: ${error.message}`,
);
return false;
}
}
// Deprecated alias for backward compatibility
public abortStreaming(sessionId: string): boolean {
return this.cancelRequest(sessionId);
}
}
|