Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: extend memory_apply_patch for memory block create and delete (#8832)
Kevin Lin8872c2b5d32e
diff --git a/letta/functions/function_sets/base.py b/letta/functions/function_sets/base.pyindex f1318875a..02db2c208 100644--- a/letta/functions/function_sets/base.py+++ b/letta/functions/function_sets/base.py@@ -464,51 +464,35 @@ def memory_insert(agent_state: "AgentState", label: str, new_str: str, insert_lidef memory_apply_patch(agent_state: "AgentState", label: str, patch: str) -> str: # type: ignore"""- Apply a unified-diff style patch to a memory block by anchoring on content and context (not line numbers).-- The patch format is a simplified unified diff that supports one or more hunks. Each hunk may optionally- start with a line beginning with `@@` and then contains lines that begin with one of:- - " " (space): context lines that must match the current memory content- - "-": lines to remove (must match exactly in the current content)- - "+": lines to add-- Notes:- - Do not include line number prefixes like "Line 12:" anywhere in the patch. Line numbers are for display only.+ Apply a simplified unified-diff style patch to one or more memory blocks.++ Backwards compatible behavior:+ - If `patch` contains no "***" headers, it applies the patch to the single memory block+ identified by `label`.++ Extended, codex-style behavior (multi-block):+ - `*** Add Block: <label>`+ - Optional next line: `Description: <text>`+ - File contents are given by subsequent lines starting with `+`+ - `*** Delete Block: <label>`+ - `*** Update Block: <label>`+ - Patch body is the same simplified unified diff format (lines start with " ", "-", "+")+ - Optional "@@" lines can be used to delimit hunks+ - `*** Move to: <new_label>`+ - Renames the most recent block referenced by an Add/Update/Delete header++ - Do not include line number prefixes like "12→" anywhere in the patch. Line numbers are for display only.- Do not include the line-number warning banner. Provide only the text to edit.- Tabs are normalized to spaces for matching consistency.Args:- label (str): The memory block to edit, identified by its label.- patch (str): The simplified unified-diff patch text composed of context (" "), deletion ("-"), and addition ("+") lines. Optional- lines beginning with "@@" can be used to delimit hunks. Do not include visual line numbers or warning banners.-- Examples:- Simple replacement:- label="human",- patch:- @@- -Their name is Alice- +Their name is Bob-- Replacement with surrounding context for disambiguation:- label="persona",- patch:- @@- Persona:- -Friendly and curious- +Friendly, curious, and precise- Likes: Hiking-- Insertion (no deletions) between two context lines:- label="todos",- patch:- @@- - [ ] Step 1: Gather requirements- + [ ] Step 1.5: Clarify stakeholders- - [ ] Step 2: Draft design+ label (str): The label of the memory block to patch. Required for single-block mode (when patch contains no "***" headers). Set to empty string "" when using multi-block mode with "*** Add Block:", "*** Delete Block:", or "*** Update Block:" headers.+ patch (str): The unified diff-style patch to apply. Can be either: (1) a simple unified diff for single-block mode, or (2) a multi-block patch with "***" headers for creating, deleting, updating, or renaming multiple blocks.Returns:str: A success message if the patch applied cleanly; raises ValueError otherwise.++"""raise NotImplementedError("This should never be invoked directly. Contact Letta if you see this error message.")diff --git a/letta/services/tool_executor/core_tool_executor.py b/letta/services/tool_executor/core_tool_executor.pyindex 5688bcad1..a8d0edfce 100644--- a/letta/services/tool_executor/core_tool_executor.py+++ b/letta/services/tool_executor/core_tool_executor.py@@ -414,17 +414,18 @@ class LettaCoreToolExecutor(ToolExecutor):return success_msgasync def memory_apply_patch(self, agent_state: AgentState, actor: User, label: str, patch: str) -> str:- """Apply a simplified unified-diff style patch to a memory block, anchored on content and context.+ """Apply a simplified unified-diff style patch to one or more memory blocks.- Args:- label: The memory block label to modify.- patch: Patch text with lines starting with " ", "-", or "+" and optional "@@" hunk headers.+ Backwards compatible behavior:+ - If `patch` contains no "***" headers, this behaves like the legacy implementation and+ applies the patch to the single memory block identified by `label`.- Returns:- Success message on clean application; raises ValueError on mismatch/ambiguity.+ Extended, codex-style behavior (multi-block):+ - `*** Add Block: <label>` (+ lines become initial content; optional `Description:` header)+ - `*** Delete Block: <label>`+ - `*** Update Block: <label>` (apply unified-diff hunks to that block)+ - `*** Move to: <new_label>` (rename the most recent block in the patch)"""- if agent_state.memory.get_block(label).read_only:- raise ValueError(f"{READ_ONLY_BLOCK_EDIT_ERROR}")# Guardrails: forbid visual line numbers and warning bannersif MEMORY_TOOLS_LINE_NUMBER_PREFIX_REGEX.search(patch or ""):@@ -434,94 +435,263 @@ class LettaCoreToolExecutor(ToolExecutor):if CORE_MEMORY_LINE_NUMBER_WARNING in (patch or ""):raise ValueError("Patch contains the line number warning banner, which is not allowed. Provide only the text to edit.")- current_value = str(agent_state.memory.get_block(label).value).expandtabs()patch = str(patch).expandtabs()- current_lines = current_value.split("\n")- # Ignore common diff headers- raw_lines = patch.splitlines()- patch_lines = [ln for ln in raw_lines if not ln.startswith("*** ") and not ln.startswith("---") and not ln.startswith("+++")]-- # Split into hunks using '@@' as delimiter- hunks: list[list[str]] = []- h: list[str] = []- for ln in patch_lines:- if ln.startswith("@@"):- if h:- hunks.append(h)- h = []+ def normalize_label_to_path(lbl: str) -> str:+ # Keep consistent with other memory tool path parsing+ return f"/memories/{lbl.strip()}"++ def apply_unified_patch_to_value(current_value: str, patch_text: str) -> str:+ current_value = str(current_value).expandtabs()+ patch_text = str(patch_text).expandtabs()++ current_lines = current_value.split("\n")++ # Ignore common diff headers+ raw_lines = patch_text.splitlines()+ patch_lines = [ln for ln in raw_lines if not ln.startswith("*** ") and not ln.startswith("---") and not ln.startswith("+++")]++ # Split into hunks using '@@' as delimiter+ hunks: list[list[str]] = []+ h: list[str] = []+ for ln in patch_lines:+ if ln.startswith("@@"):+ if h:+ hunks.append(h)+ h = []+ continue+ if ln.startswith(" ") or ln.startswith("-") or ln.startswith("+"):+ h.append(ln)+ elif ln.strip() == "":+ # Treat blank line as context for empty string line+ h.append(" ")+ else:+ # Skip unknown metadata lines+ continue+ if h:+ hunks.append(h)++ if not hunks:+ raise ValueError("No applicable hunks found in patch. Ensure lines start with ' ', '-', or '+'.")++ def find_all_subseq(hay: list[str], needle: list[str]) -> list[int]:+ out: list[int] = []+ n = len(needle)+ if n == 0:+ return out+ for i in range(0, len(hay) - n + 1):+ if hay[i : i + n] == needle:+ out.append(i)+ return out++ # Apply each hunk sequentially against the rolling buffer+ for hunk in hunks:+ expected: list[str] = []+ replacement: list[str] = []+ for ln in hunk:+ if ln.startswith(" "):+ line = ln[1:]+ expected.append(line)+ replacement.append(line)+ elif ln.startswith("-"):+ line = ln[1:]+ expected.append(line)+ elif ln.startswith("+"):+ line = ln[1:]+ replacement.append(line)++ if not expected and replacement:+ # Pure insertion with no context: append at end+ current_lines = current_lines + replacement+ continue++ matches = find_all_subseq(current_lines, expected)+ if len(matches) == 0:+ sample = "\n".join(expected[:4])+ raise ValueError(+ "Failed to apply patch: expected hunk context not found in the memory block. "+ f"Verify the target lines exist and try providing more context. Expected start:\n{sample}"+ )+ if len(matches) > 1:+ raise ValueError(+ "Failed to apply patch: hunk context matched multiple places in the memory block. "+ "Please add more unique surrounding context to disambiguate."+ )++ idx = matches[0]+ end = idx + len(expected)+ current_lines = current_lines[:idx] + replacement + current_lines[end:]++ return "\n".join(current_lines)++ def is_extended_patch(patch_text: str) -> bool:+ return any(+ ln.startswith("*** Add Block:")+ or ln.startswith("*** Delete Block:")+ or ln.startswith("*** Update Block:")+ or ln.startswith("*** Move to:")+ for ln in patch_text.splitlines()+ )++ # Legacy mode: patch targets the provided `label`+ if not is_extended_patch(patch):+ try:+ memory_block = agent_state.memory.get_block(label)+ except KeyError:+ raise ValueError(f"Error: Memory block '{label}' does not exist")++ if memory_block.read_only:+ raise ValueError(f"{READ_ONLY_BLOCK_EDIT_ERROR}")++ new_value = apply_unified_patch_to_value(str(memory_block.value), patch)+ agent_state.memory.update_block_value(label=label, value=new_value)+ await self.agent_manager.update_memory_if_changed_async(agent_id=agent_state.id, new_memory=agent_state.memory, actor=actor)++ return (+ f"The core memory block with label `{label}` has been edited. "+ "Review the changes and make sure they are as expected (correct indentation, no duplicate lines, etc). "+ "Edit the memory block again if necessary."+ )++ # Extended mode: parse codex-like patch operations for memory blocks+ lines = patch.splitlines()+ i = 0+ actions: list[dict] = []+ current_action: Optional[dict] = None+ last_action_label: Optional[str] = None++ def flush_action():+ nonlocal current_action, actions+ if current_action is not None:+ actions.append(current_action)+ current_action = None++ while i < len(lines):+ ln = lines[i]++ if ln.startswith("*** Add Block:"):+ flush_action()+ target_label = ln.split(":", 1)[1].strip()+ if not target_label:+ raise ValueError("*** Add Block: must specify a non-empty label")+ current_action = {"kind": "add", "label": target_label, "description": "", "content_lines": []}+ last_action_label = target_label+ i += 1+ # Optional description header: Description: ... (single-line)+ if i < len(lines) and lines[i].startswith("Description:"):+ current_action["description"] = lines[i].split(":", 1)[1].strip()+ i += 1continue- if ln.startswith(" ") or ln.startswith("-") or ln.startswith("+"):- h.append(ln)- elif ln.strip() == "":- # Treat blank line as context for empty string line- h.append(" ")- else:- # Skip unknown metadata lines++ if ln.startswith("*** Delete Block:"):+ flush_action()+ target_label = ln.split(":", 1)[1].strip()+ if not target_label:+ raise ValueError("*** Delete Block: must specify a non-empty label")+ actions.append({"kind": "delete", "label": target_label})+ last_action_label = target_label+ i += 1continue- if h:- hunks.append(h)- if not hunks:- raise ValueError("No applicable hunks found in patch. Ensure lines start with ' ', '-', or '+'.")+ if ln.startswith("*** Update Block:"):+ flush_action()+ target_label = ln.split(":", 1)[1].strip()+ if not target_label:+ raise ValueError("*** Update Block: must specify a non-empty label")+ current_action = {"kind": "update", "label": target_label, "patch_lines": []}+ last_action_label = target_label+ i += 1+ continue- def find_all_subseq(hay: list[str], needle: list[str]) -> list[int]:- out: list[int] = []- n = len(needle)- if n == 0:- return out- for i in range(0, len(hay) - n + 1):- if hay[i : i + n] == needle:- out.append(i)- return out-- # Apply each hunk sequentially against the rolling buffer- for hunk in hunks:- expected: list[str] = []- replacement: list[str] = []- for ln in hunk:- if ln.startswith(" "):- line = ln[1:]- expected.append(line)- replacement.append(line)- elif ln.startswith("-"):- line = ln[1:]- expected.append(line)- elif ln.startswith("+"):- line = ln[1:]- replacement.append(line)-- if not expected and replacement:- # Pure insertion with no context: append at end- current_lines = current_lines + replacement+ if ln.startswith("*** Move to:"):+ new_label = ln.split(":", 1)[1].strip()+ if not new_label:+ raise ValueError("*** Move to: must specify a non-empty new label")+ if last_action_label is None:+ raise ValueError("*** Move to: must follow an Add/Update/Delete header")+ actions.append({"kind": "rename", "old_label": last_action_label, "new_label": new_label})+ last_action_label = new_label+ i += 1continue- matches = find_all_subseq(current_lines, expected)- if len(matches) == 0:- sample = "\n".join(expected[:4])- raise ValueError(- "Failed to apply patch: expected hunk context not found in the memory block. "- f"Verify the target lines exist and try providing more context. Expected start:\n{sample}"+ # Collect body lines for current action+ if current_action is not None:+ if current_action["kind"] == "add":+ if ln.startswith("+"):+ current_action["content_lines"].append(ln[1:])+ elif ln.strip() == "":+ current_action["content_lines"].append("")+ else:+ # ignore unknown metadata lines+ pass+ elif current_action["kind"] == "update":+ current_action["patch_lines"].append(ln)+ i += 1+ continue++ # Otherwise ignore unrelated lines (e.g. leading @@ markers)+ i += 1++ flush_action()++ if not actions:+ raise ValueError("No operations found. Provide at least one of: *** Add Block, *** Delete Block, *** Update Block.")++ results: list[str] = []+ for action in actions:+ kind = action["kind"]++ if kind == "add":+ try:+ existing = agent_state.memory.get_block(action["label"])+ # If we get here, the block exists+ raise ValueError(f"Error: Memory block '{action['label']}' already exists")+ except KeyError:+ # Block doesn't exist, which is what we want for adding+ pass++ content = "\n".join(action["content_lines"]).rstrip("\n")+ await self.memory_create(+ agent_state,+ actor,+ path=normalize_label_to_path(action["label"]),+ description=action.get("description", ""),+ file_text=content,)- if len(matches) > 1:- raise ValueError(- "Failed to apply patch: hunk context matched multiple places in the memory block. "- "Please add more unique surrounding context to disambiguate."+ results.append(f"Created memory block '{action['label']}'")++ elif kind == "delete":+ await self.memory_delete(agent_state, actor, path=normalize_label_to_path(action["label"]))+ results.append(f"Deleted memory block '{action['label']}'")++ elif kind == "rename":+ await self.memory_rename(+ agent_state,+ actor,+ old_path=normalize_label_to_path(action["old_label"]),+ new_path=normalize_label_to_path(action["new_label"]),)+ results.append(f"Renamed memory block '{action['old_label']}' to '{action['new_label']}'")- idx = matches[0]- end = idx + len(expected)- current_lines = current_lines[:idx] + replacement + current_lines[end:]+ elif kind == "update":+ try:+ memory_block = agent_state.memory.get_block(action["label"])+ except KeyError:+ raise ValueError(f"Error: Memory block '{action['label']}' does not exist")- new_value = "\n".join(current_lines)- agent_state.memory.update_block_value(label=label, value=new_value)- await self.agent_manager.update_memory_if_changed_async(agent_id=agent_state.id, new_memory=agent_state.memory, actor=actor)+ if memory_block.read_only:+ raise ValueError(f"{READ_ONLY_BLOCK_EDIT_ERROR}")- return (- f"The core memory block with label `{label}` has been edited. "- "Review the changes and make sure they are as expected (correct indentation, no duplicate lines, etc). "- "Edit the memory block again if necessary."- )+ patch_text = "\n".join(action["patch_lines"])+ new_value = apply_unified_patch_to_value(str(memory_block.value), patch_text)+ agent_state.memory.update_block_value(label=action["label"], value=new_value)+ await self.agent_manager.update_memory_if_changed_async(agent_id=agent_state.id, new_memory=agent_state.memory, actor=actor)+ results.append(f"Updated memory block '{action['label']}'")++ else:+ raise ValueError(f"Unknown operation kind: {kind}")++ return "Successfully applied memory patch operations:\n- " + "\n- ".join(results)async def memory_insert(self,