{
  "name": "AI Agent Safety Guard — Idempotency, Budget Caps & Kill Switch",
  "nodes": [
    {
      "parameters": {
        "content": "## 🛡️ AI AGENT SAFETY GUARD\n**What it does:** A guard sub-workflow other workflows/agents call BEFORE any outbound action (send email/message, create a charge, booking or ticket). It runs 4 checks — idempotency, monthly budget, hourly rate cap, kill switch — then an AI risk review. Only allowed actions execute. Every decision is logged to a Google Sheets guard ledger and Telegram gets a summary.\n\n**You'll need:**\n- OpenAI API key (platform.openai.com)\n- Google Sheets OAuth2 credentials\n- Telegram bot token + your chat ID (@BotFather → /newbot)\n- A target endpoint URL that performs the action (your own API / Zapier webhook / another n8n workflow)\n\n**Status flow in Sheets:** `NEW` → `PROCESSING` → `DONE` / `BLOCKED_DUPLICATE` / `BLOCKED_BUDGET` / `BLOCKED_RATE` / `BLOCKED_KILLSWITCH` / `BLOCKED_AGENT` / `FAILED`\n\n**Call it like this (POST JSON):** `{ \"client_id\": \"acme\", \"action_type\": \"send_email\", \"recipient\": \"customer@example.com\", \"payload\": { \"subject\": \"...\", \"body\": \"...\" }, \"estimated_tokens\": 1200 }`",
        "height": 220,
        "width": 4080,
        "color": 5
      },
      "id": "91ea42ef-3473-454a-94eb-2c06af558cdc",
      "name": "STICKY — Title",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -240,
        -160
      ]
    },
    {
      "parameters": {
        "content": "## STEP 1 — Receive the action request\nWebhook (POST /guard-action) receives the action → CONFIG node holds every editable value → normalize the request and build a SHA-256 idempotency key from client + action_type + recipient + payload.",
        "height": 420,
        "width": 1160,
        "color": 4
      },
      "id": "904bebf8-7d23-40b3-9429-49bc6feb6095",
      "name": "STICKY — STEP 1",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -240,
        180
      ]
    },
    {
      "parameters": {
        "content": "## STEP 2 — Log + read the ledger\nAppend the request to the Guard Ledger as `NEW` → read the whole ledger back so the guard checks can see every past decision.",
        "height": 420,
        "width": 720,
        "color": 4
      },
      "id": "40084fda-f102-4bc5-90be-95dd029f1534",
      "name": "STICKY — STEP 2",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        940,
        180
      ]
    },
    {
      "parameters": {
        "content": "## STEP 3 — Four guard checks\nKill switch? Replay of an idempotency key? Monthly budget exceeded? Hourly rate cap hit? Any hit blocks the action immediately — nothing executes.",
        "height": 420,
        "width": 720,
        "color": 4
      },
      "id": "54f6887e-fc5e-492f-8720-589bb5368753",
      "name": "STICKY — STEP 3",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1680,
        180
      ]
    },
    {
      "parameters": {
        "content": "## STEP 4 — AI risk review\nAI Agent (gpt-4o-mini + Structured Output Parser) reviews the action and returns a verdict {verdict: allow|block, reason, risk_score}. Score at/above the threshold blocks it.",
        "height": 420,
        "width": 720,
        "color": 4
      },
      "id": "29adb764-610b-4e30-94a9-b0f0cd79d451",
      "name": "STICKY — STEP 4",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        2400,
        180
      ]
    },
    {
      "parameters": {
        "content": "## STEP 5 — Execute + log + reply\nAllowed actions execute via one generic HTTP Request to your target endpoint (Idempotency-Key header) → verify the response → ledger flips to `DONE` (or `FAILED`) → webhook reply + Telegram summary.",
        "height": 420,
        "width": 720,
        "color": 4
      },
      "id": "bdcd6c01-df6b-4cb0-accc-445a88af0199",
      "name": "STICKY — STEP 5",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        3120,
        180
      ]
    },
    {
      "parameters": {
        "content": "## STEP 6 — Blocked paths\nAny blocked decision (duplicate, budget, rate, kill switch, or AI verdict) is written back to the ledger with its BLOCKED_* status, returned to the caller as {allowed: false}, and Telegram-notified. Nothing executes on a blocked path.",
        "height": 400,
        "width": 1920,
        "color": 4
      },
      "id": "c366bd6a-ea48-44b3-b795-e98c4201a590",
      "name": "STICKY — STEP 6",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1200,
        680
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "guard-action",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "f247562d-f0d9-490b-8c28-e324ddfc2181",
      "name": "Webhook — Guard Request",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        300
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "306efe32-0878-466b-9ec6-7fb94514bae2",
              "name": "monthly_budget_usd",
              "type": "string",
              "value": "100"
            },
            {
              "id": "d4ae85b1-1ca4-48a8-9286-877459033445",
              "name": "max_actions_per_hour",
              "type": "string",
              "value": "20"
            },
            {
              "id": "6b17af02-e4ab-46f7-909d-a1a6ca13c6ea",
              "name": "kill_switch_enabled",
              "type": "string",
              "value": "false"
            },
            {
              "id": "b3836cb8-1d3e-4f92-9716-991601921a36",
              "name": "cost_per_1k_tokens_usd",
              "type": "string",
              "value": "0.0006"
            },
            {
              "id": "1fcd3a3e-0c9c-4c90-8f28-befe6a3386c8",
              "name": "guard_sheet_id",
              "type": "string",
              "value": "PASTE_YOUR_GUARD_SHEET_ID"
            },
            {
              "id": "6bde885e-56b5-4cfb-b2ac-18ab259c8884",
              "name": "ledger_sheet",
              "type": "string",
              "value": "Guard Ledger"
            },
            {
              "id": "5bfe6413-554c-4948-bbef-e1e0c443d107",
              "name": "telegram_chat_id",
              "type": "string",
              "value": "PASTE_YOUR_TELEGRAM_CHAT_ID"
            },
            {
              "id": "597c649a-b8d8-47a1-bb09-3ad6f1624ad7",
              "name": "target_endpoint_url",
              "type": "string",
              "value": "PASTE_YOUR_TARGET_ENDPOINT_URL"
            },
            {
              "id": "de5c5331-fef5-4753-99b1-a2b60f5151e2",
              "name": "target_api_key",
              "type": "string",
              "value": "PASTE_YOUR_TARGET_API_KEY"
            },
            {
              "id": "f9b11fe1-cd4e-4568-af2d-01bedfe53769",
              "name": "openai_model",
              "type": "string",
              "value": "gpt-4o-mini"
            },
            {
              "id": "d334000f-f5de-420e-9512-98ecda40fc77",
              "name": "risk_block_threshold",
              "type": "string",
              "value": "70"
            }
          ]
        },
        "options": {}
      },
      "id": "0c0f315b-99f3-4b50-a1f1-d7c1cd0ac7ec",
      "name": "CONFIG — Guard Policy",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        240,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// Normalize the incoming guard request and build a SHA-256 idempotency key\n// from client + action_type + recipient + payload. Same key = same action:\n// a retry can never execute twice.\nconst body = $json.body || $json;\nconst client_id = (body.client_id || '').toString().trim();\nconst action_type = (body.action_type || '').toString().trim();\nconst recipient = (body.recipient || '').toString().trim();\nconst payload = typeof body.payload === 'string' ? body.payload : JSON.stringify(body.payload || {});\nconst estimated_tokens = Number(body.estimated_tokens) || 0;\nconst keyMaterial = [client_id, action_type, recipient, payload].join('|');\nlet idempotency_key = '';\ntry {\n  const crypto = require('crypto');\n  idempotency_key = crypto.createHash('sha256').update(keyMaterial).digest('hex');\n} catch (e) {\n  // Fallback deterministic hash if crypto is unavailable in this runtime\n  let h1 = 0xdeadbeef, h2 = 0x41c6ce57;\n  for (let i = 0; i < keyMaterial.length; i++) {\n    const ch = keyMaterial.charCodeAt(i);\n    h1 = Math.imul(h1 ^ ch, 2654435761);\n    h2 = Math.imul(h2 ^ ch, 1597334677);\n  }\n  idempotency_key = 'fallback-' + (h1 >>> 0).toString(16) + (h2 >>> 0).toString(16);\n}\nreturn [{ json: {\n  timestamp: new Date().toISOString(),\n  idempotency_key, client_id, action_type, recipient, payload,\n  estimated_tokens, status: 'NEW', cost_usd: 0, decision_reason: '', provider_ref: '',\n} }];",
        "mode": "runOnceForAllItems"
      },
      "id": "342174e8-c4a7-4f0d-ba5d-e77527ebe3c5",
      "name": "Code — Normalize Request & Idempotency Key",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        480,
        300
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "resource": "sheetWithinDocument",
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Guard Ledger"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false,
          "value": {
            "timestamp": "={{ $json.timestamp }}",
            "idempotency_key": "={{ $json.idempotency_key }}",
            "client_id": "={{ $json.client_id }}",
            "action_type": "={{ $json.action_type }}",
            "recipient": "={{ $json.recipient }}",
            "status": "={{ $json.status }}",
            "cost_usd": "={{ $json.cost_usd }}",
            "decision_reason": "={{ $json.decision_reason }}",
            "provider_ref": "={{ $json.provider_ref }}"
          }
        },
        "options": {}
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "",
          "name": "Google Sheets API"
        }
      },
      "id": "cabb78db-ba42-4120-9f65-20c0f11816f4",
      "name": "Google Sheets — Log Request NEW",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        720,
        300
      ]
    },
    {
      "parameters": {
        "operation": "read",
        "resource": "sheetWithinDocument",
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Guard Ledger"
        },
        "options": {}
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "",
          "name": "Google Sheets API"
        }
      },
      "id": "2077ed72-b275-41fd-a1ca-2fe59cac0229",
      "name": "Google Sheets — Read Guard Ledger",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        960,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// Four guard checks: kill switch, idempotency replay, monthly budget, hourly rate cap.\n// Cost is estimated from estimated_tokens at the per-1k-token rate in CONFIG;\n// the budget check sums cost_usd for this client in the current month.\nconst cfg = $('CONFIG \\u2014 Guard Policy').first().json;\nconst req = $('Code \\u2014 Normalize Request & Idempotency Key').first().json;\nconst ledger = $input.all().map(i => i.json);\nconst norm = (s) => (s || '').toString().trim().toLowerCase();\nconst now = new Date();\nconst monthPrefix = now.toISOString().slice(0, 7); // YYYY-MM\nconst oneHourAgo = now.getTime() - 60 * 60 * 1000;\nconst ratePer1k = Number(cfg.cost_per_1k_tokens_usd) || 0.0006;\nconst cost_usd = (req.estimated_tokens / 1000) * ratePer1k;\nconst monthlyBudget = Number(cfg.monthly_budget_usd) || 100;\nconst maxPerHour = Number(cfg.max_actions_per_hour) || 20;\nconst killSwitch = norm(cfg.kill_switch_enabled) === 'true';\n\n// Idempotency: the NEW row we just appended counts once; 2+ rows with the\n// same key (or any non-NEW row with it) means this action already ran.\nconst sameKey = ledger.filter(r => norm(r.idempotency_key) === norm(req.idempotency_key));\nconst duplicate = sameKey.length >= 2 || sameKey.some(r => norm(r.status) !== 'new');\n// Monthly spend: sum cost_usd for this client in the current month (non-blocked rows)\nconst monthSpend = ledger\n  .filter(r => norm(r.client_id) === norm(req.client_id)\n    && (r.timestamp || '').toString().slice(0, 7) === monthPrefix\n    && !norm(r.status).startsWith('blocked'))\n  .reduce((s, r) => s + (Number(r.cost_usd) || 0), 0);\n// Hourly rate: actions by this client in the last hour (non-blocked rows)\nconst hourCount = ledger.filter(r => norm(r.client_id) === norm(req.client_id)\n  && !norm(r.status).startsWith('blocked')\n  && new Date(r.timestamp || 0).getTime() >= oneHourAgo).length;\n\nlet guard_status = 'PROCESSING';\nlet decision_reason = '';\nif (killSwitch) {\n  guard_status = 'BLOCKED_KILLSWITCH';\n  decision_reason = 'Kill switch is ON (kill_switch_enabled = true) — all actions blocked';\n} else if (duplicate) {\n  guard_status = 'BLOCKED_DUPLICATE';\n  decision_reason = 'Duplicate action: idempotency key ' + req.idempotency_key.slice(0, 12) + '... is already in the ledger';\n} else if (monthSpend + cost_usd > monthlyBudget) {\n  guard_status = 'BLOCKED_BUDGET';\n  decision_reason = 'Monthly budget $' + monthlyBudget + ' would be exceeded (spent $' + monthSpend.toFixed(4) + ' + this action $' + cost_usd.toFixed(4) + ')';\n} else if (hourCount >= maxPerHour) {\n  guard_status = 'BLOCKED_RATE';\n  decision_reason = 'Rate cap hit: ' + hourCount + ' actions in the last hour (max ' + maxPerHour + ')';\n}\nreturn [{ json: {\n  ...req,\n  cost_usd: Number(cost_usd.toFixed(6)),\n  month_spend: Number(monthSpend.toFixed(4)),\n  hour_count: hourCount,\n  guard_status, decision_reason,\n  status: guard_status,\n} }];",
        "mode": "runOnceForAllItems"
      },
      "id": "168d4ac8-996a-4eb4-81f1-d466f9e5a133",
      "name": "Code — Check Guard Rules",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1200,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "id": "8ab44ba4-afb2-4b4e-8b99-534d1717419b",
              "leftValue": "={{ $json.guard_status }}",
              "rightValue": "PROCESSING",
              "operator": {
                "type": "string",
                "operation": "notEquals",
                "name": "filter.operator.string.notEquals"
              }
            }
          ],
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          }
        },
        "options": {}
      },
      "id": "2d399655-b07e-486a-b45e-adc81142e9a8",
      "name": "IF — Guard Blocked?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1440,
        300
      ]
    },
    {
      "parameters": {
        "options": {
          "systemMessage": "=You are a strict AI safety reviewer. Review the requested outbound action BEFORE it executes. Block anything that looks like spam, a mass send, a duplicate of a recent action, a payment/charge the user did not explicitly approve, a message to the wrong audience, or content that is misleading, harmful, or off-brand. Be conservative: when in doubt, block and explain why. Output ONLY via the structured output parser."
        },
        "text": "=Action to review:\nClient: {{ $json.client_id }}\nAction type: {{ $json.action_type }}\nRecipient: {{ $json.recipient }}\nPayload: {{ $json.payload }}\nEstimated cost: ${{ $json.cost_usd }} (month spend so far: ${{ $json.month_spend }}, actions in the last hour: {{ $json.hour_count }})\n\nGuard checks already passed: not a duplicate, within monthly budget and hourly rate cap, kill switch off.\n\nReturn a verdict (allow / block), a short reason, and a risk_score from 0 (harmless) to 100 (definitely harmful)."
      },
      "id": "caa58a14-22fc-4d4b-b735-501b41264cd6",
      "name": "AI Agent — Risk Review",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        1680,
        300
      ]
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4o-mini"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "id": "",
          "name": "OpenAI API"
        }
      },
      "id": "8ee8fa33-fa1b-48ba-aa12-8080d5cbfb26",
      "name": "OpenAI Chat Model — Risk Review",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        1680,
        560
      ]
    },
    {
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"verdict\": \"allow / block\",\n  \"reason\": \"one or two sentences explaining the verdict\",\n  \"risk_score\": 0\n}"
      },
      "id": "bb4ae5aa-994a-4a45-916e-604fb9a1843c",
      "name": "Structured Output Parser — Risk Verdict",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.2,
      "position": [
        1920,
        560
      ]
    },
    {
      "parameters": {
        "jsCode": "// Combine the AI verdict with the risk threshold from CONFIG.\n// Block when the agent says block OR the risk score hits the threshold.\nconst req = $('Code \\u2014 Check Guard Rules').first().json;\nconst cfg = $('CONFIG \\u2014 Guard Policy').first().json;\nconst out = $json.output || {};\nconst threshold = Number(cfg.risk_block_threshold) || 70;\nconst risk = Number(out.risk_score);\nconst verdict = String(out.verdict || '').toLowerCase();\nlet decision = 'allow';\nlet decision_reason = out.reason || '';\nif (verdict !== 'allow') {\n  decision = 'block';\n  decision_reason = 'AI agent blocked it: ' + (out.reason || 'no reason given');\n} else if (!Number.isNaN(risk) && risk >= threshold) {\n  decision = 'block';\n  decision_reason = 'Risk score ' + risk + ' is at/above the block threshold ' + threshold + ': ' + (out.reason || '');\n} else {\n  decision_reason = 'AI agent allowed it (risk ' + (Number.isNaN(risk) ? 'n/a' : risk) + '/' + threshold + '): ' + (out.reason || '');\n}\nreturn [{ json: {\n  ...req,\n  status: 'PROCESSING',\n  agent_verdict: out.verdict || '',\n  risk_score: Number.isNaN(risk) ? '' : risk,\n  decision, decision_reason,\n} }];",
        "mode": "runOnceForAllItems"
      },
      "id": "069fde99-8fd4-42bb-9a11-c731573f74c6",
      "name": "Code — Build Agent Decision",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1920,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "id": "3e4e4a2c-737d-4c53-b0b7-6ed2890e486a",
              "leftValue": "={{ $json.decision }}",
              "rightValue": "allow",
              "operator": {
                "type": "string",
                "operation": "equals",
                "name": "filter.operator.string.equals"
              }
            }
          ],
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          }
        },
        "options": {}
      },
      "id": "c770e848-3549-4cb1-9226-a5e92e671bbf",
      "name": "IF — Agent Allows?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        2160,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('CONFIG \\u2014 Guard Policy').first().json.target_endpoint_url }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Idempotency-Key",
              "value": "={{ $json.idempotency_key }}"
            },
            {
              "name": "Authorization",
              "value": "=Bearer {{ $('CONFIG \\u2014 Guard Policy').first().json.target_api_key }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "contentType": "json",
        "specifyBody": "json",
        "jsonBody": "= {{ JSON.stringify({ action_type: $json.action_type, recipient: $json.recipient, payload: $json.payload, idempotency_key: $json.idempotency_key }) }}",
        "options": {}
      },
      "id": "109bdad4-2347-484a-9243-06741d003215",
      "name": "HTTP Request — Execute Target Action",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2400,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// The target endpoint must confirm success; anything else is FAILED,\n// and a FAILED row is visible in the ledger (never silently marked DONE).\nconst res = $input.first().json;\nconst req = $('Code \\u2014 Build Agent Decision').first().json;\nconst ok = !!(res && (res.ok === true || res.success === true\n  || [200, 201, 202].includes(Number(res.statusCode || res.status))));\nreturn [{ json: {\n  ...req,\n  status: ok ? 'DONE' : 'FAILED',\n  provider_ref: (res && (res.id || res.message_id || res.reference || '')) || '',\n  decision_reason: ok ? req.decision_reason\n    : 'Target endpoint did not confirm success: ' + JSON.stringify(res).slice(0, 200),\n} }];",
        "mode": "runOnceForAllItems"
      },
      "id": "79cca454-4e89-4da0-b77c-96bc3b5fab6a",
      "name": "Code — Verify Execution",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2640,
        300
      ]
    },
    {
      "parameters": {
        "operation": "update",
        "resource": "sheetWithinDocument",
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Guard Ledger"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "idempotency_key"
          ],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false,
          "value": {
            "idempotency_key": "={{ $json.idempotency_key }}",
            "status": "={{ $json.status }}",
            "cost_usd": "={{ $json.cost_usd }}",
            "decision_reason": "={{ $json.decision_reason }}",
            "provider_ref": "={{ $json.provider_ref }}"
          }
        },
        "options": {}
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "",
          "name": "Google Sheets API"
        }
      },
      "id": "b8e8ba10-b3d5-4eae-90b0-0dc54fd98ede",
      "name": "Google Sheets — Update Ledger DONE",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        2880,
        300
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "= {{ JSON.stringify({ allowed: $json.status === 'DONE', status: $json.status, idempotency_key: $json.idempotency_key, decision_reason: $json.decision_reason || '', provider_ref: $json.provider_ref || '' }) }}",
        "options": {}
      },
      "id": "e091d274-b446-4e1e-9f42-fd19fe4f9783",
      "name": "Respond to Webhook — Allowed",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        3120,
        300
      ]
    },
    {
      "parameters": {
        "chatId": "={{ $('CONFIG \\u2014 Guard Policy').first().json.telegram_chat_id }}",
        "text": "=\\U0001F6E1\\uFE0F *Guard decision: {{ $json.status }}*\\n\\nAction: {{ $json.action_type }}\\nClient: {{ $json.client_id }}\\nRecipient: {{ $json.recipient }}\\nCost: ${{ $json.cost_usd }} (month spend: ${{ $json.month_spend }})\\nReason: {{ $json.decision_reason }}\\nProvider ref: {{ $json.provider_ref }}",
        "additionalFields": {
          "parse_mode": "Markdown"
        }
      },
      "credentials": {
        "telegramApi": {
          "id": "",
          "name": "Telegram Bot API"
        }
      },
      "id": "a0f47d95-cfe6-4d34-95f1-1b719b0fca2e",
      "name": "Telegram — Guard Decision Summary",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        3360,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "const j = $input.first().json;\nreturn [{ json: { ...j, status: j.guard_status || 'BLOCKED', provider_ref: '' } }];",
        "mode": "runOnceForAllItems"
      },
      "id": "76fc63d7-1009-409f-b4b4-0a1c2461d697",
      "name": "Code — Set Blocked Status",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1440,
        760
      ]
    },
    {
      "parameters": {
        "operation": "update",
        "resource": "sheetWithinDocument",
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Guard Ledger"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "idempotency_key"
          ],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false,
          "value": {
            "idempotency_key": "={{ $json.idempotency_key }}",
            "status": "={{ $json.status }}",
            "cost_usd": "={{ $json.cost_usd }}",
            "decision_reason": "={{ $json.decision_reason }}",
            "provider_ref": "={{ $json.provider_ref }}"
          }
        },
        "options": {}
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "",
          "name": "Google Sheets API"
        }
      },
      "id": "3bcf1f8c-db25-4d9f-8f0a-dca022e1b87a",
      "name": "Google Sheets — Update Ledger BLOCKED",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1680,
        760
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "= {{ JSON.stringify({ allowed: false, status: $json.status, idempotency_key: $json.idempotency_key, decision_reason: $json.decision_reason || '' }) }}",
        "options": {}
      },
      "id": "23e0001d-e3ec-40bd-a3ad-b3d097daf24e",
      "name": "Respond to Webhook — Blocked",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        2640,
        760
      ]
    },
    {
      "parameters": {
        "chatId": "={{ $('CONFIG \\u2014 Guard Policy').first().json.telegram_chat_id }}",
        "text": "=\\U0001F6A8 *Guard BLOCKED an action*\\n\\nStatus: {{ $json.status }}\\nAction: {{ $json.action_type }}\\nClient: {{ $json.client_id }}\\nRecipient: {{ $json.recipient }}\\nReason: {{ $json.decision_reason }}\\n\\nNothing was executed.",
        "additionalFields": {
          "parse_mode": "Markdown"
        }
      },
      "credentials": {
        "telegramApi": {
          "id": "",
          "name": "Telegram Bot API"
        }
      },
      "id": "c858997e-8a83-451e-b75e-93fe1ac350a7",
      "name": "Telegram — Guard Blocked Alert",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        2880,
        760
      ]
    },
    {
      "parameters": {
        "jsCode": "const j = $input.first().json;\nreturn [{ json: { ...j, status: 'BLOCKED_AGENT', provider_ref: '' } }];",
        "mode": "runOnceForAllItems"
      },
      "id": "f7c999ff-1f23-4360-957d-692253f36932",
      "name": "Code — Set Agent Blocked",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2160,
        940
      ]
    },
    {
      "parameters": {
        "operation": "update",
        "resource": "sheetWithinDocument",
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Guard Ledger"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "idempotency_key"
          ],
          "schema": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false,
          "value": {
            "idempotency_key": "={{ $json.idempotency_key }}",
            "status": "={{ $json.status }}",
            "cost_usd": "={{ $json.cost_usd }}",
            "decision_reason": "={{ $json.decision_reason }}",
            "provider_ref": "={{ $json.provider_ref }}"
          }
        },
        "options": {}
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "",
          "name": "Google Sheets API"
        }
      },
      "id": "483a16b8-3321-4219-ab11-fd87693f794d",
      "name": "Google Sheets — Update Ledger BLOCKED_AGENT",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        2400,
        940
      ]
    }
  ],
  "connections": {
    "Webhook — Guard Request": {
      "main": [
        [
          {
            "node": "CONFIG — Guard Policy",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "CONFIG — Guard Policy": {
      "main": [
        [
          {
            "node": "Code — Normalize Request & Idempotency Key",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code — Normalize Request & Idempotency Key": {
      "main": [
        [
          {
            "node": "Google Sheets — Log Request NEW",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets — Log Request NEW": {
      "main": [
        [
          {
            "node": "Google Sheets — Read Guard Ledger",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets — Read Guard Ledger": {
      "main": [
        [
          {
            "node": "Code — Check Guard Rules",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code — Check Guard Rules": {
      "main": [
        [
          {
            "node": "IF — Guard Blocked?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF — Guard Blocked?": {
      "main": [
        [
          {
            "node": "Code — Set Blocked Status",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "AI Agent — Risk Review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code — Set Blocked Status": {
      "main": [
        [
          {
            "node": "Google Sheets — Update Ledger BLOCKED",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets — Update Ledger BLOCKED": {
      "main": [
        [
          {
            "node": "Respond to Webhook — Blocked",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Respond to Webhook — Blocked": {
      "main": [
        [
          {
            "node": "Telegram — Guard Blocked Alert",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent — Risk Review": {
      "main": [
        [
          {
            "node": "Code — Build Agent Decision",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code — Build Agent Decision": {
      "main": [
        [
          {
            "node": "IF — Agent Allows?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF — Agent Allows?": {
      "main": [
        [
          {
            "node": "HTTP Request — Execute Target Action",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Code — Set Agent Blocked",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code — Set Agent Blocked": {
      "main": [
        [
          {
            "node": "Google Sheets — Update Ledger BLOCKED_AGENT",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets — Update Ledger BLOCKED_AGENT": {
      "main": [
        [
          {
            "node": "Respond to Webhook — Blocked",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP Request — Execute Target Action": {
      "main": [
        [
          {
            "node": "Code — Verify Execution",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code — Verify Execution": {
      "main": [
        [
          {
            "node": "Google Sheets — Update Ledger DONE",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets — Update Ledger DONE": {
      "main": [
        [
          {
            "node": "Respond to Webhook — Allowed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Respond to Webhook — Allowed": {
      "main": [
        [
          {
            "node": "Telegram — Guard Decision Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model — Risk Review": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent — Risk Review",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parser — Risk Verdict": {
      "ai_outputParser": [
        [
          {
            "node": "AI Agent — Risk Review",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "cortexflow-ai-agent-safety-guard-v1",
  "meta": {
    "templateCredsSetupCompleted": false,
    "instanceId": ""
  },
  "pinData": {},
  "tags": [
    {
      "name": "cortexflow-template"
    }
  ]
}