-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner.py
247 lines (212 loc) · 8.55 KB
/
runner.py
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
import argparse
import atexit
import json
import logging
import os
import signal
import sys
import time
import uuid
from subprocess import Popen
from typing import List
import toml
from collaborative_gym.core import TeamMemberConfig
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Runner:
"""
Manages human-agent collaboration sessions.
This class handles the lifecycle of human-agent collaboration sessions, including
launching task environment and team members (agents, users, etc.), managing their
processes, and ensuring proper cleanup on exit.
It uses Redis for inter-process communication and maintains session state.
Attributes:
result_dir: Directory for storing session results
redis_url: URL for Redis connection used by team members
subprocesses: List of active subprocess handles
sessions: List of active session UUIDs
"""
def __init__(
self,
result_dir: str = "./workdir/results",
redis_url: str = "redis://localhost:6379/0",
):
if not os.path.exists(result_dir):
os.makedirs(result_dir)
self.result_dir = result_dir
self.redis_url = redis_url
self.subprocesses: List[Popen[bytes]] = []
self.sessions = []
def check_session_exists(self, session_uuid: str) -> bool:
"""
Check if a session with the given UUID exists.
Args:
session_uuid: Unique identifier for the session to check
Returns:
bool: True if the session exists, False otherwise
"""
return session_uuid in self.sessions
def launch_team_member(self, env_uuid: str, member: TeamMemberConfig):
"""
Launch a team member process with the specified configuration.
Creates and starts a subprocess for the team member, configuring it with
the appropriate environment UUID and Redis connection. Handles different
member types (cmd_user, simulated_user, agent, gui_user) appropriately.
Args:
env_uuid: Unique identifier for the environment
member: Configuration for the team member to launch
"""
if member.type == "cmd_user":
start_member_command = (
f"{member.start_node_base_command} "
f"--node-name {member.name} --env-uuid {env_uuid} --redis-url {self.redis_url}"
)
elif member.type == "simulated_user":
start_member_command = (
f"{member.start_node_base_command} "
f"--node-name {member.name} --env-uuid {env_uuid} --redis-url {self.redis_url}"
)
elif member.type == "agent":
start_member_command = (
f"{member.start_node_base_command} "
f"--node-name {member.name} --env-uuid {env_uuid} "
f"--redis-url {self.redis_url}"
)
elif member.type == "gui_user":
return
agent_process = Popen(
[start_member_command],
shell=True,
preexec_fn=os.setsid, # Start the subprocess in a new process group
)
self.subprocesses.append(agent_process)
time.sleep(5) # Wait for the node to start
def start_session(
self,
session_uuid: str,
env_config_path: str,
members: List[TeamMemberConfig],
max_steps: int,
disable_collaboration: bool = False,
add_tick: bool = False,
tick_interval: float = 60,
max_tick_cnt: int = 5,
):
"""
Start a new human-agent collaboration session.
Creates and launches all necessary processes for a collaborative session,
including team members and the environment itself. Optionally adds a tick
process for managing timeouts.
Args:
session_uuid: Unique identifier for the new session
env_config_path: Path to the environment configuration file
members: List of team member configurations
max_steps: Maximum number of steps allowed in the session
disable_collaboration: If True, only task actions are allowed
add_tick: If True, adds a process to handle timeouts
tick_interval: Time in seconds between tick checks
max_tick_cnt: Maximum number of ticks before timeout
"""
if session_uuid in self.sessions:
print(f"Session {session_uuid} already started")
return
self.sessions.append(session_uuid)
env_uuid = f"env_{session_uuid}"
for member in members:
self.launch_team_member(env_uuid, member)
team_member_names = [member.name for member in members]
start_env_command = (
f"python -m collaborative_gym.command start-env-node "
f"--node-name task_env --env-config-toml {env_config_path} --env-uuid {env_uuid} "
f"--team-members '{json.dumps(team_member_names)}' --max-steps {max_steps} "
f"--tick-interval {tick_interval} --max-tick-cnt {max_tick_cnt} "
f"--result-dir {self.result_dir} --redis-url {self.redis_url}"
)
print(start_env_command)
if disable_collaboration:
start_env_command += " --disable-collaboration"
env_process = Popen(
[start_env_command],
shell=True,
preexec_fn=os.setsid, # Start the subprocess in a new process group
)
self.subprocesses.append(env_process)
if add_tick:
start_tick_command = (
f"python -m collaborative_gym.command start-env-tick-node --env-node-name task_env "
f"--env-uuid {env_uuid} --redis-url {self.redis_url}"
)
tick_process = Popen(
[start_tick_command],
shell=True,
preexec_fn=os.setsid, # Start the subprocess in a new process group
)
self.subprocesses.append(tick_process)
def cleanup_subprocesses(self):
"""
Terminate all managed subprocesses gracefully.
Sends SIGTERM to each subprocess group and waits for them to exit.
This ensures all child processes are properly cleaned up.
"""
for proc in self.subprocesses:
try:
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
proc.wait()
print(f"Terminated process group {proc.pid}")
except Exception as e:
print(f"Failed to terminate {proc.pid}: {e}")
def reset(self):
"""
Reset the runner to its initial state.
Terminates all running processes and clears session records.
"""
self.cleanup_subprocesses()
self.subprocesses = []
self.sessions = []
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--env-config-path", type=str, required=True)
parser.add_argument("--team-member-config-path", type=str, required=True)
parser.add_argument(
"--disable-collaboration",
action="store_true",
help="When set, the environment will only support task actions and not collaboration actions.",
)
parser.add_argument(
"--add-tick",
action="store_true",
help="When set, the environment will send messages to remind the agents when there is no "
"activity for too long.",
)
parser.add_argument(
"--max-steps",
type=int,
default=100,
help="The maximum number of steps the environment",
)
parser.add_argument("--secret-path", type=str, default="secrets.toml")
parser.add_argument("--redis-url", type=str, default="redis://localhost:6379/0")
args = parser.parse_args()
secrets = toml.load(args.secret_path)
for k in secrets:
os.environ[k] = secrets[k]
runner = Runner()
def handle_exit_signal(signum, frame):
runner.cleanup_subprocesses()
sys.exit(0)
atexit.register(runner.cleanup_subprocesses)
signal.signal(signal.SIGINT, handle_exit_signal)
signal.signal(signal.SIGTERM, handle_exit_signal)
team_member_config = toml.load(args.team_member_config_path)
runner.start_session(
session_uuid=str(uuid.uuid4()),
env_config_path=args.env_config_path,
members=[
TeamMemberConfig(**member) for member in team_member_config["team_member"]
],
max_steps=args.max_steps,
disable_collaboration=args.disable_collaboration,
add_tick=args.add_tick,
)
for node_process in runner.subprocesses:
node_process.wait()