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 | 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 25x 25x 25x 25x 25x 25x 27x 27x 27x 27x 27x 4x 23x 25x 25x 25x 25x 25x 25x 25x 25x 39x 39x 39x 39x 1x 1x 1x 1x 1x 1x 1x 1x 1x 39x 1x 1x 1x 1x 1x 38x 11x 11x 5x 5x 38x 6x 6x 6x 6x 3x 32x 32x 38x 38x 38x 1x 1x 1x 38x 38x 38x 38x 38x 38x 38x 32x 38x 7x 7x 7x 7x 38x 25x 25x 25x 70x 70x 2x 70x 2x 2x 25x 25x 38x 8x 30x | import { Inject, Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AIAction, SessionInput, Session } from '../core-entities';
import { LlmOutputParserService } from './parser/llm-output-parser.service';
import {
ActionExecutionResult,
PlanExecutionContext,
} from './llm-orchestration.interfaces';
import { ActionHandler } from './action-handlers/action-handler.interface';
import { PostExecutionHook } from './hooks/post-execution-hook.interface';
import { McpToolActionHandler } from './action-handlers/mcp-tool-action.handler';
import { AIActionStatus } from '../ai-actions/ai-actions.service';
import { ApplicationStateService } from '../application-state/application-state.service';
import { ExecutionLogsService } from '../execution-logs/execution-logs.service';
import { ToolHooksService } from '../tool-hooks/tool-hooks.service';
import { LlmToolCall } from '../llm-provider/llm-provider.interface';
import { McpService } from '../mcp/mcp.service';
@Injectable()
export class LlmTurnProcessorService {
private readonly logger = new Logger(LlmTurnProcessorService.name);
constructor(
private readonly parser: LlmOutputParserService,
@Inject('ACTION_HANDLER_REGISTRY')
private readonly handlerRegistry: Map<string, ActionHandler>,
@Inject('POST_EXECUTION_HOOKS')
private readonly postExecutionHooks: PostExecutionHook[],
@InjectRepository(AIAction)
private readonly aiActionsRepository: Repository<AIAction>,
@InjectRepository(SessionInput)
private readonly sessionInputsRepository: Repository<SessionInput>,
@InjectRepository(Session)
private readonly sessionsRepository: Repository<Session>,
private readonly applicationStateService: ApplicationStateService,
private readonly executionLogsService: ExecutionLogsService,
private readonly toolHooksService: ToolHooksService,
private readonly mcpService: McpService,
) {}
public async processTurn(sessionInput: SessionInput): Promise<SessionInput> {
this.logger.log(`Starting new orchestration for input ${sessionInput.id}`);
// Fetch session to get system_prompt_id
const session = await this.sessionsRepository.findOne({
where: { id: sessionInput.session_id },
select: ['id', 'system_prompt_id'],
});
// Parse tool_calls from session input (JSON string)
const toolCalls = sessionInput.tool_calls
? (JSON.parse(sessionInput.tool_calls) as LlmToolCall[])
: null;
// PARSE: Unified parser handles both XML and Native Tool Calls
const { explanation, actions: parsedActions } = await this.parser.parse(
sessionInput.raw_llm_response,
toolCalls,
);
const actionOrder = [
'create_file',
'quick_edit',
'patch',
'overwrite_file',
'delete_file',
'final',
'ask_user',
'new-session',
'run_command',
'request_context',
];
parsedActions.sort((a, b) => {
const indexA = actionOrder.indexOf(a.tool_name);
const indexB = actionOrder.indexOf(b.tool_name);
const effectiveIndexA = indexA === -1 ? Infinity : indexA;
const effectiveIndexB = indexB === -1 ? Infinity : indexB;
if (effectiveIndexA === effectiveIndexB) {
return 0; // Don't re-order if they are same type or both unknown
}
return effectiveIndexA - effectiveIndexB;
});
sessionInput.llm_response_explanation = explanation;
await this.sessionInputsRepository.save(sessionInput);
// 2. CREATE CONTEXT
const executionContext = new PlanExecutionContext();
executionContext.session_id = sessionInput.session_id;
executionContext.system_prompt_id = session?.system_prompt_id || null;
executionContext.originalParsedActions = parsedActions;
const createdActions: AIAction[] = [];
// 3. EXECUTE PLAN
for (const action of parsedActions) {
let handler = this.handlerRegistry.get(action.tool_name);
let result: ActionExecutionResult;
// --- BEFORE HOOKS ---
const beforeHooks = await this.toolHooksService.findByTrigger(
action.tool_name,
'before',
);
let hookHalted = false;
for (const hook of beforeHooks) {
try {
this.logger.log(
`Running BEFORE hook: ${hook.script_filename} for tool ${action.tool_name}`,
);
const hookResult = await this.toolHooksService.executeHook(
hook.script_filename,
{
hook_type: 'before',
action: { tool_name: action.tool_name, args: action.arguments },
plan_context: executionContext,
},
);
if (hookResult.should_halt_plan) {
this.logger.warn(`Hook ${hook.script_filename} halted execution.`);
executionContext.flags.should_halt = true;
executionContext.flags.halt_reason = `Hook ${hook.script_filename} returned halt signal.`;
hookHalted = true;
break;
}
} catch (e) {
this.logger.error(`Before-hook failed: ${e.message}`);
}
}
if (hookHalted) {
// If blocked by hook, record the action as failed/blocked
const aiActionEntity = this.aiActionsRepository.create({
input_id: sessionInput.id,
sessionInput: { id: sessionInput.id },
action_type: action.tool_name,
status: AIActionStatus.EXECUTION_FAILED,
order_of_execution: createdActions.length,
original_content_for_revert: null,
});
const savedAction = await this.aiActionsRepository.save(aiActionEntity);
createdActions.push(savedAction);
await this.executionLogsService.createLog({
action_id: savedAction.id,
error_message:
executionContext.flags.halt_reason || 'Blocked by tool hook.',
output: 'Action execution prevented by a "before" hook.',
});
break;
}
if (!handler) {
// Check if this is an MCP tool call (serverName__toolName pattern)
const mcpMatch = action.tool_name.match(/^([^_]+)__(.+)$/);
if (mcpMatch) {
const [, serverName, toolName] = mcpMatch;
handler = new McpToolActionHandler(
serverName,
toolName,
this.mcpService,
'',
);
}
}
if (!handler) {
this.logger.warn(
`No handler found for tool: ${action.tool_name}. Skipping.`,
);
executionContext.feedback.invalidToolErrors.push({
tool_name: action.tool_name,
arguments: action.arguments,
});
result = {
status: 'FAILURE',
summary: `Tool '${action.tool_name}' is not a valid tool.`,
error_message: `No handler registered for tool name '${action.tool_name}'.`,
persisted_args: action.arguments,
execution_log: {
output: '',
error_message: `No handler registered for tool name '${action.tool_name}'.`,
},
};
// Return error to LLM via tool results for native tool calling
if (action.toolCallId) {
executionContext.toolResults.push({
toolCallId: action.toolCallId,
toolName: action.tool_name,
result: `Error: Tool '${action.tool_name}' does not exist. Please use a valid tool.`,
});
}
} else {
try {
result = await handler.execute(action.arguments, executionContext);
} catch (error) {
this.logger.error(
`Handler for ${action.tool_name} failed during execution: ${error.message}`,
error.stack,
);
result = {
status: 'FAILURE',
summary: `An unexpected error occurred: ${error.message}`,
error_message: error.message,
persisted_args: action.arguments,
};
}
}
// --- AFTER HOOKS ---
// Run hooks regardless of tool success/failure, they might want to know about failures
if (result) {
const afterHooks = await this.toolHooksService.findByTrigger(
action.tool_name,
'after',
);
for (const hook of afterHooks) {
try {
this.logger.log(
`Running AFTER hook: ${hook.script_filename} for tool ${action.tool_name}`,
);
await this.toolHooksService.executeHook(hook.script_filename, {
hook_type: 'after',
action: {
tool_name: action.tool_name,
args: action.arguments,
result: {
status: result.status,
output: result.execution_log?.output,
error: result.error_message,
},
},
plan_context: executionContext,
});
} catch (e) {
this.logger.error(`After-hook failed: ${e.message}`);
}
}
}
const executionStrategy =
await this.applicationStateService.getExecutionStrategy();
this.logger.log(`Using execution strategy: ${executionStrategy}`);
const successStatus = this.getSuccessStatusForStrategy(executionStrategy);
const aiActionEntity = this.aiActionsRepository.create({
input_id: sessionInput.id,
sessionInput: { id: sessionInput.id },
action_type: action.tool_name,
status:
result.status === 'SUCCESS'
? successStatus
: AIActionStatus.EXECUTION_FAILED,
order_of_execution: createdActions.length,
original_content_for_revert: result.original_content_for_revert,
tool_call_id: action.toolCallId || null,
...result.persisted_args,
});
const savedAction = await this.aiActionsRepository.save(aiActionEntity);
createdActions.push(savedAction);
// If handler result includes an execution log, create it now.
if (result.execution_log) {
await this.executionLogsService.createLog({
action_id: savedAction.id,
output: result.execution_log.output,
error_message: result.execution_log.error_message,
});
}
// Collect tool results for follow-up hook (native tool calling mode)
// Skip if we already pushed in the !handler block above
if (action.toolCallId && handler) {
const output = result.execution_log?.output || '';
// Use execution_log.error_message if available, otherwise use result.error_message
const error =
result.execution_log?.error_message || result.error_message || '';
const combinedResult = error
? `${output}\n\nError: ${error}`.trim()
: output;
executionContext.toolResults.push({
toolCallId: action.toolCallId,
toolName: action.tool_name,
result: combinedResult,
});
}
// Note: Tool results are no longer appended to in-memory history.
// Chat history is now reconstructed purely from DB records.
Iif (executionContext.flags.should_halt) {
this.logger.log(
`Execution context flagged to halt. Reason: ${executionContext.flags.halt_reason}. Ending plan execution early.`,
);
break;
}
}
sessionInput.aiActions = createdActions;
// 4. POST-EXECUTION HOOKS
this.logger.log(
`Running ${this.postExecutionHooks.length} post-execution hooks.`,
);
for (const hook of this.postExecutionHooks) {
try {
await hook.run(sessionInput, executionContext);
} catch (error) {
this.logger.error(
`Post-execution hook ${hook.constructor.name} failed: ${error.message}`,
error.stack,
);
}
if (executionContext.flags.should_halt_hooks) {
this.logger.log(
`Hook chain halted by ${hook.constructor.name}. Skipping subsequent hooks.`,
);
break;
}
}
this.logger.log(`Orchestration finished for input ${sessionInput.id}.`);
return this.sessionInputsRepository.save(sessionInput);
}
private getSuccessStatusForStrategy(strategy: string): AIActionStatus {
switch (strategy) {
case 'auto_apply':
return AIActionStatus.CONFIRMED_KEPT;
case 'review_first':
case 'apply_revert':
// In new execute-first model, both these strategies result
// in an applied action that is pending user review/confirmation,
// making it revertible from the UI.
return AIActionStatus.APPLIED_PENDING_REVIEW;
default:
// Default to the safest, revertible option if the strategy is unknown.
this.logger.warn(
`Unknown execution strategy: '${strategy}'. Defaulting to APPLIED_PENDING_REVIEW.`,
);
return AIActionStatus.APPLIED_PENDING_REVIEW;
}
}
}
|