{
  "name": "Alalvera: send a finished conversation",
  "nodes": [
    {
      "id": "a1",
      "name": "Notes",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -60,
        -300
      ],
      "parameters": {
        "width": 760,
        "height": 260,
        "content": "## Alalvera: send a finished conversation\n1. In 'Send to Alalvera' choose Create new credential (Header Auth): Name Authorization, Value Bearer followed by your Alalvera key (alv_live_...).\n2. Connect the end of your chatbot flow to 'Connect your flow here'. Each item needs: conversationId, agentName, endedAt, and messages [{ id, role, text, time }].\n3. Run it with one conversation. Success is the 'Done' node lighting up with Alalvera's answer.\nGuide: integrations/n8n/README.md"
      }
    },
    {
      "id": "a2",
      "name": "Connect your flow here",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        0,
        0
      ],
      "parameters": {}
    },
    {
      "id": "a3",
      "name": "Build Alalvera body",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "language": "javaScript",
        "jsCode": "// Builds the body Alalvera's POST /v1/conversations takes (docs/api-v1.md).\n// Input, one item per finished conversation:\n//   conversationId  text   your chatbot's id for the conversation (required)\n//   agentName       text   the AI agent's name, e.g. \"Support bot\" (default \"n8n\")\n//   startedAt       time   optional; only used as the time of a message that has none\n//   endedAt         time   optional; default: now\n//   messages        list   each { id?, role, text, time? }\n//                          role: customer | bot | human_agent (also user, assistant, ai, agent, human)\nconst item = $input.item.json;\nconst fail = (why) => {\n  throw new Error(\"Alalvera: \" + why);\n};\n\nconst ROLES = {\n  customer: \"customer\", user: \"customer\", visitor: \"customer\", human: \"customer\",\n  bot: \"bot\", assistant: \"bot\", ai: \"bot\", chatbot: \"bot\",\n  human_agent: \"human_agent\", agent: \"human_agent\", staff: \"human_agent\", operator: \"human_agent\",\n};\n// Plain ASCII keeps the text safe through any encoding on the way; it parses back to exactly the same words.\nconst ascii = (json) => json.replace(/[\\u007f-\\uffff]/g, (c) => \"\\\\u\" + c.charCodeAt(0).toString(16).padStart(4, \"0\"));\nconst clean = (s) => String(s).replace(/\\u0000/g, \"\").toWellFormed();\nconst iso = (v, what) => {\n  const d = new Date(v);\n  if (Number.isNaN(d.getTime())) fail(what + \" is not a time: \" + JSON.stringify(v));\n  return d.toISOString();\n};\n\nif (item.conversationId === undefined || item.conversationId === null || String(item.conversationId).trim() === \"\") fail(\"conversationId is missing\");\nif (!Array.isArray(item.messages) || item.messages.length === 0) fail(\"messages must be a non-empty list\");\n\nconst now = new Date().toISOString();\nconst fallbackTime = item.startedAt ? iso(item.startedAt, \"startedAt\") : now;\nconst messages = item.messages.map((m, i) => {\n  const role = ROLES[String(m.role ?? \"\").trim().toLowerCase()];\n  if (!role) fail(\"messages[\" + i + \"].role must be customer, bot or human_agent, got \" + JSON.stringify(m.role));\n  if (typeof m.text !== \"string\") fail(\"messages[\" + i + \"].text must be text\");\n  return {\n    id: clean(m.id === undefined || m.id === null || m.id === \"\" ? i + 1 : m.id),\n    role,\n    text: clean(m.text),\n    sent_at: m.time ? iso(m.time, \"messages[\" + i + \"].time\") : fallbackTime,\n  };\n});\n\nconst payload = {\n  platform: clean(item.agentName && String(item.agentName).trim() ? String(item.agentName).trim() : \"n8n\").slice(0, 100),\n  external_id: clean(String(item.conversationId)).slice(0, 500),\n  ended_at: item.endedAt ? iso(item.endedAt, \"endedAt\") : now,\n  messages,\n};\n\nconst body = ascii(JSON.stringify(payload));\nif (body.length > 1000000) fail(\"the conversation is larger than the size Alalvera takes\");\nreturn { json: { body } };"
      }
    },
    {
      "id": "a5",
      "name": "Send to Alalvera",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        440,
        0
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.alalvera.net/v1/conversations",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "contentType": "raw",
        "rawContentType": "application/json",
        "body": "={{ $('Build Alalvera body').item.json.body }}",
        "options": {
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true
            }
          },
          "timeout": 20000
        }
      },
      "onError": "continueRegularOutput",
      "credentials": {
        "httpHeaderAuth": {
          "id": "",
          "name": "Alalvera key"
        }
      }
    },
    {
      "id": "a6",
      "name": "Read the answer",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        0
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "language": "javaScript",
        "jsCode": "// Reads Alalvera's answer (docs/api-v1.md, \"POST /v1/conversations\"). Retries only what can pass by itself:\n// 429, 5xx and a lost connection. Everything else is explained and stops the flow.\nconst MAX_ATTEMPTS = 3;\nconst r = $input.item.json;\nconst status = Number(r.statusCode);\nconst attempt = $runIndex + 1;\nconst answer = typeof r.body === \"object\" && r.body !== null ? r.body : {};\nconst said = answer.error || answer.message || \"\";\n\nif (status >= 200 && status < 300) {\n  return { json: { ok: true, retry: false, status, message: answer.status === \"skipped\" ? \"Alalvera skipped it: the bot said nothing in this conversation.\" : \"Alalvera accepted the conversation.\", answer } };\n}\nconst lost = !Number.isFinite(status);\nconst retryable = lost || status === 429 || status >= 500;\nif (retryable && attempt < MAX_ATTEMPTS) {\n  const asked = Number(r.headers && r.headers[\"retry-after\"]);\n  const waitSeconds = Math.min(Number.isFinite(asked) && asked > 0 ? asked : 5 * attempt, 60);\n  return { json: { ok: false, retry: true, status: lost ? null : status, waitSeconds, message: \"Alalvera answered \" + (lost ? \"nothing\" : status) + \"; trying again in \" + waitSeconds + \" s (attempt \" + attempt + \" of \" + MAX_ATTEMPTS + \").\" } };\n}\nconst WHY = {\n  400: \"Alalvera could not read the conversation (\" + said + \"). Check the input fields the template documents.\",\n  401: \"Alalvera does not know this key (\" + said + \"): it is wrong, revoked or malformed. Check the Alalvera credential: the value must be 'Bearer ' and then the key, and the key must not have been revoked.\",\n  402: \"Your Alalvera subscription is not active, so new conversations are not accepted.\",\n  409: \"Your Alalvera account is scheduled for deletion, so nothing new is kept.\",\n  413: \"The conversation is larger than Alalvera accepts.\",\n  415: \"Alalvera did not get content-type application/json. Keep the Raw body and its content type as the template has them.\",\n};\nconst message = lost ? \"Alalvera could not be reached after \" + MAX_ATTEMPTS + \" tries.\" : WHY[status] || \"Alalvera answered \" + status + (said ? \" (\" + said + \")\" : \"\") + (retryable ? \" after \" + MAX_ATTEMPTS + \" tries\" : \"\") + \".\";\nreturn { json: { ok: false, retry: false, status: lost ? null : status, message } };"
      }
    },
    {
      "id": "a7",
      "name": "Try again?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        1100,
        0
      ],
      "parameters": {
        "conditions": {
          "boolean": [
            {
              "value1": "={{ $json.retry }}",
              "value2": true
            }
          ]
        }
      }
    },
    {
      "id": "a8",
      "name": "Wait before trying again",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        1100,
        220
      ],
      "parameters": {
        "resume": "timeInterval",
        "amount": "={{ $json.waitSeconds }}",
        "unit": "seconds"
      }
    },
    {
      "id": "a9",
      "name": "Accepted?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        1320,
        -80
      ],
      "parameters": {
        "conditions": {
          "boolean": [
            {
              "value1": "={{ $json.ok }}",
              "value2": true
            }
          ]
        }
      }
    },
    {
      "id": "a10",
      "name": "Done",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        1540,
        -160
      ],
      "parameters": {}
    },
    {
      "id": "a11",
      "name": "Stop and explain",
      "type": "n8n-nodes-base.stopAndError",
      "typeVersion": 1,
      "position": [
        1540,
        40
      ],
      "parameters": {
        "errorMessage": "={{ $json.message }}"
      }
    }
  ],
  "connections": {
    "Connect your flow here": {
      "main": [
        [
          {
            "node": "Build Alalvera body",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Alalvera body": {
      "main": [
        [
          {
            "node": "Send to Alalvera",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send to Alalvera": {
      "main": [
        [
          {
            "node": "Read the answer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read the answer": {
      "main": [
        [
          {
            "node": "Try again?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Try again?": {
      "main": [
        [
          {
            "node": "Wait before trying again",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Accepted?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait before trying again": {
      "main": [
        [
          {
            "node": "Send to Alalvera",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Accepted?": {
      "main": [
        [
          {
            "node": "Done",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Stop and explain",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}
