-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
366 lines (308 loc) · 14.1 KB
/
Copy pathindex.html
File metadata and controls
366 lines (308 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Hermes Agent — Pyodide</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'SF Mono', Menlo, monospace; background: #0d1117; color: #c9d1d9; padding: 20px; }
h1 { color: #58a6ff; margin-bottom: 8px; font-size: 1.4em; }
.subtitle { color: #8b949e; margin-bottom: 20px; font-size: 0.9em; }
#status { padding: 12px; background: #161b22; border: 1px solid #30363d; border-radius: 6px; margin-bottom: 16px; white-space: pre-wrap; font-size: 0.85em; max-height: 200px; overflow-y: auto; }
#chat { display: flex; flex-direction: column; height: calc(100vh - 300px); min-height: 300px; }
#messages { flex: 1; overflow-y: auto; padding: 12px; background: #161b22; border: 1px solid #30363d; border-radius: 6px 6px 0 0; }
.msg { margin-bottom: 12px; line-height: 1.5; white-space: pre-wrap; }
.msg.user { color: #58a6ff; }
.msg.user::before { content: "› "; color: #8b949e; }
.msg.assistant { color: #c9d1d9; }
.msg.assistant::before { content: "⚕ "; color: #f0883e; }
.msg.system { color: #8b949e; font-style: italic; font-size: 0.85em; }
.msg.error { color: #f85149; font-size: 0.85em; }
#input-row { display: flex; }
#input { flex: 1; padding: 10px 14px; font-family: inherit; font-size: 0.95em; background: #0d1117; color: #c9d1d9; border: 1px solid #30363d; border-top: none; border-radius: 0 0 0 6px; outline: none; }
#input:focus { border-color: #58a6ff; }
#send { padding: 10px 20px; font-family: inherit; font-size: 0.95em; background: #238636; color: #fff; border: 1px solid #238636; border-top: none; border-radius: 0 0 6px 0; cursor: pointer; }
#send:hover { background: #2ea043; }
#send:disabled { background: #30363d; border-color: #30363d; cursor: not-allowed; }
#api-row { display: flex; gap: 8px; margin-bottom: 16px; align-items: center; flex-wrap: wrap; }
#api-row label { color: #8b949e; font-size: 0.85em; white-space: nowrap; }
#api-row input, #api-row select { padding: 6px 10px; font-family: inherit; font-size: 0.85em; background: #0d1117; color: #c9d1d9; border: 1px solid #30363d; border-radius: 4px; outline: none; }
#api-row input:focus, #api-row select:focus { border-color: #58a6ff; }
#api-key { flex: 1; min-width: 200px; }
</style>
</head>
<body>
<h1>⚕ Hermes Agent</h1>
<p class="subtitle">Running in-browser via Pyodide • API calls proxied through VM server</p>
<div id="api-row">
<label for="api-key">API Key:</label>
<input id="api-key" type="password" placeholder="sk-or-... (OpenRouter key)" />
<label for="model-select">Model:</label>
<select id="model-select">
<option value="google/gemini-2.0-flash-001">gemini-2.0-flash</option>
<option value="anthropic/claude-sonnet-4-20250514">claude-sonnet-4</option>
<option value="openai/gpt-4o">gpt-4o</option>
<option value="meta-llama/llama-3.1-70b-instruct">llama-3.1-70b</option>
</select>
</div>
<div id="status">Initializing Pyodide...</div>
<div id="chat">
<div id="messages"></div>
<div id="input-row">
<input id="input" type="text" placeholder="Loading agent..." disabled />
<button id="send" disabled>Send</button>
</div>
</div>
<script src="https://cdn.jsdelivr.net/pyodide/v0.27.6/full/pyodide.js"></script>
<script>
const statusEl = document.getElementById('status');
const messagesEl = document.getElementById('messages');
const inputEl = document.getElementById('input');
const sendBtn = document.getElementById('send');
const apiKeyEl = document.getElementById('api-key');
const modelEl = document.getElementById('model-select');
let pyodide = null;
function log(msg) {
statusEl.textContent += '\n' + msg;
statusEl.scrollTop = statusEl.scrollHeight;
}
function addMessage(role, content) {
const div = document.createElement('div');
div.className = 'msg ' + role;
div.textContent = content;
messagesEl.appendChild(div);
messagesEl.scrollTop = messagesEl.scrollHeight;
}
async function init() {
try {
log('Loading Pyodide runtime...');
pyodide = await loadPyodide({
stdout: (text) => { if (text.trim()) log('[py] ' + text); },
stderr: (text) => { if (text.trim()) log('[py:err] ' + text); },
});
// Register JS proxy functions — ALL HTTP goes through same-origin /api/*
// This completely avoids CORS and browser-forbidden XHR headers
pyodide.registerJsModule("_js_proxy", {
call_llm: async function(requestJson) {
const req = JSON.parse(requestJson);
const resp = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(req),
});
return await resp.text();
},
// Generic HTTP proxy — used by requests.get/post monkey-patch
do_fetch: async function(requestJson) {
const resp = await fetch('/api/fetch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: requestJson,
});
const status = resp.status;
const body = await resp.text();
const ct = resp.headers.get('content-type') || '';
return JSON.stringify({ status, body, content_type: ct });
}
});
log('Installing packages...');
await pyodide.loadPackage(['micropip', 'sqlite3', 'pyyaml']);
await pyodide.runPythonAsync(`
import micropip
await micropip.install([
'openai', 'httpx', 'pydantic', 'tenacity',
'python-dotenv', 'jinja2', 'fire', 'requests',
])
`);
log('Packages installed.');
log('Downloading hermes-agent bundle...');
const resp = await fetch('/hermes-agent-bundle.tar.gz');
const buf = await resp.arrayBuffer();
pyodide.FS.writeFile('/tmp/bundle.tar.gz', new Uint8Array(buf));
log('Unpacking agent code...');
await pyodide.runPythonAsync(`
import tarfile, os, sys
os.makedirs('/home/pyodide/hermes-agent', exist_ok=True)
with tarfile.open('/tmp/bundle.tar.gz', 'r:gz') as tar:
tar.extractall('/home/pyodide/hermes-agent')
sys.path.insert(0, '/home/pyodide/hermes-agent')
os.environ['PYODIDE'] = '1'
os.environ['HERMES_HOME'] = '/home/pyodide/.hermes'
os.makedirs('/home/pyodide/.hermes/logs', exist_ok=True)
os.makedirs('/home/pyodide/.hermes/sessions', exist_ok=True)
print(f'Agent code unpacked. Files: {len(os.listdir("/home/pyodide/hermes-agent"))}')
`);
log('Loading hermes-agent...');
await pyodide.runPythonAsync(`
# Import and patch pyodide_shims FIRST
import pyodide_shims
# NOW install the proxy transport that routes through /api/chat
# This completely replaces the _FetchTransport with one that uses
# our JS bridge (fetch to same-origin /api/chat) instead of
# trying to reach OpenRouter directly from the browser.
import httpx
import json
from pyodide.ffi import run_sync as _pyodide_run_sync
import _js_proxy
class _ServerProxyTransport(httpx.BaseTransport):
"""Routes all HTTP through the VM's /api/chat endpoint via JS fetch.
The JS fetch() goes to the same-origin server (no CORS).
The server then makes the real HTTP call to OpenRouter/OpenAI/etc.
"""
def __init__(self):
self._api_key = None
self._base_url = None
def configure(self, api_key, base_url):
self._api_key = api_key
self._base_url = base_url
def handle_request(self, request: httpx.Request) -> httpx.Response:
url_str = str(request.url)
# Only proxy chat completions — stub out everything else
if '/chat/completions' not in url_str:
# Models list, etc. — return empty stub
return httpx.Response(200, json={"data": [], "object": "list"})
# Parse the request body
body = json.loads(request.content) if request.content else {}
# Build proxy request
proxy_req = json.dumps({
"api_key": self._api_key or "",
"base_url": self._base_url or "https://openrouter.ai/api/v1",
"payload": body,
})
# Call JS fetch via the registered module — completely avoids
# XMLHttpRequest and its forbidden-header issues
resp_text = _pyodide_run_sync(_js_proxy.call_llm(proxy_req))
return httpx.Response(
status_code=200,
headers={"content-type": "application/json"},
content=resp_text.encode("utf-8") if isinstance(resp_text, str) else resp_text,
)
# Create a global transport instance
_proxy_transport = _ServerProxyTransport()
# Monkey-patch pyodide_shims so make_openai_client uses our proxy transport
import pyodide_shims as _shims
def _patched_get_fetch_transport():
return _proxy_transport
_shims._get_fetch_transport = _patched_get_fetch_transport
_shims._fetch_transport = _proxy_transport
# Also monkey-patch the OpenAI client constructor to always use our transport
import openai
_OrigOpenAI = openai.OpenAI
def _PatchedOpenAI(**kwargs):
kwargs.pop('http_client', None) # Remove any existing http_client
custom_httpx = httpx.Client(transport=_proxy_transport)
kwargs['http_client'] = custom_httpx
return _OrigOpenAI(**kwargs)
openai.OpenAI = _PatchedOpenAI
# Monkey-patch requests library to route through JS bridge too
# This is needed because model_metadata.py calls requests.get() to fetch
# model info from OpenRouter, and browser_tool.py uses requests.post()
import requests as _requests
class _ProxyResponse:
"""Minimal requests.Response work-alike returned by our proxy."""
def __init__(self, status_code, text, content_type=''):
self.status_code = status_code
self.text = text
self.content = text.encode('utf-8') if isinstance(text, str) else text
self.headers = {'content-type': content_type}
self.ok = 200 <= status_code < 300
def json(self):
return json.loads(self.text)
def raise_for_status(self):
if not self.ok:
raise Exception(f'HTTP {self.status_code}')
_orig_requests_get = _requests.get
_orig_requests_post = _requests.post
def _proxied_get(url, **kwargs):
req = json.dumps({"url": url, "method": "GET", "headers": {}})
resp_json = _pyodide_run_sync(_js_proxy.do_fetch(req))
resp = json.loads(resp_json)
return _ProxyResponse(resp['status'], resp['body'], resp.get('content_type', ''))
def _proxied_post(url, **kwargs):
headers = kwargs.get('headers', {})
data = kwargs.get('data')
json_body = kwargs.get('json')
body = None
if json_body is not None:
body = json.dumps(json_body)
headers.setdefault('Content-Type', 'application/json')
elif data is not None:
body = data if isinstance(data, str) else json.dumps(data)
req = json.dumps({"url": url, "method": "POST", "headers": headers, "body": body})
resp_json = _pyodide_run_sync(_js_proxy.do_fetch(req))
resp = json.loads(resp_json)
return _ProxyResponse(resp['status'], resp['body'], resp.get('content_type', ''))
_requests.get = _proxied_get
_requests.post = _proxied_post
print('requests library patched to use server proxy')
# Now import the agent
from run_agent import AIAgent
print('AIAgent imported successfully')
print('All proxy transports installed')
`);
log('\\n✅ Agent ready! Enter your API key and send a message.');
inputEl.disabled = false;
sendBtn.disabled = false;
inputEl.placeholder = 'Type a message...';
inputEl.focus();
} catch (e) {
log('ERROR: ' + e.message);
console.error(e);
addMessage('error', 'Failed to load agent: ' + e.message);
}
}
async function sendMessage() {
const text = inputEl.value.trim();
if (!text) return;
const apiKey = apiKeyEl.value.trim();
if (!apiKey) {
addMessage('error', 'Please enter an API key (OpenRouter key starting with sk-or-...)');
apiKeyEl.focus();
return;
}
const model = modelEl.value;
addMessage('user', text);
inputEl.value = '';
sendBtn.disabled = true;
inputEl.disabled = true;
try {
const escaped = text.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n');
const escapedKey = apiKey.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
const result = await pyodide.runPythonAsync(`
import os
os.environ['OPENROUTER_API_KEY'] = '${escapedKey}'
# Configure the proxy transport with the user's key
_proxy_transport.configure('${escapedKey}', 'https://openrouter.ai/api/v1')
try:
agent = AIAgent(
base_url='https://openrouter.ai/api/v1',
model='${model}',
api_key='${escapedKey}',
quiet_mode=True,
enabled_toolsets=['memory', 'planning'],
)
result = agent.run_conversation('${escaped}')
_response = result.get('final_response', str(result)) if isinstance(result, dict) else str(result)
except Exception as e:
import traceback
_response = f'Error: {type(e).__name__}: {e}'
traceback.print_exc()
_response
`);
addMessage('assistant', result);
} catch (e) {
addMessage('error', 'Error: ' + e.message);
console.error(e);
}
sendBtn.disabled = false;
inputEl.disabled = false;
inputEl.focus();
}
sendBtn.addEventListener('click', sendMessage);
inputEl.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !sendBtn.disabled) sendMessage();
});
init();
</script>
</body>
</html>