🙌 OpenHands: AI-Driven Development
Use generic types (#1680)
Jim Suf8d4b1ab0d85
diff --git a/agenthub/README.md b/agenthub/README.mdindex f7a045cf43..c0b151eda9 100644--- a/agenthub/README.md+++ b/agenthub/README.md@@ -16,14 +16,18 @@ Every agent also has a `self.llm` which it can use to interact with the LLM confSee the [LiteLLM docs for `self.llm.completion`](https://docs.litellm.ai/docs/completion).## State+The `state` contains:-* A history of actions taken by the agent, as well as any observations (e.g. file content, command output) from those actions-* A list of actions/observations that have happened since the most recent step-* A [`plan`](https://github.com/OpenDevin/OpenDevin/blob/main/opendevin/plan.py), which contains the main goal- * The agent can add and modify subtasks through the `AddTaskAction` and `ModifyTaskAction`++- A history of actions taken by the agent, as well as any observations (e.g. file content, command output) from those actions+- A list of actions/observations that have happened since the most recent step+- A [`plan`](https://github.com/OpenDevin/OpenDevin/blob/main/opendevin/plan.py), which contains the main goal+ - The agent can add and modify subtasks through the `AddTaskAction` and `ModifyTaskAction`## Actions+Here is a list of available Actions, which can be returned by `agent.step()`:+- [`CmdRunAction`](../opendevin/action/bash.py) - Runs a command inside a sandboxed terminal- [`CmdKillAction`](../opendevin/action/bash.py) - Kills a background command- [`IPythonRunCellAction`](../opendevin/action/bash.py) - Execute a block of Python code interactively (in Jupyter notebook) and receives `CmdOutputObservation`. Requires setting up `jupyter` [plugin](../opendevin/sandbox/plugins) as a requirement.@@ -43,11 +47,13 @@ Here is a list of available Actions, which can be returned by `agent.step()`:You can use `action.to_dict()` and `action_from_dict` to serialize and deserialize actions.## Observations+There are also several types of Observations. These are typically available in the step following the corresponding Action.But they may also appear as a result of asynchronous events (e.g. a message from the user, logs from a command runningin the background).Here is a list of available Observations:+- [`CmdOutputObservation`](../opendevin/observation/run.py)- [`BrowserOutputObservation`](../opendevin/observation/browse.py)- [`FileReadObservation`](../opendevin/observation/files.py)@@ -59,19 +65,24 @@ Here is a list of available Observations:You can use `observation.to_dict()` and `observation_from_dict` to serialize and deserialize observations.## Interface+Every agent must implement the following methods:### `step`+```def step(self, state: "State") -> "Action"```+`step` moves the agent forward one step towards its goal. This probably meanssending a prompt to the LLM, then parsing the response into an `Action`.### `search_memory`+```-def search_memory(self, query: str) -> List[str]:+def search_memory(self, query: str) -> list[str]:```+`search_memory` should return a list of events that match the query. This will be usedfor the `recall` action.diff --git a/agenthub/SWE_agent/agent.py b/agenthub/SWE_agent/agent.pyindex a40828f6bb..0efb9112b8 100644--- a/agenthub/SWE_agent/agent.py+++ b/agenthub/SWE_agent/agent.py@@ -1,5 +1,3 @@-from typing import List-from opendevin.controller.agent import Agentfrom opendevin.controller.state.state import Statefrom opendevin.events.action import (@@ -32,7 +30,7 @@ class SWEAgent(Agent):super().__init__(llm)self.memory_window = 4self.max_retries = 2- self.running_memory: List[str] = []+ self.running_memory: list[str] = []self.cur_file: str = ''self.cur_line: int = 0@@ -41,7 +39,7 @@ class SWEAgent(Agent):memory = MEMORY_FORMAT(action.to_memory(), observation.to_memory())self.running_memory.append(memory)- def _think_act(self, messages: List[dict]) -> tuple[Action, str]:+ def _think_act(self, messages: list[dict]) -> tuple[Action, str]:resp = self.llm.completion(messages=messages,temperature=0.05,@@ -99,7 +97,7 @@ class SWEAgent(Agent):self.latest_action = actionreturn action- def search_memory(self, query: str) -> List[str]:+ def search_memory(self, query: str) -> list[str]:return [item for item in self.running_memory if query in item]def reset(self) -> None:diff --git a/agenthub/delegator_agent/agent.py b/agenthub/delegator_agent/agent.pyindex 65c5ad6afd..2d150f5025 100644--- a/agenthub/delegator_agent/agent.py+++ b/agenthub/delegator_agent/agent.py@@ -1,5 +1,3 @@-from typing import List-from opendevin.controller.agent import Agentfrom opendevin.controller.state.state import Statefrom opendevin.events.action import Action, AgentDelegateAction, AgentFinishAction@@ -81,5 +79,5 @@ class DelegatorAgent(Agent):else:raise Exception('Invalid delegate state')- def search_memory(self, query: str) -> List[str]:+ def search_memory(self, query: str) -> list[str]:return []diff --git a/agenthub/dummy_agent/agent.py b/agenthub/dummy_agent/agent.pyindex 61af279871..33a5f23d60 100644--- a/agenthub/dummy_agent/agent.py+++ b/agenthub/dummy_agent/agent.py@@ -1,5 +1,5 @@import time-from typing import List, TypedDict+from typing import TypedDictfrom opendevin.controller.agent import Agentfrom opendevin.controller.state.state import State@@ -35,7 +35,7 @@ FIXME: There are a few problems this surfaced"""ActionObs = TypedDict(- 'ActionObs', {'action': Action, 'observations': List[Observation]}+ 'ActionObs', {'action': Action, 'observations': list[Observation]})BACKGROUND_CMD = 'echo "This is in the background" && sleep .1 && echo "This too"'@@ -49,7 +49,7 @@ class DummyAgent(Agent):def __init__(self, llm: LLM):super().__init__(llm)- self.steps: List[ActionObs] = [+ self.steps: list[ActionObs] = [{'action': AddTaskAction(parent='0', goal='check the current directory'),'observations': [NullObservation('')],@@ -160,5 +160,5 @@ class DummyAgent(Agent):), f'Expected observation {expected_obs}, got {hist_obs}'return self.steps[state.iteration]['action']- def search_memory(self, query: str) -> List[str]:+ def search_memory(self, query: str) -> list[str]:return ['I am a computer.']diff --git a/agenthub/micro/agent.py b/agenthub/micro/agent.pyindex 7393ceca47..3a9509237a 100644--- a/agenthub/micro/agent.py+++ b/agenthub/micro/agent.py@@ -1,5 +1,4 @@import json-from typing import Dict, Listfrom jinja2 import BaseLoader, Environment@@ -59,7 +58,7 @@ def to_json(obj, **kwargs):class MicroAgent(Agent):prompt = ''- agent_definition: Dict = {}+ agent_definition: dict = {}def __init__(self, llm: LLM):super().__init__(llm)@@ -83,5 +82,5 @@ class MicroAgent(Agent):action = parse_response(action_resp)return action- def search_memory(self, query: str) -> List[str]:+ def search_memory(self, query: str) -> list[str]:return []diff --git a/agenthub/micro/instructions.py b/agenthub/micro/instructions.pyindex adbfb19d87..73e72eb2b3 100644--- a/agenthub/micro/instructions.py+++ b/agenthub/micro/instructions.py@@ -1,7 +1,6 @@import os-from typing import Dict-instructions: Dict = {}+instructions: dict = {}base_dir = os.path.dirname(os.path.abspath(__file__)) + '/_instructions'for root, dirs, files in os.walk(base_dir):diff --git a/agenthub/monologue_agent/agent.py b/agenthub/monologue_agent/agent.pyindex 19b345bfa2..d845523f07 100644--- a/agenthub/monologue_agent/agent.py+++ b/agenthub/monologue_agent/agent.py@@ -1,5 +1,3 @@-from typing import List-import agenthub.monologue_agent.utils.prompts as promptsfrom agenthub.monologue_agent.utils.monologue import Monologuefrom opendevin.controller.agent import Agent@@ -239,7 +237,7 @@ class MonologueAgent(Agent):self.latest_action = actionreturn action- def search_memory(self, query: str) -> List[str]:+ def search_memory(self, query: str) -> list[str]:"""Uses VectorIndexRetriever to find related memories within the long term memory.Uses search to produce top 10 results.@@ -248,7 +246,7 @@ class MonologueAgent(Agent):- query (str): The query that we want to find related memories forReturns:- - List[str]: A list of top 10 text results that matched the query+ - list[str]: A list of top 10 text results that matched the query"""if self.memory is None:return []diff --git a/agenthub/monologue_agent/utils/memory.py b/agenthub/monologue_agent/utils/memory.pyindex 3922cdb7df..3b5e36eb08 100644--- a/agenthub/monologue_agent/utils/memory.py+++ b/agenthub/monologue_agent/utils/memory.py@@ -171,7 +171,7 @@ class LongTermMemory:- k (int): Number of top results to returnReturns:- - List[str]: List of top k results found in current memory+ - list[str]: list of top k results found in current memory"""retriever = VectorIndexRetriever(index=self.index,diff --git a/agenthub/monologue_agent/utils/monologue.py b/agenthub/monologue_agent/utils/monologue.pyindex 6008789abb..1e3e987067 100644--- a/agenthub/monologue_agent/utils/monologue.py+++ b/agenthub/monologue_agent/utils/monologue.py@@ -36,7 +36,7 @@ class Monologue:Get the current thoughts of the agent.Returns:- - List: The list of thoughts that the agent has.+ - list: The list of thoughts that the agent has."""return self.thoughtsdiff --git a/agenthub/monologue_agent/utils/prompts.py b/agenthub/monologue_agent/utils/prompts.pyindex 920603d323..773f04fad9 100644--- a/agenthub/monologue_agent/utils/prompts.py+++ b/agenthub/monologue_agent/utils/prompts.py@@ -1,6 +1,5 @@import refrom json import JSONDecodeError-from typing import Listfrom opendevin.core.config import configfrom opendevin.core.exceptions import LLMOutputError@@ -98,7 +97,7 @@ You can also use the same action and args from the source monologue."""-def get_summarize_monologue_prompt(thoughts: List[dict]):+def get_summarize_monologue_prompt(thoughts: list[dict]):"""Gets the prompt for summarizing the monologue@@ -112,16 +111,16 @@ def get_summarize_monologue_prompt(thoughts: List[dict]):def get_request_action_prompt(task: str,- thoughts: List[dict],- background_commands_obs: List[CmdOutputObservation] = [],+ thoughts: list[dict],+ background_commands_obs: list[CmdOutputObservation] = [],):"""Gets the action prompt formatted with appropriate values.Parameters:- task (str): The current task the agent is trying to accomplish- - thoughts (List[dict]): The agent's current thoughts- - background_commands_obs (List[CmdOutputObservation]): List of all observed background commands running+ - thoughts (list[dict]): The agent's current thoughts+ - background_commands_obs (list[CmdOutputObservation]): list of all observed background commands runningReturns:- str: Formatted prompt string with hint, task, monologue, and background included@@ -203,7 +202,7 @@ def parse_action_response(response: str) -> Action:return action_from_dict(action_dict)-def parse_summary_response(response: str) -> List[dict]:+def parse_summary_response(response: str) -> list[dict]:"""Parses a summary of the monologue@@ -211,7 +210,7 @@ def parse_summary_response(response: str) -> List[dict]:- response (str): The response string to be parsedReturns:- - List[dict]: The list of summaries output by the model+ - list[dict]: The list of summaries output by the model"""parsed = json.loads(response)return parsed['new_monologue']diff --git a/agenthub/planner_agent/agent.py b/agenthub/planner_agent/agent.pyindex f2b518964f..adc565bc0f 100644--- a/agenthub/planner_agent/agent.py+++ b/agenthub/planner_agent/agent.py@@ -1,5 +1,3 @@-from typing import List-from opendevin.controller.agent import Agentfrom opendevin.controller.state.state import Statefrom opendevin.events.action import Action, AgentFinishAction@@ -46,5 +44,5 @@ class PlannerAgent(Agent):action = parse_response(action_resp)return action- def search_memory(self, query: str) -> List[str]:+ def search_memory(self, query: str) -> list[str]:return []diff --git a/agenthub/planner_agent/prompt.py b/agenthub/planner_agent/prompt.pyindex 6ae0ed851a..318b093052 100644--- a/agenthub/planner_agent/prompt.py+++ b/agenthub/planner_agent/prompt.py@@ -1,5 +1,4 @@import json-from typing import List, Tuplefrom opendevin.controller.state.plan import Planfrom opendevin.core.logger import opendevin_logger as logger@@ -124,14 +123,14 @@ def get_hint(latest_action_id: str) -> str:return hints.get(latest_action_id, '')-def get_prompt(plan: Plan, history: List[Tuple[Action, Observation]]) -> str:+def get_prompt(plan: Plan, history: list[tuple[Action, Observation]]) -> str:"""Gets the prompt for the planner agent.Formatted with the most recent action-observation pairs, current task, and hint based on last actionParameters:- plan (Plan): The original plan outlined by the user with LLM defined tasks- - history (List[Tuple[Action, Observation]]): List of corresponding action-observation pairs+ - history (list[tuple[Action, Observation]]): list of corresponding action-observation pairsReturns:- str: The formatted string prompt with historical valuesdiff --git a/docs/modules/usage/agents.md b/docs/modules/usage/agents.mdindex 0fa5da3694..7e61b4a5d3 100644--- a/docs/modules/usage/agents.md+++ b/docs/modules/usage/agents.md@@ -8,12 +8,13 @@ sidebar_position: 3### Description-This agent implements the CodeAct idea ([paper](https://arxiv.org/abs/2402.13463), [tweet](https://twitter.com/xingyaow_/status/1754556835703751087)) that consolidates LLM agents’ **act**ions into a unified **code** action space for both *simplicity* and *performance* (see paper for more details).+This agent implements the CodeAct idea ([paper](https://arxiv.org/abs/2402.13463), [tweet](https://twitter.com/xingyaow_/status/1754556835703751087)) that consolidates LLM agents’ **act**ions into a unified **code** action space for both _simplicity_ and _performance_ (see paper for more details).The conceptual idea is illustrated below. At each turn, the agent can:1. **Converse**: Communicate with humans in natural language to ask for clarification, confirmation, etc.2. **CodeAct**: Choose to perform the task by executing code+- Execute any valid Linux `bash` command- Execute any valid `Python` code with [an interactive Python interpreter](https://ipython.org/). This is simulated through `bash` command, see plugin system below for more details.@@ -22,6 +23,7 @@ The conceptual idea is illustrated below. At each turn, the agent can:### Plugin SystemTo make the CodeAct agent more powerful with only access to `bash` action space, CodeAct agent leverages OpenDevin's plugin system:+- [Jupyter plugin](https://github.com/OpenDevin/OpenDevin/tree/main/opendevin/runtime/plugins/jupyter): for IPython execution via bash command- [SWE-agent tool plugin](https://github.com/OpenDevin/OpenDevin/tree/main/opendevin/runtime/plugins/swe_agent_commands): Powerful bash command line tools for software development tasks introduced by [swe-agent](https://github.com/princeton-nlp/swe-agent).@@ -29,8 +31,7 @@ To make the CodeAct agent more powerful with only access to `bash` action space,https://github.com/OpenDevin/OpenDevin/assets/38853559/f592a192-e86c-4f48-ad31-d69282d5f6ac-*Example of CodeActAgent with `gpt-4-turbo-2024-04-09` performing a data science task (linear regression)*-+_Example of CodeActAgent with `gpt-4-turbo-2024-04-09` performing a data science task (linear regression)_### Actions@@ -50,18 +51,17 @@ https://github.com/OpenDevin/OpenDevin/assets/38853559/f592a192-e86c-4f48-ad31-d### Methods-| Method | Description |-| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `__init__` | Initializes an agent with `llm` and a list of messages `List[Mapping[str, str]]` |+| Method | Description |+| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |+| `__init__` | Initializes an agent with `llm` and a list of messages `list[Mapping[str, str]]` || `step` | Performs one step using the CodeAct Agent. This includes gathering info on previous steps and prompting the model to make a command to execute. |-| `search_memory` | Not yet implemented |+| `search_memory` | Not yet implemented |### Work-in-progress & Next step[] Support web-browsing[] Complete the workflow for CodeAct agent to submit Github PRs-## Monologue Agent### Descriptiondiff --git a/opendevin/controller/agent.py b/opendevin/controller/agent.pyindex da57337b58..4a736798bd 100644--- a/opendevin/controller/agent.py+++ b/opendevin/controller/agent.py@@ -1,5 +1,5 @@from abc import ABC, abstractmethod-from typing import TYPE_CHECKING, Dict, List, Type+from typing import TYPE_CHECKING, Typeif TYPE_CHECKING:from opendevin.controller.state.state import State@@ -20,8 +20,8 @@ class Agent(ABC):It tracks the execution status and maintains a history of interactions."""- _registry: Dict[str, Type['Agent']] = {}- sandbox_plugins: List[PluginRequirement] = []+ _registry: dict[str, Type['Agent']] = {}+ sandbox_plugins: list[PluginRequirement] = []def __init__(self,@@ -49,7 +49,7 @@ class Agent(ABC):pass@abstractmethod- def search_memory(self, query: str) -> List[str]:+ def search_memory(self, query: str) -> list[str]:"""Searches the agent's memory for information relevant to the given query.diff --git a/opendevin/controller/state/plan.py b/opendevin/controller/state/plan.pyindex 369a2b0884..73b58b40e4 100644--- a/opendevin/controller/state/plan.py+++ b/opendevin/controller/state/plan.py@@ -1,5 +1,3 @@-from typing import List-from opendevin.core.exceptions import PlanInvalidStateErrorfrom opendevin.core.logger import opendevin_logger as logger@@ -21,14 +19,14 @@ class Task:id: strgoal: strparent: 'Task | None'- subtasks: List['Task']+ subtasks: list['Task']def __init__(self,parent: 'Task | None',goal: str,state: str = OPEN_STATE,- subtasks: List = [],+ subtasks: list = [],):"""Initializes a new instance of the Task class.@@ -186,7 +184,7 @@ class Plan:task = task.subtasks[part]return task- def add_subtask(self, parent_id: str, goal: str, subtasks: List = []):+ def add_subtask(self, parent_id: str, goal: str, subtasks: list = []):"""Adds a subtask to a parent task.Args:diff --git a/opendevin/controller/state/state.py b/opendevin/controller/state/state.pyindex 4888602386..ec9475add0 100644--- a/opendevin/controller/state/state.py+++ b/opendevin/controller/state/state.py@@ -1,5 +1,4 @@from dataclasses import dataclass, field-from typing import Dict, List, Tuplefrom opendevin.controller.state.plan import Planfrom opendevin.events.action import (@@ -17,8 +16,8 @@ class State:iteration: int = 0# number of characters we have sent to and received from LLM so far for current tasknum_of_chars: int = 0- background_commands_obs: List[CmdOutputObservation] = field(default_factory=list)- history: List[Tuple[Action, Observation]] = field(default_factory=list)- updated_info: List[Tuple[Action, Observation]] = field(default_factory=list)- inputs: Dict = field(default_factory=dict)- outputs: Dict = field(default_factory=dict)+ background_commands_obs: list[CmdOutputObservation] = field(default_factory=list)+ history: list[tuple[Action, Observation]] = field(default_factory=list)+ updated_info: list[tuple[Action, Observation]] = field(default_factory=list)+ inputs: dict = field(default_factory=dict)+ outputs: dict = field(default_factory=dict)diff --git a/opendevin/events/action/agent.py b/opendevin/events/action/agent.pyindex dca704713d..3a5d57a9b1 100644--- a/opendevin/events/action/agent.py+++ b/opendevin/events/action/agent.py@@ -1,5 +1,5 @@from dataclasses import dataclass, field-from typing import ClassVar, Dict+from typing import ClassVarfrom opendevin.core.schema import ActionType@@ -43,7 +43,7 @@ class AgentSummarizeAction(Action):@dataclassclass AgentFinishAction(Action):- outputs: Dict = field(default_factory=dict)+ outputs: dict = field(default_factory=dict)thought: str = ''action: str = ActionType.FINISH@@ -54,7 +54,7 @@ class AgentFinishAction(Action):@dataclassclass AgentRejectAction(Action):- outputs: Dict = field(default_factory=dict)+ outputs: dict = field(default_factory=dict)thought: str = ''action: str = ActionType.REJECTdiff --git a/opendevin/events/observation/recall.py b/opendevin/events/observation/recall.pyindex df1a9209e9..3ee65cd681 100644--- a/opendevin/events/observation/recall.py+++ b/opendevin/events/observation/recall.py@@ -1,5 +1,4 @@from dataclasses import dataclass-from typing import Listfrom opendevin.core.schema import ObservationType@@ -12,7 +11,7 @@ class AgentRecallObservation(Observation):This data class represents a list of memories recalled by the agent."""- memories: List[str]+ memories: list[str]role: str = 'assistant'observation: str = ObservationType.RECALLdiff --git a/opendevin/events/stream.py b/opendevin/events/stream.pyindex 3b2cbd3c92..1966b00e08 100644--- a/opendevin/events/stream.py+++ b/opendevin/events/stream.py@@ -1,7 +1,7 @@import asynciofrom datetime import datetimefrom enum import Enum-from typing import Callable, Dict, List+from typing import Callablefrom opendevin.core.logger import opendevin_logger as logger@@ -21,8 +21,8 @@ class EventSource(str, Enum):class EventStream:- _subscribers: Dict[str, Callable] = {}- _events: List[Event] = []+ _subscribers: dict[str, Callable] = {}+ _events: list[Event] = []_lock = asyncio.Lock()def subscribe(self, id: EventStreamSubscriber, callback: Callable):diff --git a/opendevin/runtime/docker/exec_box.py b/opendevin/runtime/docker/exec_box.pyindex 1de97d217f..ba686e1175 100644--- a/opendevin/runtime/docker/exec_box.py+++ b/opendevin/runtime/docker/exec_box.py@@ -7,7 +7,6 @@ import timeimport uuidfrom collections import namedtuplefrom glob import glob-from typing import Dict, List, Tupleimport docker@@ -32,7 +31,7 @@ class DockerExecBox(Sandbox):docker_client: docker.DockerClientcur_background_id = 0- background_commands: Dict[int, Process] = {}+ background_commands: dict[int, Process] = {}def __init__(self,@@ -95,7 +94,7 @@ class DockerExecBox(Sandbox):if exit_code != 0:raise Exception(f'Failed to setup devin user: {logs}')- def get_exec_cmd(self, cmd: str) -> List[str]:+ def get_exec_cmd(self, cmd: str) -> list[str]:if self.run_as_devin:return ['su', 'devin', '-c', cmd]else:@@ -107,7 +106,7 @@ class DockerExecBox(Sandbox):bg_cmd = self.background_commands[id]return bg_cmd.read_logs()- def execute(self, cmd: str) -> Tuple[int, str]:+ def execute(self, cmd: str) -> tuple[int, str]:# TODO: each execute is not stateful! We need to keep track of the current working directorydef run_command(container, command):return container.exec_run(diff --git a/opendevin/runtime/docker/local_box.py b/opendevin/runtime/docker/local_box.pyindex f122f35971..212f3ba8b2 100644--- a/opendevin/runtime/docker/local_box.py+++ b/opendevin/runtime/docker/local_box.py@@ -2,7 +2,6 @@ import atexitimport osimport subprocessimport sys-from typing import Dict, Tuplefrom opendevin.core.config import configfrom opendevin.core.logger import opendevin_logger as logger@@ -29,12 +28,12 @@ class LocalBox(Sandbox):def __init__(self, timeout: int = 120):os.makedirs(config.workspace_base, exist_ok=True)self.timeout = timeout- self.background_commands: Dict[int, Process] = {}+ self.background_commands: dict[int, Process] = {}self.cur_background_id = 0atexit.register(self.cleanup)super().__init__()- def execute(self, cmd: str) -> Tuple[int, str]:+ def execute(self, cmd: str) -> tuple[int, str]:try:completed_process = subprocess.run(cmd,diff --git a/opendevin/runtime/docker/process.py b/opendevin/runtime/docker/process.pyindex 11b37da22c..dac505f7d0 100644--- a/opendevin/runtime/docker/process.py+++ b/opendevin/runtime/docker/process.py@@ -1,6 +1,5 @@import selectimport sys-from typing import Tuplefrom opendevin.runtime.process import Process@@ -33,7 +32,7 @@ class DockerProcess(Process):def command(self) -> str:return self._command- def parse_docker_exec_output(self, logs: bytes) -> Tuple[bytes, bytes]:+ def parse_docker_exec_output(self, logs: bytes) -> tuple[bytes, bytes]:"""When you execute a command using `exec` in a docker container, the output produced will be in bytes. this function parses the output of a Docker exec command.@@ -61,7 +60,7 @@ class DockerProcess(Process):logs (bytes): The raw output logs of the command.Returns:- Tuple[bytes, bytes]: A tuple containing the parsed output and any remaining data.+ tuple[bytes, bytes]: A tuple containing the parsed output and any remaining data."""res = b''tail = b''diff --git a/opendevin/runtime/docker/ssh_box.py b/opendevin/runtime/docker/ssh_box.pyindex eddb44b92d..4e3da8ad1e 100644--- a/opendevin/runtime/docker/ssh_box.py+++ b/opendevin/runtime/docker/ssh_box.py@@ -7,7 +7,6 @@ import timeimport uuidfrom collections import namedtuplefrom glob import glob-from typing import Dict, List, Tuple, Unionimport dockerfrom pexpect import pxssh@@ -41,7 +40,7 @@ class DockerSSHBox(Sandbox):_ssh_port: intcur_background_id = 0- background_commands: Dict[int, Process] = {}+ background_commands: dict[int, Process] = {}def __init__(self,@@ -210,7 +209,7 @@ class DockerSSHBox(Sandbox):self.ssh.sendline(f'cd {self.sandbox_workspace_dir}')self.ssh.prompt()- def get_exec_cmd(self, cmd: str) -> List[str]:+ def get_exec_cmd(self, cmd: str) -> list[str]:if self.run_as_devin:return ['su', 'opendevin', '-c', cmd]else:@@ -222,7 +221,7 @@ class DockerSSHBox(Sandbox):bg_cmd = self.background_commands[id]return bg_cmd.read_logs()- def execute(self, cmd: str) -> Tuple[int, str]:+ def execute(self, cmd: str) -> tuple[int, str]:cmd = cmd.strip()# use self.sshself.ssh.sendline(cmd)@@ -411,7 +410,7 @@ class DockerSSHBox(Sandbox):raise extry:- network_kwargs: Dict[str, Union[str, Dict[str, int]]] = {}+ network_kwargs: dict[str, str | dict[str, int]] = {}if self.use_host_network:network_kwargs['network_mode'] = 'host'else:@@ -440,9 +439,11 @@ class DockerSSHBox(Sandbox):mount_dir: {'bind': self.sandbox_workspace_dir, 'mode': 'rw'},# mount cache directory to /home/opendevin/.cache for pip cache reuseconfig.cache_dir: {- 'bind': '/home/opendevin/.cache'- if self.run_as_devin- else '/root/.cache',+ 'bind': (+ '/home/opendevin/.cache'+ if self.run_as_devin+ else '/root/.cache'+ ),'mode': 'rw',},},diff --git a/opendevin/runtime/e2b/sandbox.py b/opendevin/runtime/e2b/sandbox.pyindex 60cfe11a53..38033b71e4 100644--- a/opendevin/runtime/e2b/sandbox.py+++ b/opendevin/runtime/e2b/sandbox.py@@ -1,7 +1,6 @@import osimport tarfilefrom glob import glob-from typing import Dict, Tuplefrom e2b import Sandbox as E2BSandboxfrom e2b.sandbox.exception import (@@ -18,7 +17,7 @@ from opendevin.runtime.sandbox import Sandboxclass E2BBox(Sandbox):closed = Falsecur_background_id = 0- background_commands: Dict[int, Process] = {}+ background_commands: dict[int, Process] = {}_cwd: str = '/home/user'def __init__(@@ -73,7 +72,7 @@ class E2BBox(Sandbox):assert isinstance(proc, E2BProcess)return '\n'.join([m.line for m in proc.output_messages])- def execute(self, cmd: str) -> Tuple[int, str]:+ def execute(self, cmd: str) -> tuple[int, str]:process = self.sandbox.process.start(cmd, env_vars=self._env)try:process_output = process.wait(timeout=self.timeout)diff --git a/opendevin/runtime/files.py b/opendevin/runtime/files.pyindex 8dfa9a0b70..d7072a4239 100644--- a/opendevin/runtime/files.py+++ b/opendevin/runtime/files.py@@ -1,16 +1,16 @@from pathlib import Path-from typing import Any, Dict, List+from typing import Anyclass WorkspaceFile:name: str- children: List['WorkspaceFile']+ children: list['WorkspaceFile']- def __init__(self, name: str, children: List['WorkspaceFile']):+ def __init__(self, name: str, children: list['WorkspaceFile']):self.name = nameself.children = children- def to_dict(self) -> Dict[str, Any]:+ def to_dict(self) -> dict[str, Any]:"""Converts the File object to a dictionary.Returns:diff --git a/opendevin/runtime/plugins/mixin.py b/opendevin/runtime/plugins/mixin.pyindex f7096caf77..6a00aacaad 100644--- a/opendevin/runtime/plugins/mixin.py+++ b/opendevin/runtime/plugins/mixin.py@@ -1,5 +1,5 @@import os-from typing import List, Protocol, Tuple+from typing import Protocolfrom opendevin.core.logger import opendevin_logger as loggerfrom opendevin.runtime.plugins.requirement import PluginRequirement@@ -8,7 +8,7 @@ from opendevin.runtime.plugins.requirement import PluginRequirementclass SandboxProtocol(Protocol):# https://stackoverflow.com/questions/51930339/how-do-i-correctly-add-type-hints-to-mixin-classes- def execute(self, cmd: str) -> Tuple[int, str]: ...+ def execute(self, cmd: str) -> tuple[int, str]: ...def copy_to(self, host_src: str, sandbox_dest: str, recursive: bool = False): ...@@ -16,7 +16,7 @@ class SandboxProtocol(Protocol):class PluginMixin:"""Mixin for Sandbox to support plugins."""- def init_plugins(self: SandboxProtocol, requirements: List[PluginRequirement]):+ def init_plugins(self: SandboxProtocol, requirements: list[PluginRequirement]):"""Load a plugin into the sandbox."""for requirement in requirements:# copy over the filesdiff --git a/opendevin/runtime/plugins/swe_agent_commands/__init__.py b/opendevin/runtime/plugins/swe_agent_commands/__init__.pyindex f7763f31fc..66316f36b2 100644--- a/opendevin/runtime/plugins/swe_agent_commands/__init__.py+++ b/opendevin/runtime/plugins/swe_agent_commands/__init__.py@@ -1,6 +1,5 @@import osfrom dataclasses import dataclass, field-from typing import Listfrom opendevin.runtime.plugins.requirement import PluginRequirementfrom opendevin.runtime.plugins.swe_agent_commands.parse_commands import (@@ -39,7 +38,7 @@ class SWEAgentCommandsRequirement(PluginRequirement):sandbox_dest: str = '/opendevin/plugins/swe_agent_commands'bash_script_path: str = 'setup_default.sh'- scripts_filepaths: List[str | None] = field(+ scripts_filepaths: list[str | None] = field(default_factory=lambda: DEFAULT_SCRIPT_FILEPATHS)documentation: str = DEFAULT_DOCUMENTATION@@ -66,7 +65,7 @@ class SWEAgentCursorCommandsRequirement(PluginRequirement):sandbox_dest: str = '/opendevin/plugins/swe_agent_commands'bash_script_path: str = 'setup_cursor_mode.sh'- scripts_filepaths: List[str | None] = field(+ scripts_filepaths: list[str | None] = field(default_factory=lambda: CURSOR_SCRIPT_FILEPATHS)documentation: str = CURSOR_DOCUMENTATIONdiff --git a/opendevin/runtime/runtime.py b/opendevin/runtime/runtime.pyindex 179ddcc5e2..2c5735334f 100644--- a/opendevin/runtime/runtime.py+++ b/opendevin/runtime/runtime.py@@ -1,5 +1,4 @@from abc import abstractmethod-from typing import Listfrom opendevin.core.config import configfrom opendevin.events.action import (@@ -62,7 +61,7 @@ class Runtime:self.sandbox = create_sandbox(sid, config.sandbox_type)self.browser = BrowserEnv()- def init_sandbox_plugins(self, plugins: List[PluginRequirement]) -> None:+ def init_sandbox_plugins(self, plugins: list[PluginRequirement]) -> None:self.sandbox.init_plugins(plugins)async def run_action(self, action: Action) -> Observation:@@ -83,7 +82,7 @@ class Runtime:observation = await getattr(self, action_id)(action)return observation- def get_background_obs(self) -> List[CmdOutputObservation]:+ def get_background_obs(self) -> list[CmdOutputObservation]:"""Returns all observations that have accumulated in the runtime's background.Right now, this is just background commands, but could include e.g. asyncronousdiff --git a/opendevin/runtime/sandbox.py b/opendevin/runtime/sandbox.pyindex 1cbbc68ca0..fb278a06f6 100644--- a/opendevin/runtime/sandbox.py+++ b/opendevin/runtime/sandbox.py@@ -1,14 +1,13 @@import osfrom abc import ABC, abstractmethod-from typing import Dict, Tuplefrom opendevin.runtime.docker.process import Processfrom opendevin.runtime.plugins.mixin import PluginMixinclass Sandbox(ABC, PluginMixin):- background_commands: Dict[int, Process] = {}- _env: Dict[str, str] = {}+ background_commands: dict[int, Process] = {}+ _env: dict[str, str] = {}def __init__(self, **kwargs):for key in os.environ:@@ -20,7 +19,7 @@ class Sandbox(ABC, PluginMixin):self._env[key] = value@abstractmethod- def execute(self, cmd: str) -> Tuple[int, str]:+ def execute(self, cmd: str) -> tuple[int, str]:pass@abstractmethoddiff --git a/opendevin/server/auth/auth.py b/opendevin/server/auth/auth.pyindex e90a40d6e6..98507e8f81 100644--- a/opendevin/server/auth/auth.py+++ b/opendevin/server/auth/auth.py@@ -1,5 +1,4 @@import os-from typing import Dictimport jwtfrom jwt.exceptions import InvalidTokenError@@ -36,7 +35,7 @@ def get_sid_from_token(token: str) -> str:return ''-def sign_token(payload: Dict[str, object]) -> str:+def sign_token(payload: dict[str, object]) -> str:"""Signs a JWT token."""# payload = {# "sid": sid,diff --git a/opendevin/server/session/manager.py b/opendevin/server/session/manager.pyindex f8910f012b..c3f9535a71 100644--- a/opendevin/server/session/manager.py+++ b/opendevin/server/session/manager.py@@ -1,7 +1,7 @@import atexitimport jsonimport os-from typing import Callable, Dict+from typing import Callablefrom fastapi import WebSocket@@ -15,7 +15,7 @@ SESSION_CACHE_FILE = os.path.join(CACHE_DIR, 'sessions.json')class SessionManager:- _sessions: Dict[str, Session] = {}+ _sessions: dict[str, Session] = {}def __init__(self):self._load_sessions()@@ -38,7 +38,7 @@ class SessionManager:logger.info('Saving sessions...')self._save_sessions()- async def send(self, sid: str, data: Dict[str, object]) -> bool:+ async def send(self, sid: str, data: dict[str, object]) -> bool:"""Sends data to the client."""message_stack.add_message(sid, 'assistant', data)if sid not in self._sessions:diff --git a/opendevin/server/session/msg_stack.py b/opendevin/server/session/msg_stack.pyindex c328073c72..8290486101 100644--- a/opendevin/server/session/msg_stack.py+++ b/opendevin/server/session/msg_stack.py@@ -2,7 +2,6 @@ import atexitimport jsonimport osimport uuid-from typing import Dictfrom opendevin.core.logger import opendevin_logger as loggerfrom opendevin.core.schema.action import ActionType@@ -14,9 +13,9 @@ MSG_CACHE_FILE = os.path.join(CACHE_DIR, 'messages.json')class Message:id: str = str(uuid.uuid4())role: str # "user"| "assistant"- payload: Dict[str, object]+ payload: dict[str, object]- def __init__(self, role: str, payload: Dict[str, object]):+ def __init__(self, role: str, payload: dict[str, object]):self.role = roleself.payload = payload@@ -24,14 +23,14 @@ class Message:return {'id': self.id, 'role': self.role, 'payload': self.payload}@classmethod- def from_dict(cls, data: Dict):+ def from_dict(cls, data: dict):m = cls(data['role'], data['payload'])m.id = data['id']return mclass MessageStack:- _messages: Dict[str, list[Message]] = {}+ _messages: dict[str, list[Message]] = {}def __init__(self):self._load_messages()@@ -41,7 +40,7 @@ class MessageStack:logger.info('Saving messages...')self._save_messages()- def add_message(self, sid: str, role: str, message: Dict[str, object]):+ def add_message(self, sid: str, role: str, message: dict[str, object]):if sid not in self._messages:self._messages[sid] = []self._messages[sid].append(Message(role, message))@@ -51,7 +50,7 @@ class MessageStack:returndel self._messages[sid]- def get_messages(self, sid: str) -> list[Dict[str, object]]:+ def get_messages(self, sid: str) -> list[dict[str, object]]:if sid not in self._messages:return []return [msg.to_dict() for msg in self._messages[sid]]diff --git a/opendevin/server/session/session.py b/opendevin/server/session/session.pyindex a53914019c..0ca5c6d968 100644--- a/opendevin/server/session/session.py+++ b/opendevin/server/session/session.py@@ -1,5 +1,5 @@import time-from typing import Callable, Dict+from typing import Callablefrom fastapi import WebSocket, WebSocketDisconnect@@ -44,7 +44,7 @@ class Session:self.is_alive = Falselogger.exception('Error in loop_recv: %s', e)- async def send(self, data: Dict[str, object]) -> bool:+ async def send(self, data: dict[str, object]) -> bool:try:if self.websocket is None or not self.is_alive:return False@@ -68,7 +68,7 @@ class Session:self.is_alive = Trueself.last_active_ts = int(time.time())- def load_from_data(self, data: Dict) -> bool:+ def load_from_data(self, data: dict) -> bool:self.last_active_ts = data.get('last_active_ts', 0)if self.last_active_ts < int(time.time()) - DEL_DELT_SEC:return False