{
  "name": "06 - Arena Agent Bridge (۹ ایجنت از طریق پل)",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "seconds",
              "secondsInterval": 15
            }
          ]
        }
      },
      "id": "schedule-trigger",
      "name": "Schedule Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -620,
        0
      ]
    },
    {
      "parameters": {
        "source": "database",
        "workflowId": {
          "__rl": true,
          "value": "02 - Telegram Polling",
          "mode": "list"
        },
        "mode": "lastOnly",
        "options": {
          "waitForSubWorkflow": false
        }
      },
      "id": "latest-message",
      "name": "Latest Message",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.2,
      "position": [
        -420,
        0
      ],
      "notes": "اگر ورک‌فلوی ۰۲ را نساخته‌اید، این گره را غیرفعال کنید",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// ── کارت پیام تست ──────────────────────────────────────────────────────────\nlet item = null;\ntry {\n  const rows = $('Latest Message').all().map((i) => i.json).filter(Boolean);\n  if (rows.length) item = rows[rows.length - 1];\n} catch (e) { /* ورک‌فلوی ۰۲ هنوز اجرا نشده */ }\n\nconst chat_id = item?.chat_id || 0;\nconst agent = 'AG03';\nconst question = item?.text || 'این یک پیام تست است. دستگاه را بررسی کن.';\n\nconst system_prompt = [\n  'تو AG03 هستی — کارگردان محتوا و موشن.',\n  'بدون شاهد ادعا نکن. هر ادعا را با [شاهد: ...] یا «⚠️ نیازمند تأیید» علامت بزن.',\n  'حداکثر ۶۰۰ کاراکتر. فارسی و کوتاه.',\n].join('\\n');\n\nreturn [{ json: {\n  chat_id, agent, question, system_prompt,\n  session_id: `n8n-${agent}`,        // هر ایجنت یک سشن پایدار در Arena\n  from_real_message: Boolean(item),\n  warning: chat_id ? '' : '⚠️ chat_id صفر است — پیام به تلگرام فرستاده نمی‌شود (فقط تست پاسخ)',\n} }];\n"
      },
      "id": "build-test-card",
      "name": "Build Test Card",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -220,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// ── Context سه‌بخشی ─────────────────────────────────────────────────────────\nconst item = $input.first().json;\n\nconst notionBlock = 'هیچ رکورد فعالی خوانده نشد → «داده‌ای در دست نیست»، نه صفر و نه تأیید.';\nconst historyBlock = 'تاریخچه‌ای در دست نیست.';\n\nconst user_prompt = `# Context عملیاتی — ${item.agent}\n\n## بخش ب — داده‌های Notion (حداکثر ۱۰ رکورد)\n${notionBlock}\n\n## بخش ج — تاریخچهٔ ۳۰ پیام آخر گروه (قدیمی → جدید)\n${historyBlock}\n\n## بخش الف — درخواست اکنون\n${item.question}\n\nپاسخ را فارسی، کوتاه و با برچسب شاهد بده.`;\n\nreturn [{ json: { ...item, user_prompt } }];\n"
      },
      "id": "build-context",
      "name": "Build Context",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -20,
        0
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $env.ARENA_BRIDGE_URL || 'http://127.0.0.1:20140/v1/chat/completions' }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Authorization",
              "value": "=Bearer {{ $env.ARENA_AGENT_BRIDGE_KEY }}"
            },
            {
              "name": "x-codex-session-id",
              "value": "={{ $json.session_id }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": {
          "model": "={{ $json.model || 'active' }}",
          "stream": false,
          "messages": [
            {
              "role": "system",
              "content": "={{ $json.system_prompt }}"
            },
            {
              "role": "user",
              "content": "={{ $json.user_prompt }}"
            }
          ]
        },
        "options": {
          "timeout": 180000,
          "response": {
            "response": {
              "responseFormat": "json"
            }
          }
        }
      },
      "id": "arena-chat",
      "name": "Arena Chat",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        340,
        0
      ],
      "notes": "پل محلی → Arena (سشن پایدار به‌ازای هر ایجنت)",
      "notesInFlow": true
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.openai.com/v1/chat/completions",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $env.OPENAI_API_KEY }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": {
          "model": "gpt-4o-mini",
          "temperature": 0.4,
          "max_tokens": 1200,
          "messages": [
            {
              "role": "system",
              "content": "={{ $json.system_prompt }}"
            },
            {
              "role": "user",
              "content": "={{ $json.user_prompt }}"
            }
          ]
        },
        "options": {
          "timeout": 120000
        }
      },
      "id": "openai-chat-(fallback)",
      "name": "OpenAI Chat (fallback)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        340,
        200
      ],
      "notes": "فقط اگر پل و کلید Arena آماده نبود — این گره را غیرفعال نگه دارید",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// ── یکسان‌سازی خروجی ───────────────────────────────────────────────────────\nconst item = $input.first().json;\nconst raw = item.choices?.[0]?.message?.content ?? item.content ?? '';\nlet answer = String(raw).trim();\n\nif (!answer) {\n  answer = '⚠️ پاسخ خالی برگشت.\\n1) پل اجراست؟ (http://127.0.0.1:20140)\\n2) در GUI پل لاگین شده‌اید؟ (GET /ready باید 200 بدهد)\\n3) ARENA_AGENT_BRIDGE_KEY درست است؟';\n}\nif (!/شاهد|نیازمند تأیید/.test(answer)) {\n  answer += '\\n\\n⚠️ این پاسخ هیچ شاهد صریحی ندارد — نیازمند تأیید مدیر.';\n}\n\nconst MAX = 3500, chunks = [];\nlet rest = answer;\nwhile (rest.length > MAX) {\n  let cut = rest.lastIndexOf('\\n', MAX);\n  if (cut < MAX * 0.5) cut = MAX;\n  chunks.push(rest.slice(0, cut));\n  rest = rest.slice(cut).trim();\n}\nif (rest) chunks.push(rest);\nreturn chunks.map((c, i) => ({ json: { ...item, answer: c, part: i + 1, parts: chunks.length } }));\n"
      },
      "id": "pick-answer",
      "name": "Pick Answer",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        540,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "const item = $input.first().json;\nconst esc = (s) => String(s)\n  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n  .replace(/\\*\\*(.+?)\\*\\*/g, '<b>$1</b>')\n  .replace(/`([^`]+)`/g, '<code>$1</code>');\nconst head = item.part === 1 ? `<b>${item.agent} — Arena</b>\\n\\n`\n                             : `<b>${item.agent}</b> (ادامه ${item.part}/${item.parts})\\n\\n`;\nreturn [{ json: { ...item, telegram_text: head + esc(item.answer) } }];\n"
      },
      "id": "format-telegram",
      "name": "Format Telegram",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        740,
        0
      ]
    },
    {
      "parameters": {
        "chatId": "={{ $json.chat_id }}",
        "text": "={{ $json.telegram_text }}",
        "additionalFields": {
          "parse_mode": "HTML",
          "appendAttribution": false
        }
      },
      "id": "send-answer",
      "name": "Send Answer",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        940,
        0
      ],
      "notes": "اگر chat_id صفر باشد تلگرام خطا می‌دهد",
      "notesInFlow": true
    }
  ],
  "connections": {
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Latest Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Latest Message": {
      "main": [
        [
          {
            "node": "Build Test Card",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Test Card": {
      "main": [
        [
          {
            "node": "Build Context",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Context": {
      "main": [
        [
          {
            "node": "Arena Chat",
            "type": "main",
            "index": 0
          },
          {
            "node": "OpenAI Chat (fallback)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Arena Chat": {
      "main": [
        [
          {
            "node": "Pick Answer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat (fallback)": {
      "main": [
        [
          {
            "node": "Pick Answer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pick Answer": {
      "main": [
        [
          {
            "node": "Format Telegram",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Telegram": {
      "main": [
        [
          {
            "node": "Send Answer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "pinData": {},
  "meta": {
    "instanceId": "tg-agents-bot"
  },
  "tags": []
}