| 458 | * @returns Enhanced system prompt with agent context |
| 459 | */ |
| 460 | export function buildSystemPromptWithAgentContext( |
| 461 | baseSystemPrompt: string, |
| 462 | referenceData: AgentReferenceData[] |
| 463 | ): string { |
| 464 | let systemPrompt = baseSystemPrompt; |
| 465 | |
| 466 | if (referenceData.length > 0) { |
| 467 | systemPrompt += "\n\n=== REFERENCED AGENTS ===\n"; |
| 468 | systemPrompt += "The user has referenced the following agents for editing/improvement:\n\n"; |
| 469 | |
| 470 | referenceData.forEach(data => { |
| 471 | const { reference, agent, code, memory, recentRuns } = data; |
| 472 | |
| 473 | if (!agent) { |
| 474 | systemPrompt += `## @${reference.agentId} - AGENT NOT FOUND\n`; |
| 475 | systemPrompt += `The user referenced @${reference.agentId} but this agent doesn't exist.\n\n`; |
| 476 | return; |
| 477 | } |
| 478 | |
| 479 | systemPrompt += `## @${reference.agentId} - ${agent.name}\n`; |
| 480 | systemPrompt += `Description: ${agent.description}\n`; |
| 481 | systemPrompt += `Model: ${agent.model_name}\n`; |
| 482 | systemPrompt += `Loop Interval: ${agent.loop_interval_seconds}s\n\n`; |
| 483 | |
| 484 | // Add system prompt |
| 485 | systemPrompt += `### System Prompt:\n`; |
| 486 | systemPrompt += `${agent.system_prompt}\n\n`; |
| 487 | |
| 488 | // Add code if available |
| 489 | if (code) { |
| 490 | systemPrompt += `### Code:\n`; |
| 491 | systemPrompt += `\`\`\`python\n${code}\n\`\`\`\n\n`; |
| 492 | } |
| 493 | |
| 494 | // Add memory if not empty |
| 495 | if (memory.trim()) { |
| 496 | systemPrompt += `### Memory:\n`; |
| 497 | systemPrompt += `${memory.substring(0, 500)}${memory.length > 500 ? '...' : ''}\n\n`; |
| 498 | } |
| 499 | |
| 500 | // Add recent performance data |
| 501 | if (recentRuns.length > 0) { |
| 502 | systemPrompt += `### Recent Performance (last ${recentRuns.length} runs):\n`; |
| 503 | |
| 504 | const successCount = recentRuns.filter(run => !run.hasError).length; |
| 505 | systemPrompt += `Success Rate: ${successCount}/${recentRuns.length}\n`; |
| 506 | |
| 507 | if (recentRuns.some(run => run.duration)) { |
| 508 | const avgDuration = recentRuns |
| 509 | .filter(run => run.duration) |
| 510 | .reduce((sum, run) => sum + (run.duration || 0), 0) / recentRuns.length; |
| 511 | systemPrompt += `Average Duration: ${avgDuration.toFixed(1)}s\n`; |
| 512 | } |
| 513 | |
| 514 | // Add detailed run information |
| 515 | recentRuns.forEach((run, i) => { |
| 516 | systemPrompt += `\n#### Run ${i + 1} (${new Date(run.startTime).toLocaleString()}):\n`; |
| 517 | systemPrompt += `Status: ${run.hasError ? 'FAILED' : 'SUCCESS'}\n`; |