Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions anton/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -1149,7 +1149,7 @@ def _bottom_toolbar():
complete_while_typing=True,
)

memory_manage = MemoryManage(console, settings, cortex, episodic=episodic)
memory_manage = MemoryManage(console, settings, cortex, episodic=episodic, history_store=history_store)
try:
while True:
# Memory confirmation UX — show pending lessons before prompt
Expand Down Expand Up @@ -1281,7 +1281,7 @@ def _bottom_toolbar():
)
continue
elif cmd == "/memory":
await memory_manage.handle(cmd=stripped)
await memory_manage.handle(cmd=stripped, session=session)
continue
elif cmd == "/connect":
arg = parts[1].strip() if len(parts) > 1 else ""
Expand Down
66 changes: 3 additions & 63 deletions anton/commands/share.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
"""Slash-command handlers for /share."""
from __future__ import annotations

import ast
import getpass
import json
import os
import re
import tempfile
import uuid
from dataclasses import asdict
from datetime import datetime, timezone
from pathlib import Path
Expand Down Expand Up @@ -344,66 +342,6 @@ def handle_share_history(
# ── import ────────────────────────────────────────────────────────────────────


def _episodic_to_api_history(episodes: list[dict]) -> list[dict]:
"""Convert episodic episode list to Anthropic API message format for HistoryStore.

Processes episodes sequentially:
user -> {"role":"user","content":text}
tool_call -> {"role":"assistant","content":[tool_use block]} (generates id)
scratchpad -> skipped (content captured in tool_result)
tool_result -> {"role":"user","content":[tool_result block]} (uses id from preceding tool_call)
assistant -> {"role":"assistant","content":text}
"""
history: list[dict] = []
i = 0
while i < len(episodes):
ep = episodes[i]
role = ep.get("role", "")

if role == "user":
history.append({"role": "user", "content": ep["content"]})
i += 1

elif role == "tool_call":
tool_id = f"toolu_{uuid.uuid4().hex[:24]}"
tool_name = ep.get("meta", {}).get("tool", "unknown")
content_str = ep.get("content", "{}")
try:
tool_input = json.loads(content_str)
except Exception:
try:
tool_input = ast.literal_eval(content_str)
except Exception:
tool_input = {"raw": content_str}

history.append({
"role": "assistant",
"content": [{"type": "tool_use", "id": tool_id, "name": tool_name, "input": tool_input}],
})
i += 1

# Skip optional scratchpad episode
if i < len(episodes) and episodes[i].get("role") == "scratchpad":
i += 1

# Consume matching tool_result
if i < len(episodes) and episodes[i].get("role") == "tool_result":
history.append({
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": tool_id, "content": episodes[i]["content"]}],
})
i += 1

elif role == "assistant":
history.append({"role": "assistant", "content": ep["content"]})
i += 1

else:
i += 1

return history


async def import_v0_1(
console: Console,
session: "ChatSession",
Expand Down Expand Up @@ -451,7 +389,9 @@ async def import_v0_1(
episodic.log(ep)

# reconstruct API history and save to history_store
api_history = _episodic_to_api_history(raw_history)
from anton.memory.history_store import HistoryStore

api_history = HistoryStore.episodes_to_api_history(raw_history)
if history_store and new_session_id:
history_store.save(new_session_id, api_history)

Expand Down
44 changes: 24 additions & 20 deletions anton/core/memory/episodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ def enabled(self) -> bool:
def enabled(self, value: bool) -> None:
self._enabled = value

@property
def session_id(self) -> str | None:
return self._session_id

def start_session(self) -> str:
"""Create a new JSONL file for this session and return the session ID."""
now = datetime.now(timezone.utc)
Expand Down Expand Up @@ -200,33 +204,33 @@ def recall(

return matches

def get_episodes(self) -> list[Episode]:
"""Return all episodes across all sessions, newest-first."""
if not self._dir.is_dir():
return []
result = []
for path in sorted(self._dir.glob("*.jsonl"), reverse=True):
try:
for line in path.read_text(encoding="utf-8").splitlines():
if line.strip():
ep = Episode(**json.loads(line))
if ep.role not in ("memory_read", "memory_write"):
result.append(ep)
except Exception:
continue
return result

def get_conversation(self) -> list[Episode]:
"""Yield conversation episodes for the current session (excludes memory entries)."""
for ep in self.get_items():
if ep.role not in ["memory_write", "memory_read"]:
yield ep

def del_episode(self, session_id: str) -> bool:
path = self._dir / f"{session_id}.jsonl"
if not path.is_file():
def del_episode_entry(self, turn: int) -> bool:
"""Remove all episode lines for *turn* from the current session file."""
if self._file is None or not self._file.is_file():
return False
kept = []
removed = 0
for line in self._file.read_text(encoding="utf-8").splitlines(keepends=True):
if not line.strip():
kept.append(line)
continue
try:
ep = Episode(**json.loads(line))
if ep.turn == turn:
removed += 1
continue
except Exception:
pass
kept.append(line)
if removed == 0:
return False
path.unlink()
self._file.write_text("".join(kept), encoding="utf-8")
return True

def recall_formatted(
Expand Down
80 changes: 80 additions & 0 deletions anton/memory/history_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@

from __future__ import annotations

import ast
import json
import os
import tempfile
import uuid
from datetime import datetime, timezone
from pathlib import Path

from typing import TYPE_CHECKING

if TYPE_CHECKING:
from anton.core.memory.episodes import EpisodicMemory


class HistoryStore:
"""Persist and retrieve full chat history for session resume."""
Expand Down Expand Up @@ -56,6 +63,79 @@ def load(self, session_id: str) -> list[dict] | None:
except Exception:
return None

@staticmethod
def episodes_to_api_history(episodes: list[dict]) -> list[dict]:
"""Convert episodic episode list to Anthropic API message format for HistoryStore.

Processes episodes sequentially:
user -> {"role":"user","content":text}
tool_call -> {"role":"assistant","content":[tool_use block]} (generates id)
scratchpad -> skipped (content captured in tool_result)
tool_result -> {"role":"user","content":[tool_result block]} (uses id from preceding tool_call)
assistant -> {"role":"assistant","content":text}
"""
history: list[dict] = []
i = 0
while i < len(episodes):
ep = episodes[i]
role = ep.get("role", "")

if role == "user":
history.append({"role": "user", "content": ep["content"]})
i += 1

elif role == "tool_call":
tool_id = f"toolu_{uuid.uuid4().hex[:24]}"
tool_name = ep.get("meta", {}).get("tool", "unknown")
content_str = ep.get("content", "{}")
try:
tool_input = json.loads(content_str)
except Exception:
try:
tool_input = ast.literal_eval(content_str)
except Exception:
tool_input = {"raw": content_str}

history.append({
"role": "assistant",
"content": [{"type": "tool_use", "id": tool_id, "name": tool_name, "input": tool_input}],
})
i += 1

# Skip optional scratchpad episode
if i < len(episodes) and episodes[i].get("role") == "scratchpad":
i += 1

# Consume matching tool_result
if i < len(episodes) and episodes[i].get("role") == "tool_result":
history.append({
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": tool_id, "content": episodes[i]["content"]}],
})
i += 1

elif role == "assistant":
history.append({"role": "assistant", "content": ep["content"]})
i += 1

else:
i += 1

return history

def rebuild_from_episodic(self, episodic: "EpisodicMemory") -> list[dict]:
"""Rebuild and persist API history from current episodic session.

Reads episodes via get_conversation(), converts to API format,
saves to HistoryStore, and returns the result.
"""
from dataclasses import asdict
episodes = [asdict(ep) for ep in episodic.get_conversation()]
history = self.episodes_to_api_history(episodes)
if episodic.session_id:
self.save(episodic.session_id, history)
return history

def list_sessions(self, limit: int = 20) -> list[dict]:
"""List recent sessions with history, newest-first.

Expand Down
Loading
Loading