11import asyncio
22import os
3- import signal
4- import sys
53import click
64import uvicorn
7- import threading
8- import time
95
106from dotenv import load_dotenv
117from openagent .agent .agent import OpenAgent
1410load_dotenv (dotenv_path = os .path .join (os .getcwd (), ".env" ))
1511
1612
17- def win_handler (signum , frame ):
18- sys .exit ()
19-
20-
21- async def shutdown (agent , loop ):
13+ def shutdown ():
2214 click .echo ("\n Shutting down..." )
23- agent .stop ()
24- tasks = [t for t in asyncio .all_tasks () if t is not asyncio .current_task ()]
25- for task in tasks :
26- task .cancel ()
27- await asyncio .gather (* tasks , return_exceptions = True )
28- loop .stop ()
29-
30-
31- def check_exit_windows (loop ):
32- """Check for exit command on Windows (press 'q' to quit)"""
33- import msvcrt
34-
35- while True :
36- if msvcrt .kbhit ():
37- key = msvcrt .getch ().decode ("utf-8" ).lower ()
38- if key == "q" :
39- print ("\n Shutting down..." )
40- os ._exit (0 ) # Force exit
41- time .sleep (1 )
42-
43-
44- def check_exit_unix (loop ):
45- """Check for exit command on Unix (press 'q' to quit)"""
46- print ("\n Press 'q' to quit..." )
47- while True :
48- try :
49- # Non-blocking read from stdin
50- import select
51-
52- if select .select ([sys .stdin ], [], [], 0 )[0 ]:
53- key = sys .stdin .read (1 )
54- if key == "q" :
55- print ("\n Shutting down..." )
56- os ._exit (0 )
57- except Exception as e :
58- print (f"Error reading input: { e } " )
59- time .sleep (1 )
15+ os ._exit (0 )
6016
6117
6218@click .group ()
@@ -81,35 +37,18 @@ def start(file, host, port):
8137 loop = asyncio .new_event_loop ()
8238 asyncio .set_event_loop (loop )
8339
84- # Set platform specific handlers
85- if sys .platform == "win32" :
86- signal .signal (signal .SIGINT , win_handler )
87- check_exit_func = check_exit_windows
88- else :
89- loop .add_signal_handler (
90- signal .SIGINT , lambda : asyncio .create_task (shutdown (agent , loop ))
91- )
92- loop .add_signal_handler (
93- signal .SIGTERM , lambda : asyncio .create_task (shutdown (agent , loop ))
94- )
95- check_exit_func = check_exit_unix
96-
9740 # Create FastAPI config
98- config = uvicorn .Config (app , host = host , port = port , loop = loop )
41+ config = uvicorn .Config (app , host = host , port = port )
9942 server = uvicorn .Server (config )
10043
10144 # Run both FastAPI and OpenAgent
10245 loop .create_task (agent .start ())
10346 loop .create_task (server .serve ())
10447
105- # Start exit command checker in a separate thread
106- exit_thread = threading .Thread (target = check_exit_func , args = (loop ,), daemon = True )
107- exit_thread .start ()
108-
10948 try :
11049 loop .run_forever ()
11150 except KeyboardInterrupt :
112- loop .run_until_complete (shutdown (agent , loop ))
51+ loop .run_until_complete (shutdown ())
11352 finally :
11453 loop .close ()
11554
0 commit comments