| 77 | pass |
| 78 | |
| 79 | class TermNetWebSocketServer: |
| 80 | def __init__(self, host="localhost", port=876): |
| 81 | self.host = host |
| 82 | self.port = port |
| 83 | self.connected_clients = set() |
| 84 | self.term = None |
| 85 | self.agent = None |
| 86 | |
| 87 | async def initialize_termnet(self): |
| 88 | """Initialize the TerminalSession and TermNetAgent""" |
| 89 | if self.term is None: |
| 90 | self.term = TerminalSession() |
| 91 | await self.term.start() |
| 92 | self.agent = TermNetAgent(self.term) |
| 93 | |
| 94 | async def stream_agent_response(self, websocket, user_input: str): |
| 95 | """Stream the agent's response back to the client with real-time capture""" |
| 96 | try: |
| 97 | # Create stream capture |
| 98 | capture = StreamCapture(websocket) |
| 99 | |
| 100 | # Send initial response start |
| 101 | start_msg = { |
| 102 | "type": "response_start", |
| 103 | "timestamp": time.time() |
| 104 | } |
| 105 | try: |
| 106 | await websocket.send(json.dumps(start_msg)) |
| 107 | except: |
| 108 | return |
| 109 | |
| 110 | # Temporarily redirect stdout |
| 111 | original_stdout = sys.stdout |
| 112 | sys.stdout = capture |
| 113 | |
| 114 | try: |
| 115 | # Call the agent's chat method |
| 116 | await self.agent.chat(user_input) |
| 117 | |
| 118 | # Allow final buffer processing |
| 119 | await asyncio.sleep(0.1) |
| 120 | await capture.process_buffer() |
| 121 | |
| 122 | finally: |
| 123 | # Restore original stdout |
| 124 | sys.stdout = original_stdout |
| 125 | |
| 126 | # Send end of response |
| 127 | end_msg = { |
| 128 | "type": "response_end", |
| 129 | "timestamp": time.time() |
| 130 | } |
| 131 | try: |
| 132 | await websocket.send(json.dumps(end_msg)) |
| 133 | except: |
| 134 | pass |
| 135 | |
| 136 | except Exception as e: |