(agentId: string)
| 258 | * Execute a single iteration of the agent's loop |
| 259 | */ |
| 260 | export async function executeAgentIteration(agentId: string): Promise<void> { |
| 261 | const loopData = activeLoops[agentId]; |
| 262 | if (!loopData?.isRunning) { |
| 263 | // This log is outside an iteration, so no ID is needed. |
| 264 | Logger.debug(agentId, `Skipping execution for stopped agent`); |
| 265 | return; |
| 266 | } |
| 267 | |
| 268 | // --- ITERATION START --- |
| 269 | const iterationId = `iter_${new Date().toISOString()}_${Math.random().toString(36).substring(2, 9)}`; |
| 270 | const iterationStartTime = Date.now(); |
| 271 | |
| 272 | try { |
| 273 | const agent = await getAgent(agentId); |
| 274 | const agentCode = await getAgentCode(agentId) || ''; |
| 275 | if (!agent) throw new Error(`Agent ${agentId} not found`); |
| 276 | |
| 277 | // Logger dispatches the window event automatically |
| 278 | Logger.info(agentId, `Iteration started`, { |
| 279 | logType: 'iteration-start', |
| 280 | iterationId, |
| 281 | content: { |
| 282 | model: agent.model_name, |
| 283 | interval: agent.loop_interval_seconds, |
| 284 | intervalMs: loopData.intervalMs, |
| 285 | iterationStartTime |
| 286 | } |
| 287 | }); |
| 288 | |
| 289 | const preprocessResult = await preProcess(agentId, agent.system_prompt, iterationId); |
| 290 | |
| 291 | // Determine output source: cached or from model |
| 292 | let output: ModelOutput; |
| 293 | let fromCache = false; |
| 294 | |
| 295 | // Check if we should use cached response (no significant change detected) |
| 296 | const shouldUseCache = agent.only_on_significant_change && |
| 297 | !(await detectSignificantChange(agentId, preprocessResult)); |
| 298 | |
| 299 | if (shouldUseCache) { |
| 300 | // Use cached output |
| 301 | const cachedOutput = activeLoops[agentId]?.lastOutput; |
| 302 | if (!cachedOutput) { |
| 303 | throw new Error("No cached response available - this shouldn't happen after first iteration"); |
| 304 | } |
| 305 | output = cachedOutput; |
| 306 | fromCache = true; |
| 307 | } else { |
| 308 | // Call the model |
| 309 | Logger.info(agentId, `Prompt`, { logType: 'model-prompt', iterationId, content: preprocessResult }); |
| 310 | |
| 311 | let token: string | undefined; |
| 312 | if (loopData.getToken) { |
| 313 | try { |
| 314 | Logger.debug(agentId, 'Requesting fresh API token...', { iterationId }); |
| 315 | token = await loopData.getToken(); |
| 316 | } catch (error) { |
| 317 | Logger.warn(agentId, `Could not retrieve auth token: ${error}. Continuing without it.`, { iterationId }); |
no test coverage detected