guac-bridge 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ __version__ = "0.2.0"
2
+
guac_bridge/client.py ADDED
@@ -0,0 +1,561 @@
1
+ #!/usr/bin/env python3
2
+ """Local OpenAI HTTP endpoint over an authenticated Apache Guacamole terminal."""
3
+ import argparse
4
+ import asyncio
5
+ import base64
6
+ import contextlib
7
+ import getpass
8
+ import json
9
+ import logging
10
+ import os
11
+ import shlex
12
+ import ssl
13
+ import sys
14
+ import time
15
+ import urllib.parse
16
+ import uuid
17
+
18
+ import aiohttp
19
+ from aiohttp import web
20
+
21
+ LOG = logging.getLogger('guac-llm')
22
+ PATHS = {'/v1/models': 'GET', '/v1/chat/completions': 'POST', '/v1/completions': 'POST'}
23
+
24
+
25
+ class BridgeError(Exception):
26
+ pass
27
+
28
+
29
+ def instruction(*args):
30
+ return ','.join(str(len(str(arg))) + '.' + str(arg) for arg in args) + ';'
31
+
32
+
33
+ class Parser:
34
+ """Incremental Guacamole length-prefixed instruction parser."""
35
+ def __init__(self):
36
+ self.buffer = ''
37
+
38
+ def feed(self, text):
39
+ self.buffer += text
40
+ if len(self.buffer) > 16 * 1024 * 1024:
41
+ raise BridgeError('Guacamole instruction exceeds size limit')
42
+ result = []
43
+ start = 0
44
+ while start < len(self.buffer):
45
+ pos, args = start, []
46
+ while True:
47
+ dot = self.buffer.find('.', pos)
48
+ if dot < 0:
49
+ self.buffer = self.buffer[start:]
50
+ return result
51
+ length = self.buffer[pos:dot]
52
+ if not length.isdecimal() or len(length) > 9:
53
+ raise BridgeError('Invalid Guacamole instruction length')
54
+ end = dot + 1 + int(length)
55
+ if end >= len(self.buffer):
56
+ self.buffer = self.buffer[start:]
57
+ return result
58
+ args.append(self.buffer[dot + 1:end])
59
+ separator = self.buffer[end]
60
+ pos = end + 1
61
+ if separator == ';':
62
+ result.append(args)
63
+ start = pos
64
+ break
65
+ if separator != ',':
66
+ raise BridgeError('Invalid Guacamole separator')
67
+ self.buffer = self.buffer[start:]
68
+ return result
69
+
70
+
71
+ def parse_url(url, connection=None, data_source=None):
72
+ parts = urllib.parse.urlsplit(url)
73
+ if parts.scheme not in ('http', 'https') or not parts.netloc or parts.username or parts.password:
74
+ raise BridgeError('Supply an http(s) Guacamole URL without embedded credentials')
75
+ kind = 'c'
76
+ if '/client/' in parts.fragment:
77
+ encoded = urllib.parse.unquote(parts.fragment.split('/client/', 1)[1].split('?')[0])
78
+ try:
79
+ decoded = base64.b64decode(encoded + '=' * (-len(encoded) % 4)).decode()
80
+ found_id, kind, found_source = decoded.split('\0')
81
+ except (ValueError, UnicodeError) as exc:
82
+ raise BridgeError('Cannot decode connection from URL; use --connection-id and --data-source') from exc
83
+ connection = connection or found_id
84
+ data_source = data_source or found_source
85
+ if not connection or not data_source or kind not in ('c', 'g'):
86
+ raise BridgeError('Include #/client/... in URL, or supply --connection-id and --data-source')
87
+ base = urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path.rstrip('/') + '/', '', ''))
88
+ return base, connection, kind, data_source
89
+
90
+
91
+ def bootstrap(args):
92
+ executable = ('"$HOME"/' + shlex.quote(args.server_command[2:])
93
+ if args.server_command.startswith('~/') else shlex.quote(args.server_command))
94
+ command = executable + ' ' + ' '.join(shlex.quote(str(value)) for value in (
95
+ '--upstream', args.upstream,
96
+ '--request-timeout', args.request_timeout, '--max-requests', args.max_requests)) + '\n'
97
+ if len(command.encode()) > 3900:
98
+ raise BridgeError('Remote bootstrap exceeds terminal canonical line limit')
99
+ return command.encode()
100
+
101
+
102
+ class Tunnel:
103
+ def __init__(self, session, base, params, mode):
104
+ self.session, self.base, self.params, self.mode = session, base, params, mode
105
+ self.ws = None
106
+ self.ident = None
107
+ self.lock = asyncio.Lock()
108
+ self.closed = False
109
+
110
+ async def connect(self):
111
+ if self.mode != 'http':
112
+ url = self.base.replace('https://', 'wss://', 1).replace('http://', 'ws://', 1)
113
+ try:
114
+ self.ws = await self.session.ws_connect(
115
+ url + 'websocket-tunnel', params=self.params, protocols=('guacamole',),
116
+ heartbeat=20, max_msg_size=16 * 1024 * 1024,
117
+ origin=urllib.parse.urlunsplit((*urllib.parse.urlsplit(self.base)[:2], '', '', '')))
118
+ self.mode = 'websocket'
119
+ return
120
+ except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
121
+ if self.mode == 'websocket':
122
+ raise BridgeError('WebSocket tunnel failed; try --transport http') from exc
123
+ LOG.info('WebSocket unavailable; trying Guacamole HTTP tunnel')
124
+ self.mode = 'http'
125
+ async with self.session.post(self.base + 'tunnel?connect', data=self.params,
126
+ allow_redirects=False) as response:
127
+ if response.status != 200:
128
+ raise BridgeError('HTTP tunnel connect returned status ' + str(response.status))
129
+ self.ident = (await response.text()).strip()
130
+ try:
131
+ uuid.UUID(self.ident)
132
+ except ValueError as exc:
133
+ raise BridgeError('HTTP tunnel did not return a tunnel UUID') from exc
134
+
135
+ async def send(self, *args):
136
+ payload = instruction(*args)
137
+ async with self.lock:
138
+ if self.closed:
139
+ raise BridgeError('Guacamole tunnel is closed')
140
+ if self.ws:
141
+ await self.ws.send_str(payload)
142
+ else:
143
+ async with self.session.post(self.base + 'tunnel?write:' + self.ident,
144
+ data=payload.encode(),
145
+ headers={'Content-Type': 'application/octet-stream'},
146
+ allow_redirects=False) as response:
147
+ if response.status != 200:
148
+ raise BridgeError('HTTP tunnel write failed: ' + str(response.status))
149
+ await response.read()
150
+
151
+ async def messages(self):
152
+ if self.ws:
153
+ async for message in self.ws:
154
+ if message.type == aiohttp.WSMsgType.TEXT:
155
+ yield message.data
156
+ elif message.type == aiohttp.WSMsgType.ERROR:
157
+ raise BridgeError('WebSocket tunnel failed')
158
+ return
159
+ counter = 0
160
+ import codecs
161
+ decoder = codecs.getincrementaldecoder('utf-8')()
162
+ while not self.closed:
163
+ async with self.session.get(self.base + 'tunnel?read:' + self.ident + ':' + str(counter),
164
+ allow_redirects=False) as response:
165
+ if response.status != 200:
166
+ raise BridgeError('HTTP tunnel read failed: ' + str(response.status))
167
+ async for chunk in response.content.iter_any():
168
+ yield decoder.decode(chunk)
169
+ counter += 1
170
+
171
+ async def close(self):
172
+ self.closed = True
173
+ if self.ws:
174
+ await self.ws.close()
175
+
176
+
177
+ class Bridge:
178
+ helper_name = 'guac-llm-server'
179
+
180
+ def helper_command(self):
181
+ return bootstrap(self.args)
182
+
183
+ def __init__(self, args, session, base, conn, kind, data_source, token):
184
+ self.args, self.session = args, session
185
+ self.base, self.conn, self.kind, self.data_source = base, conn, kind, data_source
186
+ self.token = token
187
+ self.tunnel = None
188
+ self.reader = None
189
+ self.maintainer = None
190
+ self.synced = asyncio.Event()
191
+ self.ready = asyncio.Event()
192
+ self.failed = asyncio.Event()
193
+ self.failure = None
194
+ self.input_lock = asyncio.Lock()
195
+ self.acks = asyncio.Queue()
196
+ self.input_stream = 0
197
+ self.output_stream = None
198
+ self.output_buffer = b''
199
+ self.requests = {}
200
+ self.last_seen = time.monotonic()
201
+ self.closing = False
202
+
203
+ async def start(self):
204
+ params = [('token', self.token), ('GUAC_DATA_SOURCE', self.data_source),
205
+ ('GUAC_ID', self.conn), ('GUAC_TYPE', self.kind),
206
+ ('GUAC_WIDTH', '1024'), ('GUAC_HEIGHT', '768'), ('GUAC_DPI', '96'),
207
+ ('GUAC_TIMEZONE', 'Europe/Berlin'), ('GUAC_IMAGE', 'image/png')]
208
+ self.tunnel = Tunnel(self.session, self.base, params, self.args.transport)
209
+ await self.tunnel.connect()
210
+ LOG.info('Connected via %s; waiting for terminal', self.tunnel.mode)
211
+ self.reader = asyncio.create_task(self.read_loop())
212
+ await self.wait_for(self.synced.wait(), self.args.connect_timeout)
213
+ await self.wait_for(asyncio.sleep(self.args.startup_delay), self.args.connect_timeout)
214
+ ack = self.new_ack()
215
+ await self.tunnel.send('pipe', self.input_stream, 'text/plain', 'STDIN')
216
+ await self.wait_for(ack, self.args.connect_timeout)
217
+ await self.send_input(self.helper_command())
218
+ try:
219
+ await self.wait_for(self.ready.wait(), self.args.connect_timeout)
220
+ except asyncio.TimeoutError as exc:
221
+ raise BridgeError('Remote helper did not become ready. Check ' + self.helper_name +
222
+ ' installation/PATH, shell readiness, and Guacamole STDIN/output pipes; '
223
+ 'try --startup-delay 5.') from exc
224
+ self.maintainer = asyncio.create_task(self.maintain())
225
+ LOG.info('Remote helper ready')
226
+
227
+ async def wait_for(self, awaitable, timeout):
228
+ operation = asyncio.ensure_future(awaitable)
229
+ failed = asyncio.create_task(self.failed.wait())
230
+ try:
231
+ done, _ = await asyncio.wait((operation, failed), timeout=timeout,
232
+ return_when=asyncio.FIRST_COMPLETED)
233
+ if failed in done:
234
+ raise BridgeError(self.failure or 'Guacamole disconnected')
235
+ if operation in done:
236
+ return operation.result()
237
+ raise asyncio.TimeoutError()
238
+ finally:
239
+ for task in (operation, failed):
240
+ if not task.done():
241
+ task.cancel()
242
+ await asyncio.gather(operation, failed, return_exceptions=True)
243
+
244
+ def new_ack(self):
245
+ future = asyncio.get_running_loop().create_future()
246
+ self.acks.put_nowait(future)
247
+ return future
248
+
249
+ async def send_input(self, data):
250
+ async with self.input_lock:
251
+ pending = []
252
+ try:
253
+ for offset in range(0, len(data), 3072):
254
+ pending.append(self.new_ack())
255
+ await self.tunnel.send('blob', self.input_stream,
256
+ base64.b64encode(data[offset:offset + 3072]).decode())
257
+ if len(pending) >= 8:
258
+ await self.wait_for(pending.pop(0), self.args.connect_timeout)
259
+ for future in pending:
260
+ await self.wait_for(future, self.args.connect_timeout)
261
+ except BaseException:
262
+ self.fail('Terminal input failed; restart the bridge')
263
+ raise
264
+
265
+ async def send_event(self, event):
266
+ await self.send_input(base64.b64encode(json.dumps(event, separators=(',', ':')).encode()) + b'\n')
267
+
268
+ def fail(self, message):
269
+ if self.failed.is_set() or self.closing:
270
+ return
271
+ self.failure = message
272
+ self.failed.set()
273
+ LOG.error('%s', message)
274
+ for queue in self.requests.values():
275
+ # A bounded queue can be full when the consumer is slow. Discard buffered
276
+ # bytes on failure; never replace a truncated stream with a success marker.
277
+ while not queue.empty():
278
+ queue.get_nowait()
279
+ queue.put_nowait({'type': 'error', 'message': message})
280
+
281
+ async def read_loop(self):
282
+ parser = Parser()
283
+ try:
284
+ async for text in self.tunnel.messages():
285
+ for args in parser.feed(text):
286
+ opcode, *values = args
287
+ if opcode == 'sync':
288
+ await self.tunnel.send('sync', values[0])
289
+ self.synced.set()
290
+ elif opcode == 'ack' and int(values[0]) == self.input_stream:
291
+ if not self.acks.empty():
292
+ future = self.acks.get_nowait()
293
+ if not future.done():
294
+ if int(values[2]) == 0:
295
+ future.set_result(None)
296
+ else:
297
+ future.set_exception(BridgeError('Guacamole rejected STDIN pipe: ' + values[2]))
298
+ elif opcode == 'pipe':
299
+ if values[2] == 'LLM' and self.output_stream is None:
300
+ self.output_stream = int(values[0])
301
+ await self.tunnel.send('ack', values[0], 'OK', 0)
302
+ else:
303
+ await self.tunnel.send('ack', values[0], 'Unsupported stream', 256)
304
+ elif opcode == 'blob' and int(values[0]) == self.output_stream:
305
+ self.output_buffer += base64.b64decode(values[1], validate=True)
306
+ if len(self.output_buffer) > 128 * 1024:
307
+ raise BridgeError('Remote frame exceeds limit')
308
+ while b'\n' in self.output_buffer:
309
+ line, self.output_buffer = self.output_buffer.split(b'\n', 1)
310
+ if line.strip():
311
+ event = json.loads(base64.b64decode(line.strip(), validate=True))
312
+ self.dispatch(event)
313
+ await self.tunnel.send('ack', values[0], 'OK', 0)
314
+ elif opcode == 'end' and int(values[0]) == self.output_stream:
315
+ raise BridgeError('Remote helper output pipe closed')
316
+ elif opcode == 'error':
317
+ raise BridgeError('Guacamole error status ' + (values[1] if len(values) > 1 else 'unknown'))
318
+ elif opcode == 'disconnect':
319
+ raise BridgeError('Guacamole disconnected')
320
+ elif opcode in ('img', 'file', 'audio', 'video', 'body') and values:
321
+ # We intentionally do not render the graphical terminal.
322
+ await self.tunnel.send('ack', values[0], 'Not needed', 256)
323
+ self.fail('Guacamole tunnel closed; restart the bridge')
324
+ except asyncio.CancelledError:
325
+ raise
326
+ except Exception as exc:
327
+ self.fail(str(exc) if isinstance(exc, BridgeError) else 'Guacamole transport/protocol failure: ' + type(exc).__name__)
328
+
329
+ def dispatch(self, event):
330
+ self.last_seen = time.monotonic()
331
+ if event['type'] == 'ready':
332
+ if event.get('version') != 1:
333
+ raise BridgeError('Unsupported remote helper version')
334
+ self.ready.set()
335
+ elif event['type'] != 'heartbeat':
336
+ queue = self.requests.get(event.get('id'))
337
+ if queue:
338
+ try:
339
+ queue.put_nowait(event)
340
+ except asyncio.QueueFull as exc:
341
+ raise BridgeError('Remote response exceeded flow control window') from exc
342
+
343
+ async def maintain(self):
344
+ refreshed = time.monotonic()
345
+ try:
346
+ while True:
347
+ await asyncio.sleep(10)
348
+ if time.monotonic() - self.last_seen > 45:
349
+ self.fail('Remote helper heartbeat lost; restart the bridge')
350
+ return
351
+ if time.monotonic() - refreshed > 60 and self.kind == 'c':
352
+ path = 'api/session/data/' + urllib.parse.quote(self.data_source, safe='')
353
+ path += '/connections/' + urllib.parse.quote(self.conn, safe='')
354
+ async with self.session.get(self.base + path, params={'token': self.token},
355
+ timeout=aiohttp.ClientTimeout(total=15),
356
+ allow_redirects=False) as response:
357
+ if response.status != 200:
358
+ self.fail('Guacamole session refresh failed: HTTP ' + str(response.status))
359
+ return
360
+ await response.read()
361
+ refreshed = time.monotonic()
362
+ except asyncio.CancelledError:
363
+ raise
364
+ except Exception:
365
+ self.fail('Guacamole session refresh failed; restart the bridge')
366
+
367
+ async def proxy(self, request):
368
+ if self.args.local_api_key and request.headers.get('Authorization') != 'Bearer ' + self.args.local_api_key:
369
+ return web.json_response({'error': {'message': 'Invalid local API key'}}, status=401)
370
+ if self.failed.is_set():
371
+ return web.json_response({'error': {'message': self.failure}}, status=503)
372
+ if request.query_string:
373
+ return web.json_response({'error': {'message': 'Query parameters are not supported'}}, status=400)
374
+ body = await request.read()
375
+ if len(self.requests) >= self.args.max_requests:
376
+ return web.json_response({'error': {'message': 'Bridge concurrency limit reached'}}, status=429)
377
+ ident = uuid.uuid4().hex
378
+ queue = asyncio.Queue(maxsize=16)
379
+ self.requests[ident] = queue
380
+ headers = {k: v for k, v in request.headers.items()
381
+ if k.lower() in ('authorization', 'content-type', 'accept', 'x-request-id')}
382
+ # Keep framing/decompression simple and byte-for-byte at the local endpoint.
383
+ headers['Accept-Encoding'] = 'identity'
384
+ if self.args.upstream_api_key:
385
+ headers['Authorization'] = 'Bearer ' + self.args.upstream_api_key
386
+ response, complete = None, False
387
+ try:
388
+ async with asyncio.timeout(self.args.request_timeout):
389
+ await self.send_event({'type': 'request', 'id': ident, 'method': request.method,
390
+ 'path': request.path, 'body': base64.b64encode(body).decode(),
391
+ 'headers': headers})
392
+ while True:
393
+ event = await self.next_event(queue, request)
394
+ kind = event['type']
395
+ if kind == 'headers':
396
+ if response is not None:
397
+ raise BridgeError('Duplicate upstream headers')
398
+ response = web.StreamResponse(status=event['status'], headers=event['headers'])
399
+ await response.prepare(request)
400
+ elif kind == 'data':
401
+ if response is None:
402
+ raise BridgeError('Missing upstream headers')
403
+ await response.write(base64.b64decode(event['body'], validate=True))
404
+ await self.send_event({'type': 'credit', 'id': ident})
405
+ elif kind == 'end':
406
+ if response is None:
407
+ raise BridgeError('Missing upstream response')
408
+ await response.write_eof()
409
+ complete = True
410
+ return response
411
+ elif kind == 'error':
412
+ raise BridgeError(event['message'])
413
+ except (BridgeError, asyncio.TimeoutError, ConnectionError, aiohttp.ClientError) as exc:
414
+ status = 504 if isinstance(exc, asyncio.TimeoutError) else 502
415
+ message = str(exc) if isinstance(exc, BridgeError) else ('Request timed out' if status == 504 else 'Connection lost')
416
+ if response is None:
417
+ return web.json_response({'error': {'message': message, 'type': 'bridge_error'}}, status=status)
418
+ LOG.warning('Response interrupted: %s', message)
419
+ if request.transport:
420
+ request.transport.abort()
421
+ return response
422
+ finally:
423
+ self.requests.pop(ident, None)
424
+ if not complete and not self.failed.is_set():
425
+ with contextlib.suppress(Exception):
426
+ await asyncio.wait_for(self.send_event({'type': 'cancel', 'id': ident}), timeout=5)
427
+
428
+ async def next_event(self, queue, request):
429
+ # Detect a disconnected HTTP consumer even while vLLM is still prefilling.
430
+ while True:
431
+ if request.transport is None or request.transport.is_closing():
432
+ raise ConnectionError('Local client disconnected')
433
+ try:
434
+ return await asyncio.wait_for(queue.get(), timeout=1)
435
+ except asyncio.TimeoutError:
436
+ if self.failed.is_set():
437
+ raise BridgeError(self.failure)
438
+
439
+ async def close(self):
440
+ self.closing = True
441
+ if self.tunnel and self.ready.is_set() and not self.failed.is_set():
442
+ with contextlib.suppress(Exception):
443
+ await asyncio.wait_for(self.send_event({'type': 'shutdown'}), timeout=3)
444
+ if self.tunnel and not self.tunnel.closed:
445
+ with contextlib.suppress(Exception):
446
+ await asyncio.wait_for(self.tunnel.send('end', self.input_stream), timeout=2)
447
+ for task in (self.maintainer, self.reader):
448
+ if task:
449
+ task.cancel()
450
+ await asyncio.gather(*(t for t in (self.maintainer, self.reader) if t), return_exceptions=True)
451
+ if self.tunnel:
452
+ await self.tunnel.close()
453
+
454
+
455
+ async def login(session, base, username, password, timeout):
456
+ async with session.post(base + 'api/tokens', data={'username': username, 'password': password},
457
+ timeout=aiohttp.ClientTimeout(total=timeout), allow_redirects=False) as response:
458
+ if response.status != 200:
459
+ raise BridgeError('Guacamole login returned HTTP ' + str(response.status) +
460
+ '. This tool supports the standard username/password login API; '
461
+ 'SSO/MFA or an external login portal requires adaptation.')
462
+ try:
463
+ payload = await response.json(content_type=None)
464
+ return payload['authToken']
465
+ except (ValueError, KeyError) as exc:
466
+ raise BridgeError('Login did not return a Guacamole authToken; check the URL base path') from exc
467
+
468
+
469
+ async def serve(args):
470
+ base, conn, kind, source = parse_url(args.url, args.connection_id, args.data_source)
471
+ command = bootstrap(args) # Validate helper availability/size before login.
472
+ del command
473
+ username = args.username or input('Guacamole username: ')
474
+ password = os.environ.get('GUAC_PASSWORD') or getpass.getpass('Guacamole password: ')
475
+ tls = ssl.create_default_context(cafile=args.ca_file)
476
+ if args.insecure:
477
+ tls.check_hostname = False
478
+ tls.verify_mode = ssl.CERT_NONE
479
+ LOG.warning('TLS verification disabled by --insecure')
480
+ timeout = aiohttp.ClientTimeout(total=None, sock_connect=args.connect_timeout)
481
+ connector = aiohttp.TCPConnector(ssl=tls)
482
+ async with aiohttp.ClientSession(connector=connector, timeout=timeout,
483
+ trust_env=True, auto_decompress=False,
484
+ headers={'Accept-Encoding': 'identity'}) as session:
485
+ token = await login(session, base, username, password, args.connect_timeout)
486
+ password = None
487
+ bridge = Bridge(args, session, base, conn, kind, source, token)
488
+ runner = None
489
+ try:
490
+ await bridge.start()
491
+ app = web.Application(client_max_size=args.max_body_mib * 1024 * 1024)
492
+ for path, method in PATHS.items():
493
+ app.router.add_route(method, path, bridge.proxy)
494
+
495
+ async def health(request):
496
+ return web.json_response({'ready': bridge.ready.is_set() and not bridge.failed.is_set()},
497
+ status=503 if bridge.failed.is_set() else 200)
498
+ app.router.add_get('/health', health)
499
+ runner = web.AppRunner(app, access_log=None, shutdown_timeout=5)
500
+ await runner.setup()
501
+ await web.TCPSite(runner, '127.0.0.1', args.port).start()
502
+ LOG.info('Local API: http://127.0.0.1:%s/v1 (Ctrl+C to stop)', args.port)
503
+ await bridge.failed.wait()
504
+ raise BridgeError(bridge.failure)
505
+ finally:
506
+ if runner:
507
+ await runner.cleanup()
508
+ await bridge.close()
509
+ with contextlib.suppress(Exception):
510
+ async with session.delete(base + 'api/tokens/' + urllib.parse.quote(token, safe=''),
511
+ timeout=aiohttp.ClientTimeout(total=5), allow_redirects=False) as response:
512
+ await response.read()
513
+
514
+
515
+ def cli():
516
+ parser = argparse.ArgumentParser(description=__doc__)
517
+ parser.add_argument('--url', required=True, help='Guacamole URL, including #/client/...')
518
+ parser.add_argument('--username', help='Guacamole login username; otherwise prompted')
519
+ parser.add_argument('--port', type=int, default=8000, help='Local loopback port (default: 8000)')
520
+ parser.add_argument('--upstream', default='http://127.0.0.1:8000', help='Server-side loopback vLLM URL')
521
+ parser.add_argument('--connection-id', help='Override URL connection identifier')
522
+ parser.add_argument('--data-source', help='Override URL data source, e.g. mysql')
523
+ parser.add_argument('--transport', choices=('auto', 'websocket', 'http'), default='auto')
524
+ parser.add_argument('--server-command', default='~/.local/bin/guac-llm-server',
525
+ help='Installed helper executable on server; absolute path recommended')
526
+ parser.add_argument('--startup-delay', type=float, default=2, help='Seconds for remote shell startup')
527
+ parser.add_argument('--connect-timeout', type=float, default=30)
528
+ parser.add_argument('--request-timeout', type=float, default=1800, help='Maximum request duration, seconds')
529
+ parser.add_argument('--max-requests', type=int, default=4)
530
+ parser.add_argument('--max-body-mib', type=int, default=16)
531
+ parser.add_argument('--ca-file', help='Corporate CA PEM file for HTTPS verification')
532
+ parser.add_argument('--insecure', action='store_true', help='Disable HTTPS certificate verification')
533
+ args = parser.parse_args()
534
+ args.upstream_api_key = os.environ.get('VLLM_API_KEY')
535
+ args.local_api_key = os.environ.get('BRIDGE_API_KEY')
536
+ if not 1 <= args.port <= 65535 or not 1 <= args.max_requests <= 16:
537
+ parser.error('Port must be 1..65535; --max-requests must be 1..16')
538
+ if min(args.connect_timeout, args.request_timeout, args.max_body_mib) <= 0 or args.startup_delay < 0:
539
+ parser.error('Timeouts/body limit must be positive; startup delay cannot be negative')
540
+ if args.max_body_mib > 16:
541
+ parser.error('--max-body-mib cannot exceed 16 (remote framing limit)')
542
+ upstream = urllib.parse.urlsplit(args.upstream)
543
+ if (upstream.scheme != 'http' or upstream.hostname not in ('127.0.0.1', 'localhost', '::1')
544
+ or upstream.username or upstream.password or upstream.query or upstream.fragment):
545
+ parser.error('--upstream must be HTTP on server loopback, with no credentials/query/fragment')
546
+ logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
547
+ try:
548
+ asyncio.run(serve(args))
549
+ except KeyboardInterrupt:
550
+ pass
551
+ except (BridgeError, OSError, aiohttp.ClientError, asyncio.TimeoutError) as exc:
552
+ # aiohttp exception strings can include authenticated tunnel URLs. Do not log them.
553
+ LOG.error('%s', str(exc) if isinstance(exc, BridgeError) else type(exc).__name__ +
554
+ ': connection failed; check network, proxy, certificate, and local port')
555
+ return 1
556
+ return 0
557
+
558
+
559
+ if __name__ == '__main__':
560
+ raise SystemExit(cli())
561
+
guac_bridge/server.py ADDED
@@ -0,0 +1,160 @@
1
+ """Server-side stdin/stdout relay, launched inside a Guacamole SSH terminal."""
2
+ import base64
3
+ import http.client
4
+ import json
5
+ import os
6
+ import socket
7
+ import sys
8
+ import threading
9
+ import urllib.parse
10
+
11
+
12
+ def run(config):
13
+ upstream = urllib.parse.urlsplit(config['upstream'])
14
+ if upstream.scheme != 'http' or upstream.hostname not in ('localhost', '127.0.0.1', '::1'):
15
+ raise ValueError('Upstream must be HTTP on server loopback')
16
+ stop = threading.Event()
17
+ lock = threading.Lock()
18
+ states = {}
19
+ state_lock = threading.Lock()
20
+ old_tty = None
21
+ if os.isatty(0):
22
+ import termios
23
+ import tty
24
+ old_tty = termios.tcgetattr(0)
25
+ tty.setraw(0)
26
+
27
+ def output(data):
28
+ with lock:
29
+ sys.stdout.buffer.write(data)
30
+ sys.stdout.buffer.flush()
31
+
32
+ def emit(event):
33
+ with lock:
34
+ if not stop.is_set():
35
+ sys.stdout.buffer.write(base64.b64encode(json.dumps(event, separators=(',', ':')).encode()) + b'\n')
36
+ sys.stdout.buffer.flush()
37
+
38
+ def worker(req, state):
39
+ ident = req['id']
40
+ conn = None
41
+ try:
42
+ path = req['path']
43
+ if path not in ('/v1/chat/completions', '/v1/completions', '/v1/models'):
44
+ raise ValueError('Unsupported endpoint')
45
+ conn = http.client.HTTPConnection(upstream.hostname, upstream.port or 80, timeout=5)
46
+ state['conn'] = conn
47
+ conn.connect()
48
+ state['sock'] = conn.sock
49
+ conn.sock.settimeout(config['timeout'])
50
+ if state['cancel'].is_set():
51
+ return
52
+ conn.request(req['method'], upstream.path.rstrip('/') + path,
53
+ body=base64.b64decode(req['body'], validate=True), headers=req['headers'])
54
+ response = conn.getresponse()
55
+ headers = {k: v for k, v in response.getheaders()
56
+ if k.lower() in ('content-type', 'content-encoding', 'retry-after', 'x-request-id')}
57
+ emit({'type': 'headers', 'id': ident, 'status': response.status, 'headers': headers})
58
+ while not state['cancel'].is_set():
59
+ # read1 returns available bytes; read(4096) would delay SSE tokens.
60
+ data = response.read1(4096)
61
+ if not data:
62
+ break
63
+ while not state['cancel'].is_set():
64
+ if state['credits'].acquire(timeout=1):
65
+ break
66
+ if state['cancel'].is_set():
67
+ break
68
+ emit({'type': 'data', 'id': ident, 'body': base64.b64encode(data).decode()})
69
+ if not state['cancel'].is_set():
70
+ emit({'type': 'end', 'id': ident})
71
+ except Exception as exc:
72
+ if not state['cancel'].is_set():
73
+ emit({'type': 'error', 'id': ident,
74
+ 'message': 'Upstream HTTP failed: ' + type(exc).__name__})
75
+ finally:
76
+ if conn:
77
+ conn.close()
78
+ with state_lock:
79
+ states.pop(ident, None)
80
+
81
+ def cancel(state):
82
+ state['cancel'].set()
83
+ sock = state.get('sock')
84
+ if sock:
85
+ try:
86
+ sock.shutdown(socket.SHUT_RDWR)
87
+ except OSError:
88
+ pass
89
+
90
+ def heartbeat():
91
+ while not stop.wait(10):
92
+ emit({'type': 'heartbeat'})
93
+
94
+ # Flag 2 enables per-frame autoflush, essential for readiness and SSE latency.
95
+ output(b'\x1b]482202;2;LLM\x07')
96
+ try:
97
+ emit({'type': 'ready', 'version': 1})
98
+ threading.Thread(target=heartbeat, daemon=True).start()
99
+ while True:
100
+ line = sys.stdin.buffer.readline(48 * 1024 * 1024)
101
+ if not line:
102
+ break
103
+ req = json.loads(base64.b64decode(line.strip(), validate=True))
104
+ kind = req.get('type')
105
+ if kind == 'shutdown':
106
+ break
107
+ ident = req.get('id')
108
+ if kind in ('credit', 'cancel'):
109
+ with state_lock:
110
+ state = states.get(ident)
111
+ if state:
112
+ if kind == 'credit':
113
+ state['credits'].release()
114
+ else:
115
+ cancel(state)
116
+ elif kind == 'request':
117
+ with state_lock:
118
+ if ident in states or len(states) >= config['max_requests']:
119
+ emit({'type': 'error', 'id': ident, 'message': 'Remote concurrency limit'})
120
+ continue
121
+ state = {'credits': threading.Semaphore(8), 'cancel': threading.Event()}
122
+ states[ident] = state
123
+ threading.Thread(target=worker, args=(req, state), daemon=True).start()
124
+ finally:
125
+ stop.set()
126
+ with state_lock:
127
+ active = list(states.values())
128
+ for state in active:
129
+ cancel(state)
130
+ # Serialize closing with writes from the daemon threads.
131
+ with lock:
132
+ sys.stdout.buffer.write(b'\x1b]482203;\x07')
133
+ sys.stdout.buffer.flush()
134
+ if old_tty is not None:
135
+ termios.tcsetattr(0, termios.TCSANOW, old_tty)
136
+
137
+
138
+ def cli():
139
+ import argparse
140
+ parser = argparse.ArgumentParser(description='Relay vLLM HTTP through a Guacamole SSH terminal.')
141
+ parser.add_argument('--upstream', default='http://127.0.0.1:8000')
142
+ parser.add_argument('--request-timeout', type=float, default=1800)
143
+ parser.add_argument('--max-requests', type=int, default=4)
144
+ args = parser.parse_args()
145
+ url = urllib.parse.urlsplit(args.upstream)
146
+ if (url.scheme != 'http' or url.hostname not in ('localhost', '127.0.0.1', '::1')
147
+ or url.username or url.password or url.query or url.fragment):
148
+ parser.error('--upstream must be HTTP on loopback, without credentials/query/fragment')
149
+ if not 1 <= args.max_requests <= 16 or args.request_timeout <= 0:
150
+ parser.error('--max-requests must be 1..16 and --request-timeout must be positive')
151
+ try:
152
+ run({'upstream': args.upstream, 'timeout': args.request_timeout,
153
+ 'max_requests': args.max_requests})
154
+ except (KeyboardInterrupt, BrokenPipeError, OSError):
155
+ return 1
156
+ return 0
157
+
158
+
159
+ if __name__ == '__main__':
160
+ raise SystemExit(cli())
@@ -0,0 +1,216 @@
1
+ """Expose the remote server's SSH service on local loopback through Guacamole."""
2
+ import argparse
3
+ import asyncio
4
+ import base64
5
+ import contextlib
6
+ import getpass
7
+ import logging
8
+ import os
9
+ import shlex
10
+ import ssl
11
+ import time
12
+ import urllib.parse
13
+ import uuid
14
+
15
+ import aiohttp
16
+
17
+ from .client import Bridge, BridgeError, login, parse_url
18
+
19
+ LOG = logging.getLogger('guac-ssh')
20
+ CHUNK = 4096
21
+ WINDOW = 8
22
+
23
+
24
+ class SSHBridge(Bridge):
25
+ helper_name = 'guac-ssh-server'
26
+
27
+ def __init__(self, *args, **kwargs):
28
+ super().__init__(*args, **kwargs)
29
+ self.credits = {}
30
+ self.connections = set()
31
+
32
+ def helper_command(self):
33
+ executable = ('"$HOME"/' + shlex.quote(self.args.server_command[2:])
34
+ if self.args.server_command.startswith('~/') else shlex.quote(self.args.server_command))
35
+ values = ('--stdio', '--target-host', self.args.target_host, '--target-port', self.args.target_port,
36
+ '--max-connections', self.args.max_connections, '--connect-timeout', self.args.connect_timeout)
37
+ command = executable + ' ' + ' '.join(shlex.quote(str(v)) for v in values) + '\n'
38
+ if len(command.encode()) > 3900:
39
+ raise BridgeError('Helper command exceeds terminal line limit')
40
+ return command.encode()
41
+
42
+ async def send_event(self, event):
43
+ # A connection cancellation must not interrupt a frame shared with other
44
+ # TCP connections, leaving an incomplete Base64 line in the remote PTY.
45
+ task = asyncio.create_task(super().send_event(event))
46
+ try:
47
+ await asyncio.shield(task)
48
+ except asyncio.CancelledError:
49
+ with contextlib.suppress(Exception):
50
+ await task
51
+ raise
52
+
53
+ def dispatch(self, event):
54
+ if event.get('type') == 'ready' and event.get('protocol') != 'ssh-tcp':
55
+ raise BridgeError('Expected guac-ssh-server; incorrect remote helper')
56
+ if event.get('type') == 'credit':
57
+ self.last_seen = time.monotonic()
58
+ semaphore = self.credits.get(event.get('id'))
59
+ if semaphore:
60
+ semaphore.release()
61
+ else:
62
+ super().dispatch(event)
63
+
64
+ async def accept(self, reader, writer):
65
+ task = asyncio.current_task()
66
+ if self.failed.is_set() or self.closing or len(self.requests) >= self.args.max_connections:
67
+ writer.close()
68
+ with contextlib.suppress(Exception):
69
+ await writer.wait_closed()
70
+ return
71
+ self.connections.add(task)
72
+ ident = uuid.uuid4().hex
73
+ queue = asyncio.Queue(maxsize=WINDOW + 4)
74
+ self.requests[ident] = queue
75
+ self.credits[ident] = asyncio.BoundedSemaphore(WINDOW)
76
+ tasks = []
77
+ try:
78
+ await self.send_event({'type': 'open', 'id': ident})
79
+ event = await self.wait_for(queue.get(), self.args.connect_timeout)
80
+ if event['type'] != 'opened':
81
+ raise BridgeError(event.get('message', 'SSH target did not open'))
82
+
83
+ async def upload():
84
+ while True:
85
+ await self.credits[ident].acquire()
86
+ data = await reader.read(CHUNK)
87
+ if not data:
88
+ self.credits[ident].release()
89
+ await self.send_event({'type': 'eof', 'id': ident})
90
+ return
91
+ await self.send_event({'type': 'data', 'id': ident,
92
+ 'body': base64.b64encode(data).decode()})
93
+
94
+ async def download():
95
+ while True:
96
+ event = await queue.get()
97
+ kind = event['type']
98
+ if kind == 'data':
99
+ data = base64.b64decode(event['body'], validate=True)
100
+ if len(data) > CHUNK:
101
+ raise BridgeError('TCP frame exceeds limit')
102
+ writer.write(data)
103
+ await writer.drain()
104
+ await self.send_event({'type': 'credit', 'id': ident})
105
+ elif kind in ('eof', 'closed'):
106
+ if writer.can_write_eof():
107
+ writer.write_eof()
108
+ await writer.drain()
109
+ return
110
+ elif kind == 'error':
111
+ raise BridgeError(event['message'])
112
+ else:
113
+ raise BridgeError('Unexpected TCP relay event')
114
+
115
+ tasks = [asyncio.create_task(upload()), asyncio.create_task(download())]
116
+ await asyncio.gather(*tasks)
117
+ except asyncio.CancelledError:
118
+ raise
119
+ except (BridgeError, ConnectionError, OSError, asyncio.TimeoutError) as exc:
120
+ LOG.warning('%s', str(exc) if isinstance(exc, BridgeError) else 'SSH TCP connection interrupted')
121
+ if writer.transport:
122
+ writer.transport.abort()
123
+ finally:
124
+ for child in tasks:
125
+ child.cancel()
126
+ await asyncio.gather(*tasks, return_exceptions=True)
127
+ if not self.failed.is_set() and self.tunnel and not self.tunnel.closed:
128
+ with contextlib.suppress(Exception):
129
+ await asyncio.wait_for(self.send_event({'type': 'close', 'id': ident}), 5)
130
+ self.requests.pop(ident, None)
131
+ self.credits.pop(ident, None)
132
+ writer.close()
133
+ with contextlib.suppress(Exception):
134
+ await asyncio.wait_for(writer.wait_closed(), 2)
135
+ self.connections.discard(task)
136
+
137
+ async def close(self):
138
+ self.closing = True
139
+ tasks = list(self.connections)
140
+ for task in tasks:
141
+ task.cancel()
142
+ await asyncio.gather(*tasks, return_exceptions=True)
143
+ await super().close()
144
+
145
+
146
+ async def serve(args):
147
+ base, conn, kind, source = parse_url(args.url, args.connection_id, args.data_source)
148
+ username = args.username or input('Guacamole username: ')
149
+ password = os.environ.get('GUAC_PASSWORD') or getpass.getpass('Guacamole password: ')
150
+ tls = ssl.create_default_context(cafile=args.ca_file)
151
+ if args.insecure:
152
+ tls.check_hostname = False
153
+ tls.verify_mode = ssl.CERT_NONE
154
+ LOG.warning('TLS verification disabled by --insecure')
155
+ connector = aiohttp.TCPConnector(ssl=tls)
156
+ async with aiohttp.ClientSession(connector=connector, trust_env=True, auto_decompress=False,
157
+ timeout=aiohttp.ClientTimeout(total=None, sock_connect=args.connect_timeout),
158
+ headers={'Accept-Encoding': 'identity'}) as session:
159
+ token = await login(session, base, username, password, args.connect_timeout)
160
+ password = None
161
+ bridge = SSHBridge(args, session, base, conn, kind, source, token)
162
+ listener = None
163
+ try:
164
+ await bridge.start()
165
+ listener = await asyncio.start_server(bridge.accept, '127.0.0.1', args.port)
166
+ LOG.info('SSH bridge: 127.0.0.1:%s -> server %s:%s (Ctrl+C to stop)',
167
+ args.port, args.target_host, args.target_port)
168
+ await bridge.failed.wait()
169
+ raise BridgeError(bridge.failure)
170
+ finally:
171
+ if listener:
172
+ listener.close()
173
+ await bridge.close()
174
+ if listener:
175
+ await listener.wait_closed()
176
+ with contextlib.suppress(Exception):
177
+ async with session.delete(base + 'api/tokens/' + urllib.parse.quote(token, safe=''),
178
+ timeout=aiohttp.ClientTimeout(total=5), allow_redirects=False) as response:
179
+ await response.read()
180
+
181
+
182
+ def cli():
183
+ parser = argparse.ArgumentParser(description=__doc__)
184
+ parser.add_argument('--url', required=True, help='Full Guacamole connection URL')
185
+ parser.add_argument('--username', help='Guacamole username; otherwise prompted')
186
+ parser.add_argument('--port', type=int, default=2222, help='Local loopback listener port')
187
+ parser.add_argument('--target-host', choices=('127.0.0.1', 'localhost', '::1'), default='127.0.0.1')
188
+ parser.add_argument('--target-port', type=int, default=22, help='Server-side loopback SSH port')
189
+ parser.add_argument('--max-connections', type=int, default=8)
190
+ parser.add_argument('--server-command', default='~/.local/bin/guac-ssh-server', help='Remote helper executable path')
191
+ parser.add_argument('--connection-id')
192
+ parser.add_argument('--data-source')
193
+ parser.add_argument('--transport', choices=('auto', 'websocket', 'http'), default='auto')
194
+ parser.add_argument('--startup-delay', type=float, default=2)
195
+ parser.add_argument('--connect-timeout', type=float, default=30)
196
+ parser.add_argument('--ca-file', help='Corporate CA PEM bundle')
197
+ parser.add_argument('--insecure', action='store_true', help='Disable Guacamole TLS verification')
198
+ args = parser.parse_args()
199
+ if not (1 <= args.port <= 65535 and 1 <= args.target_port <= 65535 and 1 <= args.max_connections <= 16):
200
+ parser.error('Ports must be 1..65535 and connection limit must be 1..16')
201
+ if args.connect_timeout <= 0 or args.startup_delay < 0:
202
+ parser.error('Timeout must be positive and startup delay cannot be negative')
203
+ logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
204
+ try:
205
+ asyncio.run(serve(args))
206
+ except KeyboardInterrupt:
207
+ pass
208
+ except (BridgeError, OSError, aiohttp.ClientError, asyncio.TimeoutError) as exc:
209
+ LOG.error('%s', str(exc) if isinstance(exc, BridgeError) else type(exc).__name__ +
210
+ ': check network, proxy, TLS trust, and local port')
211
+ return 1
212
+ return 0
213
+
214
+
215
+ if __name__ == '__main__':
216
+ raise SystemExit(cli())
@@ -0,0 +1,187 @@
1
+ """Binary TCP relay to a loopback SSH service, over a Guacamole terminal."""
2
+ import argparse
3
+ import asyncio
4
+ import base64
5
+ import contextlib
6
+ import json
7
+ import os
8
+ import signal
9
+ import sys
10
+ import threading
11
+
12
+ CHUNK = 4096
13
+ WINDOW = 8
14
+
15
+
16
+ async def relay(args):
17
+ events = asyncio.Queue(maxsize=64)
18
+ channels = {}
19
+ loop = asyncio.get_running_loop()
20
+ stopping = threading.Event()
21
+
22
+ def emit(event):
23
+ data = base64.b64encode(json.dumps(event, separators=(',', ':')).encode())
24
+ sys.stdout.buffer.write(data + b'\n')
25
+ sys.stdout.buffer.flush()
26
+
27
+ def stdin_reader():
28
+ try:
29
+ while not stopping.is_set():
30
+ line = sys.stdin.buffer.readline(65536)
31
+ if not line:
32
+ event = {'type': 'shutdown'}
33
+ else:
34
+ if not line.endswith(b'\n'):
35
+ raise ValueError('Frame too large')
36
+ event = json.loads(base64.b64decode(line.strip(), validate=True))
37
+ future = asyncio.run_coroutine_threadsafe(events.put(event), loop)
38
+ future.result()
39
+ if event.get('type') == 'shutdown':
40
+ return
41
+ except Exception:
42
+ if not stopping.is_set() and not loop.is_closed():
43
+ asyncio.run_coroutine_threadsafe(events.put({'type': 'shutdown'}), loop)
44
+
45
+ async def connection(ident, state):
46
+ writer = None
47
+ tasks = []
48
+ try:
49
+ reader, writer = await asyncio.wait_for(
50
+ asyncio.open_connection(args.target_host, args.target_port), args.connect_timeout)
51
+ emit({'type': 'opened', 'id': ident})
52
+
53
+ async def receive_tcp():
54
+ while True:
55
+ await state['credits'].acquire()
56
+ data = await reader.read(CHUNK)
57
+ if not data:
58
+ state['credits'].release()
59
+ emit({'type': 'eof', 'id': ident})
60
+ return
61
+ emit({'type': 'data', 'id': ident, 'body': base64.b64encode(data).decode()})
62
+
63
+ async def send_tcp():
64
+ while True:
65
+ data = await state['input'].get()
66
+ if data is None:
67
+ if writer.can_write_eof():
68
+ writer.write_eof()
69
+ await writer.drain()
70
+ return
71
+ writer.write(data)
72
+ await writer.drain()
73
+ emit({'type': 'credit', 'id': ident})
74
+
75
+ tasks = [asyncio.create_task(receive_tcp()), asyncio.create_task(send_tcp())]
76
+ await asyncio.gather(*tasks)
77
+ emit({'type': 'closed', 'id': ident})
78
+ except asyncio.CancelledError:
79
+ raise
80
+ except Exception as exc:
81
+ emit({'type': 'error', 'id': ident,
82
+ 'message': 'SSH target connection failed: ' + type(exc).__name__})
83
+ finally:
84
+ for task in tasks:
85
+ task.cancel()
86
+ await asyncio.gather(*tasks, return_exceptions=True)
87
+ if writer:
88
+ writer.close()
89
+ with contextlib.suppress(Exception):
90
+ await asyncio.wait_for(writer.wait_closed(), 2)
91
+ channels.pop(ident, None)
92
+
93
+ async def heartbeat():
94
+ while True:
95
+ await asyncio.sleep(10)
96
+ emit({'type': 'heartbeat'})
97
+
98
+ # LLM is the established transport pipe name, shared by both relay modes.
99
+ sys.stdout.buffer.write(b'\x1b]482202;2;LLM\x07')
100
+ sys.stdout.buffer.flush()
101
+ emit({'type': 'ready', 'version': 1, 'protocol': 'ssh-tcp'})
102
+ main = asyncio.current_task()
103
+ for sig in (signal.SIGTERM, signal.SIGHUP):
104
+ loop.add_signal_handler(sig, main.cancel)
105
+ thread = threading.Thread(target=stdin_reader, daemon=True)
106
+ thread.start()
107
+ pulse = asyncio.create_task(heartbeat())
108
+ try:
109
+ while True:
110
+ event = await events.get()
111
+ kind, ident = event.get('type'), event.get('id')
112
+ if kind == 'shutdown':
113
+ break
114
+ if kind == 'open':
115
+ if not isinstance(ident, str) or not ident or len(ident) > 64:
116
+ raise ValueError('Invalid connection ID')
117
+ if ident in channels:
118
+ raise ValueError('Duplicate connection ID')
119
+ if len(channels) >= args.max_connections:
120
+ emit({'type': 'error', 'id': ident, 'message': 'SSH connection limit reached'})
121
+ continue
122
+ state = {'input': asyncio.Queue(maxsize=WINDOW + 1),
123
+ 'credits': asyncio.BoundedSemaphore(WINDOW), 'eof': False}
124
+ channels[ident] = state
125
+ state['task'] = asyncio.create_task(connection(ident, state))
126
+ continue
127
+ state = channels.get(ident)
128
+ if state is None:
129
+ continue
130
+ if kind == 'data':
131
+ data = base64.b64decode(event['body'], validate=True)
132
+ if len(data) > CHUNK or state['eof']:
133
+ raise ValueError('Invalid TCP data frame')
134
+ state['input'].put_nowait(data)
135
+ elif kind == 'credit':
136
+ state['credits'].release()
137
+ elif kind == 'eof':
138
+ if state['eof']:
139
+ raise ValueError('Duplicate TCP EOF')
140
+ state['eof'] = True
141
+ state['input'].put_nowait(None)
142
+ elif kind == 'close':
143
+ state['task'].cancel()
144
+ finally:
145
+ stopping.set()
146
+ pulse.cancel()
147
+ tasks = [state['task'] for state in list(channels.values())]
148
+ for task in tasks:
149
+ task.cancel()
150
+ await asyncio.gather(pulse, *tasks, return_exceptions=True)
151
+ sys.stdout.buffer.write(b'\x1b]482203;\x07')
152
+ sys.stdout.buffer.flush()
153
+ for sig in (signal.SIGTERM, signal.SIGHUP):
154
+ loop.remove_signal_handler(sig)
155
+
156
+
157
+ def cli():
158
+ parser = argparse.ArgumentParser(description=__doc__)
159
+ parser.add_argument('--stdio', action='store_true', help='Run the machine protocol; supplied by guac-ssh-client')
160
+ parser.add_argument('--target-host', choices=('127.0.0.1', 'localhost', '::1'), default='127.0.0.1')
161
+ parser.add_argument('--target-port', type=int, default=22)
162
+ parser.add_argument('--connect-timeout', type=float, default=30)
163
+ parser.add_argument('--max-connections', type=int, default=8)
164
+ args = parser.parse_args()
165
+ if not args.stdio:
166
+ parser.error('This helper is started automatically by guac-ssh-client. Do not run it manually.')
167
+ if not 1 <= args.target_port <= 65535 or not 1 <= args.max_connections <= 16 or args.connect_timeout <= 0:
168
+ parser.error('Invalid target port, connection limit (1..16), or timeout')
169
+ old = None
170
+ try:
171
+ if os.isatty(0):
172
+ import termios
173
+ import tty
174
+ old = termios.tcgetattr(0)
175
+ tty.setraw(0)
176
+ asyncio.run(relay(args))
177
+ except (asyncio.CancelledError, KeyboardInterrupt, BrokenPipeError, OSError, ValueError):
178
+ return 1
179
+ finally:
180
+ if old is not None:
181
+ with contextlib.suppress(OSError):
182
+ termios.tcsetattr(0, termios.TCSANOW, old)
183
+ return 0
184
+
185
+
186
+ if __name__ == '__main__':
187
+ raise SystemExit(cli())
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: guac-bridge
3
+ Version: 0.2.0
4
+ Summary: Bridge remote LLM APIs and SSH over an Apache Guacamole terminal
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/himbeles/guac-bridge
7
+ Project-URL: Issues, https://github.com/himbeles/guac-bridge/issues
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: aiohttp<4,>=3.10
12
+ Dynamic: license-file
13
+
14
+ # Guac Bridge
15
+
16
+ Access an OpenAI-compatible endpoint or SSH service on a server through its
17
+ Guacamole web terminal.
18
+
19
+ ## Install
20
+
21
+ Install on both your client computer and the server. Requires Python 3.11+ and
22
+ [uv](https://docs.astral.sh/uv/).
23
+
24
+ ```shell
25
+ uv tool install guac-bridge
26
+ uv tool update-shell
27
+ ```
28
+
29
+ The client starts the appropriate server helper automatically. Keep the client
30
+ running while using the bridge; stop it with **Ctrl+C**.
31
+
32
+ For the commands below, copy the full URL from your browser after opening the
33
+ desired Guacamole connection. Replace `CLIENT_ID` and `YOUR_USERNAME` with
34
+ your connection details. Your Guacamole password is prompted.
35
+
36
+ ## Usage: LLM bridge
37
+
38
+ The server's OpenAI-compatible endpoint should be available at
39
+ `http://127.0.0.1:8000`.
40
+
41
+ On your client computer:
42
+
43
+ ```shell
44
+ guac-llm-client --url "https://guacamole.example.com/#/client/CLIENT_ID" --username YOUR_USERNAME
45
+ ```
46
+
47
+ Configure your LLM application with:
48
+
49
+ | Setting | Value |
50
+ | --- | --- |
51
+ | OpenAI base URL | `http://127.0.0.1:8000/v1` |
52
+ | Chat completions URL | `http://127.0.0.1:8000/v1/chat/completions` |
53
+ | Model | A model ID from `/v1/models` |
54
+ | API key | The key required by the server endpoint, or a placeholder if none is required |
55
+
56
+ Requests, streamed responses, and the application's API key are forwarded to
57
+ the server endpoint.
58
+
59
+ Use `--upstream http://127.0.0.1:9000` for a different server-side endpoint
60
+ (omit `/v1`), or `--port 18000` for a different local port.
61
+
62
+ ## Usage: SSH bridge
63
+
64
+ The server's SSH service should be reachable at `127.0.0.1:22`.
65
+
66
+ On your client computer:
67
+
68
+ ```shell
69
+ guac-ssh-client --url "https://guacamole.example.com/#/client/CLIENT_ID" --username YOUR_USERNAME
70
+ ```
71
+
72
+ In another local terminal:
73
+
74
+ ```shell
75
+ ssh -p 2222 serveruser@127.0.0.1
76
+ ```
77
+
78
+ Use the server's SSH username and its usual password or SSH key. SSH
79
+ authentication and host-key verification are handled by your SSH client.
80
+ SCP and SFTP work through the same local port.
81
+
82
+ To forward the server's OpenAI-compatible endpoint through SSH:
83
+
84
+ ```shell
85
+ ssh -p 2222 -N -L 8000:127.0.0.1:8000 serveruser@127.0.0.1
86
+ ```
87
+
88
+ Use `--target-port` to select a different server-side SSH port and `--port`
89
+ to change the local listener.
90
+
91
+ Both bridges support `--ca-file company-ca.pem` for a custom certificate
92
+ authority and `--transport http` to use Guacamole's HTTP tunnel.
93
+ If a helper is installed outside `~/.local/bin/`, pass its full path with
94
+ `--server-command`. Run either client with `--help` for all options.
95
+
96
+ ## Contribution
97
+
98
+ Submit issues and pull requests on
99
+ [GitHub](https://github.com/himbeles/guac-bridge).
100
+ Include tests for behavior changes.
101
+
102
+ From a repository checkout, run the test suite in an environment with Bash and
103
+ PTY support:
104
+
105
+ ```shell
106
+ uv run python -m unittest discover -s tests -v
107
+ ```
108
+
109
+ ## Architecture
110
+
111
+ Each client logs into Guacamole and starts its matching server helper inside
112
+ the terminal session. Framed, Base64-encoded messages travel through Guacamole's
113
+ input and output pipes.
114
+
115
+ | Bridge | Local listener | Server helper |
116
+ | --- | --- | --- |
117
+ | LLM | OpenAI-compatible HTTP API | Forwards requests and streamed responses to the server endpoint |
118
+ | SSH | TCP port for your SSH client | Relays bytes to the server's SSH service |
119
+
120
+ Listeners bind to local loopback. Helpers connect to services on the server's
121
+ loopback interface, so no additional inbound server port is needed. Per-connection
122
+ flow control bounds buffering; disconnecting Guacamole closes active connections.
@@ -0,0 +1,11 @@
1
+ guac_bridge/__init__.py,sha256=wvkRrh7soGDfH5EAe7WrQtTiyy54VwwkWDyle5cJ6X8,23
2
+ guac_bridge/client.py,sha256=4oMy9TyVr_6w6ID-YiLNL1D4LG9H2Ncl8VfU5kLDwdQ,28128
3
+ guac_bridge/server.py,sha256=qm-WZaVzDeqSo8xuLCKzc6eXYEXHJYpStNbGyqq9U4Y,6316
4
+ guac_bridge/ssh_client.py,sha256=2w5VgONffDBzYTyJjTPKBBzdj6eJ95gKBMe98e7PnfY,9839
5
+ guac_bridge/ssh_server.py,sha256=RBOIge-iWrZAI3qvlqyBTaj_rwoVhmnPvZv_-2RkuJY,7414
6
+ guac_bridge-0.2.0.dist-info/licenses/LICENSE,sha256=ESYyLizI0WWtxMeS7rGVcX3ivMezm-HOd5WdeOh-9oU,1056
7
+ guac_bridge-0.2.0.dist-info/METADATA,sha256=BOFsZ0Y_gll886HE3vza095-P-WX9BYUxdv6Q2cimeY,3900
8
+ guac_bridge-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ guac_bridge-0.2.0.dist-info/entry_points.txt,sha256=N__qZ5gDuoF519ypppTgsHxR7zVtlknQzfDafRrorAY,190
10
+ guac_bridge-0.2.0.dist-info/top_level.txt,sha256=0sZAaWVnM-Sbwkgih1UEJ_wAOVJY6RQ3tlyvxUvjrN8,12
11
+ guac_bridge-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,5 @@
1
+ [console_scripts]
2
+ guac-llm-client = guac_bridge.client:cli
3
+ guac-llm-server = guac_bridge.server:cli
4
+ guac-ssh-client = guac_bridge.ssh_client:cli
5
+ guac-ssh-server = guac_bridge.ssh_server:cli
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ guac_bridge