Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
fix: deprecate `cursor` param and replace with `before`, `after` (#736)
mlong93819e36035628
diff --git a/alembic/versions/6fbe9cace832_adding_indexes_to_models.py b/alembic/versions/6fbe9cace832_adding_indexes_to_models.pynew file mode 100644index 000000000..6331fed76--- /dev/null+++ b/alembic/versions/6fbe9cace832_adding_indexes_to_models.py@@ -0,0 +1,43 @@+"""adding indexes to models++Revision ID: 6fbe9cace832+Revises: f895232c144a+Create Date: 2025-01-23 11:02:59.534372++"""++from typing import Sequence, Union++from alembic import op++# revision identifiers, used by Alembic.+revision: str = "6fbe9cace832"+down_revision: Union[str, None] = "f895232c144a"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ # ### commands auto generated by Alembic - please adjust! ###+ op.create_index("agent_passages_created_at_id_idx", "agent_passages", ["created_at", "id"], unique=False)+ op.create_index("ix_agents_created_at", "agents", ["created_at", "id"], unique=False)+ op.create_index("created_at_label_idx", "block", ["created_at", "label"], unique=False)+ op.create_index("ix_jobs_created_at", "jobs", ["created_at", "id"], unique=False)+ op.create_index("ix_messages_created_at", "messages", ["created_at", "id"], unique=False)+ op.create_index("source_passages_created_at_id_idx", "source_passages", ["created_at", "id"], unique=False)+ op.create_index("source_created_at_id_idx", "sources", ["created_at", "id"], unique=False)+ op.create_index("ix_tools_created_at_name", "tools", ["created_at", "name"], unique=False)+ # ### end Alembic commands ###+++def downgrade() -> None:+ # ### commands auto generated by Alembic - please adjust! ###+ op.drop_index("ix_tools_created_at_name", table_name="tools")+ op.drop_index("source_created_at_id_idx", table_name="sources")+ op.drop_index("source_passages_created_at_id_idx", table_name="source_passages")+ op.drop_index("ix_messages_created_at", table_name="messages")+ op.drop_index("ix_jobs_created_at", table_name="jobs")+ op.drop_index("created_at_label_idx", table_name="block")+ op.drop_index("ix_agents_created_at", table_name="agents")+ op.drop_index("agent_passages_created_at_id_idx", table_name="agent_passages")+ # ### end Alembic commands ###diff --git a/letta/client/client.py b/letta/client/client.pyindex 8c9f5cf61..aaf5d21bf 100644--- a/letta/client/client.py+++ b/letta/client/client.py@@ -206,7 +206,7 @@ class AbstractClient(object):) -> Tool:raise NotImplementedError- def list_tools(self, cursor: Optional[str] = None, limit: Optional[int] = 50) -> List[Tool]:+ def list_tools(self, after: Optional[str] = None, limit: Optional[int] = 50) -> List[Tool]:raise NotImplementedErrordef get_tool(self, id: str) -> Tool:@@ -266,7 +266,7 @@ class AbstractClient(object):def list_attached_sources(self, agent_id: str) -> List[Source]:raise NotImplementedError- def list_files_from_source(self, source_id: str, limit: int = 1000, cursor: Optional[str] = None) -> List[FileMetadata]:+ def list_files_from_source(self, source_id: str, limit: int = 1000, after: Optional[str] = None) -> List[FileMetadata]:raise NotImplementedErrordef update_source(self, source_id: str, name: Optional[str] = None) -> Source:@@ -279,12 +279,12 @@ class AbstractClient(object):raise NotImplementedErrordef get_archival_memory(- self, agent_id: str, before: Optional[str] = None, after: Optional[str] = None, limit: Optional[int] = 1000+ self, agent_id: str, after: Optional[str] = None, before: Optional[str] = None, limit: Optional[int] = 1000) -> List[Passage]:raise NotImplementedErrordef get_messages(- self, agent_id: str, before: Optional[str] = None, after: Optional[str] = None, limit: Optional[int] = 1000+ self, agent_id: str, after: Optional[str] = None, before: Optional[str] = None, limit: Optional[int] = 1000) -> List[Message]:raise NotImplementedError@@ -297,7 +297,7 @@ class AbstractClient(object):def create_org(self, name: Optional[str] = None) -> Organization:raise NotImplementedError- def list_orgs(self, cursor: Optional[str] = None, limit: Optional[int] = 50) -> List[Organization]:+ def list_orgs(self, after: Optional[str] = None, limit: Optional[int] = 50) -> List[Organization]:raise NotImplementedErrordef delete_org(self, org_id: str) -> Organization:@@ -337,13 +337,13 @@ class AbstractClient(object):"""raise NotImplementedError- def list_sandbox_configs(self, limit: int = 50, cursor: Optional[str] = None) -> List[SandboxConfig]:+ def list_sandbox_configs(self, limit: int = 50, after: Optional[str] = None) -> List[SandboxConfig]:"""List all sandbox configurations.Args:limit (int, optional): The maximum number of sandbox configurations to return. Defaults to 50.- cursor (Optional[str], optional): The pagination cursor for retrieving the next set of results.+ after (Optional[str], optional): The pagination cursor for retrieving the next set of results.Returns:List[SandboxConfig]: A list of sandbox configurations.@@ -394,7 +394,7 @@ class AbstractClient(object):raise NotImplementedErrordef list_sandbox_env_vars(- self, sandbox_config_id: str, limit: int = 50, cursor: Optional[str] = None+ self, sandbox_config_id: str, limit: int = 50, after: Optional[str] = None) -> List[SandboxEnvironmentVariable]:"""List all environment variables associated with a sandbox configuration.@@ -402,7 +402,7 @@ class AbstractClient(object):Args:sandbox_config_id (str): The ID of the sandbox configuration to retrieve environment variables for.limit (int, optional): The maximum number of environment variables to return. Defaults to 50.- cursor (Optional[str], optional): The pagination cursor for retrieving the next set of results.+ after (Optional[str], optional): The pagination cursor for retrieving the next set of results.Returns:List[SandboxEnvironmentVariable]: A list of environment variables.@@ -477,7 +477,12 @@ class RESTClient(AbstractClient):self._default_embedding_config = default_embedding_configdef list_agents(- self, tags: Optional[List[str]] = None, query_text: Optional[str] = None, limit: int = 50, cursor: Optional[str] = None+ self,+ tags: Optional[List[str]] = None,+ query_text: Optional[str] = None,+ limit: int = 50,+ before: Optional[str] = None,+ after: Optional[str] = None,) -> List[AgentState]:params = {"limit": limit}if tags:@@ -487,11 +492,13 @@ class RESTClient(AbstractClient):if query_text:params["query_text"] = query_text- if cursor:- params["cursor"] = cursor+ if before:+ params["before"] = before++ if after:+ params["after"] = afterresponse = requests.get(f"{self.base_url}/{self.api_prefix}/agents", headers=self.headers, params=params)- print(f"\nLIST RESPONSE\n{response.json()}\n")return [AgentState(**agent) for agent in response.json()]def agent_exists(self, agent_id: str) -> bool:@@ -1358,7 +1365,7 @@ class RESTClient(AbstractClient):def load_data(self, connector: DataConnector, source_name: str):raise NotImplementedError- def load_file_to_source(self, filename: str, source_id: str, blocking=True):+ def load_file_to_source(self, filename: str, source_id: str, blocking=True) -> Job:"""Load a file into a source@@ -1426,20 +1433,20 @@ class RESTClient(AbstractClient):raise ValueError(f"Failed to list attached sources: {response.text}")return [Source(**source) for source in response.json()]- def list_files_from_source(self, source_id: str, limit: int = 1000, cursor: Optional[str] = None) -> List[FileMetadata]:+ def list_files_from_source(self, source_id: str, limit: int = 1000, after: Optional[str] = None) -> List[FileMetadata]:"""List files from source with pagination support.Args:source_id (str): ID of the sourcelimit (int): Number of files to return- cursor (Optional[str]): Pagination cursor for fetching the next page+ after (str): Get files after a certain timeReturns:List[FileMetadata]: List of files"""# Prepare query parameters for pagination- params = {"limit": limit, "cursor": cursor}+ params = {"limit": limit, "after": after}# Make the request to the FastAPI endpointresponse = requests.get(f"{self.base_url}/{self.api_prefix}/sources/{source_id}/files", headers=self.headers, params=params)@@ -1639,7 +1646,7 @@ class RESTClient(AbstractClient):raise ValueError(f"Failed to update tool: {response.text}")return Tool(**response.json())- def list_tools(self, cursor: Optional[str] = None, limit: Optional[int] = 50) -> List[Tool]:+ def list_tools(self, after: Optional[str] = None, limit: Optional[int] = 50) -> List[Tool]:"""List available tools for the user.@@ -1647,8 +1654,8 @@ class RESTClient(AbstractClient):tools (List[Tool]): List of tools"""params = {}- if cursor:- params["cursor"] = str(cursor)+ if after:+ params["after"] = afterif limit:params["limit"] = limit@@ -1727,15 +1734,15 @@ class RESTClient(AbstractClient):raise ValueError(f"Failed to list embedding configs: {response.text}")return [EmbeddingConfig(**config) for config in response.json()]- def list_orgs(self, cursor: Optional[str] = None, limit: Optional[int] = 50) -> List[Organization]:+ def list_orgs(self, after: Optional[str] = None, limit: Optional[int] = 50) -> List[Organization]:"""Retrieves a list of all organizations in the database, with optional pagination.- @param cursor: the pagination cursor, if any+ @param after: the pagination cursor, if any@param limit: the maximum number of organizations to retrieve@return: a list of Organization objects"""- params = {"cursor": cursor, "limit": limit}+ params = {"after": after, "limit": limit}response = requests.get(f"{self.base_url}/{ADMIN_PREFIX}/orgs", headers=self.headers, params=params)if response.status_code != 200:raise ValueError(f"Failed to retrieve organizations: {response.text}")@@ -1778,6 +1785,12 @@ class RESTClient(AbstractClient):def create_sandbox_config(self, config: Union[LocalSandboxConfig, E2BSandboxConfig]) -> SandboxConfig:"""Create a new sandbox configuration.++ Args:+ config (Union[LocalSandboxConfig, E2BSandboxConfig]): The sandbox settings.++ Returns:+ SandboxConfig: The created sandbox configuration."""payload = {"config": config.model_dump(),@@ -1790,6 +1803,13 @@ class RESTClient(AbstractClient):def update_sandbox_config(self, sandbox_config_id: str, config: Union[LocalSandboxConfig, E2BSandboxConfig]) -> SandboxConfig:"""Update an existing sandbox configuration.++ Args:+ sandbox_config_id (str): The ID of the sandbox configuration to update.+ config (Union[LocalSandboxConfig, E2BSandboxConfig]): The updated sandbox settings.++ Returns:+ SandboxConfig: The updated sandbox configuration."""payload = {"config": config.model_dump(),@@ -1806,6 +1826,9 @@ class RESTClient(AbstractClient):def delete_sandbox_config(self, sandbox_config_id: str) -> None:"""Delete a sandbox configuration.++ Args:+ sandbox_config_id (str): The ID of the sandbox configuration to delete."""response = requests.delete(f"{self.base_url}/{self.api_prefix}/sandbox-config/{sandbox_config_id}", headers=self.headers)if response.status_code == 404:@@ -1813,11 +1836,18 @@ class RESTClient(AbstractClient):elif response.status_code != 204:raise ValueError(f"Failed to delete sandbox config with ID '{sandbox_config_id}': {response.text}")- def list_sandbox_configs(self, limit: int = 50, cursor: Optional[str] = None) -> List[SandboxConfig]:+ def list_sandbox_configs(self, limit: int = 50, after: Optional[str] = None) -> List[SandboxConfig]:"""List all sandbox configurations.++ Args:+ limit (int, optional): The maximum number of sandbox configurations to return. Defaults to 50.+ after (Optional[str], optional): The pagination cursor for retrieving the next set of results.++ Returns:+ List[SandboxConfig]: A list of sandbox configurations."""- params = {"limit": limit, "cursor": cursor}+ params = {"limit": limit, "after": after}response = requests.get(f"{self.base_url}/{self.api_prefix}/sandbox-config", headers=self.headers, params=params)if response.status_code != 200:raise ValueError(f"Failed to list sandbox configs: {response.text}")@@ -1828,6 +1858,15 @@ class RESTClient(AbstractClient):) -> SandboxEnvironmentVariable:"""Create a new environment variable for a sandbox configuration.++ Args:+ sandbox_config_id (str): The ID of the sandbox configuration to associate the environment variable with.+ key (str): The name of the environment variable.+ value (str): The value of the environment variable.+ description (Optional[str], optional): A description of the environment variable. Defaults to None.++ Returns:+ SandboxEnvironmentVariable: The created environment variable."""payload = {"key": key, "value": value, "description": description}response = requests.post(@@ -1844,6 +1883,15 @@ class RESTClient(AbstractClient):) -> SandboxEnvironmentVariable:"""Update an existing environment variable.++ Args:+ env_var_id (str): The ID of the environment variable to update.+ key (Optional[str], optional): The updated name of the environment variable. Defaults to None.+ value (Optional[str], optional): The updated value of the environment variable. Defaults to None.+ description (Optional[str], optional): The updated description of the environment variable. Defaults to None.++ Returns:+ SandboxEnvironmentVariable: The updated environment variable."""payload = {k: v for k, v in {"key": key, "value": value, "description": description}.items() if v is not None}response = requests.patch(@@ -1858,6 +1906,9 @@ class RESTClient(AbstractClient):def delete_sandbox_env_var(self, env_var_id: str) -> None:"""Delete an environment variable by its ID.++ Args:+ env_var_id (str): The ID of the environment variable to delete."""response = requests.delete(f"{self.base_url}/{self.api_prefix}/sandbox-config/environment-variable/{env_var_id}", headers=self.headers@@ -1868,12 +1919,20 @@ class RESTClient(AbstractClient):raise ValueError(f"Failed to delete environment variable with ID '{env_var_id}': {response.text}")def list_sandbox_env_vars(- self, sandbox_config_id: str, limit: int = 50, cursor: Optional[str] = None+ self, sandbox_config_id: str, limit: int = 50, after: Optional[str] = None) -> List[SandboxEnvironmentVariable]:"""List all environment variables associated with a sandbox configuration.++ Args:+ sandbox_config_id (str): The ID of the sandbox configuration to retrieve environment variables for.+ limit (int, optional): The maximum number of environment variables to return. Defaults to 50.+ after (Optional[str], optional): The pagination cursor for retrieving the next set of results.++ Returns:+ List[SandboxEnvironmentVariable]: A list of environment variables."""- params = {"limit": limit, "cursor": cursor}+ params = {"limit": limit, "after": after}response = requests.get(f"{self.base_url}/{self.api_prefix}/sandbox-config/{sandbox_config_id}/environment-variable",headers=self.headers,@@ -2034,7 +2093,8 @@ class RESTClient(AbstractClient):def get_run_messages(self,run_id: str,- cursor: Optional[str] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,limit: Optional[int] = 100,ascending: bool = True,role: Optional[MessageRole] = None,@@ -2044,7 +2104,8 @@ class RESTClient(AbstractClient):Args:job_id: ID of the job- cursor: Cursor for pagination+ before: Cursor for pagination+ after: Cursor for paginationlimit: Maximum number of messages to returnascending: Sort order by creation timerole: Filter by message role (user/assistant/system/tool)@@ -2052,7 +2113,8 @@ class RESTClient(AbstractClient):List of messages matching the filter criteria"""params = {- "cursor": cursor,+ "before": before,+ "after": after,"limit": limit,"ascending": ascending,"role": role,@@ -2150,15 +2212,15 @@ class RESTClient(AbstractClient):def get_tags(self,- cursor: Optional[str] = None,- limit: Optional[int] = None,+ after: Optional[str] = None,+ limit: int = 100,query_text: Optional[str] = None,) -> List[str]:"""Get a list of all unique tags.Args:- cursor: Optional cursor for pagination (last tag seen)+ after: Optional cursor for pagination (first tag seen)limit: Optional maximum number of tags to returnquery_text: Optional text to filter tags@@ -2166,8 +2228,8 @@ class RESTClient(AbstractClient):List[str]: List of unique tags"""params = {}- if cursor:- params["cursor"] = cursor+ if after:+ params["after"] = afterif limit:params["limit"] = limitif query_text:@@ -2237,11 +2299,18 @@ class LocalClient(AbstractClient):# agentsdef list_agents(- self, query_text: Optional[str] = None, tags: Optional[List[str]] = None, limit: int = 100, cursor: Optional[str] = None+ self,+ query_text: Optional[str] = None,+ tags: Optional[List[str]] = None,+ limit: int = 100,+ before: Optional[str] = None,+ after: Optional[str] = None,) -> List[AgentState]:self.interface.clear()- return self.server.agent_manager.list_agents(actor=self.user, tags=tags, query_text=query_text, limit=limit, cursor=cursor)+ return self.server.agent_manager.list_agents(+ actor=self.user, tags=tags, query_text=query_text, limit=limit, before=before, after=after+ )def agent_exists(self, agent_id: Optional[str] = None, agent_name: Optional[str] = None) -> bool:"""@@ -2989,7 +3058,7 @@ class LocalClient(AbstractClient):id: str,name: Optional[str] = None,description: Optional[str] = None,- func: Optional[callable] = None,+ func: Optional[Callable] = None,tags: Optional[List[str]] = None,return_char_limit: int = FUNCTION_RETURN_CHAR_LIMIT,) -> Tool:@@ -3020,14 +3089,14 @@ class LocalClient(AbstractClient):return self.server.tool_manager.update_tool_by_id(tool_id=id, tool_update=ToolUpdate(**update_data), actor=self.user)- def list_tools(self, cursor: Optional[str] = None, limit: Optional[int] = 50) -> List[Tool]:+ def list_tools(self, after: Optional[str] = None, limit: Optional[int] = 50) -> List[Tool]:"""List available tools for the user.Returns:tools (List[Tool]): List of tools"""- return self.server.tool_manager.list_tools(cursor=cursor, limit=limit, actor=self.user)+ return self.server.tool_manager.list_tools(after=after, limit=limit, actor=self.user)def get_tool(self, id: str) -> Optional[Tool]:"""@@ -3226,19 +3295,19 @@ class LocalClient(AbstractClient):"""return self.server.agent_manager.list_attached_sources(agent_id=agent_id, actor=self.user)- def list_files_from_source(self, source_id: str, limit: int = 1000, cursor: Optional[str] = None) -> List[FileMetadata]:+ def list_files_from_source(self, source_id: str, limit: int = 1000, after: Optional[str] = None) -> List[FileMetadata]:"""List files from source.Args:source_id (str): ID of the sourcelimit (int): The # of items to return- cursor (str): The cursor for fetching the next page+ after (str): The cursor for fetching the next pageReturns:files (List[FileMetadata]): List of files"""- return self.server.source_manager.list_files(source_id=source_id, limit=limit, cursor=cursor, actor=self.user)+ return self.server.source_manager.list_files(source_id=source_id, limit=limit, after=after, actor=self.user)def update_source(self, source_id: str, name: Optional[str] = None) -> Source:"""@@ -3296,17 +3365,20 @@ class LocalClient(AbstractClient):passages (List[Passage]): List of passages"""- return self.server.get_agent_archival_cursor(user_id=self.user_id, agent_id=agent_id, limit=limit)+ return self.server.get_agent_archival(user_id=self.user_id, agent_id=agent_id, limit=limit)# recall memory- def get_messages(self, agent_id: str, cursor: Optional[str] = None, limit: Optional[int] = 1000) -> List[Message]:+ def get_messages(+ self, agent_id: str, before: Optional[str] = None, after: Optional[str] = None, limit: Optional[int] = 1000+ ) -> List[Message]:"""Get messages from an agent with pagination.Args:agent_id (str): ID of the agent- cursor (str): Get messages after a certain time+ before (str): Get messages before a certain time+ after (str): Get messages after a certain timelimit (int): Limit number of messagesReturns:@@ -3314,10 +3386,11 @@ class LocalClient(AbstractClient):"""self.interface.clear()- return self.server.get_agent_recall_cursor(+ return self.server.get_agent_recall(user_id=self.user_id,agent_id=agent_id,- before=cursor,+ before=before,+ after=after,limit=limit,reverse=True,)@@ -3436,8 +3509,8 @@ class LocalClient(AbstractClient):def create_org(self, name: Optional[str] = None) -> Organization:return self.server.organization_manager.create_organization(pydantic_org=Organization(name=name))- def list_orgs(self, cursor: Optional[str] = None, limit: Optional[int] = 50) -> List[Organization]:- return self.server.organization_manager.list_organizations(cursor=cursor, limit=limit)+ def list_orgs(self, after: Optional[str] = None, limit: Optional[int] = 50) -> List[Organization]:+ return self.server.organization_manager.list_organizations(limit=limit, after=after)def delete_org(self, org_id: str) -> Organization:return self.server.organization_manager.delete_organization_by_id(org_id=org_id)@@ -3464,11 +3537,11 @@ class LocalClient(AbstractClient):"""return self.server.sandbox_config_manager.delete_sandbox_config(sandbox_config_id=sandbox_config_id, actor=self.user)- def list_sandbox_configs(self, limit: int = 50, cursor: Optional[str] = None) -> List[SandboxConfig]:+ def list_sandbox_configs(self, limit: int = 50, after: Optional[str] = None) -> List[SandboxConfig]:"""List all sandbox configurations."""- return self.server.sandbox_config_manager.list_sandbox_configs(actor=self.user, limit=limit, cursor=cursor)+ return self.server.sandbox_config_manager.list_sandbox_configs(actor=self.user, limit=limit, after=after)def create_sandbox_env_var(self, sandbox_config_id: str, key: str, value: str, description: Optional[str] = None@@ -3499,13 +3572,13 @@ class LocalClient(AbstractClient):return self.server.sandbox_config_manager.delete_sandbox_env_var(env_var_id=env_var_id, actor=self.user)def list_sandbox_env_vars(- self, sandbox_config_id: str, limit: int = 50, cursor: Optional[str] = None+ self, sandbox_config_id: str, limit: int = 50, after: Optional[str] = None) -> List[SandboxEnvironmentVariable]:"""List all environment variables associated with a sandbox configuration."""return self.server.sandbox_config_manager.list_sandbox_env_vars(- sandbox_config_id=sandbox_config_id, actor=self.user, limit=limit, cursor=cursor+ sandbox_config_id=sandbox_config_id, actor=self.user, limit=limit, after=after)def update_agent_memory_block_label(self, agent_id: str, current_label: str, new_label: str) -> Memory:@@ -3626,7 +3699,8 @@ class LocalClient(AbstractClient):def get_run_messages(self,run_id: str,- cursor: Optional[str] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,limit: Optional[int] = 100,ascending: bool = True,role: Optional[MessageRole] = None,@@ -3636,21 +3710,23 @@ class LocalClient(AbstractClient):Args:run_id: ID of the run- cursor: Cursor for pagination+ before: Cursor for pagination+ after: Cursor for paginationlimit: Maximum number of messages to returnascending: Sort order by creation timerole: Filter by message role (user/assistant/system/tool)-Returns:List of messages matching the filter criteria"""params = {- "cursor": cursor,+ "before": before,+ "after": after,"limit": limit,"ascending": ascending,"role": role,}- return self.server.job_manager.get_run_messages_cursor(run_id=run_id, actor=self.user, **params)++ return self.server.job_manager.get_run_messages(run_id=run_id, actor=self.user, **params)def get_run_usage(self,@@ -3712,9 +3788,9 @@ class LocalClient(AbstractClient):def get_tags(self,- cursor: str = None,- limit: int = 100,- query_text: str = None,+ after: Optional[str] = None,+ limit: Optional[int] = None,+ query_text: Optional[str] = None,) -> List[str]:"""Get all tags.@@ -3722,4 +3798,4 @@ class LocalClient(AbstractClient):Returns:tags (List[str]): List of tags"""- return self.server.agent_manager.list_tags(actor=self.user, cursor=cursor, limit=limit, query_text=query_text)+ return self.server.agent_manager.list_tags(actor=self.user, after=after, limit=limit, query_text=query_text)diff --git a/letta/functions/function_sets/multi_agent.py b/letta/functions/function_sets/multi_agent.pyindex 015ac9c1a..40202ed9e 100644--- a/letta/functions/function_sets/multi_agent.py+++ b/letta/functions/function_sets/multi_agent.py@@ -74,7 +74,7 @@ def send_message_to_agents_matching_all_tags(self: "Agent", message: str, tags:server = get_letta_server()# Retrieve agents that match ALL specified tags- matching_agents = server.agent_manager.list_agents(actor=self.user, tags=tags, match_all_tags=True, cursor=None, limit=100)+ matching_agents = server.agent_manager.list_agents(actor=self.user, tags=tags, match_all_tags=True, limit=100)async def send_messages_to_all_agents():tasks = [diff --git a/letta/orm/agent.py b/letta/orm/agent.pyindex 1ea922775..e6b149875 100644--- a/letta/orm/agent.py+++ b/letta/orm/agent.py@@ -1,7 +1,7 @@import uuidfrom typing import TYPE_CHECKING, List, Optional-from sqlalchemy import JSON, String+from sqlalchemy import JSON, Index, Stringfrom sqlalchemy.orm import Mapped, mapped_column, relationshipfrom letta.orm.block import Block@@ -27,6 +27,7 @@ if TYPE_CHECKING:class Agent(SqlalchemyBase, OrganizationMixin):__tablename__ = "agents"__pydantic_model__ = PydanticAgentState+ __table_args__ = (Index("ix_agents_created_at", "created_at", "id"),)# agent generates its own id# TODO: We want to migrate all the ORM models to do this, so we will need to move this to the SqlalchemyBasediff --git a/letta/orm/block.py b/letta/orm/block.pyindex 7395b0afc..ecfa6fe1b 100644--- a/letta/orm/block.py+++ b/letta/orm/block.py@@ -1,6 +1,6 @@from typing import TYPE_CHECKING, Optional, Type-from sqlalchemy import JSON, BigInteger, Integer, UniqueConstraint, event+from sqlalchemy import JSON, BigInteger, Index, Integer, UniqueConstraint, eventfrom sqlalchemy.orm import Mapped, attributes, mapped_column, relationshipfrom letta.constants import CORE_MEMORY_BLOCK_CHAR_LIMIT@@ -20,7 +20,10 @@ class Block(OrganizationMixin, SqlalchemyBase):__tablename__ = "block"__pydantic_model__ = PydanticBlock# This may seem redundant, but is necessary for the BlocksAgents composite FK relationship- __table_args__ = (UniqueConstraint("id", "label", name="unique_block_id_label"),)+ __table_args__ = (+ UniqueConstraint("id", "label", name="unique_block_id_label"),+ Index("created_at_label_idx", "created_at", "label"),+ )template_name: Mapped[Optional[str]] = mapped_column(nullable=True, doc="the unique name that identifies a block in a human-readable way"diff --git a/letta/orm/job.py b/letta/orm/job.pyindex aacb6785d..a99b542c6 100644--- a/letta/orm/job.py+++ b/letta/orm/job.py@@ -1,7 +1,7 @@from datetime import datetimefrom typing import TYPE_CHECKING, List, Optional-from sqlalchemy import JSON, String+from sqlalchemy import JSON, Index, Stringfrom sqlalchemy.orm import Mapped, mapped_column, relationshipfrom letta.orm.enums import JobType@@ -25,6 +25,7 @@ class Job(SqlalchemyBase, UserMixin):__tablename__ = "jobs"__pydantic_model__ = PydanticJob+ __table_args__ = (Index("ix_jobs_created_at", "created_at", "id"),)status: Mapped[JobStatus] = mapped_column(String, default=JobStatus.created, doc="The current status of the job.")completed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True, doc="The unix timestamp of when the job was completed.")diff --git a/letta/orm/message.py b/letta/orm/message.pyindex 809bcdf53..0591528c4 100644--- a/letta/orm/message.py+++ b/letta/orm/message.py@@ -14,7 +14,10 @@ class Message(SqlalchemyBase, OrganizationMixin, AgentMixin):"""Defines data model for storing Message objects"""__tablename__ = "messages"- __table_args__ = (Index("ix_messages_agent_created_at", "agent_id", "created_at"),)+ __table_args__ = (+ Index("ix_messages_agent_created_at", "agent_id", "created_at"),+ Index("ix_messages_created_at", "created_at", "id"),+ )__pydantic_model__ = PydanticMessageid: Mapped[str] = mapped_column(primary_key=True, doc="Unique message identifier")diff --git a/letta/orm/passage.py b/letta/orm/passage.pyindex 492c60217..617edaeff 100644--- a/letta/orm/passage.py+++ b/letta/orm/passage.py@@ -45,8 +45,12 @@ class BasePassage(SqlalchemyBase, OrganizationMixin):@declared_attrdef __table_args__(cls):if settings.letta_pg_uri_no_default:- return (Index(f"{cls.__tablename__}_org_idx", "organization_id"), {"extend_existing": True})- return ({"extend_existing": True},)+ return (+ Index(f"{cls.__tablename__}_org_idx", "organization_id"),+ Index(f"{cls.__tablename__}_created_at_id_idx", "created_at", "id"),+ {"extend_existing": True},+ )+ return (Index(f"{cls.__tablename__}_created_at_id_idx", "created_at", "id"), {"extend_existing": True})class SourcePassage(BasePassage, FileMixin, SourceMixin):diff --git a/letta/orm/source.py b/letta/orm/source.pyindex e7443ea67..055f140e2 100644--- a/letta/orm/source.py+++ b/letta/orm/source.py@@ -1,6 +1,6 @@from typing import TYPE_CHECKING, List, Optional-from sqlalchemy import JSON+from sqlalchemy import JSON, Indexfrom sqlalchemy.orm import Mapped, mapped_column, relationshipfrom letta.orm import FileMetadata@@ -23,6 +23,11 @@ class Source(SqlalchemyBase, OrganizationMixin):__tablename__ = "sources"__pydantic_model__ = PydanticSource+ __table_args__ = (+ Index(f"source_created_at_id_idx", "created_at", "id"),+ {"extend_existing": True},+ )+name: Mapped[str] = mapped_column(doc="the name of the source, must be unique within the org", nullable=False)description: Mapped[str] = mapped_column(nullable=True, doc="a human-readable description of the source")embedding_config: Mapped[EmbeddingConfig] = mapped_column(EmbeddingConfigColumn, doc="Configuration settings for embedding.")diff --git a/letta/orm/sqlalchemy_base.py b/letta/orm/sqlalchemy_base.pyindex fd0c1e3af..375417f89 100644--- a/letta/orm/sqlalchemy_base.py+++ b/letta/orm/sqlalchemy_base.py@@ -3,7 +3,7 @@ from enum import Enumfrom functools import wrapsfrom typing import TYPE_CHECKING, List, Literal, Optional, Tuple, Union-from sqlalchemy import String, and_, desc, func, or_, select+from sqlalchemy import String, and_, func, or_, selectfrom sqlalchemy.exc import DBAPIError, IntegrityError, TimeoutErrorfrom sqlalchemy.orm import Mapped, Session, mapped_column@@ -52,7 +52,8 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):cls,*,db_session: "Session",- cursor: Optional[str] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,start_date: Optional[datetime] = None,end_date: Optional[datetime] = None,limit: Optional[int] = 50,@@ -69,12 +70,13 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):**kwargs,) -> List["SqlalchemyBase"]:"""- List records with cursor-based pagination, ordering by created_at.- Cursor is an ID, but pagination is based on the cursor object's created_at value.+ List records with before/after pagination, ordering by created_at.+ Can use both before and after to fetch a window of records.Args:db_session: SQLAlchemy session- cursor: ID of the last item seen (for pagination)+ before: ID of item to paginate before (upper bound)+ after: ID of item to paginate after (lower bound)start_date: Filter items after this dateend_date: Filter items before this datelimit: Maximum number of items to return@@ -89,13 +91,25 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):raise ValueError("start_date must be earlier than or equal to end_date")logger.debug(f"Listing {cls.__name__} with kwarg filters {kwargs}")+with db_session as session:- # If cursor provided, get the reference object- cursor_obj = None- if cursor:- cursor_obj = session.get(cls, cursor)- if not cursor_obj:- raise NoResultFound(f"No {cls.__name__} found with id {cursor}")+ # Get the reference objects for pagination+ before_obj = None+ after_obj = None++ if before:+ before_obj = session.get(cls, before)+ if not before_obj:+ raise NoResultFound(f"No {cls.__name__} found with id {before}")++ if after:+ after_obj = session.get(cls, after)+ if not after_obj:+ raise NoResultFound(f"No {cls.__name__} found with id {after}")++ # Validate that before comes after the after object if both are provided+ if before_obj and after_obj and before_obj.created_at < after_obj.created_at:+ raise ValueError("'before' reference must be later than 'after' reference")query = select(cls)@@ -122,8 +136,8 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):else:# Match ANY tag - use join and filterquery = (- query.join(cls.tags).filter(cls.tags.property.mapper.class_.tag.in_(tags)).group_by(cls.id) # Deduplicate results- )+ query.join(cls.tags).filter(cls.tags.property.mapper.class_.tag.in_(tags)).group_by(cls.id)+ ) # Deduplicate results# Group by primary key and all necessary columns to avoid JSON comparisonquery = query.group_by(cls.id)@@ -150,16 +164,35 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):if end_date:query = query.filter(cls.created_at < end_date)- # Cursor-based pagination- if cursor_obj:- if ascending:- query = query.where(cls.created_at >= cursor_obj.created_at).where(- or_(cls.created_at > cursor_obj.created_at, cls.id > cursor_obj.id)- )+ # Handle pagination based on before/after+ if before or after:+ conditions = []++ if before and after:+ # Window-based query - get records between before and after+ conditions = [+ or_(cls.created_at < before_obj.created_at, and_(cls.created_at == before_obj.created_at, cls.id < before_obj.id)),+ or_(cls.created_at > after_obj.created_at, and_(cls.created_at == after_obj.created_at, cls.id > after_obj.id)),+ ]else:- query = query.where(cls.created_at <= cursor_obj.created_at).where(- or_(cls.created_at < cursor_obj.created_at, cls.id < cursor_obj.id)- )+ # Pure pagination query+ if before:+ conditions.append(+ or_(+ cls.created_at < before_obj.created_at,+ and_(cls.created_at == before_obj.created_at, cls.id < before_obj.id),+ )+ )+ if after:+ conditions.append(+ or_(+ cls.created_at > after_obj.created_at,+ and_(cls.created_at == after_obj.created_at, cls.id > after_obj.id),+ )+ )++ if conditions:+ query = query.where(and_(*conditions))# Text searchif query_text:@@ -184,7 +217,9 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):# SQLite with custom vector typequery_embedding_binary = adapt_array(query_embedding)query = query.order_by(- func.cosine_distance(cls.embedding, query_embedding_binary).asc(), cls.created_at.asc(), cls.id.asc()+ func.cosine_distance(cls.embedding, query_embedding_binary).asc(),+ cls.created_at.asc() if ascending else cls.created_at.desc(),+ cls.id.asc(),)is_ordered = True@@ -195,13 +230,28 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):# Apply orderingif not is_ordered:if ascending:- query = query.order_by(cls.created_at, cls.id)+ query = query.order_by(cls.created_at.asc(), cls.id.asc())else:- query = query.order_by(desc(cls.created_at), desc(cls.id))+ query = query.order_by(cls.created_at.desc(), cls.id.desc())++ # Apply limit, adjusting for both bounds if necessary+ if before and after:+ # When both bounds are provided, we need to fetch enough records to satisfy+ # the limit while respecting both bounds. We'll fetch more and then trim.+ query = query.limit(limit * 2)+ else:+ query = query.limit(limit)++ results = list(session.execute(query).scalars())- query = query.limit(limit)+ # If we have both bounds, take the middle portion+ if before and after and len(results) > limit:+ middle = len(results) // 2+ start = max(0, middle - limit // 2)+ end = min(len(results), start + limit)+ results = results[start:end]- return list(session.execute(query).scalars())+ return results@classmethod@handle_db_timeout@@ -449,12 +499,10 @@ class SqlalchemyBase(CommonSqlalchemyMetaMixins, Base):def to_pydantic(self) -> "BaseModel":"""converts to the basic pydantic model counterpart"""+ model = self.__pydantic_model__.model_validate(self)if hasattr(self, "metadata_"):- model_dict = {k: v for k, v in self.__dict__.items() if k in self.__pydantic_model__.model_fields}- model_dict["metadata"] = self.metadata_- return self.__pydantic_model__.model_validate(model_dict)-- return self.__pydantic_model__.model_validate(self)+ model.metadata = self.metadata_+ return modeldef to_record(self) -> "BaseModel":"""Deprecated accessor for to_pydantic"""diff --git a/letta/orm/tool.py b/letta/orm/tool.pyindex 0b443d27c..bb47566b8 100644--- a/letta/orm/tool.py+++ b/letta/orm/tool.py@@ -1,6 +1,6 @@from typing import TYPE_CHECKING, List, Optional-from sqlalchemy import JSON, String, UniqueConstraint+from sqlalchemy import JSON, Index, String, UniqueConstraintfrom sqlalchemy.orm import Mapped, mapped_column, relationship# TODO everything in functions should live in this model@@ -26,7 +26,10 @@ class Tool(SqlalchemyBase, OrganizationMixin):# Add unique constraint on (name, _organization_id)# An organization should not have multiple tools with the same name- __table_args__ = (UniqueConstraint("name", "organization_id", name="uix_name_organization"),)+ __table_args__ = (+ UniqueConstraint("name", "organization_id", name="uix_name_organization"),+ Index("ix_tools_created_at_name", "created_at", "name"),+ )name: Mapped[str] = mapped_column(doc="The display name of the tool.")tool_type: Mapped[ToolType] = mapped_column(diff --git a/letta/schemas/job.py b/letta/schemas/job.pyindex 0ffbf2c72..35ea9cd73 100644--- a/letta/schemas/job.py+++ b/letta/schemas/job.py@@ -12,7 +12,7 @@ class JobBase(OrmMetadataBase):__id_prefix__ = "job"status: JobStatus = Field(default=JobStatus.created, description="The status of the job.")completed_at: Optional[datetime] = Field(None, description="The unix timestamp of when the job was completed.")- metadata: Optional[dict] = Field(None, description="The metadata of the job.")+ metadata: Optional[dict] = Field(None, validation_alias="metadata_", description="The metadata of the job.")job_type: JobType = Field(default=JobType.JOB, description="The type of the job.")diff --git a/letta/schemas/passage.py b/letta/schemas/passage.pyindex 648364c24..74ab8f0c9 100644--- a/letta/schemas/passage.py+++ b/letta/schemas/passage.py@@ -23,7 +23,7 @@ class PassageBase(OrmMetadataBase):# file associationfile_id: Optional[str] = Field(None, description="The unique identifier of the file associated with the passage.")- metadata: Optional[Dict] = Field({}, description="The metadata of the passage.")+ metadata: Optional[Dict] = Field({}, validation_alias="metadata_", description="The metadata of the passage.")class Passage(PassageBase):diff --git a/letta/schemas/source.py b/letta/schemas/source.pyindex 796f50eba..0f00d6b8e 100644--- a/letta/schemas/source.py+++ b/letta/schemas/source.py@@ -33,7 +33,7 @@ class Source(BaseSource):description: Optional[str] = Field(None, description="The description of the source.")embedding_config: EmbeddingConfig = Field(..., description="The embedding configuration used by the source.")organization_id: Optional[str] = Field(None, description="The ID of the organization that created the source.")- metadata: Optional[dict] = Field(None, description="Metadata associated with the source.")+ metadata: Optional[dict] = Field(None, validation_alias="metadata_", description="Metadata associated with the source.")# metadata fieldscreated_by_id: Optional[str] = Field(None, description="The id of the user that made this Tool.")diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.pyindex d4034c172..e34b5400b 100644--- a/letta/server/rest_api/routers/v1/agents.py+++ b/letta/server/rest_api/routers/v1/agents.py@@ -43,7 +43,8 @@ def list_agents(),server: "SyncServer" = Depends(get_letta_server),user_id: Optional[str] = Header(None, alias="user_id"),- cursor: Optional[str] = Query(None, description="Cursor for pagination"),+ before: Optional[str] = Query(None, description="Cursor for pagination"),+ after: Optional[str] = Query(None, description="Cursor for pagination"),limit: Optional[int] = Query(None, description="Limit for pagination"),query_text: Optional[str] = Query(None, description="Search agents by name"),):@@ -66,7 +67,7 @@ def list_agents(}# Call list_agents with the dynamic kwargs- agents = server.agent_manager.list_agents(actor=actor, cursor=cursor, limit=limit, **kwargs)+ agents = server.agent_manager.list_agents(actor=actor, before=before, after=after, limit=limit, **kwargs)return agents@@ -347,14 +348,11 @@ def list_archival_memory("""actor = server.user_manager.get_user_or_default(user_id=user_id)- # TODO need to add support for non-postgres here- # chroma will throw:- # raise ValueError("Cannot run get_all_cursor with chroma")-- return server.get_agent_archival_cursor(+ return server.get_agent_archival(user_id=actor.id,agent_id=agent_id,- cursor=after, # TODO: deleting before, after. is this expected?+ after=after,+ before=before,limit=limit,)@@ -429,7 +427,7 @@ def list_messages("""actor = server.user_manager.get_user_or_default(user_id=user_id)- return server.get_agent_recall_cursor(+ return server.get_agent_recall(user_id=actor.id,agent_id=agent_id,before=before,diff --git a/letta/server/rest_api/routers/v1/organizations.py b/letta/server/rest_api/routers/v1/organizations.pyindex 2f4cdb1b5..e35bf5bde 100644--- a/letta/server/rest_api/routers/v1/organizations.py+++ b/letta/server/rest_api/routers/v1/organizations.py@@ -14,7 +14,7 @@ router = APIRouter(prefix="/orgs", tags=["organization", "admin"])@router.get("/", tags=["admin"], response_model=List[Organization], operation_id="list_orgs")def get_all_orgs(- cursor: Optional[str] = Query(None),+ after: Optional[str] = Query(None),limit: Optional[int] = Query(50),server: "SyncServer" = Depends(get_letta_server),):@@ -22,7 +22,7 @@ def get_all_orgs(Get a list of all orgs in the database"""try:- orgs = server.organization_manager.list_organizations(cursor=cursor, limit=limit)+ orgs = server.organization_manager.list_organizations(after=after, limit=limit)except HTTPException:raiseexcept Exception as e:diff --git a/letta/server/rest_api/routers/v1/providers.py b/letta/server/rest_api/routers/v1/providers.pyindex be462dbf1..7feb1674b 100644--- a/letta/server/rest_api/routers/v1/providers.py+++ b/letta/server/rest_api/routers/v1/providers.py@@ -13,7 +13,7 @@ router = APIRouter(prefix="/providers", tags=["providers"])@router.get("/", tags=["providers"], response_model=List[Provider], operation_id="list_providers")def list_providers(- cursor: Optional[str] = Query(None),+ after: Optional[str] = Query(None),limit: Optional[int] = Query(50),server: "SyncServer" = Depends(get_letta_server),):@@ -21,7 +21,7 @@ def list_providers(Get a list of all custom providers in the database"""try:- providers = server.provider_manager.list_providers(cursor=cursor, limit=limit)+ providers = server.provider_manager.list_providers(after=after, limit=limit)except HTTPException:raiseexcept Exception as e:diff --git a/letta/server/rest_api/routers/v1/runs.py b/letta/server/rest_api/routers/v1/runs.pyindex 6af01c5ed..d0abd3c35 100644--- a/letta/server/rest_api/routers/v1/runs.py+++ b/letta/server/rest_api/routers/v1/runs.py@@ -75,9 +75,12 @@ async def list_run_messages(run_id: str,server: "SyncServer" = Depends(get_letta_server),user_id: Optional[str] = Header(None, alias="user_id"),- cursor: Optional[str] = Query(None, description="Cursor for pagination"),+ before: Optional[str] = Query(None, description="Cursor for pagination"),+ after: Optional[str] = Query(None, description="Cursor for pagination"),limit: Optional[int] = Query(100, description="Maximum number of messages to return"),- ascending: bool = Query(True, description="Sort order by creation time"),+ order: str = Query(+ "desc", description="Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order."+ ),role: Optional[MessageRole] = Query(None, description="Filter by role"),):"""@@ -85,9 +88,10 @@ async def list_run_messages(Args:run_id: ID of the run- cursor: Cursor for pagination+ before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list.+ after: A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list.limit: Maximum number of messages to return- ascending: Sort order by creation time+ order: Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order.role: Filter by role (user/assistant/system/tool)return_message_object: Whether to return Message objects or LettaMessage objectsuser_id: ID of the user making the request@@ -95,15 +99,19 @@ async def list_run_messages(Returns:A list of messages associated with the run. Default is List[LettaMessage]."""+ if order not in ["asc", "desc"]:+ raise HTTPException(status_code=400, detail="Order must be 'asc' or 'desc'")+actor = server.user_manager.get_user_or_default(user_id=user_id)try:- messages = server.job_manager.get_run_messages_cursor(+ messages = server.job_manager.get_run_messages(run_id=run_id,actor=actor,limit=limit,- cursor=cursor,- ascending=ascending,+ before=before,+ after=after,+ ascending=(order == "asc"),role=role,)return messagesdiff --git a/letta/server/rest_api/routers/v1/sandbox_configs.py b/letta/server/rest_api/routers/v1/sandbox_configs.pyindex edd4383ca..bb93cd368 100644--- a/letta/server/rest_api/routers/v1/sandbox_configs.py+++ b/letta/server/rest_api/routers/v1/sandbox_configs.py@@ -68,13 +68,13 @@ def delete_sandbox_config(@router.get("/", response_model=List[PydanticSandboxConfig])def list_sandbox_configs(limit: int = Query(1000, description="Number of results to return"),- cursor: Optional[str] = Query(None, description="Pagination cursor to fetch the next set of results"),+ after: Optional[str] = Query(None, description="Pagination cursor to fetch the next set of results"),sandbox_type: Optional[SandboxType] = Query(None, description="Filter for this specific sandbox type"),server: SyncServer = Depends(get_letta_server),user_id: str = Depends(get_user_id),):actor = server.user_manager.get_user_or_default(user_id=user_id)- return server.sandbox_config_manager.list_sandbox_configs(actor, limit=limit, cursor=cursor, sandbox_type=sandbox_type)+ return server.sandbox_config_manager.list_sandbox_configs(actor, limit=limit, after=after, sandbox_type=sandbox_type)### Sandbox Environment Variable Routes@@ -116,9 +116,9 @@ def delete_sandbox_env_var(def list_sandbox_env_vars(sandbox_config_id: str,limit: int = Query(1000, description="Number of results to return"),- cursor: Optional[str] = Query(None, description="Pagination cursor to fetch the next set of results"),+ after: Optional[str] = Query(None, description="Pagination cursor to fetch the next set of results"),server: SyncServer = Depends(get_letta_server),user_id: str = Depends(get_user_id),):actor = server.user_manager.get_user_or_default(user_id=user_id)- return server.sandbox_config_manager.list_sandbox_env_vars(sandbox_config_id, actor, limit=limit, cursor=cursor)+ return server.sandbox_config_manager.list_sandbox_env_vars(sandbox_config_id, actor, limit=limit, after=after)diff --git a/letta/server/rest_api/routers/v1/sources.py b/letta/server/rest_api/routers/v1/sources.pyindex 6ce045bba..0be1b8c7a 100644--- a/letta/server/rest_api/routers/v1/sources.py+++ b/letta/server/rest_api/routers/v1/sources.py@@ -165,7 +165,7 @@ def list_source_passages(def list_source_files(source_id: str,limit: int = Query(1000, description="Number of files to return"),- cursor: Optional[str] = Query(None, description="Pagination cursor to fetch the next set of results"),+ after: Optional[str] = Query(None, description="Pagination cursor to fetch the next set of results"),server: "SyncServer" = Depends(get_letta_server),user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present):@@ -173,7 +173,7 @@ def list_source_files(List paginated files associated with a data source."""actor = server.user_manager.get_user_or_default(user_id=user_id)- return server.source_manager.list_files(source_id=source_id, limit=limit, cursor=cursor, actor=actor)+ return server.source_manager.list_files(source_id=source_id, limit=limit, after=after, actor=actor)# it's redundant to include /delete in the URL path. The HTTP verb DELETE already implies that action.diff --git a/letta/server/rest_api/routers/v1/tags.py b/letta/server/rest_api/routers/v1/tags.pyindex bbdfa8815..fd889af61 100644--- a/letta/server/rest_api/routers/v1/tags.py+++ b/letta/server/rest_api/routers/v1/tags.py@@ -13,7 +13,7 @@ router = APIRouter(prefix="/tags", tags=["tag", "admin"])@router.get("/", tags=["admin"], response_model=List[str], operation_id="list_tags")def list_tags(- cursor: Optional[str] = Query(None),+ after: Optional[str] = Query(None),limit: Optional[int] = Query(50),server: "SyncServer" = Depends(get_letta_server),query_text: Optional[str] = Query(None),@@ -23,5 +23,5 @@ def list_tags(Get a list of all tags in the database"""actor = server.user_manager.get_user_or_default(user_id=user_id)- tags = server.agent_manager.list_tags(actor=actor, cursor=cursor, limit=limit, query_text=query_text)+ tags = server.agent_manager.list_tags(actor=actor, after=after, limit=limit, query_text=query_text)return tagsdiff --git a/letta/server/rest_api/routers/v1/tools.py b/letta/server/rest_api/routers/v1/tools.pyindex ce05e5bcf..14a9dc14b 100644--- a/letta/server/rest_api/routers/v1/tools.py+++ b/letta/server/rest_api/routers/v1/tools.py@@ -50,7 +50,7 @@ def retrieve_tool(@router.get("/", response_model=List[Tool], operation_id="list_tools")def list_tools(- cursor: Optional[str] = None,+ after: Optional[str] = None,limit: Optional[int] = 50,server: SyncServer = Depends(get_letta_server),user_id: Optional[str] = Header(None, alias="user_id"), # Extract user_id from header, default to None if not present@@ -60,7 +60,7 @@ def list_tools("""try:actor = server.user_manager.get_user_or_default(user_id=user_id)- return server.tool_manager.list_tools(actor=actor, cursor=cursor, limit=limit)+ return server.tool_manager.list_tools(actor=actor, after=after, limit=limit)except Exception as e:# Log or print the full exception here for debuggingprint(f"Error occurred: {e}")diff --git a/letta/server/rest_api/routers/v1/users.py b/letta/server/rest_api/routers/v1/users.pyindex 27a2feeb0..bf2de7ef5 100644--- a/letta/server/rest_api/routers/v1/users.py+++ b/letta/server/rest_api/routers/v1/users.py@@ -15,7 +15,7 @@ router = APIRouter(prefix="/users", tags=["users", "admin"])@router.get("/", tags=["admin"], response_model=List[User], operation_id="list_users")def list_users(- cursor: Optional[str] = Query(None),+ after: Optional[str] = Query(None),limit: Optional[int] = Query(50),server: "SyncServer" = Depends(get_letta_server),):@@ -23,7 +23,7 @@ def list_users(Get a list of all users in the database"""try:- next_cursor, users = server.user_manager.list_users(cursor=cursor, limit=limit)+ users = server.user_manager.list_users(after=after, limit=limit)except HTTPException:raiseexcept Exception as e:diff --git a/letta/server/server.py b/letta/server/server.pyindex 9cafebbda..02e66e5c0 100644--- a/letta/server/server.py+++ b/letta/server/server.py@@ -805,20 +805,12 @@ class SyncServer(Server):def get_recall_memory_summary(self, agent_id: str, actor: User) -> RecallMemorySummary:return RecallMemorySummary(size=self.message_manager.size(actor=actor, agent_id=agent_id))- def get_agent_archival(self, user_id: str, agent_id: str, cursor: Optional[str] = None, limit: int = 50) -> List[Passage]:- """Paginated query of all messages in agent archival memory"""- # TODO: Thread actor directly through this function, since the top level caller most likely already retrieved the user- actor = self.user_manager.get_user_or_default(user_id=user_id)-- passages = self.agent_manager.list_passages(agent_id=agent_id, actor=actor)-- return passages-- def get_agent_archival_cursor(+ def get_agent_archival(self,user_id: str,agent_id: str,- cursor: Optional[str] = None,+ after: Optional[str] = None,+ before: Optional[str] = None,limit: Optional[int] = 100,order_by: Optional[str] = "created_at",reverse: Optional[bool] = False,@@ -830,7 +822,8 @@ class SyncServer(Server):records = self.agent_manager.list_passages(actor=actor,agent_id=agent_id,- cursor=cursor,+ after=after,+ before=before,limit=limit,ascending=not reverse,)@@ -852,7 +845,7 @@ class SyncServer(Server):# TODO: return archival memory- def get_agent_recall_cursor(+ def get_agent_recall(self,user_id: str,agent_id: str,diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.pyindex a84a5df99..f4aa47265 100644--- a/letta/services/agent_manager.py+++ b/letta/services/agent_manager.py@@ -2,7 +2,7 @@ from datetime import datetimefrom typing import Dict, List, Optionalimport numpy as np-from sqlalchemy import Select, func, literal, select, union_all+from sqlalchemy import Select, and_, func, literal, or_, select, union_allfrom letta.constants import BASE_MEMORY_TOOLS, BASE_TOOLS, MAX_EMBEDDING_DIM, MULTI_AGENT_TOOLSfrom letta.embeddings import embedding_model@@ -271,10 +271,11 @@ class AgentManager:def list_agents(self,actor: PydanticUser,+ before: Optional[str] = None,+ after: Optional[str] = None,+ limit: Optional[int] = 50,tags: Optional[List[str]] = None,match_all_tags: bool = False,- cursor: Optional[str] = None,- limit: Optional[int] = 50,query_text: Optional[str] = None,**kwargs,) -> List[PydanticAgentState]:@@ -284,10 +285,11 @@ class AgentManager:with self.session_maker() as session:agents = AgentModel.list(db_session=session,+ before=before,+ after=after,+ limit=limit,tags=tags,match_all_tags=match_all_tags,- cursor=cursor,- limit=limit,organization_id=actor.organization_id if actor else None,query_text=query_text,**kwargs,@@ -723,7 +725,8 @@ class AgentManager:query_text: Optional[str] = None,start_date: Optional[datetime] = None,end_date: Optional[datetime] = None,- cursor: Optional[str] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,source_id: Optional[str] = None,embed_query: bool = False,ascending: bool = True,@@ -731,6 +734,7 @@ class AgentManager:agent_only: bool = False,) -> Select:"""Helper function to build the base passage query with all filters applied.+ Supports both before and after pagination across merged source and agent passages.Returns the query before any limit or count operations are applied."""@@ -818,30 +822,69 @@ class AgentManager:else:# SQLite with custom vector typequery_embedding_binary = adapt_array(embedded_text)- if ascending:- main_query = main_query.order_by(- func.cosine_distance(combined_query.c.embedding, query_embedding_binary).asc(),- combined_query.c.created_at.asc(),- combined_query.c.id.asc(),- )- else:- main_query = main_query.order_by(- func.cosine_distance(combined_query.c.embedding, query_embedding_binary).asc(),- combined_query.c.created_at.desc(),- combined_query.c.id.asc(),- )+ main_query = main_query.order_by(+ func.cosine_distance(combined_query.c.embedding, query_embedding_binary).asc(),+ combined_query.c.created_at.asc() if ascending else combined_query.c.created_at.desc(),+ combined_query.c.id.asc(),+ )else:if query_text:main_query = main_query.where(func.lower(combined_query.c.text).contains(func.lower(query_text)))- # Handle cursor-based pagination- if cursor:- cursor_query = select(combined_query.c.created_at).where(combined_query.c.id == cursor).scalar_subquery()+ # Handle pagination+ if before or after:+ # Create reference CTEs+ if before:+ before_ref = (+ select(combined_query.c.created_at, combined_query.c.id).where(combined_query.c.id == before).cte("before_ref")+ )+ if after:+ after_ref = (+ select(combined_query.c.created_at, combined_query.c.id).where(combined_query.c.id == after).cte("after_ref")+ )- if ascending:- main_query = main_query.where(combined_query.c.created_at > cursor_query)+ if before and after:+ # Window-based query (get records between before and after)+ main_query = main_query.where(+ or_(+ combined_query.c.created_at < select(before_ref.c.created_at).scalar_subquery(),+ and_(+ combined_query.c.created_at == select(before_ref.c.created_at).scalar_subquery(),+ combined_query.c.id < select(before_ref.c.id).scalar_subquery(),+ ),+ )+ )+ main_query = main_query.where(+ or_(+ combined_query.c.created_at > select(after_ref.c.created_at).scalar_subquery(),+ and_(+ combined_query.c.created_at == select(after_ref.c.created_at).scalar_subquery(),+ combined_query.c.id > select(after_ref.c.id).scalar_subquery(),+ ),+ )+ )else:- main_query = main_query.where(combined_query.c.created_at < cursor_query)+ # Pure pagination (only before or only after)+ if before:+ main_query = main_query.where(+ or_(+ combined_query.c.created_at < select(before_ref.c.created_at).scalar_subquery(),+ and_(+ combined_query.c.created_at == select(before_ref.c.created_at).scalar_subquery(),+ combined_query.c.id < select(before_ref.c.id).scalar_subquery(),+ ),+ )+ )+ if after:+ main_query = main_query.where(+ or_(+ combined_query.c.created_at > select(after_ref.c.created_at).scalar_subquery(),+ and_(+ combined_query.c.created_at == select(after_ref.c.created_at).scalar_subquery(),+ combined_query.c.id > select(after_ref.c.id).scalar_subquery(),+ ),+ )+ )# Add ordering if not already ordered by similarityif not embed_query:@@ -856,7 +899,7 @@ class AgentManager:combined_query.c.id.asc(),)- return main_query+ return main_query@enforce_typesdef list_passages(@@ -868,7 +911,8 @@ class AgentManager:query_text: Optional[str] = None,start_date: Optional[datetime] = None,end_date: Optional[datetime] = None,- cursor: Optional[str] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,source_id: Optional[str] = None,embed_query: bool = False,ascending: bool = True,@@ -884,7 +928,8 @@ class AgentManager:query_text=query_text,start_date=start_date,end_date=end_date,- cursor=cursor,+ before=before,+ after=after,source_id=source_id,embed_query=embed_query,ascending=ascending,@@ -924,7 +969,8 @@ class AgentManager:query_text: Optional[str] = None,start_date: Optional[datetime] = None,end_date: Optional[datetime] = None,- cursor: Optional[str] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,source_id: Optional[str] = None,embed_query: bool = False,ascending: bool = True,@@ -940,7 +986,8 @@ class AgentManager:query_text=query_text,start_date=start_date,end_date=end_date,- cursor=cursor,+ before=before,+ after=after,source_id=source_id,embed_query=embed_query,ascending=ascending,@@ -1044,14 +1091,14 @@ class AgentManager:# ======================================================================================================================@enforce_typesdef list_tags(- self, actor: PydanticUser, cursor: Optional[str] = None, limit: Optional[int] = 50, query_text: Optional[str] = None+ self, actor: PydanticUser, after: Optional[str] = None, limit: Optional[int] = 50, query_text: Optional[str] = None) -> List[str]:"""Get all tags a user has created, ordered alphabetically.Args:actor: User performing the action.- cursor: Cursor for pagination.+ after: Cursor for forward pagination.limit: Maximum number of tags to return.query_text: Query text to filter tags by.@@ -1069,8 +1116,8 @@ class AgentManager:if query_text:query = query.filter(AgentsTags.tag.ilike(f"%{query_text}%"))- if cursor:- query = query.filter(AgentsTags.tag > cursor)+ if after:+ query = query.filter(AgentsTags.tag > after)query = query.order_by(AgentsTags.tag).limit(limit)results = [tag[0] for tag in query.all()]diff --git a/letta/services/block_manager.py b/letta/services/block_manager.pyindex ad46b3bba..2d25093f7 100644--- a/letta/services/block_manager.py+++ b/letta/services/block_manager.py@@ -64,7 +64,7 @@ class BlockManager:is_template: Optional[bool] = None,template_name: Optional[str] = None,id: Optional[str] = None,- cursor: Optional[str] = None,+ after: Optional[str] = None,limit: Optional[int] = 50,) -> List[PydanticBlock]:"""Retrieve blocks based on various optional filters."""@@ -80,7 +80,7 @@ class BlockManager:if id:filters["id"] = id- blocks = BlockModel.list(db_session=session, cursor=cursor, limit=limit, **filters)+ blocks = BlockModel.list(db_session=session, after=after, limit=limit, **filters)return [block.to_pydantic() for block in blocks]diff --git a/letta/services/job_manager.py b/letta/services/job_manager.pyindex 3fd9e3c7c..59877ee05 100644--- a/letta/services/job_manager.py+++ b/letta/services/job_manager.py@@ -78,10 +78,12 @@ class JobManager:def list_jobs(self,actor: PydanticUser,- cursor: Optional[str] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,limit: Optional[int] = 50,statuses: Optional[List[JobStatus]] = None,job_type: JobType = JobType.JOB,+ ascending: bool = True,) -> List[PydanticJob]:"""List all jobs with optional pagination and status filter."""with self.session_maker() as session:@@ -93,8 +95,10 @@ class JobManager:jobs = JobModel.list(db_session=session,- cursor=cursor,+ before=before,+ after=after,limit=limit,+ ascending=ascending,**filter_kwargs,)return [job.to_pydantic() for job in jobs]@@ -112,7 +116,8 @@ class JobManager:self,job_id: str,actor: PydanticUser,- cursor: Optional[str] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,limit: Optional[int] = 100,role: Optional[MessageRole] = None,ascending: bool = True,@@ -123,7 +128,8 @@ class JobManager:Args:job_id: The ID of the job to get messages foractor: The user making the request- cursor: Cursor for pagination+ before: Cursor for pagination+ after: Cursor for paginationlimit: Maximum number of messages to returnrole: Optional filter for message roleascending: Optional flag to sort in ascending order@@ -143,7 +149,8 @@ class JobManager:# Get messagesmessages = MessageModel.list(db_session=session,- cursor=cursor,+ before=before,+ after=after,ascending=ascending,limit=limit,actor=actor,@@ -215,11 +222,52 @@ class JobManager:)@enforce_types- def get_run_messages_cursor(+ def add_job_usage(+ self,+ job_id: str,+ usage: LettaUsageStatistics,+ step_id: Optional[str] = None,+ actor: PydanticUser = None,+ ) -> None:+ """+ Add usage statistics for a job.++ Args:+ job_id: The ID of the job+ usage: Usage statistics for the job+ step_id: Optional ID of the specific step within the job+ actor: The user making the request++ Raises:+ NoResultFound: If the job does not exist or user does not have access+ """+ with self.session_maker() as session:+ # First verify job exists and user has access+ self._verify_job_access(session, job_id, actor, access=["write"])++ # Manually log step with usage data+ # TODO(@caren): log step under the hood and remove this+ usage_stats = Step(+ job_id=job_id,+ completion_tokens=usage.completion_tokens,+ prompt_tokens=usage.prompt_tokens,+ total_tokens=usage.total_tokens,+ step_count=usage.step_count,+ step_id=step_id,+ )+ if actor:+ usage_stats._set_created_and_updated_by_fields(actor.id)++ session.add(usage_stats)+ session.commit()++ @enforce_types+ def get_run_messages(self,run_id: str,actor: PydanticUser,- cursor: Optional[str] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,limit: Optional[int] = 100,role: Optional[MessageRole] = None,ascending: bool = True,@@ -231,7 +279,8 @@ class JobManager:Args:job_id: The ID of the job to get messages foractor: The user making the request- cursor: Message ID to get messages after or before+ before: Message ID to get messages after+ after: Message ID to get messages beforelimit: Maximum number of messages to returnascending: Whether to return messages in ascending orderrole: Optional role filter@@ -245,7 +294,8 @@ class JobManager:messages = self.get_job_messages(job_id=run_id,actor=actor,- cursor=cursor,+ before=before,+ after=after,limit=limit,role=role,ascending=ascending,diff --git a/letta/services/message_manager.py b/letta/services/message_manager.pyindex 48851f58c..5d813225d 100644--- a/letta/services/message_manager.py+++ b/letta/services/message_manager.py@@ -128,7 +128,8 @@ class MessageManager:self,agent_id: str,actor: Optional[PydanticUser] = None,- cursor: Optional[str] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,start_date: Optional[datetime] = None,end_date: Optional[datetime] = None,limit: Optional[int] = 50,@@ -139,7 +140,8 @@ class MessageManager:"""List user messages with flexible filtering and pagination options.Args:- cursor: Cursor-based pagination - return records after this ID (exclusive)+ before: Cursor-based pagination - return records before this ID (exclusive)+ after: Cursor-based pagination - return records after this ID (exclusive)start_date: Filter records created after this dateend_date: Filter records created before this datelimit: Maximum number of records to return@@ -156,7 +158,8 @@ class MessageManager:return self.list_messages_for_agent(agent_id=agent_id,actor=actor,- cursor=cursor,+ before=before,+ after=after,start_date=start_date,end_date=end_date,limit=limit,@@ -170,7 +173,8 @@ class MessageManager:self,agent_id: str,actor: Optional[PydanticUser] = None,- cursor: Optional[str] = None,+ before: Optional[str] = None,+ after: Optional[str] = None,start_date: Optional[datetime] = None,end_date: Optional[datetime] = None,limit: Optional[int] = 50,@@ -181,7 +185,8 @@ class MessageManager:"""List messages with flexible filtering and pagination options.Args:- cursor: Cursor-based pagination - return records after this ID (exclusive)+ before: Cursor-based pagination - return records before this ID (exclusive)+ after: Cursor-based pagination - return records after this ID (exclusive)start_date: Filter records created after this dateend_date: Filter records created before this datelimit: Maximum number of records to return@@ -201,7 +206,8 @@ class MessageManager:results = MessageModel.list(db_session=session,- cursor=cursor,+ before=before,+ after=after,start_date=start_date,end_date=end_date,limit=limit,diff --git a/letta/services/organization_manager.py b/letta/services/organization_manager.pyindex 4f1b2f9f6..b5b3ffd1a 100644--- a/letta/services/organization_manager.py+++ b/letta/services/organization_manager.py@@ -71,8 +71,12 @@ class OrganizationManager:organization.hard_delete(session)@enforce_types- def list_organizations(self, cursor: Optional[str] = None, limit: Optional[int] = 50) -> List[PydanticOrganization]:- """List organizations with pagination based on cursor (org_id) and limit."""+ def list_organizations(self, after: Optional[str] = None, limit: Optional[int] = 50) -> List[PydanticOrganization]:+ """List all organizations with optional pagination."""with self.session_maker() as session:- results = OrganizationModel.list(db_session=session, cursor=cursor, limit=limit)- return [org.to_pydantic() for org in results]+ organizations = OrganizationModel.list(+ db_session=session,+ after=after,+ limit=limit,+ )+ return [org.to_pydantic() for org in organizations]diff --git a/letta/services/provider_manager.py b/letta/services/provider_manager.pyindex 1e32d5888..01d7c7010 100644--- a/letta/services/provider_manager.py+++ b/letta/services/provider_manager.py@@ -59,11 +59,15 @@ class ProviderManager:session.commit()@enforce_types- def list_providers(self, cursor: Optional[str] = None, limit: Optional[int] = 50) -> List[PydanticProvider]:- """List providers with pagination using cursor (id) and limit."""+ def list_providers(self, after: Optional[str] = None, limit: Optional[int] = 50) -> List[PydanticProvider]:+ """List all providers with optional pagination."""with self.session_maker() as session:- results = ProviderModel.list(db_session=session, cursor=cursor, limit=limit)- return [provider.to_pydantic() for provider in results]+ providers = ProviderModel.list(+ db_session=session,+ after=after,+ limit=limit,+ )+ return [provider.to_pydantic() for provider in providers]@enforce_typesdef get_anthropic_override_provider_id(self) -> Optional[str]:diff --git a/letta/services/sandbox_config_manager.py b/letta/services/sandbox_config_manager.pyindex 8411078c9..6fa103137 100644--- a/letta/services/sandbox_config_manager.py+++ b/letta/services/sandbox_config_manager.py@@ -111,7 +111,11 @@ class SandboxConfigManager:@enforce_typesdef list_sandbox_configs(- self, actor: PydanticUser, cursor: Optional[str] = None, limit: Optional[int] = 50, sandbox_type: Optional[SandboxType] = None+ self,+ actor: PydanticUser,+ after: Optional[str] = None,+ limit: Optional[int] = 50,+ sandbox_type: Optional[SandboxType] = None,) -> List[PydanticSandboxConfig]:"""List all sandbox configurations with optional pagination."""kwargs = {"organization_id": actor.organization_id}@@ -119,7 +123,7 @@ class SandboxConfigManager:kwargs.update({"type": sandbox_type})with self.session_maker() as session:- sandboxes = SandboxConfigModel.list(db_session=session, cursor=cursor, limit=limit, **kwargs)+ sandboxes = SandboxConfigModel.list(db_session=session, after=after, limit=limit, **kwargs)return [sandbox.to_pydantic() for sandbox in sandboxes]@enforce_types@@ -207,13 +211,17 @@ class SandboxConfigManager:@enforce_typesdef list_sandbox_env_vars(- self, sandbox_config_id: str, actor: PydanticUser, cursor: Optional[str] = None, limit: Optional[int] = 50+ self,+ sandbox_config_id: str,+ actor: PydanticUser,+ after: Optional[str] = None,+ limit: Optional[int] = 50,) -> List[PydanticEnvVar]:"""List all sandbox environment variables with optional pagination."""with self.session_maker() as session:env_vars = SandboxEnvVarModel.list(db_session=session,- cursor=cursor,+ after=after,limit=limit,organization_id=actor.organization_id,sandbox_config_id=sandbox_config_id,@@ -222,13 +230,13 @@ class SandboxConfigManager:@enforce_typesdef list_sandbox_env_vars_by_key(- self, key: str, actor: PydanticUser, cursor: Optional[str] = None, limit: Optional[int] = 50+ self, key: str, actor: PydanticUser, after: Optional[str] = None, limit: Optional[int] = 50) -> List[PydanticEnvVar]:"""List all sandbox environment variables with optional pagination."""with self.session_maker() as session:env_vars = SandboxEnvVarModel.list(db_session=session,- cursor=cursor,+ after=after,limit=limit,organization_id=actor.organization_id,key=key,@@ -237,9 +245,9 @@ class SandboxConfigManager:@enforce_typesdef get_sandbox_env_vars_as_dict(- self, sandbox_config_id: str, actor: PydanticUser, cursor: Optional[str] = None, limit: Optional[int] = 50+ self, sandbox_config_id: str, actor: PydanticUser, after: Optional[str] = None, limit: Optional[int] = 50) -> Dict[str, str]:- env_vars = self.list_sandbox_env_vars(sandbox_config_id, actor, cursor, limit)+ env_vars = self.list_sandbox_env_vars(sandbox_config_id, actor, after, limit)result = {}for env_var in env_vars:result[env_var.key] = env_var.valuediff --git a/letta/services/source_manager.py b/letta/services/source_manager.pyindex fd15a0a11..41e1bb8ab 100644--- a/letta/services/source_manager.py+++ b/letta/services/source_manager.py@@ -65,12 +65,12 @@ class SourceManager:return source.to_pydantic()@enforce_types- def list_sources(self, actor: PydanticUser, cursor: Optional[str] = None, limit: Optional[int] = 50, **kwargs) -> List[PydanticSource]:+ def list_sources(self, actor: PydanticUser, after: Optional[str] = None, limit: Optional[int] = 50, **kwargs) -> List[PydanticSource]:"""List all sources with optional pagination."""with self.session_maker() as session:sources = SourceModel.list(db_session=session,- cursor=cursor,+ after=after,limit=limit,organization_id=actor.organization_id,**kwargs,@@ -149,12 +149,12 @@ class SourceManager:@enforce_typesdef list_files(- self, source_id: str, actor: PydanticUser, cursor: Optional[str] = None, limit: Optional[int] = 50+ self, source_id: str, actor: PydanticUser, after: Optional[str] = None, limit: Optional[int] = 50) -> List[PydanticFileMetadata]:"""List all files with optional pagination."""with self.session_maker() as session:files = FileMetadataModel.list(- db_session=session, cursor=cursor, limit=limit, organization_id=actor.organization_id, source_id=source_id+ db_session=session, after=after, limit=limit, organization_id=actor.organization_id, source_id=source_id)return [file.to_pydantic() for file in files]diff --git a/letta/services/tool_manager.py b/letta/services/tool_manager.pyindex 9facb1537..5ea0b6b44 100644--- a/letta/services/tool_manager.py+++ b/letta/services/tool_manager.py@@ -93,12 +93,12 @@ class ToolManager:return None@enforce_types- def list_tools(self, actor: PydanticUser, cursor: Optional[str] = None, limit: Optional[int] = 50) -> List[PydanticTool]:- """List all tools with optional pagination using cursor and limit."""+ def list_tools(self, actor: PydanticUser, after: Optional[str] = None, limit: Optional[int] = 50) -> List[PydanticTool]:+ """List all tools with optional pagination."""with self.session_maker() as session:tools = ToolModel.list(db_session=session,- cursor=cursor,+ after=after,limit=limit,organization_id=actor.organization_id,)diff --git a/letta/services/user_manager.py b/letta/services/user_manager.pyindex 061f443ee..939adcfe4 100644--- a/letta/services/user_manager.py+++ b/letta/services/user_manager.py@@ -1,4 +1,4 @@-from typing import List, Optional, Tuple+from typing import List, Optionalfrom letta.orm.errors import NoResultFoundfrom letta.orm.organization import Organization as OrganizationModel@@ -99,8 +99,12 @@ class UserManager:return self.get_default_user()@enforce_types- def list_users(self, cursor: Optional[str] = None, limit: Optional[int] = 50) -> Tuple[Optional[str], List[PydanticUser]]:- """List users with pagination using cursor (id) and limit."""+ def list_users(self, after: Optional[str] = None, limit: Optional[int] = 50) -> List[PydanticUser]:+ """List all users with optional pagination."""with self.session_maker() as session:- results = UserModel.list(db_session=session, cursor=cursor, limit=limit)- return [user.to_pydantic() for user in results]+ users = UserModel.list(+ db_session=session,+ after=after,+ limit=limit,+ )+ return [user.to_pydantic() for user in users]diff --git a/tests/test_client.py b/tests/test_client.pyindex 9dbc14684..2294c62fd 100644--- a/tests/test_client.py+++ b/tests/test_client.py@@ -249,7 +249,7 @@ def test_agent_tags(client: Union[LocalClient, RESTClient]):assert paginated_tags[1] == "agent2"# Test pagination with cursor- next_page_tags = client.get_tags(cursor="agent2", limit=2)+ next_page_tags = client.get_tags(after="agent2", limit=2)assert len(next_page_tags) == 2assert next_page_tags[0] == "agent3"assert next_page_tags[1] == "development"@@ -654,7 +654,7 @@ def test_agent_listing(client: Union[LocalClient, RESTClient], agent, search_ageassert len(first_page) == 1first_agent = first_page[0]- second_page = client.list_agents(query_text="search agent", cursor=first_agent.id, limit=1) # Use agent ID as cursor+ second_page = client.list_agents(query_text="search agent", after=first_agent.id, limit=1) # Use agent ID as cursorassert len(second_page) == 1assert second_page[0].id != first_agent.iddiff --git a/tests/test_client_legacy.py b/tests/test_client_legacy.pyindex e62b1833e..a9bfa70a9 100644--- a/tests/test_client_legacy.py+++ b/tests/test_client_legacy.py@@ -369,7 +369,7 @@ def test_list_files_pagination(client: Union[LocalClient, RESTClient], agent: Agassert files_a[0].source_id == source.id# Use the cursor from response_a to get the remaining file- files_b = client.list_files_from_source(source.id, limit=1, cursor=files_a[-1].id)+ files_b = client.list_files_from_source(source.id, limit=1, after=files_a[-1].id)assert len(files_b) == 1assert files_b[0].source_id == source.id@@ -377,7 +377,7 @@ def test_list_files_pagination(client: Union[LocalClient, RESTClient], agent: Agassert files_a[0].file_name != files_b[0].file_name# Use the cursor from response_b to list files, should be empty- files = client.list_files_from_source(source.id, limit=1, cursor=files_b[-1].id)+ files = client.list_files_from_source(source.id, limit=1, after=files_b[-1].id)assert len(files) == 0 # Should be emptydiff --git a/tests/test_managers.py b/tests/test_managers.pyindex f4ee13068..28ad057a1 100644--- a/tests/test_managers.py+++ b/tests/test_managers.py@@ -913,11 +913,18 @@ def test_list_agents_by_tags_pagination(server: SyncServer, default_user, defaul# Get second page using cursorsecond_page = server.agent_manager.list_agents(- tags=["pagination_test"], match_all_tags=True, actor=default_user, cursor=first_agent_id, limit=1+ tags=["pagination_test"], match_all_tags=True, actor=default_user, after=first_agent_id, limit=1)assert len(second_page) == 1assert second_page[0].id != first_agent_id+ # Get previous page using before+ prev_page = server.agent_manager.list_agents(+ tags=["pagination_test"], match_all_tags=True, actor=default_user, before=second_page[0].id, limit=1+ )+ assert len(prev_page) == 1+ assert prev_page[0].id == first_agent_id+# Verify we got both agents with no duplicatesall_ids = {first_page[0].id, second_page[0].id}assert len(all_ids) == 2@@ -979,10 +986,20 @@ def test_list_agents_query_text_pagination(server: SyncServer, default_user, deffirst_agent_id = first_page[0].id# Get second page using cursor- second_page = server.agent_manager.list_agents(actor=default_user, query_text="search agent", cursor=first_agent_id, limit=1)+ second_page = server.agent_manager.list_agents(actor=default_user, query_text="search agent", after=first_agent_id, limit=1)assert len(second_page) == 1assert second_page[0].id != first_agent_id+ # Test before and after+ all_agents = server.agent_manager.list_agents(actor=default_user, query_text="agent")+ assert len(all_agents) == 3+ first_agent, second_agent, third_agent = all_agents+ middle_agent = server.agent_manager.list_agents(+ actor=default_user, query_text="search agent", before=third_agent.id, after=first_agent.id+ )+ assert len(middle_agent) == 1+ assert middle_agent[0].id == second_agent.id+# Verify we got both search agents with no duplicatesall_ids = {first_page[0].id, second_page[0].id}assert len(all_ids) == 2@@ -1231,12 +1248,33 @@ def test_agent_list_passages_pagination(server, default_user, sarah_agent, agentassert len(first_page) == 2second_page = server.agent_manager.list_passages(- actor=default_user, agent_id=sarah_agent.id, cursor=first_page[-1].id, limit=2, ascending=True+ actor=default_user, agent_id=sarah_agent.id, after=first_page[-1].id, limit=2, ascending=True)assert len(second_page) == 2assert first_page[-1].id != second_page[0].idassert first_page[-1].created_at <= second_page[0].created_at+ """+ [1] [2]+ * * | * *++ [mid]+ * | * * | *+ """+ middle_page = server.agent_manager.list_passages(+ actor=default_user, agent_id=sarah_agent.id, before=second_page[-1].id, after=first_page[0].id, ascending=True+ )+ assert len(middle_page) == 2+ assert middle_page[0].id == first_page[-1].id+ assert middle_page[1].id == second_page[0].id++ middle_page_desc = server.agent_manager.list_passages(+ actor=default_user, agent_id=sarah_agent.id, before=second_page[-1].id, after=first_page[0].id, ascending=False+ )+ assert len(middle_page_desc) == 2+ assert middle_page_desc[0].id == second_page[0].id+ assert middle_page_desc[1].id == first_page[-1].id+def test_agent_list_passages_text_search(server, default_user, sarah_agent, agent_passages_setup):"""Test text search functionality of agent passages"""@@ -1401,11 +1439,11 @@ def test_list_organizations_pagination(server: SyncServer):orgs_x = server.organization_manager.list_organizations(limit=1)assert len(orgs_x) == 1- orgs_y = server.organization_manager.list_organizations(cursor=orgs_x[0].id, limit=1)+ orgs_y = server.organization_manager.list_organizations(after=orgs_x[0].id, limit=1)assert len(orgs_y) == 1assert orgs_y[0].name != orgs_x[0].name- orgs = server.organization_manager.list_organizations(cursor=orgs_y[0].id, limit=1)+ orgs = server.organization_manager.list_organizations(after=orgs_y[0].id, limit=1)assert len(orgs) == 0@@ -1870,7 +1908,7 @@ def test_message_listing_cursor(server: SyncServer, hello_world_message_fixture,"""Test cursor-based pagination functionality"""create_test_messages(server, hello_world_message_fixture, default_user)- # Make sure there are 5 messages+ # Make sure there are 6 messagesassert server.message_manager.size(actor=default_user, role=MessageRole.user) == 6# Get first page@@ -1881,11 +1919,28 @@ def test_message_listing_cursor(server: SyncServer, hello_world_message_fixture,# Get second pagesecond_page = server.message_manager.list_user_messages_for_agent(- agent_id=sarah_agent.id, actor=default_user, cursor=last_id_on_first_page, limit=3+ agent_id=sarah_agent.id, actor=default_user, after=last_id_on_first_page, limit=3)- assert len(second_page) == 3 # Should have 2 remaining messages+ assert len(second_page) == 3 # Should have 3 remaining messagesassert all(r1.id != r2.id for r1 in first_page for r2 in second_page)+ # Get the middle+ middle_page = server.message_manager.list_user_messages_for_agent(+ agent_id=sarah_agent.id, actor=default_user, before=second_page[1].id, after=first_page[0].id+ )+ assert len(middle_page) == 3+ assert middle_page[0].id == first_page[1].id+ assert middle_page[1].id == first_page[-1].id+ assert middle_page[-1].id == second_page[0].id++ middle_page_desc = server.message_manager.list_user_messages_for_agent(+ agent_id=sarah_agent.id, actor=default_user, before=second_page[1].id, after=first_page[0].id, ascending=False+ )+ assert len(middle_page_desc) == 3+ assert middle_page_desc[0].id == second_page[0].id+ assert middle_page_desc[1].id == first_page[-1].id+ assert middle_page_desc[-1].id == first_page[1].id+def test_message_listing_filtering(server: SyncServer, hello_world_message_fixture, default_user, sarah_agent):"""Test filtering messages by agent ID"""@@ -2117,7 +2172,7 @@ def test_list_sources(server: SyncServer, default_user):assert len(paginated_sources) == 1# Ensure cursor-based pagination works- next_page = server.source_manager.list_sources(actor=default_user, cursor=paginated_sources[-1].id, limit=1)+ next_page = server.source_manager.list_sources(actor=default_user, after=paginated_sources[-1].id, limit=1)assert len(next_page) == 1assert next_page[0].name != paginated_sources[0].name@@ -2217,7 +2272,7 @@ def test_list_files(server: SyncServer, default_user, default_source):assert len(paginated_files) == 1# Ensure cursor-based pagination works- next_page = server.source_manager.list_files(source_id=default_source.id, actor=default_user, cursor=paginated_files[-1].id, limit=1)+ next_page = server.source_manager.list_files(source_id=default_source.id, actor=default_user, after=paginated_files[-1].id, limit=1)assert len(next_page) == 1assert next_page[0].file_name != paginated_files[0].file_name@@ -2315,7 +2370,7 @@ def test_list_sandbox_configs(server: SyncServer, default_user):paginated_configs = server.sandbox_config_manager.list_sandbox_configs(actor=default_user, limit=1)assert len(paginated_configs) == 1- next_page = server.sandbox_config_manager.list_sandbox_configs(actor=default_user, cursor=paginated_configs[-1].id, limit=1)+ next_page = server.sandbox_config_manager.list_sandbox_configs(actor=default_user, after=paginated_configs[-1].id, limit=1)assert len(next_page) == 1assert next_page[0].id != paginated_configs[0].id@@ -2386,7 +2441,7 @@ def test_list_sandbox_env_vars(server: SyncServer, sandbox_config_fixture, defauassert len(paginated_env_vars) == 1next_page = server.sandbox_config_manager.list_sandbox_env_vars(- sandbox_config_id=sandbox_config_fixture.id, actor=default_user, cursor=paginated_env_vars[-1].id, limit=1+ sandbox_config_id=sandbox_config_fixture.id, actor=default_user, after=paginated_env_vars[-1].id, limit=1)assert len(next_page) == 1assert next_page[0].id != paginated_env_vars[0].id@@ -2540,11 +2595,46 @@ def test_list_jobs_pagination(server: SyncServer, default_user):# List jobs with a limitjobs = server.job_manager.list_jobs(actor=default_user, limit=5)-- # Assertions to check paginationassert len(jobs) == 5assert all(job.user_id == default_user.id for job in jobs)+ # Test cursor-based pagination+ first_page = server.job_manager.list_jobs(actor=default_user, limit=3, ascending=True) # [J0, J1, J2]+ assert len(first_page) == 3+ assert first_page[0].created_at <= first_page[1].created_at <= first_page[2].created_at++ last_page = server.job_manager.list_jobs(actor=default_user, limit=3, ascending=False) # [J9, J8, J7]+ assert len(last_page) == 3+ assert last_page[0].created_at >= last_page[1].created_at >= last_page[2].created_at+ first_page_ids = set(job.id for job in first_page)+ last_page_ids = set(job.id for job in last_page)+ assert first_page_ids.isdisjoint(last_page_ids)++ # Test middle page using both before and after+ middle_page = server.job_manager.list_jobs(+ actor=default_user, before=last_page[-1].id, after=first_page[-1].id, ascending=True+ ) # [J3, J4, J5, J6]+ assert len(middle_page) == 4 # Should include jobs between first and second page+ head_tail_jobs = first_page_ids.union(last_page_ids)+ assert all(job.id not in head_tail_jobs for job in middle_page)++ # Test descending order+ middle_page_desc = server.job_manager.list_jobs(+ actor=default_user, before=last_page[-1].id, after=first_page[-1].id, ascending=False+ ) # [J6, J5, J4, J3]+ assert len(middle_page_desc) == 4+ assert middle_page_desc[0].id == middle_page[-1].id+ assert middle_page_desc[1].id == middle_page[-2].id+ assert middle_page_desc[2].id == middle_page[-3].id+ assert middle_page_desc[3].id == middle_page[-4].id++ # BONUS+ job_7 = last_page[-1].id+ earliest_jobs = server.job_manager.list_jobs(actor=default_user, ascending=False, before=job_7)+ assert len(earliest_jobs) == 7+ assert all(j.id not in last_page_ids for j in earliest_jobs)+ assert all(earliest_jobs[i].created_at >= earliest_jobs[i + 1].created_at for i in range(len(earliest_jobs) - 1))+def test_list_jobs_by_status(server: SyncServer, default_user):"""Test listing jobs filtered by status."""@@ -2659,15 +2749,81 @@ def test_job_messages_pagination(server: SyncServer, default_run, default_user,assert messages[1].id == message_ids[1]# Test pagination with cursor- messages = server.job_manager.get_job_messages(+ first_page = server.job_manager.get_job_messages(job_id=default_run.id,actor=default_user,- cursor=message_ids[1],limit=2,+ ascending=True, # [M0, M1])- assert len(messages) == 2- assert messages[0].id == message_ids[2]- assert messages[1].id == message_ids[3]+ assert len(first_page) == 2+ assert first_page[0].id == message_ids[0]+ assert first_page[1].id == message_ids[1]+ assert first_page[0].created_at <= first_page[1].created_at++ last_page = server.job_manager.get_job_messages(+ job_id=default_run.id,+ actor=default_user,+ limit=2,+ ascending=False, # [M4, M3]+ )+ assert len(last_page) == 2+ assert last_page[0].id == message_ids[4]+ assert last_page[1].id == message_ids[3]+ assert last_page[0].created_at >= last_page[1].created_at++ first_page_ids = set(msg.id for msg in first_page)+ last_page_ids = set(msg.id for msg in last_page)+ assert first_page_ids.isdisjoint(last_page_ids)++ # Test middle page using both before and after+ middle_page = server.job_manager.get_job_messages(+ job_id=default_run.id,+ actor=default_user,+ before=last_page[-1].id, # M3+ after=first_page[0].id, # M0+ ascending=True, # [M1, M2]+ )+ assert len(middle_page) == 2 # Should include message between first and last pages+ assert middle_page[0].id == message_ids[1]+ assert middle_page[1].id == message_ids[2]+ head_tail_msgs = first_page_ids.union(last_page_ids)+ assert middle_page[1].id not in head_tail_msgs+ assert middle_page[0].id in first_page_ids++ # Test descending order for middle page+ middle_page = server.job_manager.get_job_messages(+ job_id=default_run.id,+ actor=default_user,+ before=last_page[-1].id, # M3+ after=first_page[0].id, # M0+ ascending=False, # [M2, M1]+ )+ assert len(middle_page) == 2 # Should include message between first and last pages+ assert middle_page[0].id == message_ids[2]+ assert middle_page[1].id == message_ids[1]++ # Test getting earliest messages+ msg_3 = last_page[-1].id+ earliest_msgs = server.job_manager.get_job_messages(+ job_id=default_run.id,+ actor=default_user,+ ascending=False,+ before=msg_3, # Get messages after M3 in descending order+ )+ assert len(earliest_msgs) == 3 # Should get M2, M1, M0+ assert all(m.id not in last_page_ids for m in earliest_msgs)+ assert earliest_msgs[0].created_at > earliest_msgs[1].created_at > earliest_msgs[2].created_at++ # Test getting earliest messages with ascending order+ earliest_msgs_ascending = server.job_manager.get_job_messages(+ job_id=default_run.id,+ actor=default_user,+ ascending=True,+ before=msg_3, # Get messages before M3 in ascending order+ )+ assert len(earliest_msgs_ascending) == 3 # Should get M0, M1, M2+ assert all(m.id not in last_page_ids for m in earliest_msgs_ascending)+ assert earliest_msgs_ascending[0].created_at < earliest_msgs_ascending[1].created_at < earliest_msgs_ascending[2].created_atdef test_job_messages_ordering(server: SyncServer, default_run, default_user, sarah_agent):@@ -2799,7 +2955,7 @@ def test_job_messages_filter(server: SyncServer, default_run, default_user, saraassert len(limited_messages) == 2-def test_get_run_messages_cursor(server: SyncServer, default_user: PydanticUser, sarah_agent):+def test_get_run_messages(server: SyncServer, default_user: PydanticUser, sarah_agent):"""Test getting messages for a run with request config."""# Create a run with custom request configrun = server.job_manager.create_job(@@ -2834,7 +2990,7 @@ def test_get_run_messages_cursor(server: SyncServer, default_user: PydanticUser,server.job_manager.add_message_to_job(job_id=run.id, message_id=created_msg.id, actor=default_user)# Get messages and verify they're converted correctly- result = server.job_manager.get_run_messages_cursor(run_id=run.id, actor=default_user)+ result = server.job_manager.get_run_messages(run_id=run.id, actor=default_user)# Verify correct number of messages. Assistant messages should be parsedassert len(result) == 6@@ -2994,7 +3150,7 @@ def test_list_tags(server: SyncServer, default_user, default_organization):assert limited_tags == tags[:2] # Should return first 2 tags# Test pagination with cursor- cursor_tags = server.agent_manager.list_tags(actor=default_user, cursor="beta")+ cursor_tags = server.agent_manager.list_tags(actor=default_user, after="beta")assert cursor_tags == ["delta", "epsilon", "gamma"] # Tags after "beta"# Test text searchdiff --git a/tests/test_server.py b/tests/test_server.pyindex 762285b73..8bbe449be 100644--- a/tests/test_server.py+++ b/tests/test_server.py@@ -394,7 +394,7 @@ def test_user_message_memory(server, user, agent_id):@pytest.mark.order(3)def test_load_data(server, user, agent_id):# create source- passages_before = server.agent_manager.list_passages(actor=user, agent_id=agent_id, cursor=None, limit=10000)+ passages_before = server.agent_manager.list_passages(actor=user, agent_id=agent_id, after=None, limit=10000)assert len(passages_before) == 0source = server.source_manager.create_source(@@ -416,7 +416,7 @@ def test_load_data(server, user, agent_id):server.agent_manager.attach_source(agent_id=agent_id, source_id=source.id, actor=user)# check archival memory size- passages_after = server.agent_manager.list_passages(actor=user, agent_id=agent_id, cursor=None, limit=10000)+ passages_after = server.agent_manager.list_passages(actor=user, agent_id=agent_id, after=None, limit=10000)assert len(passages_after) == 5@@ -439,14 +439,14 @@ def test_user_message(server, user, agent_id):def test_get_recall_memory(server, org_id, user, agent_id):# test recall memory cursor paginationactor = user- messages_1 = server.get_agent_recall_cursor(user_id=user.id, agent_id=agent_id, limit=2)+ messages_1 = server.get_agent_recall(user_id=user.id, agent_id=agent_id, limit=2)cursor1 = messages_1[-1].id- messages_2 = server.get_agent_recall_cursor(user_id=user.id, agent_id=agent_id, after=cursor1, limit=1000)- messages_3 = server.get_agent_recall_cursor(user_id=user.id, agent_id=agent_id, limit=1000)+ messages_2 = server.get_agent_recall(user_id=user.id, agent_id=agent_id, after=cursor1, limit=1000)+ messages_3 = server.get_agent_recall(user_id=user.id, agent_id=agent_id, limit=1000)messages_3[-1].idassert messages_3[-1].created_at >= messages_3[0].created_atassert len(messages_3) == len(messages_1) + len(messages_2)- messages_4 = server.get_agent_recall_cursor(user_id=user.id, agent_id=agent_id, reverse=True, before=cursor1)+ messages_4 = server.get_agent_recall(user_id=user.id, agent_id=agent_id, reverse=True, before=cursor1)assert len(messages_4) == 1# test in-context message ids@@ -477,7 +477,7 @@ def test_get_archival_memory(server, user, agent_id):actor=actor,agent_id=agent_id,ascending=False,- cursor=cursor1,+ before=cursor1,)# List all 5@@ -499,11 +499,11 @@ def test_get_archival_memory(server, user, agent_id):passage_1 = server.agent_manager.list_passages(actor=actor, agent_id=agent_id, limit=1, ascending=True)assert len(passage_1) == 1assert passage_1[0].text == "alpha"- passage_2 = server.agent_manager.list_passages(actor=actor, agent_id=agent_id, cursor=earliest.id, limit=1000, ascending=True)+ passage_2 = server.agent_manager.list_passages(actor=actor, agent_id=agent_id, after=earliest.id, limit=1000, ascending=True)assert len(passage_2) in [4, 5] # NOTE: exact size seems non-deterministic, so loosen testassert all("alpha" not in passage.text for passage in passage_2)# test safe empty return- passage_none = server.agent_manager.list_passages(actor=actor, agent_id=agent_id, cursor=latest.id, limit=1000, ascending=True)+ passage_none = server.agent_manager.list_passages(actor=actor, agent_id=agent_id, after=latest.id, limit=1000, ascending=True)assert len(passage_none) == 0@@ -630,7 +630,7 @@ def _test_get_messages_letta_format():"""Test mapping between messages and letta_messages with reverse=False."""- messages = server.get_agent_recall_cursor(+ messages = server.get_agent_recall(user_id=user.id,agent_id=agent_id,limit=1000,@@ -639,7 +639,7 @@ def _test_get_messages_letta_format()assert all(isinstance(m, Message) for m in messages)- letta_messages = server.get_agent_recall_cursor(+ letta_messages = server.get_agent_recall(user_id=user.id,agent_id=agent_id,limit=1000,@@ -930,7 +930,7 @@ def test_memory_rebuild_count(server, user, mock_e2b_api_key_none, base_tools, bdef count_system_messages_in_recall() -> Tuple[int, List[LettaMessage]]:# At this stage, there should only be 1 system message inside of recall storage- letta_messages = server.get_agent_recall_cursor(+ letta_messages = server.get_agent_recall(user_id=user.id,agent_id=agent_state.id,limit=1000,@@ -1192,7 +1192,7 @@ def test_messages_with_provider_override(server: SyncServer, user_id: str):usage = server.user_message(user_id=actor.id, agent_id=agent.id, message="Test message")assert usage, "Sending message failed"- get_messages_response = server.message_manager.list_messages_for_agent(agent_id=agent.id, actor=actor, cursor=existing_messages[-1].id)+ get_messages_response = server.message_manager.list_messages_for_agent(agent_id=agent.id, actor=actor, after=existing_messages[-1].id)assert len(get_messages_response) > 0, "Retrieving messages failed"step_ids = set([msg.step_id for msg in get_messages_response])@@ -1219,7 +1219,7 @@ def test_messages_with_provider_override(server: SyncServer, user_id: str):usage = server.user_message(user_id=actor.id, agent_id=agent.id, message="Test message")assert usage, "Sending message failed"- get_messages_response = server.message_manager.list_messages_for_agent(agent_id=agent.id, actor=actor, cursor=existing_messages[-1].id)+ get_messages_response = server.message_manager.list_messages_for_agent(agent_id=agent.id, actor=actor, after=existing_messages[-1].id)assert len(get_messages_response) > 0, "Retrieving messages failed"step_ids = set([msg.step_id for msg in get_messages_response])diff --git a/tests/test_v1_routes.py b/tests/test_v1_routes.pyindex 6bea63967..f8ddde714 100644--- a/tests/test_v1_routes.py+++ b/tests/test_v1_routes.py@@ -330,7 +330,7 @@ def test_get_run_messages(client, mock_sync_server):# Configure mock server responsesmock_sync_server.user_manager.get_user_or_default.return_value = Mock(id="user-123")- mock_sync_server.job_manager.get_run_messages_cursor.return_value = mock_messages+ mock_sync_server.job_manager.get_run_messages.return_value = mock_messages# Test successful retrievalresponse = client.get(@@ -338,9 +338,10 @@ def test_get_run_messages(client, mock_sync_server):headers={"user_id": "user-123"},params={"limit": 10,- "cursor": mock_messages[0].id,+ "before": "message-1234",+ "after": "message-6789","role": "user",- "ascending": True,+ "order": "desc",},)assert response.status_code == 200@@ -350,12 +351,13 @@ def test_get_run_messages(client, mock_sync_server):# Verify mock callsmock_sync_server.user_manager.get_user_or_default.assert_called_once_with(user_id="user-123")- mock_sync_server.job_manager.get_run_messages_cursor.assert_called_once_with(+ mock_sync_server.job_manager.get_run_messages.assert_called_once_with(run_id="run-12345678",actor=mock_sync_server.user_manager.get_user_or_default.return_value,limit=10,- cursor=mock_messages[0].id,- ascending=True,+ before="message-1234",+ after="message-6789",+ ascending=False,role="user",)@@ -365,7 +367,7 @@ def test_get_run_messages_not_found(client, mock_sync_server):# Configure mock responseserror_message = "Run 'run-nonexistent' not found"mock_sync_server.user_manager.get_user_or_default.return_value = Mock(id="user-123")- mock_sync_server.job_manager.get_run_messages_cursor.side_effect = NoResultFound(error_message)+ mock_sync_server.job_manager.get_run_messages.side_effect = NoResultFound(error_message)response = client.get("/v1/runs/run-nonexistent/messages", headers={"user_id": "user-123"})@@ -431,7 +433,7 @@ def test_get_tags(client, mock_sync_server):assert response.status_code == 200assert response.json() == ["tag1", "tag2"]mock_sync_server.agent_manager.list_tags.assert_called_once_with(- actor=mock_sync_server.user_manager.get_user_or_default.return_value, cursor=None, limit=50, query_text=None+ actor=mock_sync_server.user_manager.get_user_or_default.return_value, after=None, limit=50, query_text=None)@@ -439,12 +441,12 @@ def test_get_tags_with_pagination(client, mock_sync_server):"""Test tag listing with pagination parameters"""mock_sync_server.agent_manager.list_tags.return_value = ["tag3", "tag4"]- response = client.get("/v1/tags", params={"cursor": "tag2", "limit": 2}, headers={"user_id": "test_user"})+ response = client.get("/v1/tags", params={"after": "tag2", "limit": 2}, headers={"user_id": "test_user"})assert response.status_code == 200assert response.json() == ["tag3", "tag4"]mock_sync_server.agent_manager.list_tags.assert_called_once_with(- actor=mock_sync_server.user_manager.get_user_or_default.return_value, cursor="tag2", limit=2, query_text=None+ actor=mock_sync_server.user_manager.get_user_or_default.return_value, after="tag2", limit=2, query_text=None)@@ -457,5 +459,5 @@ def test_get_tags_with_search(client, mock_sync_server):assert response.status_code == 200assert response.json() == ["user_tag1", "user_tag2"]mock_sync_server.agent_manager.list_tags.assert_called_once_with(- actor=mock_sync_server.user_manager.get_user_or_default.return_value, cursor=None, limit=50, query_text="user"+ actor=mock_sync_server.user_manager.get_user_or_default.return_value, after=None, limit=50, query_text="user")