Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

fix(core): prevent available_skills regex from destroying memory blocks + historical step viewer (#10006)

Sarah Wooders7517c28bdee3
diff --git a/.skills/viewing-agent-context/SKILL.md b/.skills/viewing-agent-context/SKILL.md
index 06ad91e0b..16cfddf3b 100644
--- a/.skills/viewing-agent-context/SKILL.md
+++ b/.skills/viewing-agent-context/SKILL.md
@@ -1,19 +1,14 @@
---
name: viewing-agent-context
-description: Explains what is inside an agent context window by fetching preview-raw-payload and rendering a human-readable HTML report (system prompt, messages, tools, model settings). Use when users ask what the model actually receives or want to inspect context composition.
+description: Explains what is inside an agent context window by fetching preview-raw-payload (live) or ClickHouse llm_traces (historical). Renders a human-readable HTML report (system prompt, messages, tools, model settings). Use when users ask what the model actually receives, want to inspect context composition, or want to inspect a past step's payload.
---
# Viewing Agent Context
-Inspect what a given agent will send to the model by using preview-only mode:
+Two modes:
-- `POST /v1/agents/{agent_id}/messages/preview-raw-payload`
-
-The script also fetches:
-
-- `GET /v1/agents/{agent_id}`
-
-This keeps the report focused on the actual model request while also showing agent metadata (tags, compaction settings, model settings).
+1. **Live mode** (`--agent-id`): Fetch the current preview payload via `POST /v1/agents/{agent_id}/messages/preview-raw-payload`
+2. **Historical mode** (`--step-id`): Fetch a past LLM request/response from ClickHouse `otel.llm_traces`
## When to use
@@ -22,10 +17,10 @@ Use this skill when a human asks:
- "What is in this agent's context window?"
- "Show me the real prompt/messages sent to the model"
- "Can I see dry-run context?"
+- "Show me what was sent to the model for step X"
+- "Inspect a past LLM call"
-## Usage: self-hosted server
-
-Use this for local/dev/prod self-hosted Letta deployments.
+## Live mode: self-hosted server
```bash
python3 scripts/viewing_agent_context.py \
@@ -42,9 +37,7 @@ If your self-hosted server requires auth, add:
--api-key "$LETTA_API_KEY"
```
-## Usage: api.letta.com
-
-Use this for Letta Cloud.
+## Live mode: api.letta.com
```bash
python3 scripts/viewing_agent_context.py \
@@ -56,21 +49,43 @@ python3 scripts/viewing_agent_context.py \
--out ~/.letta/viewers/viewing-agent-context-<agent-id>.html
```
-## Optional args
+## Historical mode: inspect a past step
+
+Query ClickHouse for a step's full request/response payload. Requires ClickHouse credentials via `--env-file` or env vars (`CLICKHOUSE_URL`, `CLICKHOUSE_USER`, `CLICKHOUSE_PASSWORD`).
+
+```bash
+python3 scripts/viewing_agent_context.py \
+ --step-id <step-id> \
+ --env-file /path/to/.env \
+ --out ~/.letta/viewers/viewing-step-context-<step-id>.html
+```
+
+The historical HTML report includes trace metadata (agent, model, provider, call type, timestamp), token usage stats, the full request payload (system prompt, messages, tools), and the full response payload.
+
+## Args
-- `--api-key <key>`: bearer token (required for `api.letta.com`, optional for self-hosted unless auth is enabled)
-- `--timeout 60`: request timeout in seconds
-- `--out <path>`: absolute/relative path for generated HTML
+| Arg | Description |
+|-----|-------------|
+| `--agent-id` | Live mode: agent to preview (mutually exclusive with `--step-id`) |
+| `--step-id` | Historical mode: step to fetch from ClickHouse (mutually exclusive with `--agent-id`) |
+| `--env-file` | Path to `.env` with ClickHouse credentials (historical mode) |
+| `--server-url` | Letta server URL (live mode, default: `http://127.0.0.1:8283`) |
+| `--api-key` | Bearer token (live mode, required for `api.letta.com`) |
+| `--input` | Preview input text (live mode) |
+| `--max-steps` | Preview max steps (live mode, default: 1) |
+| `--timeout` | Request timeout in seconds (default: 45) |
+| `--out` | Output HTML path |
## Output
The HTML includes:
1. Request settings (model, token params, reasoning/thinking flags)
-2. Agent metadata (tags, `compaction_settings`, `model_settings`)
+2. Agent/trace metadata (tags, compaction settings, model settings — or trace metadata for historical)
3. System prompt section
4. Messages section (including system-reminder badge and newline-preserving user text rendering)
5. Tools/functions section (if present)
-6. Full raw JSON payloads (preview + agent)
+6. Response payload (historical mode only)
+7. Full raw JSON payloads
Always return the absolute output file path so the user can open it directly in a browser.
diff --git a/.skills/viewing-agent-context/scripts/viewing_agent_context.py b/.skills/viewing-agent-context/scripts/viewing_agent_context.py
index dbf36e956..b1a92464c 100755
--- a/.skills/viewing-agent-context/scripts/viewing_agent_context.py
+++ b/.skills/viewing-agent-context/scripts/viewing_agent_context.py
@@ -5,10 +5,12 @@ import argparse
import html
import json
import os
+import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from urllib.error import HTTPError, URLError
+from urllib.parse import urlparse
from urllib.request import Request, urlopen
@@ -43,6 +45,124 @@ def post_json(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeou
return None, f"Unexpected error: {e}"
+# ---------------------------------------------------------------------------
+# ClickHouse helpers
+# ---------------------------------------------------------------------------
+
+
+def _parse_ch_url(raw_url: str) -> Tuple[str, int, bool]:
+ """Return (host, port, secure) from a ClickHouse URL."""
+ if "://" not in raw_url:
+ raw_url = f"http://{raw_url}"
+ parsed = urlparse(raw_url)
+ host = parsed.hostname
+ if not host:
+ raise ValueError(f"Invalid CLICKHOUSE_URL: {raw_url}")
+ secure = parsed.scheme == "https"
+ port = parsed.port if parsed.port is not None else (8443 if secure else 8123)
+ return host, port, secure
+
+
+def _load_ch_credentials(env_file: Optional[str]) -> Tuple[str, str, str]:
+ """Load ClickHouse credentials from env file (preferred) then env vars.
+
+ Uses dotenv_values() to avoid shell expansion of $ characters in passwords.
+ """
+ from dotenv import dotenv_values
+
+ file_vals: Dict[str, Optional[str]] = {}
+ if env_file:
+ file_vals = dotenv_values(env_file)
+
+ url = (file_vals.get("CLICKHOUSE_URL") or os.getenv("CLICKHOUSE_URL") or "").strip()
+ user = (file_vals.get("CLICKHOUSE_USER") or os.getenv("CLICKHOUSE_USER") or "").strip()
+ # Password: prefer dotenv_values first (avoids shell $ expansion), then env
+ password = (file_vals.get("CLICKHOUSE_PASSWORD") or os.getenv("CLICKHOUSE_PASSWORD") or "").strip()
+
+ if not url:
+ raise ValueError("CLICKHOUSE_URL not found (check --env-file or env vars)")
+ if not user:
+ raise ValueError("CLICKHOUSE_USER not found (check --env-file or env vars)")
+ if not password:
+ raise ValueError("CLICKHOUSE_PASSWORD not found (check --env-file or env vars)")
+
+ return url, user, password
+
+
+def query_step_from_clickhouse(step_id: str, env_file: Optional[str]) -> Dict[str, Any]:
+ """Query otel.llm_traces for a step_id and return trace data."""
+ import clickhouse_connect
+
+ url, user, password = _load_ch_credentials(env_file)
+ host, port, secure = _parse_ch_url(url)
+
+ client = clickhouse_connect.get_client(
+ host=host,
+ port=port,
+ username=user,
+ password=password,
+ secure=secure,
+ )
+
+ sql = """
+ SELECT
+ step_id,
+ agent_id,
+ organization_id,
+ run_id,
+ model,
+ provider,
+ call_type,
+ is_byok,
+ prompt_tokens,
+ completion_tokens,
+ total_tokens,
+ cached_input_tokens,
+ cache_write_tokens,
+ reasoning_tokens,
+ latency_ms,
+ request_size_bytes,
+ response_size_bytes,
+ is_error,
+ error_type,
+ error_message,
+ request_json,
+ response_json,
+ llm_config_json,
+ created_at
+ FROM otel.llm_traces
+ WHERE step_id = %(step_id)s
+ ORDER BY created_at DESC
+ LIMIT 1
+ """
+
+ result = client.query(sql, parameters={"step_id": step_id})
+ if not result or not result.result_rows:
+ raise ValueError(f"No trace found for step_id={step_id}")
+
+ row = result.result_rows[0]
+ columns = list(result.column_names)
+ return dict(zip(columns, row))
+
+
+def _parse_json_str(value: Any) -> Dict[str, Any]:
+ """Parse a JSON string into a dict, handling edge cases."""
+ if not value:
+ return {}
+ if isinstance(value, dict):
+ return value
+ try:
+ parsed = json.loads(value)
+ return parsed if isinstance(parsed, dict) else {"_value": parsed}
+ except Exception:
+ return {"_raw": str(value)[:5000]}
+
+
+# ---------------------------------------------------------------------------
+# HTML rendering helpers
+# ---------------------------------------------------------------------------
+
+
def esc_json(obj: Any) -> str:
return html.escape(json.dumps(obj, indent=2, ensure_ascii=False, default=str))
@@ -236,6 +356,27 @@ def render_tools(tools: List[Any]) -> str:
return "\n".join(chunks) if chunks else "<p class='muted'>No renderable tools found.</p>"
+# ---------------------------------------------------------------------------
+# HTML builders
+# ---------------------------------------------------------------------------
+
+_COMMON_STYLE = """
+ body { font-family: ui-sans-serif, system-ui; margin: 24px; background: #fafafa; color: #111; }
+ .panel { background: #fff; border: 1px solid #e5e5e5; border-radius: 10px; padding: 12px; margin-bottom: 12px; }
+ .card { background: #fff; border: 1px solid #e5e5e5; border-radius: 8px; padding: 8px 12px; margin-bottom: 8px; }
+ .warn { background: #fff3f3; border-color: #ffcbcb; }
+ .tag { margin-left: 8px; font-size: 12px; color: #6b21a8; background: #f3e8ff; border: 1px solid #e9d5ff; border-radius: 999px; padding: 1px 8px; font-weight: 600; }
+ .chip { display: inline-block; margin: 4px 6px 0 0; font-size: 12px; color: #1d4ed8; background: #dbeafe; border: 1px solid #bfdbfe; border-radius: 999px; padding: 2px 8px; font-weight: 600; }
+ pre { white-space: pre-wrap; word-break: break-word; background: #f5f5f5; padding: 10px; border-radius: 8px; }
+ .muted { color: #666; }
+ summary { cursor: pointer; }
+ nav a { margin-right: 10px; }
+ .kv-table { border-collapse: collapse; margin: 8px 0; }
+ .kv-table td { padding: 4px 12px 4px 0; vertical-align: top; }
+ .kv-table td:first-child { font-weight: 600; white-space: nowrap; color: #333; }
+"""
+
+
def build_html(
agent_id: str,
preview_url: str,
@@ -294,18 +435,7 @@ def build_html(
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>Viewing Agent Context — {html.escape(agent_id)}</title>
- <style>
- body {{ font-family: ui-sans-serif, system-ui; margin: 24px; background: #fafafa; color: #111; }}
- .panel {{ background: #fff; border: 1px solid #e5e5e5; border-radius: 10px; padding: 12px; margin-bottom: 12px; }}
- .card {{ background: #fff; border: 1px solid #e5e5e5; border-radius: 8px; padding: 8px 12px; margin-bottom: 8px; }}
- .warn {{ background: #fff3f3; border-color: #ffcbcb; }}
- .tag {{ margin-left: 8px; font-size: 12px; color: #6b21a8; background: #f3e8ff; border: 1px solid #e9d5ff; border-radius: 999px; padding: 1px 8px; font-weight: 600; }}
- .chip {{ display: inline-block; margin: 4px 6px 0 0; font-size: 12px; color: #1d4ed8; background: #dbeafe; border: 1px solid #bfdbfe; border-radius: 999px; padding: 2px 8px; font-weight: 600; }}
- pre {{ white-space: pre-wrap; word-break: break-word; background: #f5f5f5; padding: 10px; border-radius: 8px; }}
- .muted {{ color: #666; }}
- summary {{ cursor: pointer; }}
- nav a {{ margin-right: 10px; }}
- </style>
+ <style>{_COMMON_STYLE}</style>
</head>
<body>
<h1>Viewing Agent Context (Preview-Only)</h1>
@@ -368,17 +498,233 @@ def build_html(
"""
+def build_step_html(
+ step_id: str,
+ trace_row: Dict[str, Any],
+ request_payload: Dict[str, Any],
+ response_payload: Dict[str, Any],
+ errors: List[str],
+) -> str:
+ """Build HTML report for a historical step fetched from ClickHouse."""
+ generated = datetime.now(timezone.utc).isoformat()
+ model = request_payload.get("model") if isinstance(request_payload, dict) else None
+ messages = extract_messages(request_payload) if isinstance(request_payload, dict) else []
+ system_text = extract_system_text(request_payload) if isinstance(request_payload, dict) else "<missing>"
+ tools = extract_tools(request_payload) if isinstance(request_payload, dict) else []
+
+ settings = {
+ "model": model or trace_row.get("model"),
+ "max_tokens": request_payload.get("max_tokens") if isinstance(request_payload, dict) else None,
+ "temperature": request_payload.get("temperature") if isinstance(request_payload, dict) else None,
+ "thinking": request_payload.get("thinking") if isinstance(request_payload, dict) else None,
+ "reasoning": request_payload.get("reasoning") if isinstance(request_payload, dict) else None,
+ "output_config": request_payload.get("output_config") if isinstance(request_payload, dict) else None,
+ "message_count": len(messages) if isinstance(messages, list) else None,
+ "tool_count": len(tools) if isinstance(tools, list) else None,
+ "top_keys": list(request_payload.keys()) if isinstance(request_payload, dict) else None,
+ }
+
+ warn_html = (
+ "<div class='panel warn'><strong>Warnings</strong><ul>" + "".join(f"<li>{html.escape(e)}</li>" for e in errors) + "</ul></div>"
+ if errors
+ else ""
+ )
+
+ # Trace metadata table
+ trace_meta = {
+ "step_id": trace_row.get("step_id", ""),
+ "agent_id": trace_row.get("agent_id", ""),
+ "organization_id": trace_row.get("organization_id", ""),
+ "run_id": trace_row.get("run_id", ""),
+ "model": trace_row.get("model", ""),
+ "provider": trace_row.get("provider", ""),
+ "call_type": trace_row.get("call_type", ""),
+ "is_byok": bool(trace_row.get("is_byok", False)),
+ "created_at": str(trace_row.get("created_at", "")),
+ }
+
+ token_stats = {
+ "prompt_tokens": trace_row.get("prompt_tokens", 0),
+ "completion_tokens": trace_row.get("completion_tokens", 0),
+ "total_tokens": trace_row.get("total_tokens", 0),
+ "cached_input_tokens": trace_row.get("cached_input_tokens"),
+ "cache_write_tokens": trace_row.get("cache_write_tokens"),
+ "reasoning_tokens": trace_row.get("reasoning_tokens"),
+ "latency_ms": trace_row.get("latency_ms", 0),
+ "request_size_bytes": trace_row.get("request_size_bytes", 0),
+ "response_size_bytes": trace_row.get("response_size_bytes", 0),
+ }
+
+ error_info = {}
+ if trace_row.get("is_error"):
+ error_info = {
+ "is_error": True,
+ "error_type": trace_row.get("error_type", ""),
+ "error_message": trace_row.get("error_message", ""),
+ }
+
+ def _kv_table(d: Dict[str, Any]) -> str:
+ rows = []
+ for k, v in d.items():
+ val_str = html.escape(str(v)) if v is not None else "<span class='muted'>null</span>"
+ rows.append(f"<tr><td>{html.escape(str(k))}</td><td><code>{val_str}</code></td></tr>")
+ return "<table class='kv-table'>" + "".join(rows) + "</table>"
+
+ error_section = ""
+ if error_info:
+ error_section = f"""
+ <section class='panel warn'>
+ <h2>Error</h2>
+ {_kv_table(error_info)}
+ </section>"""
+
+ # LLM config from trace
+ llm_config_raw = trace_row.get("llm_config_json", "")
+ llm_config = _parse_json_str(llm_config_raw) if llm_config_raw else {}
+ llm_config_html = esc_json(llm_config) if llm_config else "<span class='muted'>No LLM config recorded.</span>"
+
+ title_id = html.escape(step_id[:40])
+
+ return f"""<!doctype html>
+<html lang='en'>
+<head>
+ <meta charset='utf-8'>
+ <meta name='viewport' content='width=device-width, initial-scale=1'>
+ <title>Viewing Step Context — {title_id}</title>
+ <style>{_COMMON_STYLE}</style>
+</head>
+<body>
+ <h1>Viewing Step Context (Historical — ClickHouse)</h1>
+ <p class='muted'>Generated: {html.escape(generated)} | Step: <code>{html.escape(step_id)}</code></p>
+
+ {warn_html}
+
+ <nav class='panel'>
+ <a href='#trace'>Trace metadata</a>
+ <a href='#tokens'>Token usage</a>
+ <a href='#settings'>Request settings</a>
+ <a href='#system'>System</a>
+ <a href='#messages'>Messages</a>
+ <a href='#tools'>Tools</a>
+ <a href='#response'>Response</a>
+ <a href='#raw'>Raw JSON</a>
+ </nav>
+
+ <section id='trace' class='panel'>
+ <h2>Trace Metadata</h2>
+ {_kv_table(trace_meta)}
+ </section>
+
+ <section id='tokens' class='panel'>
+ <h2>Token Usage</h2>
+ {_kv_table(token_stats)}
+ </section>
+ {error_section}
+
+ <section id='settings' class='panel'>
+ <h2>Request Settings</h2>
+ <pre>{esc_json(settings)}</pre>
+ <h3 style='margin-top: 12px;'>LLM Config</h3>
+ <pre>{llm_config_html}</pre>
+ </section>
+
+ <section id='system' class='panel'>
+ <h2>System Prompt</h2>
+ <pre>{html.escape(system_text)}</pre>
+ </section>
+
+ <section id='messages' class='panel'>
+ <h2>Messages</h2>
+ {render_messages(messages)}
+ </section>
+
+ <section id='tools' class='panel'>
+ <h2>Tools / Functions</h2>
+ {render_tools(tools)}
+ </section>
+
+ <section id='response' class='panel'>
+ <h2>Response Payload</h2>
+ <pre>{esc_json(response_payload)}</pre>
+ </section>
+
+ <section id='raw' class='panel'>
+ <h2>Full Request Payload JSON</h2>
+ <pre>{esc_json(request_payload)}</pre>
+ </section>
+</body>
+</html>
+"""
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+
def main() -> int:
- parser = argparse.ArgumentParser(description="Generate a human-readable context report from preview-raw-payload only.")
- parser.add_argument("--agent-id", required=True)
+ parser = argparse.ArgumentParser(
+ description="Generate a human-readable context report from preview-raw-payload (live) or ClickHouse llm_traces (historical)."
+ )
+
+ # Mode selection: exactly one of --agent-id or --step-id
+ mode = parser.add_mutually_exclusive_group(required=True)
+ mode.add_argument("--agent-id", help="Live mode: fetch preview-raw-payload for this agent")
+ mode.add_argument("--step-id", help="Historical mode: fetch request/response from ClickHouse for this step_id")
+
+ # Live-mode options
parser.add_argument("--server-url", default=os.getenv("LETTA_SERVER_URL") or "http://127.0.0.1:8283")
parser.add_argument("--api-key", default=os.getenv("LETTA_API_KEY"))
parser.add_argument("--input", default="show me the exact context payload")
parser.add_argument("--max-steps", type=int, default=1)
+
+ # ClickHouse options
+ parser.add_argument("--env-file", help="Path to .env file with CLICKHOUSE_URL, CLICKHOUSE_USER, CLICKHOUSE_PASSWORD")
+
+ # Common
parser.add_argument("--timeout", type=float, default=45.0)
parser.add_argument("--out", default=None)
+
args = parser.parse_args()
+ # -----------------------------------------------------------------------
+ # Historical mode (--step-id)
+ # -----------------------------------------------------------------------
+ if args.step_id:
+ errors: List[str] = []
+ try:
+ trace_row = query_step_from_clickhouse(args.step_id, args.env_file)
+ except Exception as e:
+ print(f"ClickHouse query failed: {e}", file=sys.stderr)
+ return 1
+
+ request_payload = _parse_json_str(trace_row.get("request_json"))
+ response_payload = _parse_json_str(trace_row.get("response_json"))
+
+ if not request_payload:
+ errors.append("request_json was empty or unparseable")
+ if not response_payload:
+ errors.append("response_json was empty or unparseable")
+
+ out = Path(args.out).expanduser() if args.out else Path.home() / ".letta" / "viewers" / f"viewing-step-context-{args.step_id}.html"
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(
+ build_step_html(args.step_id, trace_row, request_payload, response_payload, errors),
+ encoding="utf-8",
+ )
+
+ print(f"Generated: {out}")
+ if errors:
+ print("Warnings:")
+ for e in errors:
+ print(f" - {e}")
+ else:
+ print(f"Trace fetched successfully (model={trace_row.get('model')}, created_at={trace_row.get('created_at')}).")
+ return 0
+
+ # -----------------------------------------------------------------------
+ # Live mode (--agent-id)
+ # -----------------------------------------------------------------------
server = args.server_url.rstrip("/")
preview_url = f"{server}/v1/agents/{args.agent_id}/messages/preview-raw-payload"
agent_url = f"{server}/v1/agents/{args.agent_id}"
@@ -390,7 +736,7 @@ def main() -> int:
if args.api_key:
headers["Authorization"] = f"Bearer {args.api_key}"
- errors: List[str] = []
+ errors = []
payload, err = post_json(preview_url, headers, {"input": args.input, "max_steps": args.max_steps}, args.timeout)
if err:
diff --git a/letta/agents/letta_agent_v2.py b/letta/agents/letta_agent_v2.py
index d5f93dc35..7dd1ff502 100644
--- a/letta/agents/letta_agent_v2.py
+++ b/letta/agents/letta_agent_v2.py
@@ -804,18 +804,32 @@ class LettaAgentV2(BaseAgentV2):
# Compile the new skills section from agent blocks + client skills
new_skills = self.agent_state.memory.compile_available_skills(client_skills=self.client_skills)
- # Replace existing <available_skills>...</available_skills> if present
- pattern = re.compile(r"\n*<available_skills>.*?</available_skills>", re.DOTALL)
- if pattern.search(old_text):
- new_text = pattern.sub(new_skills, old_text)
+ # Replace the STRUCTURAL <available_skills>...</available_skills> block.
+ #
+ # Memory block content may contain literal <available_skills> and
+ # </available_skills> text references (e.g. docs about the skills system).
+ # A regex approach cannot reliably distinguish structural tags from text
+ # references because non-greedy matches absorb the structural closing tag.
+ #
+ # Instead we locate the structural block by position: it is always rendered
+ # AFTER the last </system/...> memory block closing tag. We find the
+ # <available_skills> that starts after that boundary using plain string search.
+ block_close_pattern = re.compile(r"</system/[^>]+>")
+ block_closes = list(block_close_pattern.finditer(old_text))
+ search_from = block_closes[-1].end() if block_closes else 0
+
+ skills_open = old_text.find("<available_skills>", search_from)
+ skills_close = old_text.find("</available_skills>", skills_open) if skills_open >= 0 else -1
+
+ if skills_open >= 0 and skills_close >= 0:
+ # Consume leading newlines before the tag
+ trim_start = skills_open
+ while trim_start > 0 and old_text[trim_start - 1] == "\n":
+ trim_start -= 1
+ new_text = old_text[:trim_start] + new_skills + old_text[skills_close + len("</available_skills>") :]
elif new_skills:
- # No existing skills section — insert after </memory_filesystem> if present
- if "</memory_filesystem>" in old_text:
- new_text = old_text.replace("</memory_filesystem>", "</memory_filesystem>" + new_skills)
- else:
- # Fallback: insert before <memory_metadata>
- # Strip leading newlines from new_skills to avoid doubling up with
- # the existing whitespace before <memory_metadata>.
+ # No existing skills section — insert right before <memory_metadata>
+ if "<memory_metadata>" in old_text:
new_text = old_text.replace("<memory_metadata>", new_skills.lstrip("\n") + "\n\n<memory_metadata>")
else:
return in_context_messages
diff --git a/letta/schemas/memory.py b/letta/schemas/memory.py
index 111321dea..60428fb8a 100644
--- a/letta/schemas/memory.py
+++ b/letta/schemas/memory.py
@@ -373,11 +373,6 @@ class Memory(BaseModel, validate_assignment=True):
_render_tree(tree)
s.write("</memory_filesystem>")
- # Render explicit skill metadata block (agent-scoped + client-provided).
- skills_str = self.compile_available_skills(client_skills=client_skills)
- if skills_str:
- s.write(skills_str)
-
def compile_available_skills(self, client_skills=None) -> str:
"""Render the <available_skills> block from agent-scoped and client-provided skills.
@@ -564,6 +559,16 @@ class Memory(BaseModel, validate_assignment=True):
else:
self._render_memory_blocks_standard(s)
+ # Render <available_skills> AFTER all memory blocks so it appears
+ # at the end of the memory section (right before <memory_metadata>).
+ # This prevents the surgical regex replacement in
+ # _update_system_message_skills() from accidentally matching literal
+ # <available_skills> text references inside memory block content.
+ if self.git_enabled:
+ skills_str = self.compile_available_skills(client_skills=client_skills)
+ if skills_str:
+ s.write(skills_str)
+
if tool_usage_rules is not None:
desc = getattr(tool_usage_rules, "description", None) or ""
val = getattr(tool_usage_rules, "value", None) or ""
diff --git a/tests/test_memory.py b/tests/test_memory.py
index 23fffb3cf..e4f5fb6b5 100644
--- a/tests/test_memory.py
+++ b/tests/test_memory.py
@@ -463,6 +463,140 @@ def test_compile_available_skills_standalone():
assert m_empty.compile_available_skills(client_skills=[]) == ""
+def test_compile_git_skills_rendered_after_all_blocks():
+ """<available_skills> must appear AFTER all memory block closing tags.
+
+ Regression test: previously skills were rendered inside _render_memory_filesystem()
+ (right after </memory_filesystem>) which placed them BEFORE the memory blocks.
+ The surgical regex in _update_system_message_skills() could then match literal
+ <available_skills> text references inside block content and destroy intervening blocks.
+ """
+ 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=500),
+ Block(
+ label="system/project/notes",
+ value="The `<available_skills>` section is rendered after `</memory_filesystem>`.",
+ limit=500,
+ description="Notes that reference <available_skills> as literal text.",
+ ),
+ Block(label="system/persona", value="persona data", limit=500),
+ ],
+ )
+
+ client_skills = [
+ ClientSkillSchema(name="test-skill", description="A test skill.", location="skills/test-skill/SKILL.md"),
+ ]
+
+ out = m.compile(client_skills=client_skills)
+
+ # All three blocks must be present with proper open+close tags
+ assert "<system/human.md>" in out
+ assert "</system/human.md>" in out
+ assert "<system/project/notes.md>" in out
+ assert "</system/project/notes.md>" in out
+ assert "<system/persona.md>" in out
+ assert "</system/persona.md>" in out
+
+ # The structural <available_skills> block must appear AFTER the last block's closing tag
+ last_block_close = max(out.find("</system/human.md>"), out.find("</system/project/notes.md>"), out.find("</system/persona.md>"))
+ skills_start = out.rfind("<available_skills>")
+ assert skills_start > last_block_close, "<available_skills> should render after all memory block closing tags"
+
+
+def test_surgical_skills_update_preserves_blocks_with_literal_skills_text():
+ """Simulates _update_system_message_skills() regex on a prompt where block content
+ contains literal <available_skills> and </available_skills> text references.
+
+ Regression test: pattern.sub() without count=1 replaced ALL matches, which
+ could span from a literal text reference in one block to another, destroying
+ all blocks in between.
+ """
+ import re
+
+ from letta.schemas.letta_request import ClientSkillSchema
+
+ # Build a system prompt with blocks that contain literal skills XML text
+ m = Memory(
+ agent_type=AgentType.letta_v1_agent,
+ git_enabled=True,
+ blocks=[
+ Block(label="system/human", value="human data", limit=500),
+ Block(
+ label="system/project/workflow",
+ value=(
+ "Structured MemFS rendering: flat top-level sections;\n"
+ "`<core_memory>`, `<archival_memory>`, `<available_skills>`;\n"
+ "`path` -> `location`; `ClientSkillSchema` on `LettaRequest`"
+ ),
+ limit=1000,
+ description="Workflow notes.",
+ ),
+ Block(
+ label="system/project/architecture",
+ value=(
+ "`compile_available_skills()` returns the `<available_skills>...</available_skills>` string.\n"
+ "`_update_system_message_skills()` regex replaces only the `<available_skills>` XML block."
+ ),
+ limit=1000,
+ description="Architecture notes.",
+ ),
+ Block(label="system/persona", value="persona data", limit=500),
+ ],
+ )
+
+ client_skills = [
+ ClientSkillSchema(name="test-skill", description="A test skill.", location="skills/test-skill/SKILL.md"),
+ ]
+
+ old_text = m.compile(client_skills=client_skills)
+
+ # Verify the prompt has both literal text references AND the structural block
+ assert old_text.count("<available_skills>") >= 2, "Expected literal text refs + structural block"
+
+ # Simulate the surgical update (same logic as _update_system_message_skills):
+ # find the structural <available_skills> by position — after all </system/...> tags.
+ new_skills = m.compile_available_skills(client_skills=client_skills)
+
+ block_close_pattern = re.compile(r"</system/[^>]+>")
+ block_closes = list(block_close_pattern.finditer(old_text))
+ last_block_end = block_closes[-1].end() if block_closes else 0
+
+ skills_open = old_text.find("<available_skills>", last_block_end)
+ skills_close = old_text.find("</available_skills>", skills_open) if skills_open >= 0 else -1
+ assert skills_open >= 0 and skills_close >= 0, "Should find structural <available_skills> after all blocks"
+
+ trim_start = skills_open
+ while trim_start > 0 and old_text[trim_start - 1] == "\n":
+ trim_start -= 1
+ new_text = old_text[:trim_start] + new_skills + old_text[skills_close + len("</available_skills>") :]
+
+ # ALL blocks must survive the replacement
+ assert "<system/human.md>" in new_text
+ assert "</system/human.md>" in new_text
+ assert "<system/project/workflow.md>" in new_text
+ assert "</system/project/workflow.md>" in new_text
+ assert "<system/project/architecture.md>" in new_text
+ assert "</system/project/architecture.md>" in new_text
+ assert "<system/persona.md>" in new_text
+ assert "</system/persona.md>" in new_text
+
+ # Block content with literal text references must be preserved
+ assert "`<available_skills>`" in new_text
+ assert "`<available_skills>...</available_skills>`" in new_text
+
+ # The structural <available_skills> block must still be present at the end
+ structural_start = new_text.rfind("<available_skills>")
+ structural_end = new_text.rfind("</available_skills>")
+ assert structural_start > 0
+ assert structural_end > structural_start
+ assert "<name>test-skill</name>" in new_text[structural_start:structural_end]
+
+
def test_compile_git_structured_recompile_after_block_edit():
"""Editing a block value should produce a different compile() output.