{
  "name": "Telegram 9-Agent Router — POLLING (no HTTPS needed)",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "seconds",
              "secondsInterval": 5
            }
          ]
        }
      },
      "id": "n8n-poll-trigger",
      "name": "Poll Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        -1200,
        0
      ],
      "notes": "هر ۵ ثانیه getUpdates — جایگزین webhook",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// ── polling: خواندن پیام‌های جدید از Telegram getUpdates ──────────────────────\n// offset در staticData ذخیره می‌شود تا بین اجراها گم نشود.\nconst botToken = $env.TELEGRAM_BOT_TOKEN || process.env.TELEGRAM_BOT_TOKEN || '';\nif (!botToken) {\n  throw new Error('TELEGRAM_BOT_TOKEN تنظیم نشده است. آن را در متغیرهای محیطی n8n بگذارید.');\n}\n\nconst staticData = $getWorkflowStaticData('global');\nconst offset = staticData.tgOffset || 0;\n\n// در n8n Code node، این helper برای درخواست‌های async در دسترس است\nconst resp = await this.helpers.httpRequest({\n  method: 'GET',\n  url: `https://api.telegram.org/bot${botToken}/getUpdates`,\n  qs: { offset, timeout: 0, allowed_updates: JSON.stringify(['message', 'edited_message']) },\n  json: true,\n});\n\nconst updates = (resp.result || []);\nif (updates.length === 0) {\n  return [{ json: { _empty: true, route: 'ignore' } }];\n}\n\nstaticData.tgOffset = updates[updates.length - 1].update_id + 1;\n\nreturn updates.map((u) => ({ json: u }));\n"
      },
      "id": "n8n-telegram-getupdates",
      "name": "Telegram getUpdates",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -1000,
        0
      ],
      "notes": "polling با offset ذخیره‌شده در staticData",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// ── ۱) نرمال‌سازی پیام تلگرام ──────────────────────────────────────────────\nconst update = $json;\nconst msg = update.message || update.edited_message || {};\nconst chat = msg.chat || {};\nconst user = msg.from || {};\nconst text = msg.text || msg.caption || '';\n\n// نوع مدیا (برای آرشیو)\nlet media = null;\nfor (const k of ['photo', 'video', 'voice', 'audio', 'document', 'sticker']) {\n  if (msg[k]) { media = k; break; }\n}\n\n// آیا این پیام از یک ربات است؟ (جلوگیری از حلقه)\nconst fromBot = !!user.is_bot;\n\nreturn [{\n  json: {\n    message_id: msg.message_id ?? null,\n    chat_id: chat.id ?? null,\n    chat_type: chat.type ?? null,\n    chat_title: chat.title ?? chat.username ?? null,\n    user_id: user.id ?? null,\n    username: user.username ?? (user.first_name || 'unknown'),\n    sender_name: [user.first_name, user.last_name].filter(Boolean).join(' ') || 'unknown',\n    is_bot: fromBot,\n    text,\n    has_media: media !== null,\n    media_type: media,\n    reply_to_message_id: msg.reply_to_message?.message_id ?? null,\n    date: msg.date ? new Date(msg.date * 1000).toISOString() : new Date().toISOString(),\n  }\n}];\n"
      },
      "id": "n8n-normalize-message",
      "name": "Normalize Message",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -800,
        0
      ],
      "notes": "نرمال‌سازی پیام",
      "notesInFlow": true
    },
    {
      "parameters": {
        "operation": "insert",
        "collection": "chat_history",
        "options": {},
        "fields": "={{ $json }}"
      },
      "id": "n8n-save-message",
      "name": "Save Message",
      "type": "n8n-nodes-base.mongoDb",
      "typeVersion": 1,
      "position": [
        -600,
        0
      ],
      "credentials": {
        "mongoDb": {
          "id": "REPLACE_MONGO_CRED_ID",
          "name": "MongoDB - tg_agents"
        }
      },
      "notes": "آرشیو chat_history",
      "notesInFlow": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "version": 2
          },
          "conditions": [
            {
              "leftValue": "={{ $json.chat_id }}",
              "rightValue": "",
              "operator": {
                "type": "number",
                "operation": "exists",
                "singleValue": true
              }
            },
            {
              "leftValue": "={{ $json.is_bot }}",
              "rightValue": false,
              "operator": {
                "type": "boolean",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "n8n-only-real-user-messages",
      "name": "Only Real User Messages",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.2,
      "position": [
        -400,
        0
      ],
      "notes": "پیام ربات‌ها و پیام‌های بدون chat_id رد می‌شوند"
    },
    {
      "parameters": {
        "jsCode": "// ── ۲) روتینگ: @ag01..@ag08 / /all / /daily / ذخیره ───────────────────────\nconst item = $input.first().json;\nconst text = item.text || '';\nconst path = $execution?.resumeFormUrl ? '' : '';   // (بی‌استفاده)\n\nif (item.is_bot) return [{ json: { ...item, route: 'ignore' } }];\n\nconst mention = text.match(/@(ag0[1-8])\\b/i);\nconst isAll = /^\\s*\\/all(@\\w+)?\\b/i.test(text);\nconst isDaily = /^\\s*\\/daily(@\\w+)?\\b/i.test(text);\nconst isHelp = /^\\s*\\/(start|help)(@\\w+)?\\b/i.test(text);\n\nlet route = 'ignore';\nlet agent = null;\nif (mention) { route = 'single'; agent = mention[1].toUpperCase(); }\nelse if (isAll) route = 'all';\nelse if (isDaily) route = 'daily';\nelse if (isHelp) route = 'help';\n\n// متن سؤال بدون منشن/دستور\nconst question = text\n  .replace(/@(ag0[1-9])\\b/gi, '')\n  .replace(/^\\s*\\/(all|daily|help|start)(@\\w+)?/i, '')\n  .trim();\n\nreturn [{ json: { ...item, route, agent, question } }];\n"
      },
      "id": "n8n-route",
      "name": "Route",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -200,
        0
      ],
      "notes": "منشن/دستور/ذخیره",
      "notesInFlow": true
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.route }}",
                    "rightValue": "single",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "outputKey": "single"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.route }}",
                    "rightValue": "all",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "outputKey": "all"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.route }}",
                    "rightValue": "daily",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "outputKey": "daily"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.route }}",
                    "rightValue": "help",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "outputKey": "help"
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra",
          "renameFallbackOutput": "ignore"
        }
      },
      "id": "n8n-switch-route",
      "name": "Switch Route",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3,
      "position": [
        -200,
        0
      ],
      "notes": "single / all / daily / help / ignore",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// ── ۳) نگاشت ایجنت منشن‌شده به شناسه/دیتابیس ──────────────────────────────\nconst item = $input.first().json;\nconst MAP = {\n  AG01: { db: 'NOTION_DB_MARKET',   name: 'استراتژیست بازار' },\n  AG02: { db: 'NOTION_DB_COPY',     name: 'روایت‌ساز و کپی‌رایتر' },\n  AG03: { db: 'NOTION_DB_CONTENT',  name: 'کارگردان محتوا و موشن' },\n  AG04: { db: 'NOTION_DB_DESIGN',   name: 'طراح سیستم بصری' },\n  AG05: { db: 'NOTION_DB_WEB',      name: 'توسعه‌دهنده وب' },\n  AG06: { db: 'NOTION_DB_SEO',      name: 'متخصص سئو و رشد' },\n  AG07: { db: 'NOTION_DB_DATA',     name: 'تحلیل‌گر داده' },\n  AG08: { db: 'NOTION_DB_CAMPAIGN', name: 'کمپین و فروش B2B' },\n};\nconst meta = MAP[item.agent] || {};\nreturn [{ json: { ...item, agent_name: meta.name || item.agent, agent_db_env: meta.db || null } }];\n"
      },
      "id": "n8n-map-agent",
      "name": "Map Agent",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        -260
      ],
      "notes": "",
      "notesInFlow": false
    },
    {
      "parameters": {
        "operation": "aggregate",
        "collection": "chat_history",
        "options": {},
        "query": "[{\"$match\": {\"chat_id\": \"={{ $json.chat_id }}\", \"is_bot\": false}}, {\"$sort\": {\"date\": -1}}, {\"$limit\": 30}]"
      },
      "id": "n8n-chat-history",
      "name": "Chat History",
      "type": "n8n-nodes-base.mongoDb",
      "typeVersion": 1,
      "position": [
        200,
        -260
      ],
      "credentials": {
        "mongoDb": {
          "id": "REPLACE_MONGO_CRED_ID",
          "name": "MongoDB - tg_agents"
        }
      },
      "notes": "آخرین ۳۰ پیام گروه",
      "notesInFlow": true
    },
    {
      "parameters": {
        "resource": "databasePage",
        "operation": "getAll",
        "databaseId": {
          "__rl": true,
          "value": "={{ $env.NOTION_DB_}}",
          "mode": "id"
        },
        "returnAll": false,
        "limit": 10,
        "filterType": "manual",
        "matchType": "anyFilter",
        "filters": {
          "conditions": []
        },
        "options": {}
      },
      "id": "n8n-notion-records",
      "name": "Notion Records",
      "type": "n8n-nodes-base.notion",
      "typeVersion": 2.2,
      "position": [
        200,
        -80
      ],
      "notes": "دیتابیس مرتبط ایجنت — شناسه را دستی جایگزین کنید",
      "notesInFlow": true,
      "credentials": {
        "notionApi": {
          "id": "REPLACE_NOTION_CRED_ID",
          "name": "Notion API"
        }
      }
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "\n// ── ۴) بارگذاری System Prompt ایجنت از فایل ───────────────────────────────\n// مسیر پوشه پرامپت‌ها روی سرور ویندوز (در n8n > Settings > Environment Variables):\n//   N8N_AGENTS_PROMPTS_DIR=C:\\n8n\\prompts\nconst fs = require('fs');\nconst path = require('path');\n\nconst item = $input.first().json;\nconst agent = item.agent;\n\nconst dir = process.env.N8N_AGENTS_PROMPTS_DIR || $env.N8N_AGENTS_PROMPTS_DIR || '';\nconst candidates = [\n  path.join(dir, `${agent}.txt`),\n  path.join(process.env.USERPROFILE || '.', 'n8n', 'prompts', `${agent}.txt`),\n  path.join('.', 'n8n', 'prompts', `${agent}.txt`),\n];\n\nlet system_prompt = '';\nlet loaded_from = null;\nfor (const c of candidates) {\n  try {\n    if (c && fs.existsSync(c)) {\n      system_prompt = fs.readFileSync(c, 'utf8');\n      loaded_from = c;\n      break;\n    }\n  } catch (e) { /* ignore */ }\n}\n\nif (!system_prompt) {\n  system_prompt = `تو ${agent} هستی. بدون شاهد ادعا نکن و هر ادعا را با [شاهد: ...] یا ⚠️ نیازمند تأیید علامت بزن.`;\n}\n\nreturn [{ json: { ...item, system_prompt, prompt_file: loaded_from } }];\n"
      },
      "id": "n8n-load-prompt",
      "name": "Load Prompt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        200,
        -440
      ],
      "notes": "خواندن فایل n8n/prompts/AGxx.txt بر اساس $json.agent",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// ── ۵) ساخت Context ترکیبی: System Prompt + Notion + تاریخچه گروه ──────────\nconst item = $input.first().json;\nconst agent = item.agent;\n\n// پرامپت‌ها از گره «Load Prompt» می‌آیند (فایل n8n/prompts/AGxx.txt)\nconst systemPrompt = item.system_prompt || '';\n\n// رکوردهای Notion (اگر گره Notion خطا داد یا خالی بود → آرایه خالی)\nlet notionRows = [];\ntry {\n  notionRows = $('Notion Records').all().map(i => i.json).filter(r => r && Object.keys(r).length);\n} catch (e) { notionRows = []; }\n\n// تاریخچه ۳۰ پیام آخر (به ترتیب قدیمی → جدید)\nlet history = [];\ntry {\n  history = $('Chat History').all().map(i => i.json).filter(r => r && r.text !== undefined);\n} catch (e) { history = []; }\nhistory.sort((a, b) => new Date(a.date) - new Date(b.date));\n\nconst fmt = (m) => {\n  const d = new Date(m.date);\n  const stamp = d.toISOString().slice(0, 16).replace('T', ' ');\n  return `[${stamp} UTC] @${m.username || 'unknown'}: ${(m.text || '').replace(/\\s+/g, ' ').slice(0, 500)}`;\n};\nconst historyBlock = history.length ? history.map(fmt).join('\\n') : 'تاریخچه‌ای در دست نیست.';\n\nconst notionBlock = notionRows.length\n  ? notionRows.slice(0, 10).map((r, i) => {\n      const { _id, ...rest } = r;\n      return `${i + 1}. ` + Object.entries(rest)\n        .filter(([, v]) => v !== null && v !== undefined && v !== '')\n        .map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(',') : v}`).join(' | ');\n    }).join('\\n')\n  : 'هیچ رکورد فعالی یافت نشد → یعنی «داده‌ای در دست نیست»، نه صفر و نه تأیید.';\n\nconst userPrompt = `# Context عملیاتی — ${agent} (${item.agent_name})\n\n## بخش ب — داده‌های Notion (حداکثر ۱۰ رکورد اخیر)\n${notionBlock}\n\n## بخش ج — تاریخچه چت گروه (آخرین ${history.length} پیام)\n${historyBlock}\n\n---\n\n## درخواست کاربر\n${item.question || '(بدون متن)'}\n\n## دستور پاسخ\n۱. فقط در نقش ${agent} پاسخ بده و از مرز اختیار خودت بیرون نزن.\n۲. هر ادعا شاهد داشته باشد: [شاهد: ...] — ادعای بدون شاهد → ⚠️ نیازمند تأیید.\n۳. هیچ ردیف/عددی را حدس نزن. خانه خالی ≠ صفر و ≠ تأیید.\n۴. فقط ابزار رایگان پیشنهاد بده.\n۵. پایان: «✅ اقدام بعدی» (حداکثر ۳ مورد) و در صورت لزوم «⚠️ نیازمند تأیید مدیر».\n`;\n\nreturn [{\n  json: {\n    ...item,\n    system_prompt: systemPrompt,\n    user_prompt: userPrompt,\n    notion_count: notionRows.length,\n    history_count: history.length,\n  }\n}];\n"
      },
      "id": "n8n-build-prompt",
      "name": "Build Prompt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        420,
        -260
      ],
      "notes": "",
      "notesInFlow": false
    },
    {
      "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",
          "temperature": 0.4,
          "max_tokens": 2000,
          "messages": [
            {
              "role": "system",
              "content": "={{ $json.system_prompt }}"
            },
            {
              "role": "user",
              "content": "={{ $json.user_prompt }}"
            }
          ]
        },
        "options": {
          "timeout": 120000
        }
      },
      "id": "n8n-openai-chat",
      "name": "OpenAI Chat",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        640,
        -260
      ]
    },
    {
      "parameters": {
        "jsCode": "// ── ۷) کنترل کیفیت خروجی ایجنت (قبل از ارسال) ─────────────────────────────\nconst item = $input.first().json;\nconst choice = item.choices?.[0]?.message?.content ?? item.content ?? '';\nlet answer = String(choice).trim();\n\nconst problems = [];\nif (!answer) problems.push('پاسخ خالی است');\nif (!/شاهد|نیازمند تأیید/.test(answer)) problems.push('هیچ شاهد/برچسب تأییدی ندارد');\n\n// هشدار (نه مسدودسازی): برچسب‌گذاری خودکار\nlet flags = '';\nif (!/\\[شاهد/.test(answer)) flags += '\\n\\n⚠️ <i>این پاسخ هیچ شاهد صریحی ندارد — نیازمند تأیید مدیر.</i>';\nif (flags) answer += flags;\n\nconst MAX = 3500;\nconst 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);\n\nreturn chunks.map((chunk, i) => ({\n  json: {\n    ...item,\n    answer: chunk,\n    part: i + 1,\n    parts: chunks.length,\n    quality_problems: problems,\n  }\n}));\n"
      },
      "id": "n8n-self-check",
      "name": "Self Check",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        860,
        -260
      ],
      "notes": "برچسب شاهد + شکستن پیام",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// ── ۸) قالب‌بندی پیام تلگرام (HTML) ────────────────────────────────────────\nconst item = $input.first().json;\nconst escape = (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>');\n\nconst head = item.part === 1\n  ? `<b>${item.agent} — ${item.agent_name}</b>\\n\\n`\n  : `<b>${item.agent}</b> (ادامه ${item.part}/${item.parts})\\n\\n`;\n\nreturn [{ json: { ...item, telegram_text: head + escape(item.answer) } }];\n"
      },
      "id": "n8n-format-telegram",
      "name": "Format Telegram",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1080,
        -260
      ],
      "notes": "",
      "notesInFlow": false
    },
    {
      "parameters": {
        "chatId": "={{ $('Normalize Message').item.json.chat_id }}",
        "text": "={{ $json.telegram_text }}",
        "additionalFields": {
          "parse_mode": "HTML",
          "appendAttribution": false
        }
      },
      "id": "n8n-send-answer",
      "name": "Send Answer",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        1300,
        -260
      ],
      "credentials": {
        "telegramApi": {
          "id": "REPLACE_TELEGRAM_CRED_ID",
          "name": "Telegram Bot"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// ── /all : یک آیتم برای هر ایجنت فعال (به‌جز AG09) ────────────────────────\nconst item = $input.first().json;\nconst ACTIVE = ['AG01','AG02','AG03','AG04','AG05','AG06','AG07','AG08'];\nreturn ACTIVE.map((agent) => ({ json: { ...item, agent, route: 'single',\n  agent_name: agent } }));\n"
      },
      "id": "n8n-fan-out-agents",
      "name": "Fan Out Agents",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        60
      ],
      "notes": "۸ ایجنت فعال → ۸ آیتم",
      "notesInFlow": true
    },
    {
      "parameters": {
        "batchSize": 1,
        "options": {
          "reset": false
        }
      },
      "id": "n8n-loop-agents",
      "name": "Loop Agents",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        200,
        60
      ],
      "notes": "اجرای ترتیبی برای رعایت محدودیت نرخ تلگرام",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "// ── /daily : خلاصه وضعیت روز از Notion (بدون LLM) ─────────────────────────\nconst item = $input.first().json;\nconst rows = [];\ntry { rows.push(...$('Notion Records').all().map(i => i.json)); } catch (e) {}\nlet logRows = [];\ntry { logRows = $('Daily Log').all().map(i => i.json); } catch (e) {}\n\nconst lines = [`📊 <b>خلاصه وضعیت روز</b>`, ''];\nlines.push(`رکوردهای فعال دیتابیس مرتبط: <b>${rows.length}</b>`);\nrows.slice(0, 10).forEach((r, i) => {\n  const title = r.Name || r['نام'] || r.Title || r['عنوان'] || '(بدون عنوان)';\n  lines.push(`${i + 1}. ${title}`);\n});\nif (logRows.length) {\n  lines.push('', `<b>ثبت‌های اخیر daily_log:</b>`);\n  logRows.slice(0, 8).forEach(r => lines.push(`• ${r.Agent || '—'} | ${r.Mission || '—'}`));\n}\nif (!rows.length && !logRows.length) {\n  lines.push('', '⚠️ داده‌ای در دست نیست (نه صفر، نه تأیید).');\n}\nreturn [{ json: { ...item, telegram_text: lines.join('\\n') } }];\n"
      },
      "id": "n8n-daily-summary",
      "name": "Daily Summary",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        200
      ],
      "notes": "",
      "notesInFlow": false
    },
    {
      "parameters": {
        "chatId": "={{ $('Normalize Message').item.json.chat_id }}",
        "text": "={{ $json.telegram_text }}",
        "additionalFields": {
          "parse_mode": "HTML",
          "appendAttribution": false
        }
      },
      "id": "n8n-send-daily",
      "name": "Send Daily",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        220,
        200
      ],
      "credentials": {
        "telegramApi": {
          "id": "REPLACE_TELEGRAM_CRED_ID",
          "name": "Telegram Bot"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const help = `<b>راهنمای ربات ایجنت‌ها</b>\n\n@ag01 … @ag08 — منشن کن تا فقط همان ایجنت پاسخ دهد\n/all سؤال… — همه ایجنت‌های فعال (هر کدام پیام جدا)\n/daily — خلاصه وضعیت روز از Notion\n/help — همین راهنما\n\nپیام‌های بدون منشن فقط ذخیره می‌شوند.`;\nreturn [{ json: { ...$input.first().json, telegram_text: help } }];\n"
      },
      "id": "n8n-help-text",
      "name": "Help Text",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        340
      ],
      "notes": "",
      "notesInFlow": false
    },
    {
      "parameters": {
        "chatId": "={{ $('Normalize Message').item.json.chat_id }}",
        "text": "={{ $json.telegram_text }}",
        "additionalFields": {
          "parse_mode": "HTML",
          "appendAttribution": false
        }
      },
      "id": "n8n-send-help",
      "name": "Send Help",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        220,
        340
      ],
      "credentials": {
        "telegramApi": {
          "id": "REPLACE_TELEGRAM_CRED_ID",
          "name": "Telegram Bot"
        }
      }
    }
  ],
  "connections": {
    "Poll Trigger": {
      "main": [
        [
          {
            "node": "Telegram getUpdates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Telegram getUpdates": {
      "main": [
        [
          {
            "node": "Normalize Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalize Message": {
      "main": [
        [
          {
            "node": "Save Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Message": {
      "main": [
        [
          {
            "node": "Only Real User Messages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Only Real User Messages": {
      "main": [
        [
          {
            "node": "Route",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Route": {
      "main": [
        [
          {
            "node": "Switch Route",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch Route": {
      "main": [
        [
          {
            "node": "Map Agent",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Fan Out Agents",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Daily Summary",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Help Text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Map Agent": {
      "main": [
        [
          {
            "node": "Load Prompt",
            "type": "main",
            "index": 0
          },
          {
            "node": "Chat History",
            "type": "main",
            "index": 0
          },
          {
            "node": "Notion Records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Load Prompt": {
      "main": [
        [
          {
            "node": "Build Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Chat History": {
      "main": [
        [
          {
            "node": "Build Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Notion Records": {
      "main": [
        [
          {
            "node": "Build Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Prompt": {
      "main": [
        [
          {
            "node": "OpenAI Chat",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat": {
      "main": [
        [
          {
            "node": "Self Check",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Self Check": {
      "main": [
        [
          {
            "node": "Format Telegram",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Telegram": {
      "main": [
        [
          {
            "node": "Send Answer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fan Out Agents": {
      "main": [
        [
          {
            "node": "Loop Agents",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Agents": {
      "main": [
        [
          {
            "node": "Map Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Daily Summary": {
      "main": [
        [
          {
            "node": "Send Daily",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Help Text": {
      "main": [
        [
          {
            "node": "Send Help",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "saveManualExecutions": true,
    "callerPolicy": "workflowsFromSameOwner"
  },
  "staticData": null,
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": [
    {
      "name": "telegram"
    },
    {
      "name": "agents"
    },
    {
      "name": "polling"
    }
  ]
}