MCPcopy Create free account
hub / github.com/HKUDS/AutoAgent / run_command

Method run_command

autoagent/environment/docker_env.py:144–199  ·  view source on GitHub ↗

communicate with docker container and execute command, support stream output Args: command: the command to execute stream_callback: optional callback function, for handling stream output the function signature should be ca

(self, command, stream_callback=None)

Source from the content-addressed store, hash-verified

142 raise Exception(f"Failed to stop container: {result.stderr}")
143
144 def run_command(self, command, stream_callback=None):
145 """
146 communicate with docker container and execute command, support stream output
147
148 Args:
149 command: the command to execute
150 stream_callback: optional callback function, for handling stream output
151 the function signature should be callback(text: str)
152
153 Returns:
154 dict: the complete JSON result returned by the docker container
155 """
156 hostname = 'localhost'
157 port = self.communication_port
158 buffer_size = 4096
159
160 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
161 s.connect((hostname, port))
162 s.sendall(command.encode())
163
164 partial_line = ""
165 while True:
166 chunk = s.recv(buffer_size)
167 if not chunk:
168 break
169
170 # add new received data to the unfinished data
171 data = partial_line + chunk.decode('utf-8')
172 lines = data.split('\n')
173
174 # except the last line, process all complete lines
175 for line in lines[:-1]:
176 if line:
177 try:
178 response = json.loads(line)
179 if response['type'] == 'chunk':
180 # process stream output
181 if stream_callback:
182 stream_callback(response['data'])
183 elif response['type'] == 'final':
184 # return the final result
185 return {
186 'status': response['status'],
187 'result': response['result']
188 }
189 except json.JSONDecodeError:
190 print(f"Invalid JSON: {line}")
191
192 # save the possibly unfinished last line
193 partial_line = lines[-1]
194
195 # if the loop ends normally without receiving a final response
196 return {
197 'status': -1,
198 'result': 'Connection closed without final response'
199 }
200
201def with_env(env: DockerEnv):

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected