{
  "app": {
    "name": "Oneport HTTP request recovery",
    "description": "Manual non-streaming recovery. Select the same original key; fill the secret environment variable before running.",
    "icon": "📝",
    "icon_background": "#E4FBCC",
    "mode": "workflow",
    "use_icon_as_answer_icon": false
  },
  "kind": "app",
  "version": "0.7.0",
  "dependencies": [],
  "workflow": {
    "conversation_variables": [],
    "environment_variables": [
      {
        "id": "06cb1448-07ae-4455-8178-a0e2be52a9e9",
        "name": "ONEPORT_BASE_URL",
        "value": "https://oneport.kr/v1",
        "value_type": "string",
        "description": "Trusted workflow configuration; not caller input"
      },
      {
        "id": "88256168-3f9b-4d09-8a4c-d63c45f0ba61",
        "name": "ONEPORT_API_KEY",
        "value": "",
        "value_type": "secret",
        "description": "Original key or its normal Oneport rotation successor"
      }
    ],
    "features": {
      "file_upload": {
        "enabled": false
      },
      "opening_statement": "",
      "retriever_resource": {
        "enabled": false
      },
      "sensitive_word_avoidance": {
        "enabled": false
      },
      "speech_to_text": {
        "enabled": false
      },
      "suggested_questions": [],
      "suggested_questions_after_answer": {
        "enabled": false
      },
      "text_to_speech": {
        "enabled": false
      }
    },
    "graph": {
      "nodes": [
        {
          "id": "start",
          "type": "custom",
          "position": {
            "x": 0,
            "y": 0
          },
          "data": {
            "type": "start",
            "title": "Original task",
            "selected": false,
            "variables": [
              {
                "variable": "job_id",
                "label": "Original opaque job ID",
                "type": "text-input",
                "required": true,
                "max_length": 200
              },
              {
                "variable": "mode",
                "label": "Action",
                "type": "select",
                "options": [
                  "send",
                  "resume",
                  "retry-not-started"
                ],
                "default": "send",
                "required": true
              },
              {
                "variable": "request_json",
                "label": "Original Chat Completions JSON (stream:false)",
                "type": "paragraph",
                "required": false,
                "max_length": 48000
              },
              {
                "variable": "vendor_headers_json",
                "label": "Original vendor headers JSON",
                "type": "paragraph",
                "required": false,
                "default": "{}",
                "max_length": 4000
              },
              {
                "variable": "recovery_json",
                "label": "Recovery metadata from the prior output",
                "type": "paragraph",
                "required": false,
                "max_length": 2000
              }
            ]
          }
        },
        {
          "id": "prepare",
          "type": "custom",
          "position": {
            "x": 300,
            "y": 0
          },
          "data": {
            "type": "code",
            "title": "Prepare original request",
            "selected": false,
            "code_language": "python3",
            "code": "\"\"\"Pure code-node transformations. HTTP nodes own all network requests.\"\"\"\nimport hashlib\nimport json\nimport math\nimport re\n\n\ndef encoded(value):\n    return json.dumps(value, ensure_ascii=False, separators=(',', ':'), allow_nan=False)\n\n\ndef status_target(base, value, expected=None):\n    origin = base[:-3]\n    value = str(value or '')\n    path = value[len(origin):] if value.startswith(origin + '/') else value\n    match = re.fullmatch(r'/v1/requests/([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})', path, re.I)\n    if not match or (expected and expected.lower() != match[1].lower()):\n        raise ValueError('Invalid status address')\n    return {'requestId': match[1].lower(), 'statusUrl': origin + '/v1/requests/' + match[1].lower()}\n\n\ndef http_fields(prepared):\n    return {'prepared_json': encoded(prepared), 'method': prepared['method'], 'url': prepared['url'],\n            'header_lines': '\\n'.join(key + ':' + value for key, value in prepared['headers'].items()),\n            'body_json': encoded(prepared['body']), 'items': [{}]}\n\n\ndef prepare(base_url, job_id, mode, request_json, vendor_headers_json='', recovery_json=''):\n    base = base_url.rstrip('/')\n    if base != 'https://oneport.kr/v1' and not re.fullmatch(r'http://127\\.0\\.0\\.1:[1-9][0-9]{0,4}/v1', base):\n        raise ValueError('Use the Oneport URL or a loopback test fixture')\n    if not job_id.strip() or job_id == 'SET_LOGICAL_JOB_ID':\n        raise ValueError('Set the original opaque job ID')\n    if mode not in ('send', 'resume', 'retry-not-started'):\n        raise ValueError('Choose send, resume or retry-not-started')\n    body = json.loads(request_json or 'null')\n    if body is not None and (not isinstance(body, dict) or body.get('stream') is not False\n                             or not isinstance(body.get('model'), str) or body['model'] == 'SET_CHAT_MODEL_ID'):\n        raise ValueError('Use the original non-streaming Chat Completions JSON')\n    names = ('anthropic-beta', 'anthropic-version', 'openai-beta')\n    headers = {}\n    for key, value in json.loads(vendor_headers_json or '{}').items():\n        if key.lower() not in names or not isinstance(value, str) or re.search(r'[\\x00-\\x1f\\x7f]', value):\n            raise ValueError('Unsupported vendor header')\n        headers[key.lower()] = value.strip()\n    key = 'oneport-' + hashlib.sha256(job_id.encode()).hexdigest()\n    canonical_body = json.loads(json.dumps(body, ensure_ascii=False, sort_keys=True, allow_nan=False))\n    fingerprint = hashlib.sha256(encoded({'endpoint': base + '/chat/completions', 'body': canonical_body,\n                                         'headers': [[name, headers.get(name)] for name in names]}).encode()).hexdigest()\n    saved = json.loads(recovery_json or '{}')\n    if not isinstance(saved, dict) or set(saved) - {'idempotencyKey', 'fingerprint', 'requestId', 'statusUrl'}:\n        raise ValueError('Invalid recovery metadata')\n    if saved and (saved.get('idempotencyKey') != key or not re.fullmatch(r'[0-9a-f]{64}', str(saved.get('fingerprint', '')))\n                  or (('requestId' in saved) != ('statusUrl' in saved))):\n        raise ValueError('Recovery metadata does not match this job')\n    if mode == 'send' and saved:\n        raise ValueError('Use resume for an existing job')\n    if mode != 'send' and not saved:\n        raise ValueError('Provide the original recovery metadata')\n    if mode == 'retry-not-started' and not saved.get('statusUrl'):\n        raise ValueError('Recover the receipt first')\n    method = 'GET' if saved.get('statusUrl') else 'POST'\n    if method == 'POST' or mode == 'retry-not-started':\n        if body is None or (saved and saved['fingerprint'] != fingerprint):\n            raise ValueError('Provide the unchanged original request and vendor headers')\n    recovery = saved or {'idempotencyKey': key, 'fingerprint': fingerprint}\n    url = status_target(base, recovery['statusUrl'], recovery['requestId'])['statusUrl'] if method == 'GET' else base + '/chat/completions'\n    prepared = {'base': base, 'body': body, 'vendorHeaders': headers, 'mode': mode, 'recovery': recovery, 'method': method,\n                'url': url, 'headers': {**headers, 'Idempotency-Key': key} if method == 'POST' else {}, 'answer': ''}\n    return http_fields(prepared)\n\n\ndef response_of(responses):\n    return responses[0] if responses and isinstance(responses[0], dict) else {}\n\n\ndef body_of(response):\n    try:\n        value = response.get('body')\n        return json.loads(value) if isinstance(value, str) else value or {}\n    except (TypeError, ValueError):\n        return {}\n\n\ndef finish(prepared, state, action, request_status=None):\n    result = {'state': state, 'action': action, 'recovery': prepared['recovery'], 'response_stored': False}\n    if prepared.get('answer'):\n        result['answer'] = prepared['answer']\n    if request_status is not None:\n        result['requestStatus'] = request_status\n    return {'next': 'finish', 'result_json': encoded(result), **http_fields(prepared)}\n\n\ndef after_post(prepared_json, responses):\n    prepared = json.loads(prepared_json)\n    response = response_of(responses)\n    body = body_of(response)\n    headers = {key.lower(): value for key, value in response.get('headers', {}).items()}\n    status = response.get('statusCode', 0)\n    error = body.get('error', {}) if isinstance(body, dict) and isinstance(body.get('error', {}), dict) else {}\n    url = headers.get('x-gateway-status-url') or ((headers.get('location') or error.get('status_url')) if status >= 400 else None)\n    if url:\n        try:\n            prepared['recovery'] = {**prepared['recovery'], **status_target(prepared['base'], url, headers.get('x-gateway-request-id'))}\n        except (TypeError, ValueError):\n            return finish(prepared, 'recovery_required', 'invalid_status_address')\n    choices = body.get('choices', []) if isinstance(body, dict) else []\n    if 200 <= status < 300 and choices and isinstance(choices[0].get('message', {}).get('content'), str):\n        prepared['answer'] = choices[0]['message']['content']\n    if not prepared['recovery'].get('statusUrl'):\n        return finish(prepared, 'recovery_required', 'resume_same_request_may_execute')\n    prepared.update(method='GET', url=prepared['recovery']['statusUrl'], headers={})\n    return {'next': 'inspect', 'result_json': '', **http_fields(prepared)}\n\n\ndef status_view(value, expected):\n    if (not isinstance(value, dict) or value.get('id') != expected or value.get('object') != 'gateway.request'\n            or value.get('response_stored') is not False\n            or value.get('execution') not in ('claimed', 'started', 'unknown', 'not_started', 'finished')\n            or not isinstance(value.get('result'), dict) or value['result'].get('state') not in ('unknown', 'completed', 'failed', 'partial')\n            or not isinstance(value.get('settlement'), dict) or value['settlement'].get('state') not in ('unknown', 'settled', 'not_charged')):\n        return None\n    settlement = {'state': value['settlement']['state']}\n    for key in ('cost_credits', 'cost_usd'):\n        if key not in value['settlement']:\n            continue\n        amount = value['settlement'][key]\n        if amount is None or (type(amount) in (int, float) and math.isfinite(amount) and amount >= 0):\n            settlement[key] = amount\n    return {'id': expected, 'execution': value['execution'], 'result': {'state': value['result']['state']},\n            'settlement': settlement, 'response_stored': False}\n\n\ndef after_get(prepared_json, responses, allow_retry=True):\n    prepared = json.loads(prepared_json)\n    response = response_of(responses)\n    view = status_view(body_of(response), prepared['recovery']['requestId']) if response.get('statusCode') == 200 else None\n    if view is None:\n        return finish(prepared, 'status_unavailable', 'resume_status_without_new_generation')\n    if view['execution'] == 'not_started' and view['settlement']['state'] == 'not_charged':\n        if allow_retry and prepared['mode'] == 'retry-not-started':\n            prepared['recovery'] = {key: prepared['recovery'][key] for key in ('idempotencyKey', 'fingerprint')}\n            prepared.update(method='POST', url=prepared['base'] + '/chat/completions',\n                            headers={**prepared['vendorHeaders'], 'Idempotency-Key': prepared['recovery']['idempotencyKey']})\n            return {'next': 'retry', 'result_json': '', **http_fields(prepared)}\n        return finish(prepared, 'retry_available', 'retry_not_started_with_original_input', view)\n    completed = view['result']['state'] == 'completed'\n    return finish(prepared, 'completed' if completed else 'unconfirmed',\n                  ('fresh_answer_received' if prepared.get('answer') else 'answer_not_stored') if completed else 'resume_status_without_new_generation', view)\n\ndef main(base_url, job_id, mode, request_json=\"\", vendor_headers_json=\"\", recovery_json=\"\"):\n    return prepare(base_url, job_id, mode, request_json, vendor_headers_json, recovery_json)",
            "variables": [
              {
                "variable": "base_url",
                "value_selector": [
                  "env",
                  "ONEPORT_BASE_URL"
                ]
              },
              {
                "variable": "job_id",
                "value_selector": [
                  "start",
                  "job_id"
                ]
              },
              {
                "variable": "mode",
                "value_selector": [
                  "start",
                  "mode"
                ]
              },
              {
                "variable": "request_json",
                "value_selector": [
                  "start",
                  "request_json"
                ]
              },
              {
                "variable": "vendor_headers_json",
                "value_selector": [
                  "start",
                  "vendor_headers_json"
                ]
              },
              {
                "variable": "recovery_json",
                "value_selector": [
                  "start",
                  "recovery_json"
                ]
              }
            ],
            "outputs": {
              "prepared_json": {
                "type": "string"
              },
              "method": {
                "type": "string"
              },
              "url": {
                "type": "string"
              },
              "header_lines": {
                "type": "string"
              },
              "body_json": {
                "type": "string"
              },
              "items": {
                "type": "array[object]"
              }
            },
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          }
        },
        {
          "id": "initial_method",
          "type": "custom",
          "position": {
            "x": 600,
            "y": 0
          },
          "data": {
            "type": "if-else",
            "title": "Submit or inspect?",
            "selected": false,
            "cases": [
              {
                "case_id": "yes",
                "logical_operator": "and",
                "conditions": [
                  {
                    "variable_selector": [
                      "prepare",
                      "method"
                    ],
                    "comparison_operator": "is",
                    "value": "POST"
                  }
                ]
              }
            ]
          }
        },
        {
          "id": "initial_post",
          "type": "custom",
          "position": {
            "x": 900,
            "y": -250
          },
          "data": {
            "type": "iteration",
            "title": "Oneport POST",
            "selected": false,
            "start_node_id": "initial_post_start",
            "iterator_selector": [
              "prepare",
              "items"
            ],
            "output_selector": [
              "initial_post_capture",
              "response"
            ],
            "is_parallel": false,
            "parallel_nums": 1,
            "error_handle_mode": "continue-on-error",
            "flatten_output": false
          },
          "width": 650,
          "height": 260
        },
        {
          "id": "initial_post_start",
          "type": "custom",
          "position": {
            "x": 40,
            "y": 70
          },
          "data": {
            "type": "iteration-start",
            "title": "One request",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "initial_post"
          },
          "parentId": "initial_post",
          "extent": "parent"
        },
        {
          "id": "initial_post_http",
          "type": "custom",
          "position": {
            "x": 220,
            "y": 70
          },
          "data": {
            "type": "http-request",
            "title": "Oneport POST",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "initial_post",
            "method": "post",
            "url": "{{#prepare.url#}}",
            "authorization": {
              "type": "api-key",
              "config": {
                "type": "bearer",
                "api_key": "{{#env.ONEPORT_API_KEY#}}"
              }
            },
            "headers": "{{#prepare.header_lines#}}",
            "params": "",
            "body": {
              "type": "json",
              "data": [
                {
                  "key": "",
                  "type": "text",
                  "value": "{{#prepare.body_json#}}"
                }
              ]
            },
            "timeout": {
              "connect": 10,
              "read": 300,
              "write": 300
            },
            "ssl_verify": true,
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          },
          "parentId": "initial_post",
          "extent": "parent"
        },
        {
          "id": "initial_post_capture",
          "type": "custom",
          "position": {
            "x": 440,
            "y": 70
          },
          "data": {
            "type": "code",
            "title": "Keep HTTP response",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "initial_post",
            "code_language": "python3",
            "code": "def main(status_code, headers, body):\n    return {\"response\": {\"statusCode\": status_code, \"headers\": headers, \"body\": body}}",
            "variables": [
              {
                "variable": "status_code",
                "value_selector": [
                  "initial_post_http",
                  "status_code"
                ]
              },
              {
                "variable": "headers",
                "value_selector": [
                  "initial_post_http",
                  "headers"
                ]
              },
              {
                "variable": "body",
                "value_selector": [
                  "initial_post_http",
                  "body"
                ]
              }
            ],
            "outputs": {
              "response": {
                "type": "object"
              }
            },
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          },
          "parentId": "initial_post",
          "extent": "parent"
        },
        {
          "id": "post_result",
          "type": "custom",
          "position": {
            "x": 1600,
            "y": -250
          },
          "data": {
            "type": "code",
            "title": "Capture receipt",
            "selected": false,
            "code_language": "python3",
            "code": "\"\"\"Pure code-node transformations. HTTP nodes own all network requests.\"\"\"\nimport hashlib\nimport json\nimport math\nimport re\n\n\ndef encoded(value):\n    return json.dumps(value, ensure_ascii=False, separators=(',', ':'), allow_nan=False)\n\n\ndef status_target(base, value, expected=None):\n    origin = base[:-3]\n    value = str(value or '')\n    path = value[len(origin):] if value.startswith(origin + '/') else value\n    match = re.fullmatch(r'/v1/requests/([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})', path, re.I)\n    if not match or (expected and expected.lower() != match[1].lower()):\n        raise ValueError('Invalid status address')\n    return {'requestId': match[1].lower(), 'statusUrl': origin + '/v1/requests/' + match[1].lower()}\n\n\ndef http_fields(prepared):\n    return {'prepared_json': encoded(prepared), 'method': prepared['method'], 'url': prepared['url'],\n            'header_lines': '\\n'.join(key + ':' + value for key, value in prepared['headers'].items()),\n            'body_json': encoded(prepared['body']), 'items': [{}]}\n\n\ndef prepare(base_url, job_id, mode, request_json, vendor_headers_json='', recovery_json=''):\n    base = base_url.rstrip('/')\n    if base != 'https://oneport.kr/v1' and not re.fullmatch(r'http://127\\.0\\.0\\.1:[1-9][0-9]{0,4}/v1', base):\n        raise ValueError('Use the Oneport URL or a loopback test fixture')\n    if not job_id.strip() or job_id == 'SET_LOGICAL_JOB_ID':\n        raise ValueError('Set the original opaque job ID')\n    if mode not in ('send', 'resume', 'retry-not-started'):\n        raise ValueError('Choose send, resume or retry-not-started')\n    body = json.loads(request_json or 'null')\n    if body is not None and (not isinstance(body, dict) or body.get('stream') is not False\n                             or not isinstance(body.get('model'), str) or body['model'] == 'SET_CHAT_MODEL_ID'):\n        raise ValueError('Use the original non-streaming Chat Completions JSON')\n    names = ('anthropic-beta', 'anthropic-version', 'openai-beta')\n    headers = {}\n    for key, value in json.loads(vendor_headers_json or '{}').items():\n        if key.lower() not in names or not isinstance(value, str) or re.search(r'[\\x00-\\x1f\\x7f]', value):\n            raise ValueError('Unsupported vendor header')\n        headers[key.lower()] = value.strip()\n    key = 'oneport-' + hashlib.sha256(job_id.encode()).hexdigest()\n    canonical_body = json.loads(json.dumps(body, ensure_ascii=False, sort_keys=True, allow_nan=False))\n    fingerprint = hashlib.sha256(encoded({'endpoint': base + '/chat/completions', 'body': canonical_body,\n                                         'headers': [[name, headers.get(name)] for name in names]}).encode()).hexdigest()\n    saved = json.loads(recovery_json or '{}')\n    if not isinstance(saved, dict) or set(saved) - {'idempotencyKey', 'fingerprint', 'requestId', 'statusUrl'}:\n        raise ValueError('Invalid recovery metadata')\n    if saved and (saved.get('idempotencyKey') != key or not re.fullmatch(r'[0-9a-f]{64}', str(saved.get('fingerprint', '')))\n                  or (('requestId' in saved) != ('statusUrl' in saved))):\n        raise ValueError('Recovery metadata does not match this job')\n    if mode == 'send' and saved:\n        raise ValueError('Use resume for an existing job')\n    if mode != 'send' and not saved:\n        raise ValueError('Provide the original recovery metadata')\n    if mode == 'retry-not-started' and not saved.get('statusUrl'):\n        raise ValueError('Recover the receipt first')\n    method = 'GET' if saved.get('statusUrl') else 'POST'\n    if method == 'POST' or mode == 'retry-not-started':\n        if body is None or (saved and saved['fingerprint'] != fingerprint):\n            raise ValueError('Provide the unchanged original request and vendor headers')\n    recovery = saved or {'idempotencyKey': key, 'fingerprint': fingerprint}\n    url = status_target(base, recovery['statusUrl'], recovery['requestId'])['statusUrl'] if method == 'GET' else base + '/chat/completions'\n    prepared = {'base': base, 'body': body, 'vendorHeaders': headers, 'mode': mode, 'recovery': recovery, 'method': method,\n                'url': url, 'headers': {**headers, 'Idempotency-Key': key} if method == 'POST' else {}, 'answer': ''}\n    return http_fields(prepared)\n\n\ndef response_of(responses):\n    return responses[0] if responses and isinstance(responses[0], dict) else {}\n\n\ndef body_of(response):\n    try:\n        value = response.get('body')\n        return json.loads(value) if isinstance(value, str) else value or {}\n    except (TypeError, ValueError):\n        return {}\n\n\ndef finish(prepared, state, action, request_status=None):\n    result = {'state': state, 'action': action, 'recovery': prepared['recovery'], 'response_stored': False}\n    if prepared.get('answer'):\n        result['answer'] = prepared['answer']\n    if request_status is not None:\n        result['requestStatus'] = request_status\n    return {'next': 'finish', 'result_json': encoded(result), **http_fields(prepared)}\n\n\ndef after_post(prepared_json, responses):\n    prepared = json.loads(prepared_json)\n    response = response_of(responses)\n    body = body_of(response)\n    headers = {key.lower(): value for key, value in response.get('headers', {}).items()}\n    status = response.get('statusCode', 0)\n    error = body.get('error', {}) if isinstance(body, dict) and isinstance(body.get('error', {}), dict) else {}\n    url = headers.get('x-gateway-status-url') or ((headers.get('location') or error.get('status_url')) if status >= 400 else None)\n    if url:\n        try:\n            prepared['recovery'] = {**prepared['recovery'], **status_target(prepared['base'], url, headers.get('x-gateway-request-id'))}\n        except (TypeError, ValueError):\n            return finish(prepared, 'recovery_required', 'invalid_status_address')\n    choices = body.get('choices', []) if isinstance(body, dict) else []\n    if 200 <= status < 300 and choices and isinstance(choices[0].get('message', {}).get('content'), str):\n        prepared['answer'] = choices[0]['message']['content']\n    if not prepared['recovery'].get('statusUrl'):\n        return finish(prepared, 'recovery_required', 'resume_same_request_may_execute')\n    prepared.update(method='GET', url=prepared['recovery']['statusUrl'], headers={})\n    return {'next': 'inspect', 'result_json': '', **http_fields(prepared)}\n\n\ndef status_view(value, expected):\n    if (not isinstance(value, dict) or value.get('id') != expected or value.get('object') != 'gateway.request'\n            or value.get('response_stored') is not False\n            or value.get('execution') not in ('claimed', 'started', 'unknown', 'not_started', 'finished')\n            or not isinstance(value.get('result'), dict) or value['result'].get('state') not in ('unknown', 'completed', 'failed', 'partial')\n            or not isinstance(value.get('settlement'), dict) or value['settlement'].get('state') not in ('unknown', 'settled', 'not_charged')):\n        return None\n    settlement = {'state': value['settlement']['state']}\n    for key in ('cost_credits', 'cost_usd'):\n        if key not in value['settlement']:\n            continue\n        amount = value['settlement'][key]\n        if amount is None or (type(amount) in (int, float) and math.isfinite(amount) and amount >= 0):\n            settlement[key] = amount\n    return {'id': expected, 'execution': value['execution'], 'result': {'state': value['result']['state']},\n            'settlement': settlement, 'response_stored': False}\n\n\ndef after_get(prepared_json, responses, allow_retry=True):\n    prepared = json.loads(prepared_json)\n    response = response_of(responses)\n    view = status_view(body_of(response), prepared['recovery']['requestId']) if response.get('statusCode') == 200 else None\n    if view is None:\n        return finish(prepared, 'status_unavailable', 'resume_status_without_new_generation')\n    if view['execution'] == 'not_started' and view['settlement']['state'] == 'not_charged':\n        if allow_retry and prepared['mode'] == 'retry-not-started':\n            prepared['recovery'] = {key: prepared['recovery'][key] for key in ('idempotencyKey', 'fingerprint')}\n            prepared.update(method='POST', url=prepared['base'] + '/chat/completions',\n                            headers={**prepared['vendorHeaders'], 'Idempotency-Key': prepared['recovery']['idempotencyKey']})\n            return {'next': 'retry', 'result_json': '', **http_fields(prepared)}\n        return finish(prepared, 'retry_available', 'retry_not_started_with_original_input', view)\n    completed = view['result']['state'] == 'completed'\n    return finish(prepared, 'completed' if completed else 'unconfirmed',\n                  ('fresh_answer_received' if prepared.get('answer') else 'answer_not_stored') if completed else 'resume_status_without_new_generation', view)\n\ndef main(prepared_json, responses):\n    return after_post(prepared_json, responses)",
            "variables": [
              {
                "variable": "prepared_json",
                "value_selector": [
                  "prepare",
                  "prepared_json"
                ]
              },
              {
                "variable": "responses",
                "value_selector": [
                  "initial_post",
                  "output"
                ]
              }
            ],
            "outputs": {
              "prepared_json": {
                "type": "string"
              },
              "method": {
                "type": "string"
              },
              "url": {
                "type": "string"
              },
              "header_lines": {
                "type": "string"
              },
              "body_json": {
                "type": "string"
              },
              "items": {
                "type": "array[object]"
              },
              "next": {
                "type": "string"
              },
              "result_json": {
                "type": "string"
              }
            },
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          }
        },
        {
          "id": "post_has_receipt",
          "type": "custom",
          "position": {
            "x": 1900,
            "y": -250
          },
          "data": {
            "type": "if-else",
            "title": "Receipt received?",
            "selected": false,
            "cases": [
              {
                "case_id": "yes",
                "logical_operator": "and",
                "conditions": [
                  {
                    "variable_selector": [
                      "post_result",
                      "next"
                    ],
                    "comparison_operator": "is",
                    "value": "inspect"
                  }
                ]
              }
            ]
          }
        },
        {
          "id": "post_status",
          "type": "custom",
          "position": {
            "x": 2200,
            "y": -450
          },
          "data": {
            "type": "iteration",
            "title": "Inspect accepted request",
            "selected": false,
            "start_node_id": "post_status_start",
            "iterator_selector": [
              "post_result",
              "items"
            ],
            "output_selector": [
              "post_status_capture",
              "response"
            ],
            "is_parallel": false,
            "parallel_nums": 1,
            "error_handle_mode": "continue-on-error",
            "flatten_output": false
          },
          "width": 650,
          "height": 260
        },
        {
          "id": "post_status_start",
          "type": "custom",
          "position": {
            "x": 40,
            "y": 70
          },
          "data": {
            "type": "iteration-start",
            "title": "One request",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "post_status"
          },
          "parentId": "post_status",
          "extent": "parent"
        },
        {
          "id": "post_status_http",
          "type": "custom",
          "position": {
            "x": 220,
            "y": 70
          },
          "data": {
            "type": "http-request",
            "title": "Inspect accepted request",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "post_status",
            "method": "get",
            "url": "{{#post_result.url#}}",
            "authorization": {
              "type": "api-key",
              "config": {
                "type": "bearer",
                "api_key": "{{#env.ONEPORT_API_KEY#}}"
              }
            },
            "headers": "{{#post_result.header_lines#}}",
            "params": "",
            "body": {
              "type": "none",
              "data": []
            },
            "timeout": {
              "connect": 10,
              "read": 300,
              "write": 300
            },
            "ssl_verify": true,
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          },
          "parentId": "post_status",
          "extent": "parent"
        },
        {
          "id": "post_status_capture",
          "type": "custom",
          "position": {
            "x": 440,
            "y": 70
          },
          "data": {
            "type": "code",
            "title": "Keep HTTP response",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "post_status",
            "code_language": "python3",
            "code": "def main(status_code, headers, body):\n    return {\"response\": {\"statusCode\": status_code, \"headers\": headers, \"body\": body}}",
            "variables": [
              {
                "variable": "status_code",
                "value_selector": [
                  "post_status_http",
                  "status_code"
                ]
              },
              {
                "variable": "headers",
                "value_selector": [
                  "post_status_http",
                  "headers"
                ]
              },
              {
                "variable": "body",
                "value_selector": [
                  "post_status_http",
                  "body"
                ]
              }
            ],
            "outputs": {
              "response": {
                "type": "object"
              }
            },
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          },
          "parentId": "post_status",
          "extent": "parent"
        },
        {
          "id": "post_status_result",
          "type": "custom",
          "position": {
            "x": 2900,
            "y": -450
          },
          "data": {
            "type": "code",
            "title": "Read accepted state",
            "selected": false,
            "code_language": "python3",
            "code": "\"\"\"Pure code-node transformations. HTTP nodes own all network requests.\"\"\"\nimport hashlib\nimport json\nimport math\nimport re\n\n\ndef encoded(value):\n    return json.dumps(value, ensure_ascii=False, separators=(',', ':'), allow_nan=False)\n\n\ndef status_target(base, value, expected=None):\n    origin = base[:-3]\n    value = str(value or '')\n    path = value[len(origin):] if value.startswith(origin + '/') else value\n    match = re.fullmatch(r'/v1/requests/([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})', path, re.I)\n    if not match or (expected and expected.lower() != match[1].lower()):\n        raise ValueError('Invalid status address')\n    return {'requestId': match[1].lower(), 'statusUrl': origin + '/v1/requests/' + match[1].lower()}\n\n\ndef http_fields(prepared):\n    return {'prepared_json': encoded(prepared), 'method': prepared['method'], 'url': prepared['url'],\n            'header_lines': '\\n'.join(key + ':' + value for key, value in prepared['headers'].items()),\n            'body_json': encoded(prepared['body']), 'items': [{}]}\n\n\ndef prepare(base_url, job_id, mode, request_json, vendor_headers_json='', recovery_json=''):\n    base = base_url.rstrip('/')\n    if base != 'https://oneport.kr/v1' and not re.fullmatch(r'http://127\\.0\\.0\\.1:[1-9][0-9]{0,4}/v1', base):\n        raise ValueError('Use the Oneport URL or a loopback test fixture')\n    if not job_id.strip() or job_id == 'SET_LOGICAL_JOB_ID':\n        raise ValueError('Set the original opaque job ID')\n    if mode not in ('send', 'resume', 'retry-not-started'):\n        raise ValueError('Choose send, resume or retry-not-started')\n    body = json.loads(request_json or 'null')\n    if body is not None and (not isinstance(body, dict) or body.get('stream') is not False\n                             or not isinstance(body.get('model'), str) or body['model'] == 'SET_CHAT_MODEL_ID'):\n        raise ValueError('Use the original non-streaming Chat Completions JSON')\n    names = ('anthropic-beta', 'anthropic-version', 'openai-beta')\n    headers = {}\n    for key, value in json.loads(vendor_headers_json or '{}').items():\n        if key.lower() not in names or not isinstance(value, str) or re.search(r'[\\x00-\\x1f\\x7f]', value):\n            raise ValueError('Unsupported vendor header')\n        headers[key.lower()] = value.strip()\n    key = 'oneport-' + hashlib.sha256(job_id.encode()).hexdigest()\n    canonical_body = json.loads(json.dumps(body, ensure_ascii=False, sort_keys=True, allow_nan=False))\n    fingerprint = hashlib.sha256(encoded({'endpoint': base + '/chat/completions', 'body': canonical_body,\n                                         'headers': [[name, headers.get(name)] for name in names]}).encode()).hexdigest()\n    saved = json.loads(recovery_json or '{}')\n    if not isinstance(saved, dict) or set(saved) - {'idempotencyKey', 'fingerprint', 'requestId', 'statusUrl'}:\n        raise ValueError('Invalid recovery metadata')\n    if saved and (saved.get('idempotencyKey') != key or not re.fullmatch(r'[0-9a-f]{64}', str(saved.get('fingerprint', '')))\n                  or (('requestId' in saved) != ('statusUrl' in saved))):\n        raise ValueError('Recovery metadata does not match this job')\n    if mode == 'send' and saved:\n        raise ValueError('Use resume for an existing job')\n    if mode != 'send' and not saved:\n        raise ValueError('Provide the original recovery metadata')\n    if mode == 'retry-not-started' and not saved.get('statusUrl'):\n        raise ValueError('Recover the receipt first')\n    method = 'GET' if saved.get('statusUrl') else 'POST'\n    if method == 'POST' or mode == 'retry-not-started':\n        if body is None or (saved and saved['fingerprint'] != fingerprint):\n            raise ValueError('Provide the unchanged original request and vendor headers')\n    recovery = saved or {'idempotencyKey': key, 'fingerprint': fingerprint}\n    url = status_target(base, recovery['statusUrl'], recovery['requestId'])['statusUrl'] if method == 'GET' else base + '/chat/completions'\n    prepared = {'base': base, 'body': body, 'vendorHeaders': headers, 'mode': mode, 'recovery': recovery, 'method': method,\n                'url': url, 'headers': {**headers, 'Idempotency-Key': key} if method == 'POST' else {}, 'answer': ''}\n    return http_fields(prepared)\n\n\ndef response_of(responses):\n    return responses[0] if responses and isinstance(responses[0], dict) else {}\n\n\ndef body_of(response):\n    try:\n        value = response.get('body')\n        return json.loads(value) if isinstance(value, str) else value or {}\n    except (TypeError, ValueError):\n        return {}\n\n\ndef finish(prepared, state, action, request_status=None):\n    result = {'state': state, 'action': action, 'recovery': prepared['recovery'], 'response_stored': False}\n    if prepared.get('answer'):\n        result['answer'] = prepared['answer']\n    if request_status is not None:\n        result['requestStatus'] = request_status\n    return {'next': 'finish', 'result_json': encoded(result), **http_fields(prepared)}\n\n\ndef after_post(prepared_json, responses):\n    prepared = json.loads(prepared_json)\n    response = response_of(responses)\n    body = body_of(response)\n    headers = {key.lower(): value for key, value in response.get('headers', {}).items()}\n    status = response.get('statusCode', 0)\n    error = body.get('error', {}) if isinstance(body, dict) and isinstance(body.get('error', {}), dict) else {}\n    url = headers.get('x-gateway-status-url') or ((headers.get('location') or error.get('status_url')) if status >= 400 else None)\n    if url:\n        try:\n            prepared['recovery'] = {**prepared['recovery'], **status_target(prepared['base'], url, headers.get('x-gateway-request-id'))}\n        except (TypeError, ValueError):\n            return finish(prepared, 'recovery_required', 'invalid_status_address')\n    choices = body.get('choices', []) if isinstance(body, dict) else []\n    if 200 <= status < 300 and choices and isinstance(choices[0].get('message', {}).get('content'), str):\n        prepared['answer'] = choices[0]['message']['content']\n    if not prepared['recovery'].get('statusUrl'):\n        return finish(prepared, 'recovery_required', 'resume_same_request_may_execute')\n    prepared.update(method='GET', url=prepared['recovery']['statusUrl'], headers={})\n    return {'next': 'inspect', 'result_json': '', **http_fields(prepared)}\n\n\ndef status_view(value, expected):\n    if (not isinstance(value, dict) or value.get('id') != expected or value.get('object') != 'gateway.request'\n            or value.get('response_stored') is not False\n            or value.get('execution') not in ('claimed', 'started', 'unknown', 'not_started', 'finished')\n            or not isinstance(value.get('result'), dict) or value['result'].get('state') not in ('unknown', 'completed', 'failed', 'partial')\n            or not isinstance(value.get('settlement'), dict) or value['settlement'].get('state') not in ('unknown', 'settled', 'not_charged')):\n        return None\n    settlement = {'state': value['settlement']['state']}\n    for key in ('cost_credits', 'cost_usd'):\n        if key not in value['settlement']:\n            continue\n        amount = value['settlement'][key]\n        if amount is None or (type(amount) in (int, float) and math.isfinite(amount) and amount >= 0):\n            settlement[key] = amount\n    return {'id': expected, 'execution': value['execution'], 'result': {'state': value['result']['state']},\n            'settlement': settlement, 'response_stored': False}\n\n\ndef after_get(prepared_json, responses, allow_retry=True):\n    prepared = json.loads(prepared_json)\n    response = response_of(responses)\n    view = status_view(body_of(response), prepared['recovery']['requestId']) if response.get('statusCode') == 200 else None\n    if view is None:\n        return finish(prepared, 'status_unavailable', 'resume_status_without_new_generation')\n    if view['execution'] == 'not_started' and view['settlement']['state'] == 'not_charged':\n        if allow_retry and prepared['mode'] == 'retry-not-started':\n            prepared['recovery'] = {key: prepared['recovery'][key] for key in ('idempotencyKey', 'fingerprint')}\n            prepared.update(method='POST', url=prepared['base'] + '/chat/completions',\n                            headers={**prepared['vendorHeaders'], 'Idempotency-Key': prepared['recovery']['idempotencyKey']})\n            return {'next': 'retry', 'result_json': '', **http_fields(prepared)}\n        return finish(prepared, 'retry_available', 'retry_not_started_with_original_input', view)\n    completed = view['result']['state'] == 'completed'\n    return finish(prepared, 'completed' if completed else 'unconfirmed',\n                  ('fresh_answer_received' if prepared.get('answer') else 'answer_not_stored') if completed else 'resume_status_without_new_generation', view)\n\ndef main(prepared_json, responses):\n    return after_get(prepared_json, responses, False)",
            "variables": [
              {
                "variable": "prepared_json",
                "value_selector": [
                  "post_result",
                  "prepared_json"
                ]
              },
              {
                "variable": "responses",
                "value_selector": [
                  "post_status",
                  "output"
                ]
              }
            ],
            "outputs": {
              "prepared_json": {
                "type": "string"
              },
              "method": {
                "type": "string"
              },
              "url": {
                "type": "string"
              },
              "header_lines": {
                "type": "string"
              },
              "body_json": {
                "type": "string"
              },
              "items": {
                "type": "array[object]"
              },
              "next": {
                "type": "string"
              },
              "result_json": {
                "type": "string"
              }
            },
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          }
        },
        {
          "id": "post_end",
          "type": "custom",
          "position": {
            "x": 3200,
            "y": -450
          },
          "data": {
            "type": "end",
            "title": "Recovery output",
            "selected": false,
            "outputs": [
              {
                "variable": "recovery_result",
                "value_type": "string",
                "value_selector": [
                  "post_status_result",
                  "result_json"
                ]
              }
            ]
          }
        },
        {
          "id": "post_unknown_end",
          "type": "custom",
          "position": {
            "x": 2200,
            "y": -100
          },
          "data": {
            "type": "end",
            "title": "Recovery output",
            "selected": false,
            "outputs": [
              {
                "variable": "recovery_result",
                "value_type": "string",
                "value_selector": [
                  "post_result",
                  "result_json"
                ]
              }
            ]
          }
        },
        {
          "id": "initial_status",
          "type": "custom",
          "position": {
            "x": 900,
            "y": 400
          },
          "data": {
            "type": "iteration",
            "title": "Oneport status GET",
            "selected": false,
            "start_node_id": "initial_status_start",
            "iterator_selector": [
              "prepare",
              "items"
            ],
            "output_selector": [
              "initial_status_capture",
              "response"
            ],
            "is_parallel": false,
            "parallel_nums": 1,
            "error_handle_mode": "continue-on-error",
            "flatten_output": false
          },
          "width": 650,
          "height": 260
        },
        {
          "id": "initial_status_start",
          "type": "custom",
          "position": {
            "x": 40,
            "y": 70
          },
          "data": {
            "type": "iteration-start",
            "title": "One request",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "initial_status"
          },
          "parentId": "initial_status",
          "extent": "parent"
        },
        {
          "id": "initial_status_http",
          "type": "custom",
          "position": {
            "x": 220,
            "y": 70
          },
          "data": {
            "type": "http-request",
            "title": "Oneport status GET",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "initial_status",
            "method": "get",
            "url": "{{#prepare.url#}}",
            "authorization": {
              "type": "api-key",
              "config": {
                "type": "bearer",
                "api_key": "{{#env.ONEPORT_API_KEY#}}"
              }
            },
            "headers": "{{#prepare.header_lines#}}",
            "params": "",
            "body": {
              "type": "none",
              "data": []
            },
            "timeout": {
              "connect": 10,
              "read": 300,
              "write": 300
            },
            "ssl_verify": true,
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          },
          "parentId": "initial_status",
          "extent": "parent"
        },
        {
          "id": "initial_status_capture",
          "type": "custom",
          "position": {
            "x": 440,
            "y": 70
          },
          "data": {
            "type": "code",
            "title": "Keep HTTP response",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "initial_status",
            "code_language": "python3",
            "code": "def main(status_code, headers, body):\n    return {\"response\": {\"statusCode\": status_code, \"headers\": headers, \"body\": body}}",
            "variables": [
              {
                "variable": "status_code",
                "value_selector": [
                  "initial_status_http",
                  "status_code"
                ]
              },
              {
                "variable": "headers",
                "value_selector": [
                  "initial_status_http",
                  "headers"
                ]
              },
              {
                "variable": "body",
                "value_selector": [
                  "initial_status_http",
                  "body"
                ]
              }
            ],
            "outputs": {
              "response": {
                "type": "object"
              }
            },
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          },
          "parentId": "initial_status",
          "extent": "parent"
        },
        {
          "id": "status_result",
          "type": "custom",
          "position": {
            "x": 1600,
            "y": 400
          },
          "data": {
            "type": "code",
            "title": "Read existing state",
            "selected": false,
            "code_language": "python3",
            "code": "\"\"\"Pure code-node transformations. HTTP nodes own all network requests.\"\"\"\nimport hashlib\nimport json\nimport math\nimport re\n\n\ndef encoded(value):\n    return json.dumps(value, ensure_ascii=False, separators=(',', ':'), allow_nan=False)\n\n\ndef status_target(base, value, expected=None):\n    origin = base[:-3]\n    value = str(value or '')\n    path = value[len(origin):] if value.startswith(origin + '/') else value\n    match = re.fullmatch(r'/v1/requests/([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})', path, re.I)\n    if not match or (expected and expected.lower() != match[1].lower()):\n        raise ValueError('Invalid status address')\n    return {'requestId': match[1].lower(), 'statusUrl': origin + '/v1/requests/' + match[1].lower()}\n\n\ndef http_fields(prepared):\n    return {'prepared_json': encoded(prepared), 'method': prepared['method'], 'url': prepared['url'],\n            'header_lines': '\\n'.join(key + ':' + value for key, value in prepared['headers'].items()),\n            'body_json': encoded(prepared['body']), 'items': [{}]}\n\n\ndef prepare(base_url, job_id, mode, request_json, vendor_headers_json='', recovery_json=''):\n    base = base_url.rstrip('/')\n    if base != 'https://oneport.kr/v1' and not re.fullmatch(r'http://127\\.0\\.0\\.1:[1-9][0-9]{0,4}/v1', base):\n        raise ValueError('Use the Oneport URL or a loopback test fixture')\n    if not job_id.strip() or job_id == 'SET_LOGICAL_JOB_ID':\n        raise ValueError('Set the original opaque job ID')\n    if mode not in ('send', 'resume', 'retry-not-started'):\n        raise ValueError('Choose send, resume or retry-not-started')\n    body = json.loads(request_json or 'null')\n    if body is not None and (not isinstance(body, dict) or body.get('stream') is not False\n                             or not isinstance(body.get('model'), str) or body['model'] == 'SET_CHAT_MODEL_ID'):\n        raise ValueError('Use the original non-streaming Chat Completions JSON')\n    names = ('anthropic-beta', 'anthropic-version', 'openai-beta')\n    headers = {}\n    for key, value in json.loads(vendor_headers_json or '{}').items():\n        if key.lower() not in names or not isinstance(value, str) or re.search(r'[\\x00-\\x1f\\x7f]', value):\n            raise ValueError('Unsupported vendor header')\n        headers[key.lower()] = value.strip()\n    key = 'oneport-' + hashlib.sha256(job_id.encode()).hexdigest()\n    canonical_body = json.loads(json.dumps(body, ensure_ascii=False, sort_keys=True, allow_nan=False))\n    fingerprint = hashlib.sha256(encoded({'endpoint': base + '/chat/completions', 'body': canonical_body,\n                                         'headers': [[name, headers.get(name)] for name in names]}).encode()).hexdigest()\n    saved = json.loads(recovery_json or '{}')\n    if not isinstance(saved, dict) or set(saved) - {'idempotencyKey', 'fingerprint', 'requestId', 'statusUrl'}:\n        raise ValueError('Invalid recovery metadata')\n    if saved and (saved.get('idempotencyKey') != key or not re.fullmatch(r'[0-9a-f]{64}', str(saved.get('fingerprint', '')))\n                  or (('requestId' in saved) != ('statusUrl' in saved))):\n        raise ValueError('Recovery metadata does not match this job')\n    if mode == 'send' and saved:\n        raise ValueError('Use resume for an existing job')\n    if mode != 'send' and not saved:\n        raise ValueError('Provide the original recovery metadata')\n    if mode == 'retry-not-started' and not saved.get('statusUrl'):\n        raise ValueError('Recover the receipt first')\n    method = 'GET' if saved.get('statusUrl') else 'POST'\n    if method == 'POST' or mode == 'retry-not-started':\n        if body is None or (saved and saved['fingerprint'] != fingerprint):\n            raise ValueError('Provide the unchanged original request and vendor headers')\n    recovery = saved or {'idempotencyKey': key, 'fingerprint': fingerprint}\n    url = status_target(base, recovery['statusUrl'], recovery['requestId'])['statusUrl'] if method == 'GET' else base + '/chat/completions'\n    prepared = {'base': base, 'body': body, 'vendorHeaders': headers, 'mode': mode, 'recovery': recovery, 'method': method,\n                'url': url, 'headers': {**headers, 'Idempotency-Key': key} if method == 'POST' else {}, 'answer': ''}\n    return http_fields(prepared)\n\n\ndef response_of(responses):\n    return responses[0] if responses and isinstance(responses[0], dict) else {}\n\n\ndef body_of(response):\n    try:\n        value = response.get('body')\n        return json.loads(value) if isinstance(value, str) else value or {}\n    except (TypeError, ValueError):\n        return {}\n\n\ndef finish(prepared, state, action, request_status=None):\n    result = {'state': state, 'action': action, 'recovery': prepared['recovery'], 'response_stored': False}\n    if prepared.get('answer'):\n        result['answer'] = prepared['answer']\n    if request_status is not None:\n        result['requestStatus'] = request_status\n    return {'next': 'finish', 'result_json': encoded(result), **http_fields(prepared)}\n\n\ndef after_post(prepared_json, responses):\n    prepared = json.loads(prepared_json)\n    response = response_of(responses)\n    body = body_of(response)\n    headers = {key.lower(): value for key, value in response.get('headers', {}).items()}\n    status = response.get('statusCode', 0)\n    error = body.get('error', {}) if isinstance(body, dict) and isinstance(body.get('error', {}), dict) else {}\n    url = headers.get('x-gateway-status-url') or ((headers.get('location') or error.get('status_url')) if status >= 400 else None)\n    if url:\n        try:\n            prepared['recovery'] = {**prepared['recovery'], **status_target(prepared['base'], url, headers.get('x-gateway-request-id'))}\n        except (TypeError, ValueError):\n            return finish(prepared, 'recovery_required', 'invalid_status_address')\n    choices = body.get('choices', []) if isinstance(body, dict) else []\n    if 200 <= status < 300 and choices and isinstance(choices[0].get('message', {}).get('content'), str):\n        prepared['answer'] = choices[0]['message']['content']\n    if not prepared['recovery'].get('statusUrl'):\n        return finish(prepared, 'recovery_required', 'resume_same_request_may_execute')\n    prepared.update(method='GET', url=prepared['recovery']['statusUrl'], headers={})\n    return {'next': 'inspect', 'result_json': '', **http_fields(prepared)}\n\n\ndef status_view(value, expected):\n    if (not isinstance(value, dict) or value.get('id') != expected or value.get('object') != 'gateway.request'\n            or value.get('response_stored') is not False\n            or value.get('execution') not in ('claimed', 'started', 'unknown', 'not_started', 'finished')\n            or not isinstance(value.get('result'), dict) or value['result'].get('state') not in ('unknown', 'completed', 'failed', 'partial')\n            or not isinstance(value.get('settlement'), dict) or value['settlement'].get('state') not in ('unknown', 'settled', 'not_charged')):\n        return None\n    settlement = {'state': value['settlement']['state']}\n    for key in ('cost_credits', 'cost_usd'):\n        if key not in value['settlement']:\n            continue\n        amount = value['settlement'][key]\n        if amount is None or (type(amount) in (int, float) and math.isfinite(amount) and amount >= 0):\n            settlement[key] = amount\n    return {'id': expected, 'execution': value['execution'], 'result': {'state': value['result']['state']},\n            'settlement': settlement, 'response_stored': False}\n\n\ndef after_get(prepared_json, responses, allow_retry=True):\n    prepared = json.loads(prepared_json)\n    response = response_of(responses)\n    view = status_view(body_of(response), prepared['recovery']['requestId']) if response.get('statusCode') == 200 else None\n    if view is None:\n        return finish(prepared, 'status_unavailable', 'resume_status_without_new_generation')\n    if view['execution'] == 'not_started' and view['settlement']['state'] == 'not_charged':\n        if allow_retry and prepared['mode'] == 'retry-not-started':\n            prepared['recovery'] = {key: prepared['recovery'][key] for key in ('idempotencyKey', 'fingerprint')}\n            prepared.update(method='POST', url=prepared['base'] + '/chat/completions',\n                            headers={**prepared['vendorHeaders'], 'Idempotency-Key': prepared['recovery']['idempotencyKey']})\n            return {'next': 'retry', 'result_json': '', **http_fields(prepared)}\n        return finish(prepared, 'retry_available', 'retry_not_started_with_original_input', view)\n    completed = view['result']['state'] == 'completed'\n    return finish(prepared, 'completed' if completed else 'unconfirmed',\n                  ('fresh_answer_received' if prepared.get('answer') else 'answer_not_stored') if completed else 'resume_status_without_new_generation', view)\n\ndef main(prepared_json, responses):\n    return after_get(prepared_json, responses)",
            "variables": [
              {
                "variable": "prepared_json",
                "value_selector": [
                  "prepare",
                  "prepared_json"
                ]
              },
              {
                "variable": "responses",
                "value_selector": [
                  "initial_status",
                  "output"
                ]
              }
            ],
            "outputs": {
              "prepared_json": {
                "type": "string"
              },
              "method": {
                "type": "string"
              },
              "url": {
                "type": "string"
              },
              "header_lines": {
                "type": "string"
              },
              "body_json": {
                "type": "string"
              },
              "items": {
                "type": "array[object]"
              },
              "next": {
                "type": "string"
              },
              "result_json": {
                "type": "string"
              }
            },
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          }
        },
        {
          "id": "safe_retry",
          "type": "custom",
          "position": {
            "x": 1900,
            "y": 400
          },
          "data": {
            "type": "if-else",
            "title": "Verified unstarted retry?",
            "selected": false,
            "cases": [
              {
                "case_id": "yes",
                "logical_operator": "and",
                "conditions": [
                  {
                    "variable_selector": [
                      "status_result",
                      "next"
                    ],
                    "comparison_operator": "is",
                    "value": "retry"
                  }
                ]
              }
            ]
          }
        },
        {
          "id": "status_end",
          "type": "custom",
          "position": {
            "x": 2200,
            "y": 650
          },
          "data": {
            "type": "end",
            "title": "Recovery output",
            "selected": false,
            "outputs": [
              {
                "variable": "recovery_result",
                "value_type": "string",
                "value_selector": [
                  "status_result",
                  "result_json"
                ]
              }
            ]
          }
        },
        {
          "id": "retry_post",
          "type": "custom",
          "position": {
            "x": 2200,
            "y": 200
          },
          "data": {
            "type": "iteration",
            "title": "Same request re-admission",
            "selected": false,
            "start_node_id": "retry_post_start",
            "iterator_selector": [
              "status_result",
              "items"
            ],
            "output_selector": [
              "retry_post_capture",
              "response"
            ],
            "is_parallel": false,
            "parallel_nums": 1,
            "error_handle_mode": "continue-on-error",
            "flatten_output": false
          },
          "width": 650,
          "height": 260
        },
        {
          "id": "retry_post_start",
          "type": "custom",
          "position": {
            "x": 40,
            "y": 70
          },
          "data": {
            "type": "iteration-start",
            "title": "One request",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "retry_post"
          },
          "parentId": "retry_post",
          "extent": "parent"
        },
        {
          "id": "retry_post_http",
          "type": "custom",
          "position": {
            "x": 220,
            "y": 70
          },
          "data": {
            "type": "http-request",
            "title": "Same request re-admission",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "retry_post",
            "method": "post",
            "url": "{{#status_result.url#}}",
            "authorization": {
              "type": "api-key",
              "config": {
                "type": "bearer",
                "api_key": "{{#env.ONEPORT_API_KEY#}}"
              }
            },
            "headers": "{{#status_result.header_lines#}}",
            "params": "",
            "body": {
              "type": "json",
              "data": [
                {
                  "key": "",
                  "type": "text",
                  "value": "{{#status_result.body_json#}}"
                }
              ]
            },
            "timeout": {
              "connect": 10,
              "read": 300,
              "write": 300
            },
            "ssl_verify": true,
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          },
          "parentId": "retry_post",
          "extent": "parent"
        },
        {
          "id": "retry_post_capture",
          "type": "custom",
          "position": {
            "x": 440,
            "y": 70
          },
          "data": {
            "type": "code",
            "title": "Keep HTTP response",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "retry_post",
            "code_language": "python3",
            "code": "def main(status_code, headers, body):\n    return {\"response\": {\"statusCode\": status_code, \"headers\": headers, \"body\": body}}",
            "variables": [
              {
                "variable": "status_code",
                "value_selector": [
                  "retry_post_http",
                  "status_code"
                ]
              },
              {
                "variable": "headers",
                "value_selector": [
                  "retry_post_http",
                  "headers"
                ]
              },
              {
                "variable": "body",
                "value_selector": [
                  "retry_post_http",
                  "body"
                ]
              }
            ],
            "outputs": {
              "response": {
                "type": "object"
              }
            },
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          },
          "parentId": "retry_post",
          "extent": "parent"
        },
        {
          "id": "retry_result",
          "type": "custom",
          "position": {
            "x": 2900,
            "y": 200
          },
          "data": {
            "type": "code",
            "title": "Capture new receipt",
            "selected": false,
            "code_language": "python3",
            "code": "\"\"\"Pure code-node transformations. HTTP nodes own all network requests.\"\"\"\nimport hashlib\nimport json\nimport math\nimport re\n\n\ndef encoded(value):\n    return json.dumps(value, ensure_ascii=False, separators=(',', ':'), allow_nan=False)\n\n\ndef status_target(base, value, expected=None):\n    origin = base[:-3]\n    value = str(value or '')\n    path = value[len(origin):] if value.startswith(origin + '/') else value\n    match = re.fullmatch(r'/v1/requests/([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})', path, re.I)\n    if not match or (expected and expected.lower() != match[1].lower()):\n        raise ValueError('Invalid status address')\n    return {'requestId': match[1].lower(), 'statusUrl': origin + '/v1/requests/' + match[1].lower()}\n\n\ndef http_fields(prepared):\n    return {'prepared_json': encoded(prepared), 'method': prepared['method'], 'url': prepared['url'],\n            'header_lines': '\\n'.join(key + ':' + value for key, value in prepared['headers'].items()),\n            'body_json': encoded(prepared['body']), 'items': [{}]}\n\n\ndef prepare(base_url, job_id, mode, request_json, vendor_headers_json='', recovery_json=''):\n    base = base_url.rstrip('/')\n    if base != 'https://oneport.kr/v1' and not re.fullmatch(r'http://127\\.0\\.0\\.1:[1-9][0-9]{0,4}/v1', base):\n        raise ValueError('Use the Oneport URL or a loopback test fixture')\n    if not job_id.strip() or job_id == 'SET_LOGICAL_JOB_ID':\n        raise ValueError('Set the original opaque job ID')\n    if mode not in ('send', 'resume', 'retry-not-started'):\n        raise ValueError('Choose send, resume or retry-not-started')\n    body = json.loads(request_json or 'null')\n    if body is not None and (not isinstance(body, dict) or body.get('stream') is not False\n                             or not isinstance(body.get('model'), str) or body['model'] == 'SET_CHAT_MODEL_ID'):\n        raise ValueError('Use the original non-streaming Chat Completions JSON')\n    names = ('anthropic-beta', 'anthropic-version', 'openai-beta')\n    headers = {}\n    for key, value in json.loads(vendor_headers_json or '{}').items():\n        if key.lower() not in names or not isinstance(value, str) or re.search(r'[\\x00-\\x1f\\x7f]', value):\n            raise ValueError('Unsupported vendor header')\n        headers[key.lower()] = value.strip()\n    key = 'oneport-' + hashlib.sha256(job_id.encode()).hexdigest()\n    canonical_body = json.loads(json.dumps(body, ensure_ascii=False, sort_keys=True, allow_nan=False))\n    fingerprint = hashlib.sha256(encoded({'endpoint': base + '/chat/completions', 'body': canonical_body,\n                                         'headers': [[name, headers.get(name)] for name in names]}).encode()).hexdigest()\n    saved = json.loads(recovery_json or '{}')\n    if not isinstance(saved, dict) or set(saved) - {'idempotencyKey', 'fingerprint', 'requestId', 'statusUrl'}:\n        raise ValueError('Invalid recovery metadata')\n    if saved and (saved.get('idempotencyKey') != key or not re.fullmatch(r'[0-9a-f]{64}', str(saved.get('fingerprint', '')))\n                  or (('requestId' in saved) != ('statusUrl' in saved))):\n        raise ValueError('Recovery metadata does not match this job')\n    if mode == 'send' and saved:\n        raise ValueError('Use resume for an existing job')\n    if mode != 'send' and not saved:\n        raise ValueError('Provide the original recovery metadata')\n    if mode == 'retry-not-started' and not saved.get('statusUrl'):\n        raise ValueError('Recover the receipt first')\n    method = 'GET' if saved.get('statusUrl') else 'POST'\n    if method == 'POST' or mode == 'retry-not-started':\n        if body is None or (saved and saved['fingerprint'] != fingerprint):\n            raise ValueError('Provide the unchanged original request and vendor headers')\n    recovery = saved or {'idempotencyKey': key, 'fingerprint': fingerprint}\n    url = status_target(base, recovery['statusUrl'], recovery['requestId'])['statusUrl'] if method == 'GET' else base + '/chat/completions'\n    prepared = {'base': base, 'body': body, 'vendorHeaders': headers, 'mode': mode, 'recovery': recovery, 'method': method,\n                'url': url, 'headers': {**headers, 'Idempotency-Key': key} if method == 'POST' else {}, 'answer': ''}\n    return http_fields(prepared)\n\n\ndef response_of(responses):\n    return responses[0] if responses and isinstance(responses[0], dict) else {}\n\n\ndef body_of(response):\n    try:\n        value = response.get('body')\n        return json.loads(value) if isinstance(value, str) else value or {}\n    except (TypeError, ValueError):\n        return {}\n\n\ndef finish(prepared, state, action, request_status=None):\n    result = {'state': state, 'action': action, 'recovery': prepared['recovery'], 'response_stored': False}\n    if prepared.get('answer'):\n        result['answer'] = prepared['answer']\n    if request_status is not None:\n        result['requestStatus'] = request_status\n    return {'next': 'finish', 'result_json': encoded(result), **http_fields(prepared)}\n\n\ndef after_post(prepared_json, responses):\n    prepared = json.loads(prepared_json)\n    response = response_of(responses)\n    body = body_of(response)\n    headers = {key.lower(): value for key, value in response.get('headers', {}).items()}\n    status = response.get('statusCode', 0)\n    error = body.get('error', {}) if isinstance(body, dict) and isinstance(body.get('error', {}), dict) else {}\n    url = headers.get('x-gateway-status-url') or ((headers.get('location') or error.get('status_url')) if status >= 400 else None)\n    if url:\n        try:\n            prepared['recovery'] = {**prepared['recovery'], **status_target(prepared['base'], url, headers.get('x-gateway-request-id'))}\n        except (TypeError, ValueError):\n            return finish(prepared, 'recovery_required', 'invalid_status_address')\n    choices = body.get('choices', []) if isinstance(body, dict) else []\n    if 200 <= status < 300 and choices and isinstance(choices[0].get('message', {}).get('content'), str):\n        prepared['answer'] = choices[0]['message']['content']\n    if not prepared['recovery'].get('statusUrl'):\n        return finish(prepared, 'recovery_required', 'resume_same_request_may_execute')\n    prepared.update(method='GET', url=prepared['recovery']['statusUrl'], headers={})\n    return {'next': 'inspect', 'result_json': '', **http_fields(prepared)}\n\n\ndef status_view(value, expected):\n    if (not isinstance(value, dict) or value.get('id') != expected or value.get('object') != 'gateway.request'\n            or value.get('response_stored') is not False\n            or value.get('execution') not in ('claimed', 'started', 'unknown', 'not_started', 'finished')\n            or not isinstance(value.get('result'), dict) or value['result'].get('state') not in ('unknown', 'completed', 'failed', 'partial')\n            or not isinstance(value.get('settlement'), dict) or value['settlement'].get('state') not in ('unknown', 'settled', 'not_charged')):\n        return None\n    settlement = {'state': value['settlement']['state']}\n    for key in ('cost_credits', 'cost_usd'):\n        if key not in value['settlement']:\n            continue\n        amount = value['settlement'][key]\n        if amount is None or (type(amount) in (int, float) and math.isfinite(amount) and amount >= 0):\n            settlement[key] = amount\n    return {'id': expected, 'execution': value['execution'], 'result': {'state': value['result']['state']},\n            'settlement': settlement, 'response_stored': False}\n\n\ndef after_get(prepared_json, responses, allow_retry=True):\n    prepared = json.loads(prepared_json)\n    response = response_of(responses)\n    view = status_view(body_of(response), prepared['recovery']['requestId']) if response.get('statusCode') == 200 else None\n    if view is None:\n        return finish(prepared, 'status_unavailable', 'resume_status_without_new_generation')\n    if view['execution'] == 'not_started' and view['settlement']['state'] == 'not_charged':\n        if allow_retry and prepared['mode'] == 'retry-not-started':\n            prepared['recovery'] = {key: prepared['recovery'][key] for key in ('idempotencyKey', 'fingerprint')}\n            prepared.update(method='POST', url=prepared['base'] + '/chat/completions',\n                            headers={**prepared['vendorHeaders'], 'Idempotency-Key': prepared['recovery']['idempotencyKey']})\n            return {'next': 'retry', 'result_json': '', **http_fields(prepared)}\n        return finish(prepared, 'retry_available', 'retry_not_started_with_original_input', view)\n    completed = view['result']['state'] == 'completed'\n    return finish(prepared, 'completed' if completed else 'unconfirmed',\n                  ('fresh_answer_received' if prepared.get('answer') else 'answer_not_stored') if completed else 'resume_status_without_new_generation', view)\n\ndef main(prepared_json, responses):\n    return after_post(prepared_json, responses)",
            "variables": [
              {
                "variable": "prepared_json",
                "value_selector": [
                  "status_result",
                  "prepared_json"
                ]
              },
              {
                "variable": "responses",
                "value_selector": [
                  "retry_post",
                  "output"
                ]
              }
            ],
            "outputs": {
              "prepared_json": {
                "type": "string"
              },
              "method": {
                "type": "string"
              },
              "url": {
                "type": "string"
              },
              "header_lines": {
                "type": "string"
              },
              "body_json": {
                "type": "string"
              },
              "items": {
                "type": "array[object]"
              },
              "next": {
                "type": "string"
              },
              "result_json": {
                "type": "string"
              }
            },
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          }
        },
        {
          "id": "retry_has_receipt",
          "type": "custom",
          "position": {
            "x": 3200,
            "y": 200
          },
          "data": {
            "type": "if-else",
            "title": "New receipt received?",
            "selected": false,
            "cases": [
              {
                "case_id": "yes",
                "logical_operator": "and",
                "conditions": [
                  {
                    "variable_selector": [
                      "retry_result",
                      "next"
                    ],
                    "comparison_operator": "is",
                    "value": "inspect"
                  }
                ]
              }
            ]
          }
        },
        {
          "id": "retry_status",
          "type": "custom",
          "position": {
            "x": 3500,
            "y": 0
          },
          "data": {
            "type": "iteration",
            "title": "Inspect new request",
            "selected": false,
            "start_node_id": "retry_status_start",
            "iterator_selector": [
              "retry_result",
              "items"
            ],
            "output_selector": [
              "retry_status_capture",
              "response"
            ],
            "is_parallel": false,
            "parallel_nums": 1,
            "error_handle_mode": "continue-on-error",
            "flatten_output": false
          },
          "width": 650,
          "height": 260
        },
        {
          "id": "retry_status_start",
          "type": "custom",
          "position": {
            "x": 40,
            "y": 70
          },
          "data": {
            "type": "iteration-start",
            "title": "One request",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "retry_status"
          },
          "parentId": "retry_status",
          "extent": "parent"
        },
        {
          "id": "retry_status_http",
          "type": "custom",
          "position": {
            "x": 220,
            "y": 70
          },
          "data": {
            "type": "http-request",
            "title": "Inspect new request",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "retry_status",
            "method": "get",
            "url": "{{#retry_result.url#}}",
            "authorization": {
              "type": "api-key",
              "config": {
                "type": "bearer",
                "api_key": "{{#env.ONEPORT_API_KEY#}}"
              }
            },
            "headers": "{{#retry_result.header_lines#}}",
            "params": "",
            "body": {
              "type": "none",
              "data": []
            },
            "timeout": {
              "connect": 10,
              "read": 300,
              "write": 300
            },
            "ssl_verify": true,
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          },
          "parentId": "retry_status",
          "extent": "parent"
        },
        {
          "id": "retry_status_capture",
          "type": "custom",
          "position": {
            "x": 440,
            "y": 70
          },
          "data": {
            "type": "code",
            "title": "Keep HTTP response",
            "selected": false,
            "isInIteration": true,
            "iteration_id": "retry_status",
            "code_language": "python3",
            "code": "def main(status_code, headers, body):\n    return {\"response\": {\"statusCode\": status_code, \"headers\": headers, \"body\": body}}",
            "variables": [
              {
                "variable": "status_code",
                "value_selector": [
                  "retry_status_http",
                  "status_code"
                ]
              },
              {
                "variable": "headers",
                "value_selector": [
                  "retry_status_http",
                  "headers"
                ]
              },
              {
                "variable": "body",
                "value_selector": [
                  "retry_status_http",
                  "body"
                ]
              }
            ],
            "outputs": {
              "response": {
                "type": "object"
              }
            },
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          },
          "parentId": "retry_status",
          "extent": "parent"
        },
        {
          "id": "retry_status_result",
          "type": "custom",
          "position": {
            "x": 4200,
            "y": 0
          },
          "data": {
            "type": "code",
            "title": "Read new state",
            "selected": false,
            "code_language": "python3",
            "code": "\"\"\"Pure code-node transformations. HTTP nodes own all network requests.\"\"\"\nimport hashlib\nimport json\nimport math\nimport re\n\n\ndef encoded(value):\n    return json.dumps(value, ensure_ascii=False, separators=(',', ':'), allow_nan=False)\n\n\ndef status_target(base, value, expected=None):\n    origin = base[:-3]\n    value = str(value or '')\n    path = value[len(origin):] if value.startswith(origin + '/') else value\n    match = re.fullmatch(r'/v1/requests/([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})', path, re.I)\n    if not match or (expected and expected.lower() != match[1].lower()):\n        raise ValueError('Invalid status address')\n    return {'requestId': match[1].lower(), 'statusUrl': origin + '/v1/requests/' + match[1].lower()}\n\n\ndef http_fields(prepared):\n    return {'prepared_json': encoded(prepared), 'method': prepared['method'], 'url': prepared['url'],\n            'header_lines': '\\n'.join(key + ':' + value for key, value in prepared['headers'].items()),\n            'body_json': encoded(prepared['body']), 'items': [{}]}\n\n\ndef prepare(base_url, job_id, mode, request_json, vendor_headers_json='', recovery_json=''):\n    base = base_url.rstrip('/')\n    if base != 'https://oneport.kr/v1' and not re.fullmatch(r'http://127\\.0\\.0\\.1:[1-9][0-9]{0,4}/v1', base):\n        raise ValueError('Use the Oneport URL or a loopback test fixture')\n    if not job_id.strip() or job_id == 'SET_LOGICAL_JOB_ID':\n        raise ValueError('Set the original opaque job ID')\n    if mode not in ('send', 'resume', 'retry-not-started'):\n        raise ValueError('Choose send, resume or retry-not-started')\n    body = json.loads(request_json or 'null')\n    if body is not None and (not isinstance(body, dict) or body.get('stream') is not False\n                             or not isinstance(body.get('model'), str) or body['model'] == 'SET_CHAT_MODEL_ID'):\n        raise ValueError('Use the original non-streaming Chat Completions JSON')\n    names = ('anthropic-beta', 'anthropic-version', 'openai-beta')\n    headers = {}\n    for key, value in json.loads(vendor_headers_json or '{}').items():\n        if key.lower() not in names or not isinstance(value, str) or re.search(r'[\\x00-\\x1f\\x7f]', value):\n            raise ValueError('Unsupported vendor header')\n        headers[key.lower()] = value.strip()\n    key = 'oneport-' + hashlib.sha256(job_id.encode()).hexdigest()\n    canonical_body = json.loads(json.dumps(body, ensure_ascii=False, sort_keys=True, allow_nan=False))\n    fingerprint = hashlib.sha256(encoded({'endpoint': base + '/chat/completions', 'body': canonical_body,\n                                         'headers': [[name, headers.get(name)] for name in names]}).encode()).hexdigest()\n    saved = json.loads(recovery_json or '{}')\n    if not isinstance(saved, dict) or set(saved) - {'idempotencyKey', 'fingerprint', 'requestId', 'statusUrl'}:\n        raise ValueError('Invalid recovery metadata')\n    if saved and (saved.get('idempotencyKey') != key or not re.fullmatch(r'[0-9a-f]{64}', str(saved.get('fingerprint', '')))\n                  or (('requestId' in saved) != ('statusUrl' in saved))):\n        raise ValueError('Recovery metadata does not match this job')\n    if mode == 'send' and saved:\n        raise ValueError('Use resume for an existing job')\n    if mode != 'send' and not saved:\n        raise ValueError('Provide the original recovery metadata')\n    if mode == 'retry-not-started' and not saved.get('statusUrl'):\n        raise ValueError('Recover the receipt first')\n    method = 'GET' if saved.get('statusUrl') else 'POST'\n    if method == 'POST' or mode == 'retry-not-started':\n        if body is None or (saved and saved['fingerprint'] != fingerprint):\n            raise ValueError('Provide the unchanged original request and vendor headers')\n    recovery = saved or {'idempotencyKey': key, 'fingerprint': fingerprint}\n    url = status_target(base, recovery['statusUrl'], recovery['requestId'])['statusUrl'] if method == 'GET' else base + '/chat/completions'\n    prepared = {'base': base, 'body': body, 'vendorHeaders': headers, 'mode': mode, 'recovery': recovery, 'method': method,\n                'url': url, 'headers': {**headers, 'Idempotency-Key': key} if method == 'POST' else {}, 'answer': ''}\n    return http_fields(prepared)\n\n\ndef response_of(responses):\n    return responses[0] if responses and isinstance(responses[0], dict) else {}\n\n\ndef body_of(response):\n    try:\n        value = response.get('body')\n        return json.loads(value) if isinstance(value, str) else value or {}\n    except (TypeError, ValueError):\n        return {}\n\n\ndef finish(prepared, state, action, request_status=None):\n    result = {'state': state, 'action': action, 'recovery': prepared['recovery'], 'response_stored': False}\n    if prepared.get('answer'):\n        result['answer'] = prepared['answer']\n    if request_status is not None:\n        result['requestStatus'] = request_status\n    return {'next': 'finish', 'result_json': encoded(result), **http_fields(prepared)}\n\n\ndef after_post(prepared_json, responses):\n    prepared = json.loads(prepared_json)\n    response = response_of(responses)\n    body = body_of(response)\n    headers = {key.lower(): value for key, value in response.get('headers', {}).items()}\n    status = response.get('statusCode', 0)\n    error = body.get('error', {}) if isinstance(body, dict) and isinstance(body.get('error', {}), dict) else {}\n    url = headers.get('x-gateway-status-url') or ((headers.get('location') or error.get('status_url')) if status >= 400 else None)\n    if url:\n        try:\n            prepared['recovery'] = {**prepared['recovery'], **status_target(prepared['base'], url, headers.get('x-gateway-request-id'))}\n        except (TypeError, ValueError):\n            return finish(prepared, 'recovery_required', 'invalid_status_address')\n    choices = body.get('choices', []) if isinstance(body, dict) else []\n    if 200 <= status < 300 and choices and isinstance(choices[0].get('message', {}).get('content'), str):\n        prepared['answer'] = choices[0]['message']['content']\n    if not prepared['recovery'].get('statusUrl'):\n        return finish(prepared, 'recovery_required', 'resume_same_request_may_execute')\n    prepared.update(method='GET', url=prepared['recovery']['statusUrl'], headers={})\n    return {'next': 'inspect', 'result_json': '', **http_fields(prepared)}\n\n\ndef status_view(value, expected):\n    if (not isinstance(value, dict) or value.get('id') != expected or value.get('object') != 'gateway.request'\n            or value.get('response_stored') is not False\n            or value.get('execution') not in ('claimed', 'started', 'unknown', 'not_started', 'finished')\n            or not isinstance(value.get('result'), dict) or value['result'].get('state') not in ('unknown', 'completed', 'failed', 'partial')\n            or not isinstance(value.get('settlement'), dict) or value['settlement'].get('state') not in ('unknown', 'settled', 'not_charged')):\n        return None\n    settlement = {'state': value['settlement']['state']}\n    for key in ('cost_credits', 'cost_usd'):\n        if key not in value['settlement']:\n            continue\n        amount = value['settlement'][key]\n        if amount is None or (type(amount) in (int, float) and math.isfinite(amount) and amount >= 0):\n            settlement[key] = amount\n    return {'id': expected, 'execution': value['execution'], 'result': {'state': value['result']['state']},\n            'settlement': settlement, 'response_stored': False}\n\n\ndef after_get(prepared_json, responses, allow_retry=True):\n    prepared = json.loads(prepared_json)\n    response = response_of(responses)\n    view = status_view(body_of(response), prepared['recovery']['requestId']) if response.get('statusCode') == 200 else None\n    if view is None:\n        return finish(prepared, 'status_unavailable', 'resume_status_without_new_generation')\n    if view['execution'] == 'not_started' and view['settlement']['state'] == 'not_charged':\n        if allow_retry and prepared['mode'] == 'retry-not-started':\n            prepared['recovery'] = {key: prepared['recovery'][key] for key in ('idempotencyKey', 'fingerprint')}\n            prepared.update(method='POST', url=prepared['base'] + '/chat/completions',\n                            headers={**prepared['vendorHeaders'], 'Idempotency-Key': prepared['recovery']['idempotencyKey']})\n            return {'next': 'retry', 'result_json': '', **http_fields(prepared)}\n        return finish(prepared, 'retry_available', 'retry_not_started_with_original_input', view)\n    completed = view['result']['state'] == 'completed'\n    return finish(prepared, 'completed' if completed else 'unconfirmed',\n                  ('fresh_answer_received' if prepared.get('answer') else 'answer_not_stored') if completed else 'resume_status_without_new_generation', view)\n\ndef main(prepared_json, responses):\n    return after_get(prepared_json, responses, False)",
            "variables": [
              {
                "variable": "prepared_json",
                "value_selector": [
                  "retry_result",
                  "prepared_json"
                ]
              },
              {
                "variable": "responses",
                "value_selector": [
                  "retry_status",
                  "output"
                ]
              }
            ],
            "outputs": {
              "prepared_json": {
                "type": "string"
              },
              "method": {
                "type": "string"
              },
              "url": {
                "type": "string"
              },
              "header_lines": {
                "type": "string"
              },
              "body_json": {
                "type": "string"
              },
              "items": {
                "type": "array[object]"
              },
              "next": {
                "type": "string"
              },
              "result_json": {
                "type": "string"
              }
            },
            "retry_config": {
              "retry_enabled": false,
              "max_retries": 0,
              "retry_interval": 0
            }
          }
        },
        {
          "id": "retry_end",
          "type": "custom",
          "position": {
            "x": 4500,
            "y": 0
          },
          "data": {
            "type": "end",
            "title": "Recovery output",
            "selected": false,
            "outputs": [
              {
                "variable": "recovery_result",
                "value_type": "string",
                "value_selector": [
                  "retry_status_result",
                  "result_json"
                ]
              }
            ]
          }
        },
        {
          "id": "retry_unknown_end",
          "type": "custom",
          "position": {
            "x": 3500,
            "y": 350
          },
          "data": {
            "type": "end",
            "title": "Recovery output",
            "selected": false,
            "outputs": [
              {
                "variable": "recovery_result",
                "value_type": "string",
                "value_selector": [
                  "retry_result",
                  "result_json"
                ]
              }
            ]
          }
        }
      ],
      "edges": [
        {
          "id": "e1-initial-post-start-initial-post-http",
          "source": "initial_post_start",
          "sourceHandle": "source",
          "target": "initial_post_http",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "iteration-start",
            "targetType": "http-request",
            "isInIteration": true,
            "iteration_id": "initial_post"
          }
        },
        {
          "id": "e2-initial-post-http-initial-post-capture",
          "source": "initial_post_http",
          "sourceHandle": "source",
          "target": "initial_post_capture",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "http-request",
            "targetType": "code",
            "isInIteration": true,
            "iteration_id": "initial_post"
          }
        },
        {
          "id": "e3-post-status-start-post-status-http",
          "source": "post_status_start",
          "sourceHandle": "source",
          "target": "post_status_http",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "iteration-start",
            "targetType": "http-request",
            "isInIteration": true,
            "iteration_id": "post_status"
          }
        },
        {
          "id": "e4-post-status-http-post-status-capture",
          "source": "post_status_http",
          "sourceHandle": "source",
          "target": "post_status_capture",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "http-request",
            "targetType": "code",
            "isInIteration": true,
            "iteration_id": "post_status"
          }
        },
        {
          "id": "e5-initial-status-start-initial-status-http",
          "source": "initial_status_start",
          "sourceHandle": "source",
          "target": "initial_status_http",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "iteration-start",
            "targetType": "http-request",
            "isInIteration": true,
            "iteration_id": "initial_status"
          }
        },
        {
          "id": "e6-initial-status-http-initial-status-capture",
          "source": "initial_status_http",
          "sourceHandle": "source",
          "target": "initial_status_capture",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "http-request",
            "targetType": "code",
            "isInIteration": true,
            "iteration_id": "initial_status"
          }
        },
        {
          "id": "e7-retry-post-start-retry-post-http",
          "source": "retry_post_start",
          "sourceHandle": "source",
          "target": "retry_post_http",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "iteration-start",
            "targetType": "http-request",
            "isInIteration": true,
            "iteration_id": "retry_post"
          }
        },
        {
          "id": "e8-retry-post-http-retry-post-capture",
          "source": "retry_post_http",
          "sourceHandle": "source",
          "target": "retry_post_capture",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "http-request",
            "targetType": "code",
            "isInIteration": true,
            "iteration_id": "retry_post"
          }
        },
        {
          "id": "e9-retry-status-start-retry-status-http",
          "source": "retry_status_start",
          "sourceHandle": "source",
          "target": "retry_status_http",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "iteration-start",
            "targetType": "http-request",
            "isInIteration": true,
            "iteration_id": "retry_status"
          }
        },
        {
          "id": "e10-retry-status-http-retry-status-capture",
          "source": "retry_status_http",
          "sourceHandle": "source",
          "target": "retry_status_capture",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "http-request",
            "targetType": "code",
            "isInIteration": true,
            "iteration_id": "retry_status"
          }
        },
        {
          "id": "e11-start-prepare",
          "source": "start",
          "sourceHandle": "source",
          "target": "prepare",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "start",
            "targetType": "code"
          }
        },
        {
          "id": "e12-prepare-initial-method",
          "source": "prepare",
          "sourceHandle": "source",
          "target": "initial_method",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "code",
            "targetType": "if-else"
          }
        },
        {
          "id": "e13-initial-method-initial-post",
          "source": "initial_method",
          "sourceHandle": "yes",
          "target": "initial_post",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "if-else",
            "targetType": "iteration"
          }
        },
        {
          "id": "e14-initial-method-initial-status",
          "source": "initial_method",
          "sourceHandle": "false",
          "target": "initial_status",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "if-else",
            "targetType": "iteration"
          }
        },
        {
          "id": "e15-initial-post-post-result",
          "source": "initial_post",
          "sourceHandle": "source",
          "target": "post_result",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "iteration",
            "targetType": "code"
          }
        },
        {
          "id": "e16-post-result-post-has-receipt",
          "source": "post_result",
          "sourceHandle": "source",
          "target": "post_has_receipt",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "code",
            "targetType": "if-else"
          }
        },
        {
          "id": "e17-post-has-receipt-post-status",
          "source": "post_has_receipt",
          "sourceHandle": "yes",
          "target": "post_status",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "if-else",
            "targetType": "iteration"
          }
        },
        {
          "id": "e18-post-has-receipt-post-unknown-end",
          "source": "post_has_receipt",
          "sourceHandle": "false",
          "target": "post_unknown_end",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "if-else",
            "targetType": "end"
          }
        },
        {
          "id": "e19-post-status-post-status-result",
          "source": "post_status",
          "sourceHandle": "source",
          "target": "post_status_result",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "iteration",
            "targetType": "code"
          }
        },
        {
          "id": "e20-post-status-result-post-end",
          "source": "post_status_result",
          "sourceHandle": "source",
          "target": "post_end",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "code",
            "targetType": "end"
          }
        },
        {
          "id": "e21-initial-status-status-result",
          "source": "initial_status",
          "sourceHandle": "source",
          "target": "status_result",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "iteration",
            "targetType": "code"
          }
        },
        {
          "id": "e22-status-result-safe-retry",
          "source": "status_result",
          "sourceHandle": "source",
          "target": "safe_retry",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "code",
            "targetType": "if-else"
          }
        },
        {
          "id": "e23-safe-retry-retry-post",
          "source": "safe_retry",
          "sourceHandle": "yes",
          "target": "retry_post",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "if-else",
            "targetType": "iteration"
          }
        },
        {
          "id": "e24-safe-retry-status-end",
          "source": "safe_retry",
          "sourceHandle": "false",
          "target": "status_end",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "if-else",
            "targetType": "end"
          }
        },
        {
          "id": "e25-retry-post-retry-result",
          "source": "retry_post",
          "sourceHandle": "source",
          "target": "retry_result",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "iteration",
            "targetType": "code"
          }
        },
        {
          "id": "e26-retry-result-retry-has-receipt",
          "source": "retry_result",
          "sourceHandle": "source",
          "target": "retry_has_receipt",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "code",
            "targetType": "if-else"
          }
        },
        {
          "id": "e27-retry-has-receipt-retry-status",
          "source": "retry_has_receipt",
          "sourceHandle": "yes",
          "target": "retry_status",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "if-else",
            "targetType": "iteration"
          }
        },
        {
          "id": "e28-retry-has-receipt-retry-unknown-end",
          "source": "retry_has_receipt",
          "sourceHandle": "false",
          "target": "retry_unknown_end",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "if-else",
            "targetType": "end"
          }
        },
        {
          "id": "e29-retry-status-retry-status-result",
          "source": "retry_status",
          "sourceHandle": "source",
          "target": "retry_status_result",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "iteration",
            "targetType": "code"
          }
        },
        {
          "id": "e30-retry-status-result-retry-end",
          "source": "retry_status_result",
          "sourceHandle": "source",
          "target": "retry_end",
          "targetHandle": "target",
          "type": "custom",
          "data": {
            "sourceType": "code",
            "targetType": "end"
          }
        }
      ],
      "viewport": {
        "x": 0,
        "y": 0,
        "zoom": 0.5
      }
    }
  }
}
