eventstream_runtime.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import atexit
  2. import os
  3. import tempfile
  4. import threading
  5. from functools import lru_cache
  6. from pathlib import Path
  7. from typing import Callable
  8. from zipfile import ZipFile
  9. import docker
  10. import requests
  11. import tenacity
  12. from openhands.core.config import AppConfig
  13. from openhands.core.logger import DEBUG
  14. from openhands.core.logger import openhands_logger as logger
  15. from openhands.events import EventStream
  16. from openhands.events.action import (
  17. ActionConfirmationStatus,
  18. BrowseInteractiveAction,
  19. BrowseURLAction,
  20. CmdRunAction,
  21. FileEditAction,
  22. FileReadAction,
  23. FileWriteAction,
  24. IPythonRunCellAction,
  25. )
  26. from openhands.events.action.action import Action
  27. from openhands.events.observation import (
  28. ErrorObservation,
  29. NullObservation,
  30. Observation,
  31. UserRejectObservation,
  32. )
  33. from openhands.events.serialization import event_to_dict, observation_from_dict
  34. from openhands.events.serialization.action import ACTION_TYPE_TO_CLASS
  35. from openhands.runtime.base import (
  36. Runtime,
  37. RuntimeDisconnectedError,
  38. RuntimeNotFoundError,
  39. )
  40. from openhands.runtime.builder import DockerRuntimeBuilder
  41. from openhands.runtime.impl.eventstream.containers import remove_all_containers
  42. from openhands.runtime.plugins import PluginRequirement
  43. from openhands.runtime.utils import find_available_tcp_port
  44. from openhands.runtime.utils.request import send_request
  45. from openhands.runtime.utils.runtime_build import build_runtime_image
  46. from openhands.utils.async_utils import call_sync_from_async
  47. from openhands.utils.tenacity_stop import stop_if_should_exit
  48. CONTAINER_NAME_PREFIX = 'openhands-runtime-'
  49. def remove_all_runtime_containers():
  50. remove_all_containers(CONTAINER_NAME_PREFIX)
  51. atexit.register(remove_all_runtime_containers)
  52. class LogBuffer:
  53. """Synchronous buffer for Docker container logs.
  54. This class provides a thread-safe way to collect, store, and retrieve logs
  55. from a Docker container. It uses a list to store log lines and provides methods
  56. for appending, retrieving, and clearing logs.
  57. """
  58. def __init__(self, container: docker.models.containers.Container, logFn: Callable):
  59. self.init_msg = 'Runtime client initialized.'
  60. self.buffer: list[str] = []
  61. self.lock = threading.Lock()
  62. self._stop_event = threading.Event()
  63. self.log_generator = container.logs(stream=True, follow=True)
  64. self.log_stream_thread = threading.Thread(target=self.stream_logs)
  65. self.log_stream_thread.daemon = True
  66. self.log_stream_thread.start()
  67. self.log = logFn
  68. def append(self, log_line: str):
  69. with self.lock:
  70. self.buffer.append(log_line)
  71. def get_and_clear(self) -> list[str]:
  72. with self.lock:
  73. logs = list(self.buffer)
  74. self.buffer.clear()
  75. return logs
  76. def stream_logs(self):
  77. """Stream logs from the Docker container in a separate thread.
  78. This method runs in its own thread to handle the blocking
  79. operation of reading log lines from the Docker SDK's synchronous generator.
  80. """
  81. try:
  82. for log_line in self.log_generator:
  83. if self._stop_event.is_set():
  84. break
  85. if log_line:
  86. decoded_line = log_line.decode('utf-8').rstrip()
  87. self.append(decoded_line)
  88. except Exception as e:
  89. self.log('error', f'Error streaming docker logs: {e}')
  90. def __del__(self):
  91. if self.log_stream_thread.is_alive():
  92. self.log(
  93. 'warn',
  94. "LogBuffer was not properly closed. Use 'log_buffer.close()' for clean shutdown.",
  95. )
  96. self.close(timeout=5)
  97. def close(self, timeout: float = 5.0):
  98. self._stop_event.set()
  99. self.log_stream_thread.join(timeout)
  100. # Close the log generator to release the file descriptor
  101. if hasattr(self.log_generator, 'close'):
  102. self.log_generator.close()
  103. class EventStreamRuntime(Runtime):
  104. """This runtime will subscribe the event stream.
  105. When receive an event, it will send the event to runtime-client which run inside the docker environment.
  106. Args:
  107. config (AppConfig): The application configuration.
  108. event_stream (EventStream): The event stream to subscribe to.
  109. sid (str, optional): The session ID. Defaults to 'default'.
  110. plugins (list[PluginRequirement] | None, optional): List of plugin requirements. Defaults to None.
  111. env_vars (dict[str, str] | None, optional): Environment variables to set. Defaults to None.
  112. """
  113. # Need to provide this method to allow inheritors to init the Runtime
  114. # without initting the EventStreamRuntime.
  115. def init_base_runtime(
  116. self,
  117. config: AppConfig,
  118. event_stream: EventStream,
  119. sid: str = 'default',
  120. plugins: list[PluginRequirement] | None = None,
  121. env_vars: dict[str, str] | None = None,
  122. status_callback: Callable | None = None,
  123. attach_to_existing: bool = False,
  124. headless_mode: bool = True,
  125. ):
  126. super().__init__(
  127. config,
  128. event_stream,
  129. sid,
  130. plugins,
  131. env_vars,
  132. status_callback,
  133. attach_to_existing,
  134. headless_mode,
  135. )
  136. def __init__(
  137. self,
  138. config: AppConfig,
  139. event_stream: EventStream,
  140. sid: str = 'default',
  141. plugins: list[PluginRequirement] | None = None,
  142. env_vars: dict[str, str] | None = None,
  143. status_callback: Callable | None = None,
  144. attach_to_existing: bool = False,
  145. headless_mode: bool = True,
  146. ):
  147. self.config = config
  148. self._host_port = 30000 # initial dummy value
  149. self._container_port = 30001 # initial dummy value
  150. self._vscode_url: str | None = None # initial dummy value
  151. self._runtime_initialized: bool = False
  152. self.api_url = f'{self.config.sandbox.local_runtime_url}:{self._container_port}'
  153. self.session = requests.Session()
  154. self.status_callback = status_callback
  155. self.docker_client: docker.DockerClient = self._init_docker_client()
  156. self.base_container_image = self.config.sandbox.base_container_image
  157. self.runtime_container_image = self.config.sandbox.runtime_container_image
  158. self.container_name = CONTAINER_NAME_PREFIX + sid
  159. self.container = None
  160. self.action_semaphore = threading.Semaphore(1) # Ensure one action at a time
  161. self.runtime_builder = DockerRuntimeBuilder(self.docker_client)
  162. # Buffer for container logs
  163. self.log_buffer: LogBuffer | None = None
  164. if self.config.sandbox.runtime_extra_deps:
  165. self.log(
  166. 'debug',
  167. f'Installing extra user-provided dependencies in the runtime image: {self.config.sandbox.runtime_extra_deps}',
  168. )
  169. self.init_base_runtime(
  170. config,
  171. event_stream,
  172. sid,
  173. plugins,
  174. env_vars,
  175. status_callback,
  176. attach_to_existing,
  177. headless_mode,
  178. )
  179. async def connect(self):
  180. self.send_status_message('STATUS$STARTING_RUNTIME')
  181. try:
  182. await call_sync_from_async(self._attach_to_container)
  183. except docker.errors.NotFound as e:
  184. if self.attach_to_existing:
  185. self.log(
  186. 'error',
  187. f'Container {self.container_name} not found.',
  188. )
  189. raise e
  190. if self.runtime_container_image is None:
  191. if self.base_container_image is None:
  192. raise ValueError(
  193. 'Neither runtime container image nor base container image is set'
  194. )
  195. self.send_status_message('STATUS$STARTING_CONTAINER')
  196. self.runtime_container_image = build_runtime_image(
  197. self.base_container_image,
  198. self.runtime_builder,
  199. platform=self.config.sandbox.platform,
  200. extra_deps=self.config.sandbox.runtime_extra_deps,
  201. force_rebuild=self.config.sandbox.force_rebuild_runtime,
  202. )
  203. self.log(
  204. 'info', f'Starting runtime with image: {self.runtime_container_image}'
  205. )
  206. await call_sync_from_async(self._init_container)
  207. self.log(
  208. 'info',
  209. f'Container started: {self.container_name}. VSCode URL: {self.vscode_url}',
  210. )
  211. self.log_buffer = LogBuffer(self.container, self.log)
  212. if not self.attach_to_existing:
  213. self.log('info', f'Waiting for client to become ready at {self.api_url}...')
  214. self.send_status_message('STATUS$WAITING_FOR_CLIENT')
  215. await call_sync_from_async(self._wait_until_alive)
  216. if not self.attach_to_existing:
  217. self.log('info', 'Runtime is ready.')
  218. if not self.attach_to_existing:
  219. await call_sync_from_async(self.setup_initial_env)
  220. self.log(
  221. 'debug',
  222. f'Container initialized with plugins: {[plugin.name for plugin in self.plugins]}. VSCode URL: {self.vscode_url}',
  223. )
  224. if not self.attach_to_existing:
  225. self.send_status_message(' ')
  226. self._runtime_initialized = True
  227. @staticmethod
  228. @lru_cache(maxsize=1)
  229. def _init_docker_client() -> docker.DockerClient:
  230. try:
  231. return docker.from_env()
  232. except Exception as ex:
  233. logger.error(
  234. 'Launch docker client failed. Please make sure you have installed docker and started docker desktop/daemon.',
  235. )
  236. raise ex
  237. def _init_container(self):
  238. self.log('debug', 'Preparing to start container...')
  239. self.send_status_message('STATUS$PREPARING_CONTAINER')
  240. plugin_arg = ''
  241. if self.plugins is not None and len(self.plugins) > 0:
  242. plugin_arg = (
  243. f'--plugins {" ".join([plugin.name for plugin in self.plugins])} '
  244. )
  245. self._host_port = self._find_available_port()
  246. self._container_port = (
  247. self._host_port
  248. ) # in future this might differ from host port
  249. self.api_url = f'{self.config.sandbox.local_runtime_url}:{self._container_port}'
  250. use_host_network = self.config.sandbox.use_host_network
  251. network_mode: str | None = 'host' if use_host_network else None
  252. port_mapping: dict[str, list[dict[str, str]]] | None = (
  253. None
  254. if use_host_network
  255. else {f'{self._container_port}/tcp': [{'HostPort': str(self._host_port)}]}
  256. )
  257. if use_host_network:
  258. self.log(
  259. 'warn',
  260. 'Using host network mode. If you are using MacOS, please make sure you have the latest version of Docker Desktop and enabled host network feature: https://docs.docker.com/network/drivers/host/#docker-desktop',
  261. )
  262. # Combine environment variables
  263. environment = {
  264. 'port': str(self._container_port),
  265. 'PYTHONUNBUFFERED': 1,
  266. }
  267. if self.config.debug or DEBUG:
  268. environment['DEBUG'] = 'true'
  269. if self.vscode_enabled:
  270. # vscode is on port +1 from container port
  271. if isinstance(port_mapping, dict):
  272. port_mapping[f'{self._container_port + 1}/tcp'] = [
  273. {'HostPort': str(self._host_port + 1)}
  274. ]
  275. self.log('debug', f'Workspace Base: {self.config.workspace_base}')
  276. if (
  277. self.config.workspace_mount_path is not None
  278. and self.config.workspace_mount_path_in_sandbox is not None
  279. ):
  280. # e.g. result would be: {"/home/user/openhands/workspace": {'bind': "/workspace", 'mode': 'rw'}}
  281. volumes = {
  282. self.config.workspace_mount_path: {
  283. 'bind': self.config.workspace_mount_path_in_sandbox,
  284. 'mode': 'rw',
  285. }
  286. }
  287. logger.debug(f'Mount dir: {self.config.workspace_mount_path}')
  288. else:
  289. logger.debug(
  290. 'Mount dir is not set, will not mount the workspace directory to the container'
  291. )
  292. volumes = None
  293. self.log(
  294. 'debug',
  295. f'Sandbox workspace: {self.config.workspace_mount_path_in_sandbox}',
  296. )
  297. if self.config.sandbox.browsergym_eval_env is not None:
  298. browsergym_arg = (
  299. f'--browsergym-eval-env {self.config.sandbox.browsergym_eval_env}'
  300. )
  301. else:
  302. browsergym_arg = ''
  303. try:
  304. self.container = self.docker_client.containers.run(
  305. self.runtime_container_image,
  306. command=(
  307. f'/openhands/micromamba/bin/micromamba run -n openhands '
  308. f'poetry run '
  309. f'python -u -m openhands.runtime.action_execution_server {self._container_port} '
  310. f'--working-dir "{self.config.workspace_mount_path_in_sandbox}" '
  311. f'{plugin_arg}'
  312. f'--username {"openhands" if self.config.run_as_openhands else "root"} '
  313. f'--user-id {self.config.sandbox.user_id} '
  314. f'{browsergym_arg}'
  315. ),
  316. network_mode=network_mode,
  317. ports=port_mapping,
  318. working_dir='/openhands/code/', # do not change this!
  319. name=self.container_name,
  320. detach=True,
  321. environment=environment,
  322. volumes=volumes,
  323. )
  324. self.log('debug', f'Container started. Server url: {self.api_url}')
  325. self.send_status_message('STATUS$CONTAINER_STARTED')
  326. except docker.errors.APIError as e:
  327. if '409' in str(e):
  328. self.log(
  329. 'warning',
  330. f'Container {self.container_name} already exists. Removing...',
  331. )
  332. remove_all_containers(self.container_name)
  333. return self._init_container()
  334. else:
  335. self.log(
  336. 'error',
  337. f'Error: Instance {self.container_name} FAILED to start container!\n',
  338. )
  339. except Exception as e:
  340. self.log(
  341. 'error',
  342. f'Error: Instance {self.container_name} FAILED to start container!\n',
  343. )
  344. self.log('error', str(e))
  345. self.close()
  346. raise e
  347. def _attach_to_container(self):
  348. self._container_port = 0
  349. self.container = self.docker_client.containers.get(self.container_name)
  350. for port in self.container.attrs['NetworkSettings']['Ports']: # type: ignore
  351. self._container_port = int(port.split('/')[0])
  352. break
  353. self._host_port = self._container_port
  354. self.api_url = f'{self.config.sandbox.local_runtime_url}:{self._container_port}'
  355. self.log(
  356. 'debug',
  357. f'attached to container: {self.container_name} {self._container_port} {self.api_url}',
  358. )
  359. def _refresh_logs(self):
  360. self.log('debug', 'Getting container logs...')
  361. assert (
  362. self.log_buffer is not None
  363. ), 'Log buffer is expected to be initialized when container is started'
  364. logs = self.log_buffer.get_and_clear()
  365. if logs:
  366. formatted_logs = '\n'.join([f' |{log}' for log in logs])
  367. self.log(
  368. 'debug',
  369. '\n'
  370. + '-' * 35
  371. + 'Container logs:'
  372. + '-' * 35
  373. + f'\n{formatted_logs}'
  374. + '\n'
  375. + '-' * 80,
  376. )
  377. @tenacity.retry(
  378. stop=tenacity.stop_after_delay(120) | stop_if_should_exit(),
  379. retry=tenacity.retry_if_exception_type(
  380. (ConnectionError, requests.exceptions.ConnectionError)
  381. ),
  382. reraise=True,
  383. wait=tenacity.wait_fixed(2),
  384. )
  385. def _wait_until_alive(self):
  386. try:
  387. container = self.docker_client.containers.get(self.container_name)
  388. if container.status == 'exited':
  389. raise RuntimeDisconnectedError(
  390. f'Container {self.container_name} has exited.'
  391. )
  392. except docker.errors.NotFound:
  393. raise RuntimeNotFoundError(f'Container {self.container_name} not found.')
  394. self._refresh_logs()
  395. if not self.log_buffer:
  396. raise RuntimeError('Runtime client is not ready.')
  397. with send_request(
  398. self.session,
  399. 'GET',
  400. f'{self.api_url}/alive',
  401. timeout=5,
  402. ):
  403. pass
  404. def close(self, rm_all_containers: bool = True):
  405. """Closes the EventStreamRuntime and associated objects
  406. Parameters:
  407. - rm_all_containers (bool): Whether to remove all containers with the 'openhands-sandbox-' prefix
  408. """
  409. if self.log_buffer:
  410. self.log_buffer.close()
  411. if self.session:
  412. self.session.close()
  413. if self.config.sandbox.keep_runtime_alive or self.attach_to_existing:
  414. return
  415. close_prefix = (
  416. CONTAINER_NAME_PREFIX if rm_all_containers else self.container_name
  417. )
  418. remove_all_containers(close_prefix)
  419. def run_action(self, action: Action) -> Observation:
  420. if isinstance(action, FileEditAction):
  421. return self.edit(action)
  422. # set timeout to default if not set
  423. if action.timeout is None:
  424. action.timeout = self.config.sandbox.timeout
  425. with self.action_semaphore:
  426. if not action.runnable:
  427. return NullObservation('')
  428. if (
  429. hasattr(action, 'confirmation_state')
  430. and action.confirmation_state
  431. == ActionConfirmationStatus.AWAITING_CONFIRMATION
  432. ):
  433. return NullObservation('')
  434. action_type = action.action # type: ignore[attr-defined]
  435. if action_type not in ACTION_TYPE_TO_CLASS:
  436. raise ValueError(f'Action {action_type} does not exist.')
  437. if not hasattr(self, action_type):
  438. return ErrorObservation(
  439. f'Action {action_type} is not supported in the current runtime.',
  440. error_id='AGENT_ERROR$BAD_ACTION',
  441. )
  442. if (
  443. getattr(action, 'confirmation_state', None)
  444. == ActionConfirmationStatus.REJECTED
  445. ):
  446. return UserRejectObservation(
  447. 'Action has been rejected by the user! Waiting for further user input.'
  448. )
  449. self._refresh_logs()
  450. assert action.timeout is not None
  451. try:
  452. with send_request(
  453. self.session,
  454. 'POST',
  455. f'{self.api_url}/execute_action',
  456. json={'action': event_to_dict(action)},
  457. # wait a few more seconds to get the timeout error from client side
  458. timeout=action.timeout + 5,
  459. ) as response:
  460. output = response.json()
  461. obs = observation_from_dict(output)
  462. obs._cause = action.id # type: ignore[attr-defined]
  463. except requests.Timeout:
  464. raise RuntimeError(
  465. f'Runtime failed to return execute_action before the requested timeout of {action.timeout}s'
  466. )
  467. self._refresh_logs()
  468. return obs
  469. def run(self, action: CmdRunAction) -> Observation:
  470. return self.run_action(action)
  471. def run_ipython(self, action: IPythonRunCellAction) -> Observation:
  472. return self.run_action(action)
  473. def read(self, action: FileReadAction) -> Observation:
  474. return self.run_action(action)
  475. def write(self, action: FileWriteAction) -> Observation:
  476. return self.run_action(action)
  477. def browse(self, action: BrowseURLAction) -> Observation:
  478. return self.run_action(action)
  479. def browse_interactive(self, action: BrowseInteractiveAction) -> Observation:
  480. return self.run_action(action)
  481. # ====================================================================
  482. # Implement these methods (for file operations) in the subclass
  483. # ====================================================================
  484. def copy_to(
  485. self, host_src: str, sandbox_dest: str, recursive: bool = False
  486. ) -> None:
  487. if not os.path.exists(host_src):
  488. raise FileNotFoundError(f'Source file {host_src} does not exist')
  489. self._refresh_logs()
  490. try:
  491. if recursive:
  492. # For recursive copy, create a zip file
  493. with tempfile.NamedTemporaryFile(
  494. suffix='.zip', delete=False
  495. ) as temp_zip:
  496. temp_zip_path = temp_zip.name
  497. with ZipFile(temp_zip_path, 'w') as zipf:
  498. for root, _, files in os.walk(host_src):
  499. for file in files:
  500. file_path = os.path.join(root, file)
  501. arcname = os.path.relpath(
  502. file_path, os.path.dirname(host_src)
  503. )
  504. zipf.write(file_path, arcname)
  505. upload_data = {'file': open(temp_zip_path, 'rb')}
  506. else:
  507. # For single file copy
  508. upload_data = {'file': open(host_src, 'rb')}
  509. params = {'destination': sandbox_dest, 'recursive': str(recursive).lower()}
  510. with send_request(
  511. self.session,
  512. 'POST',
  513. f'{self.api_url}/upload_file',
  514. files=upload_data,
  515. params=params,
  516. timeout=300,
  517. ):
  518. pass
  519. except requests.Timeout:
  520. raise TimeoutError('Copy operation timed out')
  521. except Exception as e:
  522. raise RuntimeError(f'Copy operation failed: {str(e)}')
  523. finally:
  524. if recursive:
  525. os.unlink(temp_zip_path)
  526. self.log(
  527. 'debug', f'Copy completed: host:{host_src} -> runtime:{sandbox_dest}'
  528. )
  529. self._refresh_logs()
  530. def list_files(self, path: str | None = None) -> list[str]:
  531. """List files in the sandbox.
  532. If path is None, list files in the sandbox's initial working directory (e.g., /workspace).
  533. """
  534. self._refresh_logs()
  535. try:
  536. data = {}
  537. if path is not None:
  538. data['path'] = path
  539. with send_request(
  540. self.session,
  541. 'POST',
  542. f'{self.api_url}/list_files',
  543. json=data,
  544. timeout=10,
  545. ) as response:
  546. response_json = response.json()
  547. assert isinstance(response_json, list)
  548. return response_json
  549. except requests.Timeout:
  550. raise TimeoutError('List files operation timed out')
  551. def copy_from(self, path: str) -> Path:
  552. """Zip all files in the sandbox and return as a stream of bytes."""
  553. self._refresh_logs()
  554. try:
  555. params = {'path': path}
  556. with send_request(
  557. self.session,
  558. 'GET',
  559. f'{self.api_url}/download_files',
  560. params=params,
  561. stream=True,
  562. timeout=30,
  563. ) as response:
  564. temp_file = tempfile.NamedTemporaryFile(delete=False)
  565. for chunk in response.iter_content(chunk_size=8192):
  566. if chunk: # filter out keep-alive new chunks
  567. temp_file.write(chunk)
  568. return Path(temp_file.name)
  569. except requests.Timeout:
  570. raise TimeoutError('Copy operation timed out')
  571. def _is_port_in_use_docker(self, port):
  572. containers = self.docker_client.containers.list()
  573. for container in containers:
  574. container_ports = container.ports
  575. if str(port) in str(container_ports):
  576. return True
  577. return False
  578. def _find_available_port(self, max_attempts=5):
  579. port = 39999
  580. for _ in range(max_attempts):
  581. port = find_available_tcp_port(30000, 39999)
  582. if not self._is_port_in_use_docker(port):
  583. return port
  584. # If no port is found after max_attempts, return the last tried port
  585. return port
  586. @property
  587. def vscode_url(self) -> str | None:
  588. if self.vscode_enabled and self._runtime_initialized:
  589. if (
  590. hasattr(self, '_vscode_url') and self._vscode_url is not None
  591. ): # cached value
  592. return self._vscode_url
  593. with send_request(
  594. self.session,
  595. 'GET',
  596. f'{self.api_url}/vscode/connection_token',
  597. timeout=10,
  598. ) as response:
  599. response_json = response.json()
  600. assert isinstance(response_json, dict)
  601. if response_json['token'] is None:
  602. return None
  603. self._vscode_url = f'http://localhost:{self._host_port + 1}/?tkn={response_json["token"]}&folder={self.config.workspace_mount_path_in_sandbox}'
  604. self.log(
  605. 'debug',
  606. f'VSCode URL: {self._vscode_url}',
  607. )
  608. return self._vscode_url
  609. else:
  610. return None