# Hermes real-binary FINAL driver — apples-to-apples growing-conversation protocol.
# Fixes v2/v3 failures:
#   v2: agent.chat() did not accumulate history (msgs=2 every call) -> we now pass
#       conversation_history explicitly and VERIFY msgs grows monotonically.
#   v3: CLI path bypassed the proxy (hermes_cli/models.py rejects non-openrouter.ai
#       base_url) and the driver read stale log lines -> we use the Python API
#       (which honors base_url) and FAIL LOUDLY if no NEW proxy line appears.
# Protocol: 4 rapid turns -> 6.5 min idle -> turn 5. Identical fillers to all arms.
import json, os, time, sys

AUTH = json.load(open(os.path.expanduser('~/.hermes/auth.json')))  # [sanitized for publication]
KEY = AUTH['credential_pool']['openrouter'][0]['access_token']
os.environ['OPENROUTER_API_KEY'] = KEY

from run_agent import AIAgent

LOG = 'proxy-log.jsonl'

def proxy_lines():
    try:
        raw = open(LOG, encoding='utf-8').read().strip()
        return raw.split('\n') if raw else []
    except FileNotFoundError:
        return []

def filler(t):
    return ''.join(f"row {t}-{i} a={(i*7919)%104729} b={(i*104729)%7919} c={i%13}; " for i in range(260))

agent = AIAgent(
    base_url='http://127.0.0.1:18080/api/v1',
    api_key=KEY,
    model='anthropic/claude-sonnet-4.5',
    provider='openrouter',
)

history = []
results = []
prev_msgs = 0

def do_turn(t, label):
    global prev_msgs
    n0 = len(proxy_lines())
    idle_tag = ' AFTER IDLE' if 'idle' in label else ''
    user_msg = f"TURN {t}{idle_tag}: Reply with exactly OK{t}. Ignore: {filler(t)}"
    r = agent.run_conversation(user_msg, conversation_history=list(history))
    lines = proxy_lines()
    if len(lines) <= n0:
        print(f"FATAL {label}: NO new proxy line — calls bypassed the proxy. INVALID.", flush=True)
        sys.exit(2)
    last = json.loads(lines[-1])
    msgs = last.get('nMessages') or 0
    if msgs <= prev_msgs:
        print(f"FATAL {label}: history not growing (msgs={msgs}, prev={prev_msgs}). INVALID.", flush=True)
        sys.exit(3)
    prev_msgs = msgs
    u = last.get('usage') or {}
    d = u.get('prompt_tokens_details') or {}
    row = {
        'label': label, 'msgs': msgs, 'markers': len(last.get('markers') or []),
        'prompt_tokens': u.get('prompt_tokens'), 'cached_tokens': d.get('cached_tokens'),
        'cache_write_tokens': d.get('cache_write_tokens'), 'completion_tokens': u.get('completion_tokens'),
        'cost_usd': u.get('cost'), 'api_calls_this_turn': len(lines) - n0, 'ts': last.get('ts'),
    }
    results.append(row)
    text = None
    if isinstance(r, dict):
        for k in ('response', 'final_response', 'content', 'text', 'result'):
            v = r.get(k)
            if isinstance(v, str) and v.strip():
                text = v
                break
    if not text:
        text = f"OK{t}"
    history.append({'role': 'user', 'content': user_msg})
    history.append({'role': 'assistant', 'content': text[:200]})
    print(f"{label}: msgs={msgs} prompt={row['prompt_tokens']} cached={row['cached_tokens']} "
          f"write={row['cache_write_tokens']} markers={row['markers']} cost=${row['cost_usd']}", flush=True)

for t in range(1, 5):
    do_turn(t, f'turn{t}')

print('IDLE 390s...', flush=True)
time.sleep(390)
do_turn(5, 'turn5-after-idle')

json.dump({'harness': 'hermes-agent 0.18.0 (real, pip install)', 'provider': 'openrouter (Hermes default)',
           'model': 'anthropic/claude-sonnet-4.5', 'instrument': 'transparent logging proxy or-proxy.js',
           'turns': results}, open('results-hermes-real-final.json', 'w'), indent=1)
print('HERMES REAL FINAL COMPLETE', flush=True)
