Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat(core): restructure memFS system prompt rendering + add client_skills [LET-7760] (#9761)
Sarah Wooders0dfea991e178
diff --git a/.skills/viewing-agent-context/scripts/viewing_agent_context.py b/.skills/viewing-agent-context/scripts/viewing_agent_context.pyindex 2b4c44a08..dbf36e956 100755--- a/.skills/viewing-agent-context/scripts/viewing_agent_context.py+++ b/.skills/viewing-agent-context/scripts/viewing_agent_context.py@@ -98,19 +98,52 @@ def has_system_reminder_in_content(message: Dict[str, Any]) -> bool:return any(needle in s.lower() for s in _iter_strings(content))+def _extract_text_blocks(content: Any) -> List[str]:+ """Extract ordered human-readable text blocks from structured content arrays.++ Preview payloads often encode message content as a list of typed blocks, e.g.:+ [{"type": "text", "text": "..."}, ...]+ [{"type": "input_text", "text": "..."}, ...]++ This helper preserves that order and returns plain text blocks so we can render+ them cleanly instead of dumping JSON.+ """+ blocks: List[str] = []+ if not isinstance(content, list):+ return blocks++ for item in content:+ if isinstance(item, str):+ blocks.append(item)+ continue++ if not isinstance(item, dict):+ continue++ # Primary shape: {"type": "text"|"input_text"|..., "text": "..."}+ text_value = item.get("text")+ if isinstance(text_value, str):+ blocks.append(text_value)+ continue++ # Secondary shape: nested content arrays/strings under "content"+ nested = item.get("content")+ if isinstance(nested, str):+ blocks.append(nested)+ elif isinstance(nested, list):+ blocks.extend(_extract_text_blocks(nested))++ return blocks++def render_content_for_display(message: Dict[str, Any], msg_type: Optional[str]) -> str:content = message.get("content")- # For user messages in OpenAI-style payloads, content is often a list of blocks:- # [{"type": "input_text", "text": "..."}, ...].- # Render all input_text blocks in order with blank lines between blocks.- if message.get("role") == "user" and isinstance(content, list):- text_blocks: List[str] = []- for item in content:- if isinstance(item, dict) and item.get("type") == "input_text" and isinstance(item.get("text"), str):- text_blocks.append(item["text"])- if text_blocks:- return "\n\n".join(text_blocks)[:8000]+ # Structured multi-part content (e.g. [{"type":"text","text":"..."}])+ # should render as readable text blocks instead of JSON.+ text_blocks = _extract_text_blocks(content)+ if text_blocks:+ return "\n\n".join(text_blocks)[:8000]if isinstance(content, str):return content[:8000]@@ -236,9 +269,7 @@ def build_html(}warn_html = (- "<div class='panel warn'><strong>Warnings</strong><ul>"- + "".join(f"<li>{html.escape(e)}</li>" for e in errors)- + "</ul></div>"+ "<div class='panel warn'><strong>Warnings</strong><ul>" + "".join(f"<li>{html.escape(e)}</li>" for e in errors) + "</ul></div>"if errorselse "")@@ -370,7 +401,9 @@ def main() -> int:errors.append(f"agent: {agent_err}")payload_dict = payload if isinstance(payload, dict) else ({"raw": payload} if payload is not None else {})- agent_payload = agent_payload_raw if isinstance(agent_payload_raw, dict) else ({"raw": agent_payload_raw} if agent_payload_raw is not None else {})+ agent_payload = (+ agent_payload_raw if isinstance(agent_payload_raw, dict) else ({"raw": agent_payload_raw} if agent_payload_raw is not None else {})+ )out = Path(args.out).expanduser() if args.out else Path.home() / ".letta" / "viewers" / f"viewing-agent-context-{args.agent_id}.html"out.parent.mkdir(parents=True, exist_ok=True)diff --git a/fern/openapi.json b/fern/openapi.jsonindex 4f3f0d786..d37673374 100644--- a/fern/openapi.json+++ b/fern/openapi.json@@ -31534,6 +31534,29 @@"required": ["finish_reason", "index", "message"],"title": "Choice"},+ "ClientSkillSchema": {+ "properties": {+ "name": {+ "type": "string",+ "title": "Name",+ "description": "The name of the skill"+ },+ "description": {+ "type": "string",+ "title": "Description",+ "description": "Description of what the skill does"+ },+ "location": {+ "type": "string",+ "title": "Location",+ "description": "Path or location hint for the skill (e.g. skills/my-skill/SKILL.md)"+ }+ },+ "type": "object",+ "required": ["name", "description", "location"],+ "title": "ClientSkillSchema",+ "description": "Schema for a client-side skill passed in the request.\n\nClient-side skills represent environment-provided capabilities (e.g. project-scoped\nskills) that are not stored in the agent's MemFS but should appear in the system\nprompt's available skills section."+ },"ClientToolSchema": {"properties": {"name": {@@ -32689,6 +32712,21 @@"title": "Client Tools","description": "Client-side tools that the agent can call. When the agent calls a client-side tool, execution pauses and returns control to the client to execute the tool and provide the result via a ToolReturn."},+ "client_skills": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/ClientSkillSchema"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "title": "Client Skills",+ "description": "Client-side skills available in the environment. These are rendered in the system prompt's available skills section alongside agent-scoped skills from MemFS."+ },"override_model": {"anyOf": [{@@ -39202,6 +39240,21 @@"title": "Client Tools","description": "Client-side tools that the agent can call. When the agent calls a client-side tool, execution pauses and returns control to the client to execute the tool and provide the result via a ToolReturn."},+ "client_skills": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/ClientSkillSchema"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "title": "Client Skills",+ "description": "Client-side skills available in the environment. These are rendered in the system prompt's available skills section alongside agent-scoped skills from MemFS."+ },"override_model": {"anyOf": [{@@ -39421,6 +39474,21 @@"title": "Client Tools","description": "Client-side tools that the agent can call. When the agent calls a client-side tool, execution pauses and returns control to the client to execute the tool and provide the result via a ToolReturn."},+ "client_skills": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/ClientSkillSchema"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "title": "Client Skills",+ "description": "Client-side skills available in the environment. These are rendered in the system prompt's available skills section alongside agent-scoped skills from MemFS."+ },"override_model": {"anyOf": [{@@ -39820,6 +39888,21 @@"title": "Client Tools","description": "Client-side tools that the agent can call. When the agent calls a client-side tool, execution pauses and returns control to the client to execute the tool and provide the result via a ToolReturn."},+ "client_skills": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/ClientSkillSchema"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "title": "Client Skills",+ "description": "Client-side skills available in the environment. These are rendered in the system prompt's available skills section alongside agent-scoped skills from MemFS."+ },"override_model": {"anyOf": [{@@ -40120,6 +40203,21 @@"title": "Client Tools","description": "Client-side tools that the agent can call. When the agent calls a client-side tool, execution pauses and returns control to the client to execute the tool and provide the result via a ToolReturn."},+ "client_skills": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/ClientSkillSchema"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "title": "Client Skills",+ "description": "Client-side skills available in the environment. These are rendered in the system prompt's available skills section alongside agent-scoped skills from MemFS."+ },"override_model": {"anyOf": [{diff --git a/letta/agents/base_agent.py b/letta/agents/base_agent.pyindex 3e6019a4b..20e8dedff 100644--- a/letta/agents/base_agent.py+++ b/letta/agents/base_agent.py@@ -49,6 +49,8 @@ class BaseAgent(ABC):self.passage_manager = PassageManager()self.actor = actorself.logger = get_logger(agent_id)+ self.client_skills: list = []+ self.conversation_id: str | None = None@abstractmethodasync def step(@@ -134,6 +136,7 @@ class BaseAgent(ABC):sources=agent_state.sources,max_files_open=agent_state.max_files_open,llm_config=agent_state.llm_config,+ client_skills=self.client_skills,)system_prompt_changed = agent_state.system not in curr_system_message_text@@ -155,6 +158,8 @@ class BaseAgent(ABC):new_system_message_str = PromptGenerator.get_system_message_from_compiled_memory(system_prompt=agent_state.system,memory_with_sources=curr_memory_str,+ agent_id=agent_state.id,+ conversation_id=self.conversation_id or "default",in_context_memory_last_edit=memory_edit_timestamp,timezone=agent_state.timezone,previous_message_count=num_messages - len(in_context_messages),diff --git a/letta/agents/base_agent_v2.py b/letta/agents/base_agent_v2.pyindex 7f55343b7..2c89a3373 100644--- a/letta/agents/base_agent_v2.py+++ b/letta/agents/base_agent_v2.py@@ -11,7 +11,7 @@ from letta.schemas.message import MessageCreatefrom letta.schemas.user import Userif TYPE_CHECKING:- from letta.schemas.letta_request import ClientToolSchema+ from letta.schemas.letta_request import ClientSkillSchema, ClientToolSchemafrom letta.schemas.provider_trace import BillingContext@@ -25,6 +25,7 @@ class BaseAgentV2(ABC):self.agent_state = agent_stateself.actor = actorself.logger = get_logger(agent_state.id)+ self.conversation_id: str | None = None@propertydef agent_id(self) -> str:@@ -35,6 +36,7 @@ class BaseAgentV2(ABC):async def build_request(self,input_messages: list[MessageCreate],+ client_skills: list["ClientSkillSchema"] | None = None,) -> dict:"""Execute the agent loop in dry_run mode, returning just the generated request@@ -52,6 +54,7 @@ class BaseAgentV2(ABC):include_return_message_types: list[MessageType] | None = None,request_start_timestamp_ns: int | None = None,client_tools: list["ClientToolSchema"] | None = None,+ client_skills: list["ClientSkillSchema"] | None = None,include_compaction_messages: bool = False, # Not used in V2, but accepted for API compatibilitybilling_context: "BillingContext | None" = None,) -> LettaResponse:@@ -77,6 +80,7 @@ class BaseAgentV2(ABC):request_start_timestamp_ns: int | None = None,conversation_id: str | None = None,client_tools: list["ClientToolSchema"] | None = None,+ client_skills: list["ClientSkillSchema"] | None = None,include_compaction_messages: bool = False, # Not used in V2, but accepted for API compatibilitybilling_context: "BillingContext | None" = None,openai_responses_websocket: bool = False,diff --git a/letta/agents/letta_agent_batch.py b/letta/agents/letta_agent_batch.pyindex 35d8c8f66..c8cebc576 100644--- a/letta/agents/letta_agent_batch.py+++ b/letta/agents/letta_agent_batch.py@@ -120,6 +120,7 @@ class LettaAgentBatch(BaseAgent):self.job_manager = job_managerself.actor = actorself.max_steps = max_steps+ self.client_skills: list = []@trace_methodasync def step_until_request(@@ -613,6 +614,7 @@ class LettaAgentBatch(BaseAgent):input_messages, agent_state, self.message_manager, self.actor, run_id=None)+ self.conversation_id = Nonein_context_messages = await self._rebuild_memory_async(current_in_context_messages + new_in_context_messages, agent_state)return in_context_messagesdiff --git a/letta/agents/letta_agent_v2.py b/letta/agents/letta_agent_v2.pyindex 5fcdaa5a6..3b3f02c41 100644--- a/letta/agents/letta_agent_v2.py+++ b/letta/agents/letta_agent_v2.py@@ -33,7 +33,7 @@ from letta.schemas.agent import AgentState, UpdateAgentfrom letta.schemas.enums import AgentType, LLMCallType, MessageStreamStatus, RunStatus, StepStatusfrom letta.schemas.letta_message import LettaMessage, MessageTypefrom letta.schemas.letta_message_content import OmittedReasoningContent, ReasoningContent, RedactedReasoningContent, TextContent-from letta.schemas.letta_request import ClientToolSchema+from letta.schemas.letta_request import ClientSkillSchema, ClientToolSchemafrom letta.schemas.letta_response import LettaResponsefrom letta.schemas.letta_stop_reason import LettaStopReason, StopReasonTypefrom letta.schemas.message import Message, MessageCreate, MessageUpdate@@ -138,7 +138,7 @@ class LettaAgentV2(BaseAgentV2):)@trace_method- async def build_request(self, input_messages: list[MessageCreate]) -> dict:+ async def build_request(self, input_messages: list[MessageCreate], client_skills: list[ClientSkillSchema] | None = None) -> dict:"""Build the request data for an LLM call without actually executing it.@@ -151,6 +151,7 @@ class LettaAgentV2(BaseAgentV2):dict: The request data that would be sent to the LLM"""request = {}+ self.client_skills = client_skills or []in_context_messages, input_messages_to_persist = await _prepare_in_context_messages_no_persist_async(input_messages, self.agent_state, self.message_manager, self.actor, None)@@ -185,6 +186,7 @@ class LettaAgentV2(BaseAgentV2):include_return_message_types: list[MessageType] | None = None,request_start_timestamp_ns: int | None = None,client_tools: list[ClientToolSchema] | None = None,+ client_skills: list[ClientSkillSchema] | None = None,include_compaction_messages: bool = False, # Not used in V2, but accepted for API compatibilitybilling_context: "BillingContext | None" = None,) -> LettaResponse:@@ -205,6 +207,8 @@ class LettaAgentV2(BaseAgentV2):LettaResponse: Complete response with all messages and metadata"""self._initialize_state()+ self.conversation_id = None+ self.client_skills = client_skills or []request_span = self._request_checkpoint_start(request_start_timestamp_ns=request_start_timestamp_ns)in_context_messages, input_messages_to_persist = await _prepare_in_context_messages_no_persist_async(@@ -291,6 +295,7 @@ class LettaAgentV2(BaseAgentV2):request_start_timestamp_ns: int | None = None,conversation_id: str | None = None, # Not used in V2, but accepted for API compatibilityclient_tools: list[ClientToolSchema] | None = None,+ client_skills: list[ClientSkillSchema] | None = None,include_compaction_messages: bool = False, # Not used in V2, but accepted for API compatibilitybilling_context: BillingContext | None = None,openai_responses_websocket: bool = False, # Not used in V2, but accepted for API compatibility@@ -318,6 +323,8 @@ class LettaAgentV2(BaseAgentV2):str: JSON-formatted SSE data chunks for each completed step"""self._initialize_state()+ self.conversation_id = conversation_id+ self.client_skills = client_skills or []request_span = self._request_checkpoint_start(request_start_timestamp_ns=request_start_timestamp_ns)first_chunk = True@@ -802,6 +809,7 @@ class LettaAgentV2(BaseAgentV2):sources=agent_state.sources,max_files_open=agent_state.max_files_open,llm_config=agent_state.llm_config,+ client_skills=self.client_skills,)# Skip rebuild unless explicitly forced and unless system/memory content actually changed.@@ -824,6 +832,8 @@ class LettaAgentV2(BaseAgentV2):new_system_message_str = PromptGenerator.get_system_message_from_compiled_memory(system_prompt=agent_state.system,memory_with_sources=curr_memory_str,+ agent_id=agent_state.id,+ conversation_id=self.conversation_id or "default",in_context_memory_last_edit=memory_edit_timestamp,timezone=agent_state.timezone,previous_message_count=num_messages - len(in_context_messages),diff --git a/letta/agents/letta_agent_v3.py b/letta/agents/letta_agent_v3.pyindex a300d9fc7..e595b49a6 100644--- a/letta/agents/letta_agent_v3.py+++ b/letta/agents/letta_agent_v3.py@@ -49,7 +49,7 @@ from letta.schemas.letta_message import (extract_compaction_stats_from_packed_json,)from letta.schemas.letta_message_content import OmittedReasoningContent, ReasoningContent, RedactedReasoningContent, TextContent-from letta.schemas.letta_request import ClientToolSchema+from letta.schemas.letta_request import ClientSkillSchema, ClientToolSchemafrom letta.schemas.letta_response import LettaResponse, TurnTokenDatafrom letta.schemas.letta_stop_reason import LettaStopReason, StopReasonTypefrom letta.schemas.message import Message, MessageCreate, ToolReturn@@ -131,6 +131,8 @@ class LettaAgentV3(LettaAgentV2):self.conversation_id: str | None = None# Client-side tools passed in the request (executed by client, not server)self.client_tools: list[ClientToolSchema] = []+ # Client-side skills passed in the request (rendered in system prompt)+ self.client_skills: list[ClientSkillSchema] = []# Log probabilities from the most recent LLM call (for RL training)self.logprobs: ChoiceLogprobs | None = None# Multi-turn token tracking for RL training (accumulated across all LLM calls)@@ -160,6 +162,7 @@ class LettaAgentV3(LettaAgentV2):request_start_timestamp_ns: int | None = None,conversation_id: str | None = None,client_tools: list[ClientToolSchema] | None = None,+ client_skills: list[ClientSkillSchema] | None = None,include_compaction_messages: bool = False,billing_context: "BillingContext | None" = None,) -> LettaResponse:@@ -185,6 +188,7 @@ class LettaAgentV3(LettaAgentV2):self._initialize_state()self.conversation_id = conversation_idself.client_tools = client_tools or []+ self.client_skills = client_skills or []# Apply conversation-specific block overrides if conversation_id is providedif conversation_id:@@ -375,6 +379,7 @@ class LettaAgentV3(LettaAgentV2):request_start_timestamp_ns: int | None = None,conversation_id: str | None = None,client_tools: list[ClientToolSchema] | None = None,+ client_skills: list[ClientSkillSchema] | None = None,include_compaction_messages: bool = False,billing_context: BillingContext | None = None,openai_responses_websocket: bool = False,@@ -406,6 +411,7 @@ class LettaAgentV3(LettaAgentV2):self._initialize_state()self.conversation_id = conversation_idself.client_tools = client_tools or []+ self.client_skills = client_skills or []request_span = self._request_checkpoint_start(request_start_timestamp_ns=request_start_timestamp_ns)response_letta_messages = []first_chunk = Truediff --git a/letta/agents/voice_agent.py b/letta/agents/voice_agent.pyindex 1bf417292..86f75fae6 100644--- a/letta/agents/voice_agent.py+++ b/letta/agents/voice_agent.py@@ -150,6 +150,8 @@ class VoiceAgent(BaseAgent):in_context_messages[0].content[0].text = await PromptGenerator.compile_system_message_async(system_prompt=agent_state.system,in_context_memory=agent_state.memory,+ agent_id=agent_state.id,+ conversation_id="default",in_context_memory_last_edit=memory_edit_timestamp,timezone=agent_state.timezone,previous_message_count=self.num_messages,diff --git a/letta/groups/sleeptime_multi_agent_v3.py b/letta/groups/sleeptime_multi_agent_v3.pyindex af27e6c12..4ddb2c08b 100644--- a/letta/groups/sleeptime_multi_agent_v3.py+++ b/letta/groups/sleeptime_multi_agent_v3.py@@ -47,6 +47,7 @@ class SleeptimeMultiAgentV3(LettaAgentV2):include_return_message_types: list[MessageType] | None = None,request_start_timestamp_ns: int | None = None,client_tools: list[ClientToolSchema] | None = None,+ client_skills=None,include_compaction_messages: bool = False,billing_context: "BillingContext | None" = None,) -> LettaResponse:@@ -63,6 +64,7 @@ class SleeptimeMultiAgentV3(LettaAgentV2):include_return_message_types=include_return_message_types,request_start_timestamp_ns=request_start_timestamp_ns,client_tools=client_tools,+ client_skills=client_skills,include_compaction_messages=include_compaction_messages,billing_context=billing_context,)@@ -83,6 +85,7 @@ class SleeptimeMultiAgentV3(LettaAgentV2):request_start_timestamp_ns: int | None = None,include_return_message_types: list[MessageType] | None = None,client_tools: list[ClientToolSchema] | None = None,+ client_skills=None,include_compaction_messages: bool = False,billing_context: "BillingContext | None" = None,openai_responses_websocket: bool = False,@@ -103,6 +106,7 @@ class SleeptimeMultiAgentV3(LettaAgentV2):include_return_message_types=include_return_message_types,request_start_timestamp_ns=request_start_timestamp_ns,client_tools=client_tools,+ client_skills=client_skills,include_compaction_messages=include_compaction_messages,billing_context=billing_context,):diff --git a/letta/groups/sleeptime_multi_agent_v4.py b/letta/groups/sleeptime_multi_agent_v4.pyindex 0abc2926b..8ee71388b 100644--- a/letta/groups/sleeptime_multi_agent_v4.py+++ b/letta/groups/sleeptime_multi_agent_v4.py@@ -47,6 +47,7 @@ class SleeptimeMultiAgentV4(LettaAgentV3):request_start_timestamp_ns: int | None = None,conversation_id: str | None = None,client_tools: list[ClientToolSchema] | None = None,+ client_skills=None,include_compaction_messages: bool = False,billing_context: "BillingContext | None" = None,) -> LettaResponse:@@ -64,6 +65,7 @@ class SleeptimeMultiAgentV4(LettaAgentV3):request_start_timestamp_ns=request_start_timestamp_ns,conversation_id=conversation_id,client_tools=client_tools,+ client_skills=client_skills,include_compaction_messages=include_compaction_messages,billing_context=billing_context,)@@ -84,6 +86,7 @@ class SleeptimeMultiAgentV4(LettaAgentV3):include_return_message_types: list[MessageType] | None = None,conversation_id: str | None = None,client_tools: list[ClientToolSchema] | None = None,+ client_skills=None,include_compaction_messages: bool = False,billing_context: "BillingContext | None" = None,openai_responses_websocket: bool = False,@@ -105,6 +108,7 @@ class SleeptimeMultiAgentV4(LettaAgentV3):request_start_timestamp_ns=request_start_timestamp_ns,conversation_id=conversation_id,client_tools=client_tools,+ client_skills=client_skills,include_compaction_messages=include_compaction_messages,billing_context=billing_context,):diff --git a/letta/prompts/prompt_generator.py b/letta/prompts/prompt_generator.pyindex e3cedcaca..817b3db80 100644--- a/letta/prompts/prompt_generator.py+++ b/letta/prompts/prompt_generator.py@@ -7,7 +7,7 @@ logger = get_logger(__name__)from letta.constants import IN_CONTEXT_MEMORY_KEYWORDfrom letta.helpers import ToolRulesSolver-from letta.helpers.datetime_helpers import format_datetime, get_local_time_fast+from letta.helpers.datetime_helpers import format_datetimefrom letta.otel.tracing import trace_methodfrom letta.schemas.memory import Memory@@ -26,6 +26,8 @@ class PromptGenerator:def compile_memory_metadata_block(memory_edit_timestamp: datetime,timezone: str,+ agent_id: str,+ conversation_id: str = "default",previous_message_count: int = 0,archival_memory_size: Optional[int] = 0,archive_tags: Optional[List[str]] = None,@@ -41,6 +43,8 @@ class PromptGenerator:Args:memory_edit_timestamp: When the system prompt was last recompiledtimezone: The timezone to use for formatting timestamps (e.g., 'America/Los_Angeles')+ agent_id: The current agent ID+ conversation_id: The current conversation ID, or "default"previous_message_count: Number of messages in recall memory (conversation history)archival_memory_size: Number of items in archival memory (long-term storage)archive_tags: List of unique tags available in archival memory@@ -50,7 +54,8 @@ class PromptGenerator:Example Output:<memory_metadata>- - The current time is: 2024-01-15 10:30 AM PST+ - AGENT_ID: agent-123+ - CONVERSATION_ID: default- System prompt last recompiled: 2024-01-15 09:00 AM PST- 42 previous messages between you and the user are stored in recall memory (use tools to access them)- 156 total memories you created are stored in archival memory (use tools to access them)@@ -63,7 +68,8 @@ class PromptGenerator:# Create a metadata block of info so the agent knows about the metadata of out-of-context memoriesmetadata_lines = ["<memory_metadata>",- f"- The current system date is: {get_local_time_fast(timezone)}",+ f"- AGENT_ID: {agent_id}",+ f"- CONVERSATION_ID: {conversation_id}",f"- System prompt last recompiled: {timestamp_str}",f"- {previous_message_count} previous messages between you and the user are stored in recall memory (use tools to access them)",]@@ -101,6 +107,7 @@ class PromptGenerator:def get_system_message_from_compiled_memory(system_prompt: str,memory_with_sources: str,+ agent_id: str,in_context_memory_last_edit: datetime, # TODO move this inside of BaseMemory?timezone: str,user_defined_variables: Optional[dict] = None,@@ -109,6 +116,7 @@ class PromptGenerator:previous_message_count: int = 0,archival_memory_size: int = 0,archive_tags: Optional[List[str]] = None,+ conversation_id: str = "default",) -> str:"""Prepare the final/full system message that will be fed into the LLM API@@ -130,6 +138,8 @@ class PromptGenerator:# TODO should this all put into the memory.__repr__ function?memory_metadata_string = PromptGenerator.compile_memory_metadata_block(memory_edit_timestamp=in_context_memory_last_edit,+ agent_id=agent_id,+ conversation_id=conversation_id,previous_message_count=previous_message_count,archival_memory_size=archival_memory_size,timezone=timezone,@@ -171,6 +181,7 @@ class PromptGenerator:async def compile_system_message_async(system_prompt: str,in_context_memory: Memory,+ agent_id: str,in_context_memory_last_edit: datetime, # TODO move this inside of BaseMemory?timezone: str,user_defined_variables: Optional[dict] = None,@@ -182,6 +193,7 @@ class PromptGenerator:sources: Optional[List] = None,max_files_open: Optional[int] = None,llm_config: Optional[object] = None,+ conversation_id: str = "default",) -> str:tool_constraint_block = Noneif tool_rules_solver is not None:@@ -200,6 +212,7 @@ class PromptGenerator:return PromptGenerator.get_system_message_from_compiled_memory(system_prompt=system_prompt,memory_with_sources=memory_with_sources,+ agent_id=agent_id,in_context_memory_last_edit=in_context_memory_last_edit,timezone=timezone,user_defined_variables=user_defined_variables,@@ -207,4 +220,5 @@ class PromptGenerator:template_format=template_format,previous_message_count=previous_message_count,archival_memory_size=archival_memory_size,+ conversation_id=conversation_id,)diff --git a/letta/schemas/letta_request.py b/letta/schemas/letta_request.pyindex 05ffe7066..d551cfcbf 100644--- a/letta/schemas/letta_request.py+++ b/letta/schemas/letta_request.py@@ -23,6 +23,19 @@ class ClientToolSchema(BaseModel):parameters: Optional[Dict[str, Any]] = Field(None, description="JSON Schema for the function parameters")+class ClientSkillSchema(BaseModel):+ """Schema for a client-side skill passed in the request.++ Client-side skills represent environment-provided capabilities (e.g. project-scoped+ skills) that are not stored in the agent's MemFS but should appear in the system+ prompt's available skills section.+ """++ name: str = Field(..., description="The name of the skill")+ description: str = Field(..., description="Description of what the skill does")+ location: str = Field(..., description="Path or location hint for the skill (e.g. skills/my-skill/SKILL.md)")++class LettaRequest(BaseModel):messages: Optional[List[MessageCreateUnion]] = Field(None, description="The messages to be sent to the agent.")input: Optional[Union[str, List[LettaMessageContentUnion]]] = Field(@@ -66,6 +79,13 @@ class LettaRequest(BaseModel):"execution pauses and returns control to the client to execute the tool and provide the result via a ToolReturn.",)+ # Client-side skills+ client_skills: Optional[List[ClientSkillSchema]] = Field(+ None,+ description="Client-side skills available in the environment. These are rendered in the system prompt's "+ "available skills section alongside agent-scoped skills from MemFS.",+ )+# Model overrideoverride_model: Optional[str] = Field(None,diff --git a/letta/schemas/memory.py b/letta/schemas/memory.pyindex 6e5eb7f04..6f217acc0 100644--- a/letta/schemas/memory.py+++ b/letta/schemas/memory.py@@ -207,6 +207,10 @@ class Memory(BaseModel, validate_assignment=True):Each block is rendered as <label.md>---frontmatter---value</label.md>,matching the format stored in the git repo. Labels without a 'system/'prefix get one added automatically.++ DEPRECATED: Kept for backward compatibility. New agents use+ _render_memory_filesystem_structured() which embeds core memory+ inside the <memory_filesystem> tag."""renderable = self._get_renderable_blocks()if not renderable:@@ -237,14 +241,14 @@ class Memory(BaseModel, validate_assignment=True):s.write(f"{value}\n")s.write(f"</{tag}>")- def _render_memory_filesystem(self, s: StringIO):+ def _render_memory_filesystem(self, s: StringIO, client_skills=None):"""Render a filesystem tree view of all memory blocks.Only rendered for git-memory-enabled agents. Uses box-drawingcharacters (├──, └──, │) like the Unix `tree` command, while keepingdeterministic ordering (directories first, then files, alphabetically)."""- if not self.blocks:+ if not self.blocks and not client_skills:return# Build tree structure from block labels.@@ -369,6 +373,56 @@ class Memory(BaseModel, validate_assignment=True):_render_tree(tree)s.write("</memory_filesystem>")+ # Render explicit skill metadata block (agent-scoped + client-provided).+ all_skill_entries: list[tuple[str, str, str]] = [] # (name, description, location)+ seen_skill_names: set[str] = set()++ # Agent-scoped skills from memFS blocks.+ for block in self.blocks:+ label = block.label or ""+ if not label.startswith("skills/"):+ continue++ parts = label.split("/")+ if len(parts) < 2:+ continue++ skill_name = parts[1]+ # Only include top-level skill entries, skip nested files.+ is_top_level = len(parts) == 2 or (len(parts) == 3 and parts[2] == "SKILL")+ if not is_top_level or skill_name in seen_skill_names:+ continue++ seen_skill_names.add(skill_name)+ desc = (getattr(block, "description", None) or "").strip().split("\n")[0].strip()+ location = f"${{MEMORY_DIR}}/skills/{skill_name}/SKILL.md"+ all_skill_entries.append((skill_name, desc, location))++ # Client-provided skills.+ if client_skills:+ for cs in client_skills:+ name = cs.name+ if name in seen_skill_names:+ continue++ seen_skill_names.add(name)+ desc = (cs.description or "").strip().split("\n")[0].strip()+ location = cs.location or ""+ all_skill_entries.append((name, desc, location))++ if all_skill_entries:+ all_skill_entries.sort(key=lambda e: e[0])+ s.write("\n\n<available_skills>\n")+ for name, desc, location in all_skill_entries:+ s.write("<skill>\n")+ s.write(f"<name>{name}</name>\n")+ if desc:+ s.write(f"<description>{desc}</description>\n")+ if location:+ s.write(f"<location>{location}</location>\n")+ s.write("</skill>\n")+ s.write("</available_skills>")+def _render_directories_common(self, s: StringIO, sources, max_files_open):s.write("\n\n<directories>\n")if max_files_open is not None:@@ -469,7 +523,7 @@ class Memory(BaseModel, validate_assignment=True):s.write("</directory>\n")s.write("</directories>")- def compile(self, tool_usage_rules=None, sources=None, max_files_open=None, llm_config=None) -> str:+ def compile(self, tool_usage_rules=None, sources=None, max_files_open=None, llm_config=None, client_skills=None) -> str:"""Efficiently render memory, tool rules, and sources into a prompt string."""s = StringIO()@@ -489,7 +543,7 @@ class Memory(BaseModel, validate_assignment=True):if not is_react:if self.git_enabled:# Git-enabled: filesystem tree + file-style block rendering- self._render_memory_filesystem(s)+ self._render_memory_filesystem(s, client_skills=client_skills)self._render_memory_blocks_git(s)elif is_line_numbered:self._render_memory_blocks_line_numbered(s)@@ -513,7 +567,7 @@ class Memory(BaseModel, validate_assignment=True):return s.getvalue()@trace_method- async def compile_async(self, tool_usage_rules=None, sources=None, max_files_open=None, llm_config=None) -> str:+ async def compile_async(self, tool_usage_rules=None, sources=None, max_files_open=None, llm_config=None, client_skills=None) -> str:"""Async version that offloads to a thread for CPU-bound string building."""return await asyncio.to_thread(self.compile,@@ -521,6 +575,7 @@ class Memory(BaseModel, validate_assignment=True):sources=sources,max_files_open=max_files_open,llm_config=llm_config,+ client_skills=client_skills,)def list_block_labels(self) -> List[str]:diff --git a/letta/server/rest_api/routers/v1/agents.py b/letta/server/rest_api/routers/v1/agents.pyindex 26b188c71..eac433645 100644--- a/letta/server/rest_api/routers/v1/agents.py+++ b/letta/server/rest_api/routers/v1/agents.py@@ -1769,6 +1769,7 @@ async def send_message(request_start_timestamp_ns=request_start_timestamp_ns,include_return_message_types=request.include_return_message_types,client_tools=request.client_tools,+ client_skills=request.client_skills,include_compaction_messages=request.include_compaction_messages,billing_context=headers.billing_context,)@@ -2080,6 +2081,7 @@ async def _process_message_background(use_assistant_message=use_assistant_message,request_start_timestamp_ns=request_start_timestamp_ns,include_return_message_types=include_return_message_types,+ client_skills=[],include_compaction_messages=include_compaction_messages,billing_context=billing_context,)@@ -2373,6 +2375,7 @@ async def preview_model_request(agent_loop = AgentLoop.load(agent_state=agent, actor=actor)return await agent_loop.build_request(input_messages=request.messages,+ client_skills=request.client_skills,)diff --git a/letta/server/rest_api/routers/v1/conversations.py b/letta/server/rest_api/routers/v1/conversations.pyindex ad154c0a3..5014b77bb 100644--- a/letta/server/rest_api/routers/v1/conversations.py+++ b/letta/server/rest_api/routers/v1/conversations.py@@ -249,6 +249,7 @@ async def _send_agent_direct_message(include_return_message_types=request.include_return_message_types,override_model=request.override_model,client_tools=request.client_tools,+ client_skills=request.client_skills,)streaming_service = StreamingService(server)run, result = await streaming_service.create_agent_stream(@@ -313,6 +314,7 @@ async def _send_agent_direct_message(use_assistant_message=request.use_assistant_message,include_return_message_types=request.include_return_message_types,client_tools=request.client_tools,+ client_skills=request.client_skills,conversation_id=None,include_compaction_messages=request.include_compaction_messages,billing_context=billing_context,@@ -400,6 +402,7 @@ async def send_conversation_message(include_return_message_types=request.include_return_message_types,override_model=request.override_model,client_tools=request.client_tools,+ client_skills=request.client_skills,)streaming_service = StreamingService(server)run, result = await streaming_service.create_agent_stream(@@ -470,6 +473,7 @@ async def send_conversation_message(use_assistant_message=request.use_assistant_message,include_return_message_types=request.include_return_message_types,client_tools=request.client_tools,+ client_skills=request.client_skills,conversation_id=conversation_id,include_compaction_messages=request.include_compaction_messages,billing_context=headers.billing_context,diff --git a/letta/services/agent_manager.py b/letta/services/agent_manager.pyindex 2f9769e6f..364f306da 100644--- a/letta/services/agent_manager.py+++ b/letta/services/agent_manager.py@@ -1444,6 +1444,8 @@ class AgentManager:in_context_memory=agent_state.memory,in_context_memory_last_edit=memory_edit_timestamp,timezone=agent_state.timezone,+ agent_id=agent_state.id,+ conversation_id="default",previous_message_count=num_messages - len(agent_state.message_ids),archival_memory_size=num_archival_memories,sources=agent_state.sources,@@ -1533,6 +1535,8 @@ class AgentManager:new_system_message_str = PromptGenerator.get_system_message_from_compiled_memory(system_prompt=agent_state.system,memory_with_sources=curr_memory_str,+ agent_id=agent_state.id,+ conversation_id="default",in_context_memory_last_edit=memory_edit_timestamp,timezone=agent_state.timezone,previous_message_count=num_messages - len(agent_state.message_ids),diff --git a/letta/services/conversation_manager.py b/letta/services/conversation_manager.pyindex 22ab839eb..98d6318f5 100644--- a/letta/services/conversation_manager.py+++ b/letta/services/conversation_manager.py@@ -154,6 +154,8 @@ class ConversationManager:system_message_str = await PromptGenerator.compile_system_message_async(system_prompt=agent_state.system,in_context_memory=agent_state.memory,+ agent_id=agent_state.id,+ conversation_id=conversation_id,in_context_memory_last_edit=get_utc_time(),timezone=agent_state.timezone,user_defined_variables=None,diff --git a/letta/services/helpers/agent_manager_helper.py b/letta/services/helpers/agent_manager_helper.pyindex e4ba18fec..8de18f7b2 100644--- a/letta/services/helpers/agent_manager_helper.py+++ b/letta/services/helpers/agent_manager_helper.py@@ -253,6 +253,8 @@ def compile_system_message(in_context_memory: Memory,in_context_memory_last_edit: datetime, # TODO move this inside of BaseMemory?timezone: str,+ agent_id: str,+ conversation_id: str = "default",user_defined_variables: Optional[dict] = None,append_icm_if_missing: bool = True,template_format: Literal["f-string", "mustache"] = "f-string",@@ -289,6 +291,8 @@ def compile_system_message(# TODO should this all put into the memory.__repr__ function?memory_metadata_string = PromptGenerator.compile_memory_metadata_block(memory_edit_timestamp=in_context_memory_last_edit,+ agent_id=agent_id,+ conversation_id=conversation_id,previous_message_count=previous_message_count,archival_memory_size=archival_memory_size or 0,timezone=timezone,@@ -344,6 +348,8 @@ def initialize_message_sequence(in_context_memory=agent_state.memory,in_context_memory_last_edit=memory_edit_timestamp,timezone=agent_state.timezone,+ agent_id=agent_state.id,+ conversation_id="default",user_defined_variables=None,append_icm_if_missing=True,previous_message_count=previous_message_count,@@ -406,6 +412,8 @@ async def initialize_message_sequence_async(in_context_memory=agent_state.memory,in_context_memory_last_edit=memory_edit_timestamp,timezone=agent_state.timezone,+ agent_id=agent_state.id,+ conversation_id="default",user_defined_variables=None,append_icm_if_missing=True,previous_message_count=previous_message_count,diff --git a/letta/services/streaming_service.py b/letta/services/streaming_service.pyindex f2620f8b9..acd50023f 100644--- a/letta/services/streaming_service.py+++ b/letta/services/streaming_service.py@@ -190,6 +190,7 @@ class StreamingService:conversation_id=conversation_id,lock_key=lock_key, # For lock release (may differ from conversation_id)client_tools=request.client_tools,+ client_skills=request.client_skills,include_compaction_messages=request.include_compaction_messages,billing_context=billing_context,route_class=route_class,@@ -362,6 +363,7 @@ class StreamingService:conversation_id: Optional[str] = None,lock_key: Optional[str] = None,client_tools: Optional[list[ClientToolSchema]] = None,+ client_skills=None,include_compaction_messages: bool = False,billing_context: BillingContext | None = None,route_class: str = "foreground",@@ -400,6 +402,7 @@ class StreamingService:include_return_message_types=include_return_message_types,conversation_id=conversation_id,client_tools=client_tools,+ client_skills=client_skills,include_compaction_messages=include_compaction_messages,billing_context=billing_context,openai_responses_websocket=openai_responses_websocket,diff --git a/tests/integration_test_conversations_sdk.py b/tests/integration_test_conversations_sdk.pyindex 4d384d81b..5ee3146dd 100644--- a/tests/integration_test_conversations_sdk.py+++ b/tests/integration_test_conversations_sdk.py@@ -35,6 +35,28 @@ def agent(client: Letta):class TestConversationsSDK:"""Test conversations using the SDK client."""+ @staticmethod+ def _get_system_message_content(server_url: str, message_id: str) -> str:+ """Fetch a system message by ID via REST and return its content."""+ response = requests.get(f"{server_url}/v1/messages/{message_id}")+ assert response.status_code == 200, f"Failed to retrieve message {message_id}: {response.text}"++ payload = response.json()+ assert isinstance(payload, list) and len(payload) == 1, f"Expected one message for {message_id}, got: {payload}"+ message = payload[0]+ assert message.get("message_type") == "system_message", f"Expected system message, got: {message}"+ assert isinstance(message.get("content"), str), f"Expected string content, got: {message}"+ return message["content"]++ @staticmethod+ def _assert_system_metadata_identifiers(content: str, agent_id: str, conversation_id: str):+ """Assert system prompt metadata includes expected IDs and excludes deprecated date line."""+ assert "<memory_metadata>" in content+ assert f"- AGENT_ID: {agent_id}" in content+ assert f"- CONVERSATION_ID: {conversation_id}" in content+ assert "- System prompt last recompiled:" in content+ assert "- The current system date is:" not in content+def test_create_conversation(self, client: Letta, agent):"""Test creating a conversation for an agent."""conversation = client.conversations.create(agent_id=agent.id)@@ -99,6 +121,24 @@ class TestConversationsSDK:assert messages[1].message_type == "user_message", f"Second message should be user_message, got {messages[1].message_type}"assert getattr(messages[1], "conversation_id", None) == created.id+ def test_default_system_message_metadata_has_agent_and_default_conversation(self, client: Letta, agent, server_url: str):+ """Default conversation system prompt should include AGENT_ID and CONVERSATION_ID=default."""+ assert agent.message_ids and len(agent.message_ids) > 0, "Agent should have an initial system message"++ content = self._get_system_message_content(server_url=server_url, message_id=agent.message_ids[0])+ self._assert_system_metadata_identifiers(content=content, agent_id=agent.id, conversation_id="default")++ def test_conversation_system_message_metadata_has_agent_and_conversation_id(self, client: Letta, agent, server_url: str):+ """Conversation-scoped system prompt should include AGENT_ID and the concrete conversation ID."""+ conversation = client.conversations.create(agent_id=agent.id)+ retrieved = client.conversations.retrieve(conversation_id=conversation.id)++ assert retrieved.in_context_message_ids and len(retrieved.in_context_message_ids) > 0+ system_message_id = retrieved.in_context_message_ids[0]++ content = self._get_system_message_content(server_url=server_url, message_id=system_message_id)+ self._assert_system_metadata_identifiers(content=content, agent_id=agent.id, conversation_id=conversation.id)+def test_send_message_to_conversation(self, client: Letta, agent):"""Test sending a message to a conversation."""# Create a conversation@@ -756,9 +796,34 @@ class TestConversationsSDK:assert isinstance(data, list), "Response should be a list of messages"assert len(data) >= 3, "Should have at least system + user + assistant messages"- # Verify our message is there- user_messages = [m for m in data if m.get("message_type") == "user_message"]- assert any("Testing old pattern still works" in str(m.get("content", "")) for m in user_messages), "Should find our test message"+ def test_new_pattern_default_system_message_metadata(self, client: Letta, agent, server_url: str):+ """Agent-direct default path should render system metadata with AGENT_ID and CONVERSATION_ID=default."""+ # Trigger default conversation path via new pattern+ response = requests.post(+ f"{server_url}/v1/conversations/default/messages",+ json={+ "agent_id": agent.id,+ "messages": [{"role": "user", "content": "Please acknowledge."}],+ "streaming": False,+ },+ )+ assert response.status_code == 200, f"Expected 200, got {response.status_code}: {response.text}"++ # Read default conversation messages and inspect the first (system) message content+ list_response = requests.get(+ f"{server_url}/v1/conversations/default/messages",+ params={"agent_id": agent.id, "order": "asc"},+ )+ assert list_response.status_code == 200, f"Expected 200, got {list_response.status_code}: {list_response.text}"++ messages = list_response.json()+ assert isinstance(messages, list) and len(messages) > 0, f"Expected non-empty message list, got: {messages}"+ assert messages[0].get("message_type") == "system_message", f"Expected first message to be system_message, got: {messages[0]}"++ content = messages[0].get("content")+ assert isinstance(content, str), f"Expected system message content string, got: {messages[0]}"++ self._assert_system_metadata_identifiers(content=content, agent_id=agent.id, conversation_id="default")def test_new_pattern_send_message(self, client: Letta, agent, server_url: str):"""Test sending messages using the new pattern: conversation_id='default' + agent_id in body."""diff --git a/tests/integration_test_system_prompt_prefix_caching.py b/tests/integration_test_system_prompt_prefix_caching.pyindex 86bcd50de..1cfe56037 100644--- a/tests/integration_test_system_prompt_prefix_caching.py+++ b/tests/integration_test_system_prompt_prefix_caching.py@@ -1,9 +1,10 @@"""-Integration tests for system prompt prefix caching optimization.+Integration tests for system prompt prefix caching and recompilation.-These tests verify that the system prompt is NOT rebuilt on every agent step-(e.g. after agent memory tool calls or messages), preserving prefix caching-for LLM providers. Manual block edits via the API DO trigger recompilation.+These tests verify:+1. The system prompt template is NOT rebuilt on every step (prefix caching optimization)+2. The core memory section IS recompiled when blocks are edited via the agent API+3. The system prompt IS rebuilt after message reset"""import pytest@@ -38,14 +39,21 @@ class TestSystemPromptPrefixCaching:def test_system_prompt_stable_after_memory_tool_and_messages(self, client: Letta, agent):"""+ The system prompt *template* should not change during normal execution.++ NOTE: This test uses client.blocks.modify() (the global blocks endpoint),+ which does NOT trigger system prompt recompilation. For the agent-specific+ endpoint that DOES trigger recompilation, see+ test_core_memory_recompiled_after_agent_block_edit.+Test workflow:1. Get initial system prompt and human block value2. Tell agent to update its memory block using the memory tool- 3. Verify block was modified but system prompt hasn't changed+ 3. Verify block was modified but system prompt template hasn't changed4. Send another message to the agent- 5. Verify system prompt still hasn't changed- 6. Manually update a block via API- 7. Verify system prompt HAS changed (manual block edits trigger recompilation)+ 5. Verify system prompt template still hasn't changed+ 6. Manually update a block via global blocks API (no recompile trigger)+ 7. Send another message and verify system prompt template still hasn't changed"""# Step 1: Get initial context window, system prompt, and human block valueinitial_context = client.agents.context.retrieve(agent.id)@@ -113,32 +121,86 @@ class TestSystemPromptPrefixCaching:assert human_block, "Agent should have a 'human' memory block"# Update the block directly via API- sushi_marker = "SUSHI_MARKER_FOR_VERIFICATION"client.blocks.modify(block_id=human_block.id,- value=human_block.value + f"\nUser also likes sushi. {sushi_marker}",+ value=human_block.value + "\nUser also likes sushi.",)- # Step 7: Verify system prompt HAS changed after manual block edit via API- # Manual block edits via the standalone blocks API trigger recompilation+ # Step 7: Send another message and verify system prompt still hasn't changed+ response3 = client.agents.messages.create(+ agent_id=agent.id,+ messages=[+ {+ "role": "user",+ "content": "What foods do I like?",+ }+ ],+ )+ assert response3.messages, "Agent should respond with messages"++ # Verify system prompt STILL hasn't changed (deferred to compaction/reset)context_after_manual_update = client.agents.context.retrieve(agent.id)system_prompt_after_manual = context_after_manual_update.system_prompt- assert system_prompt_after_manual != initial_system_prompt, (- "System prompt SHOULD change after manual block update via API (triggers recompilation)"+ assert system_prompt_after_manual == initial_system_prompt, (+ "System prompt should NOT change after manual block update (deferred to compaction)")- assert sushi_marker in system_prompt_after_manual, (- "System prompt should include the updated memory block content after manual API edit"++ def test_core_memory_recompiled_after_agent_block_edit(self, client: Letta, agent):+ """+ Editing a block via the agent-specific endpoint should trigger system prompt+ recompilation. The core_memory section should reflect the updated block content.++ The agent-specific endpoint (PATCH /agents/{id}/core-memory/blocks/{label})+ explicitly calls rebuild_system_prompt_async, unlike the global blocks endpoint.+ """+ # Step 1: Get initial context window+ initial_context = client.agents.context.retrieve(agent.id)+ initial_core_memory = initial_context.core_memory+ assert initial_core_memory, "Initial core memory should not be empty"++ # Step 2: Get the human block+ human_block = None+ for block in agent.memory.blocks:+ if block.label == "human":+ human_block = block+ break+ assert human_block, "Agent should have a 'human' memory block"+ initial_block_value = human_block.value++ # Step 3: Update block via agent-specific endpoint (triggers recompilation)+ unique_marker = "RECOMPILE_TEST_MARKER_67890"+ new_value = initial_block_value + f"\n{unique_marker}: User prefers dark mode."+ client.agents.blocks.update(+ agent_id=agent.id,+ block_label="human",+ value=new_value,+ )++ # Step 4: Verify the block was updated+ updated_block = client.agents.blocks.retrieve(agent_id=agent.id, block_label="human")+ assert unique_marker in updated_block.value, "Block should contain the new marker"++ # Step 5: Get context window and verify core memory was recompiled+ updated_context = client.agents.context.retrieve(agent.id)+ updated_core_memory = updated_context.core_memory++ assert updated_core_memory != initial_core_memory, (+ "Core memory should change after block edit via agent endpoint (recompilation triggered)"+ )+ assert unique_marker in updated_core_memory, "Recompiled core memory should contain the updated block content"++ # Step 6: System prompt template should NOT change (only memory content changes)+ assert updated_context.system_prompt == initial_context.system_prompt, (+ "System prompt template should remain the same — only core memory content changes")def test_system_prompt_updates_after_reset(self, client: Letta, agent):"""Test that system prompt IS updated after message reset.- Also verifies that the standalone block API edit already triggers recompilation.1. Get initial system prompt- 2. Manually update a memory block (triggers recompilation via API)- 3. Verify system prompt HAS already changed from the block edit- 4. Reset messages- 5. Verify system prompt still includes the new memory after reset+ 2. Manually update a memory block+ 3. Reset messages+ 4. Verify system prompt HAS changed to include the new memory"""# Step 1: Get initial system promptinitial_context = client.agents.context.retrieve(agent.id)@@ -159,18 +221,10 @@ class TestSystemPromptPrefixCaching:value=human_block.value + f"\n{new_memory_content}",)- # Step 3: Verify system prompt has already changed from the block edit- context_after_edit = client.agents.context.retrieve(agent.id)- system_prompt_after_edit = context_after_edit.system_prompt- assert system_prompt_after_edit != initial_system_prompt, "System prompt SHOULD change immediately after manual block edit via API"- assert "UNIQUE_TEST_MARKER_12345" in system_prompt_after_edit, (- "System prompt should include the updated memory block content after API edit"- )-- # Step 4: Reset messages (this should also trigger system prompt rebuild)+ # Step 3: Reset messages (this should trigger system prompt rebuild)client.agents.messages.reset(agent.id)- # Step 5: Verify system prompt still includes the new memory after reset+ # Step 4: Verify system prompt HAS changed and includes the new memorycontext_after_reset = client.agents.context.retrieve(agent.id)system_prompt_after_reset = context_after_reset.system_promptdiff --git a/tests/managers/test_run_manager.py b/tests/managers/test_run_manager.pyindex 1167c19d9..4d7507b86 100644--- a/tests/managers/test_run_manager.py+++ b/tests/managers/test_run_manager.py@@ -1849,7 +1849,7 @@ async def test_list_runs_by_duration_percentile(server: SyncServer, sarah_agent,# Create runs with varied durationsrun_ids = []- durations_ms = [50, 100, 150, 200, 250, 300, 350, 400, 450, 500]+ durations_ms = [100, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 2000]for i, duration_ms in enumerate(durations_ms):run = await server.run_manager.create_run(diff --git a/tests/test_memory.py b/tests/test_memory.pyindex c747e36f4..2f87d8993 100644--- a/tests/test_memory.py+++ b/tests/test_memory.py@@ -225,98 +225,118 @@ def test_current_files_open_counts_truthy_only():assert "- current_files_open=1" in out-def test_compile_git_memory_filesystem_handles_leaf_directory_collisions():- """Git memory filesystem rendering should tolerate label prefix collisions.-- Example collisions:- - leaf at "system" and children under "system/..."- - leaf at "system/human" and children under "system/human/..."-- These occur naturally in git-backed memory where both index-like blocks and- nested blocks can exist.- """+def test_compile_git_structured_core_memory_rendering():+ """Git-enabled agents should render system/* blocks as named sections with full content,+ and <core_memory> should contain metadata-only entries."""m = Memory(agent_type=AgentType.letta_v1_agent,git_enabled=True,blocks=[- Block(label="system", value="root", limit=100),- Block(label="system/human", value="human index", limit=100),- Block(label="system/human/context", value="context", limit=100),+ Block(label="system/human", value="human data", limit=100, description="The human block"),+ Block(label="system/persona", value="persona data", limit=100, description="The persona block"),],)out = m.compile()- # Should include the filesystem view and not raise.assert "<memory_filesystem>" in outassert "system/" in out- assert "system.md" in outassert "human.md" in out+ assert "persona.md" in out++ assert "<system/human.md>" in out+ assert "</system/human.md>" in out+ assert "description: The human block" in out+ assert "human data" in out+ assert "<system/persona.md>" in out+ assert "</system/persona.md>" in out+ assert "description: The persona block" in out+ assert "persona data" in out-def test_compile_git_memory_filesystem_renders_descriptions_for_non_system_files():- """Files outside system/ should render their description in the filesystem tree.- e.g. `reference/api.md (Contains API specifications)`- System files should NOT render descriptions in the tree.+def test_compile_git_structured_skills_section():+ """skills/ blocks should render in <available_skills> section as metadata-only entries.++ Nested skill files should NOT appear. Only top-level skill entries+ with name, description, and location."""m = Memory(agent_type=AgentType.letta_v1_agent,git_enabled=True,blocks=[- Block(label="system/human", value="human data", limit=100, description="The human block"),- Block(label="system/persona", value="persona data", limit=100, description="The persona block"),- Block(label="reference/api", value="api specs", limit=100, description="Contains API specifications"),- Block(label="notes", value="my notes", limit=100, description="Personal notes and reminders"),+ Block(label="system/human", value="human data", limit=100),+ Block(+ label="skills/searching-messages",+ value="# searching messages",+ limit=100,+ description="Search past messages to recall context.",+ ),+ Block(+ label="skills/creating-skills",+ value="# creating skills",+ limit=100,+ description="Guide for creating effective skills.",+ ),+ Block(+ label="skills/creating-skills/references/workflows",+ value="nested docs",+ limit=100,+ description="Nested workflow docs (should not appear)",+ ),],)out = m.compile()- # Filesystem tree should exist- assert "<memory_filesystem>" in out+ assert "<available_skills>" in out+ assert "</available_skills>" in out- # Non-system files should have descriptions rendered- assert "api.md (Contains API specifications)" in out- assert "notes.md (Personal notes and reminders)" in out+ # Top-level skill entries with descriptions+ assert "<name>searching-messages</name>" in out+ assert "<description>Search past messages to recall context.</description>" in out+ assert "<name>creating-skills</name>" in out+ assert "<description>Guide for creating effective skills.</description>" in out- # System files should NOT have descriptions in the tree- assert "human.md (The human block)" not in out- assert "persona.md (The persona block)" not in out- # But they should still be in the tree (without description)- assert "human.md" in out- assert "persona.md" in out+ # Skill content should NOT be rendered (metadata only)+ assert "# searching messages" not in out+ assert "# creating skills" not in out++ # Nested skill files should NOT appear+ assert "references/workflows" not in out+ assert "Nested workflow docs" not in out-def test_compile_git_memory_filesystem_no_description_when_empty():- """Files outside system/ with no description should render without parentheses."""+def test_compile_git_structured_archival_memory_section():+ """Non-system, non-skills blocks should render as filesystem references only."""m = Memory(agent_type=AgentType.letta_v1_agent,git_enabled=True,blocks=[Block(label="system/human", value="human data", limit=100),- Block(label="notes", value="my notes", limit=100),+ Block(label="notes", value="my notes", limit=100, description="Personal notes"),Block(label="reference/api", value="api specs", limit=100, description="API docs"),],)out = m.compile()- # notes.md has no description, so no parentheses- assert "notes.md\n" in out or "notes.md\n" in out- # reference/api.md has a description+ assert "<memory_filesystem>" in out+ assert "notes.md (Personal notes)" in out+ assert "reference/" in outassert "api.md (API docs)" in out+ # Archival memory content should NOT be rendered+ assert "my notes" not in out+ assert "api specs" not in out-def test_compile_git_memory_filesystem_condenses_skills_to_top_level_entries():- """skills/ should render as top-level skill entries with description.- We intentionally avoid showing nested files under skills/ in the system- prompt tree to keep context concise.- """+def test_compile_git_structured_client_skills():+ """client_skills should be merged with agent skills in <available_skills>."""+ from letta.schemas.letta_request import ClientSkillSchemam = Memory(agent_type=AgentType.letta_v1_agent,@@ -327,30 +347,158 @@ def test_compile_git_memory_filesystem_condenses_skills_to_top_level_entries():label="skills/searching-messages",value="# searching messages",limit=100,- description="Search past messages to recall context.",- ),- Block(- label="skills/creating-skills",- value="# creating skills",- limit=100,- description="Guide for creating effective skills.",- ),- Block(- label="skills/creating-skills/references/workflows",- value="nested docs",- limit=100,- description="Nested workflow docs (should not appear)",+ description="Search past messages.",),],)- out = m.compile()+ client_skills = [+ ClientSkillSchema(name="playwright-skill", description="Browser automation.", location="skills/playwright-skill/SKILL.md"),+ ClientSkillSchema(name="google", description="Google Workspace CLI.", location="skills/google/SKILL.md"),+ ]- # Condensed top-level skill entries with descriptions.- assert "searching-messages (Search past messages to recall context.)" in out- assert "creating-skills (Guide for creating effective skills.)" in out+ out = m.compile(client_skills=client_skills)- # Do not show .md suffixes or nested skill docs in tree.- assert "searching-messages.md" not in out- assert "creating-skills.md" not in out- assert "references/workflows" not in out+ # All skills (agent + client) merged in <available_skills>+ assert "<available_skills>" in out+ assert "</available_skills>" in out++ # Agent skill present+ assert "<name>searching-messages</name>" in out++ # Client skills present with descriptions and locations+ assert "<name>playwright-skill</name>" in out+ assert "<description>Browser automation.</description>" in out+ assert "<location>skills/playwright-skill/SKILL.md</location>" in out+ assert "<name>google</name>" in out+ assert "<description>Google Workspace CLI.</description>" in out++ # <available_skills> should come after the filesystem tree+ fs_end = out.find("</memory_filesystem>")+ skills_start = out.find("<available_skills>")+ assert skills_start > fs_end+++def test_compile_git_structured_dedup_client_skills():+ """client_skills with the same name as agent skills should be deduplicated (agent wins)."""+ from letta.schemas.letta_request import ClientSkillSchema++ m = Memory(+ agent_type=AgentType.letta_v1_agent,+ git_enabled=True,+ blocks=[+ Block(label="system/human", value="human data", limit=100),+ Block(label="skills/my-skill", value="skill", limit=100, description="Agent skill."),+ ],+ )++ client_skills = [+ ClientSkillSchema(name="my-skill", description="Client version of same skill.", location="skills/my-skill/SKILL.md"),+ ]++ out = m.compile(client_skills=client_skills)++ # Agent skill present, client duplicate deduplicated+ assert "<available_skills>" in out+ assert "<name>my-skill</name>" in out+ # Agent skill wins — description comes from agent block, not client+ assert "<description>Agent skill.</description>" in out+ # Only one entry for the skill (deduplicated)+ assert out.count("<name>my-skill</name>") == 1+++def test_compile_git_structured_recompile_after_block_edit():+ """Editing a block value should produce a different compile() output.++ This validates the mechanism behind system prompt recompilation: when a+ block is updated, the compiled memory string changes, which base_agent's+ rebuild_memory detects via substring mismatch against the current system+ message.+ """++ human_block = Block(label="system/human", value="original human data", limit=500, description="The human block")+ persona_block = Block(label="system/persona", value="original persona data", limit=500, description="The persona block")++ m = Memory(+ agent_type=AgentType.letta_v1_agent,+ git_enabled=True,+ blocks=[human_block, persona_block],+ )++ out_before = m.compile()++ # Verify initial content renders+ assert "original human data" in out_before+ assert "original persona data" in out_before++ # Simulate a block edit (as would happen via the API)+ human_block.value = "updated human data with new info"+ out_after = m.compile()++ # Compiled output should have changed+ assert out_before != out_after++ # New value should appear, old value should not+ assert "updated human data with new info" in out_after+ assert "original human data" not in out_after++ # Unchanged block should still be present+ assert "original persona data" in out_after++ # The old compiled string should NOT be a substring of the new one+ # (this is the check base_agent uses to detect memory changes)+ assert out_before not in out_after+++def test_compile_git_structured_recompile_after_block_label_change():+ """Changing a block label should produce a different compile() output.++ Label changes affect both the named section tag and the metadata index,+ so the system prompt must be recompiled.+ """++ block = Block(label="system/human", value="human data", limit=500, description="Human context")++ m = Memory(+ agent_type=AgentType.letta_v1_agent,+ git_enabled=True,+ blocks=[block],+ )++ out_before = m.compile()+ assert "<system/human.md>" in out_before+ assert "human.md" in out_before++ # Simulate label rename+ block.label = "system/user"+ out_after = m.compile()++ # Output should change: new tag name, new metadata+ assert out_before != out_after+ assert "<system/user.md>" in out_after+ assert "</system/user.md>" in out_after+ assert "user.md" in out_after+ assert "<system/human.md>" not in out_after+++def test_compile_git_structured_recompile_after_description_change():+ """Changing a block description should produce a different compile() output."""++ block = Block(label="system/human", value="human data", limit=500, description="Original description")++ m = Memory(+ agent_type=AgentType.letta_v1_agent,+ git_enabled=True,+ blocks=[block],+ )++ out_before = m.compile()+ assert "description: Original description" in out_before++ # Simulate description edit+ block.description = "Updated description with more detail"+ out_after = m.compile()++ assert out_before != out_after+ assert "description: Updated description with more detail" in out_after+ assert "Original description" not in out_afterdiff --git a/tests/test_sources.py b/tests/test_sources.pyindex 8ceda0a51..f89f30876 100644--- a/tests/test_sources.py+++ b/tests/test_sources.py@@ -454,7 +454,7 @@ def test_agent_uses_open_close_file_correctly(disable_pinecone, disable_turbopufmessages=[MessageCreate(role="user",- content=f"Use ONLY the open_files tool to open the file named {file.file_name} with offset {offset} and length {length}",+ content=f"Use ONLY the open_files tool to open the file named test_source/{file.file_name} with offset {offset} and length {length}",)],)