Memory & Sessions¶
AgenticX keeps conversation state at three levels: in-turn session
history, persistent per-session files under .agenticx/session/<id>/,
and long-term memory via the configured platform (Bailian by default,
local otherwise). Context compression keeps long runs inside the model
window.
See Subagents, Hooks & Memory for the
user-facing /memory, /session, and /profile flows.
Memory manager¶
MemoryManager
¶
MemoryManager(workspace_dir: Path)
Two-tier memory manager: per-session state + cross-session persistent memory.
Coordinates mid-term (session: plan, reflection, tool chains) and long-term (persistent: experience, user profile) memory, plus trace logging. The conversation's working context lives in Agent.messages and is compressed by dashscope_agenticx.compression — not tracked here.
Source code in src/dashscope_agenticx/memory/manager.py
129 130 131 132 133 | |
derive_child
classmethod
¶
derive_child(parent: 'MemoryManager') -> 'MemoryManager'
Build an isolated manager for a sub-agent.
The child gets a fresh SessionMemory (own plan/reflection/tool_chains,
under a child-* subdirectory) so its tool failures and plans never
touch the parent's counters, while sharing the parent's persistent
experience store and trace logger.
Source code in src/dashscope_agenticx/memory/manager.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | |
close
¶
close() -> None
Release ephemeral child state without touching parent stores.
Source code in src/dashscope_agenticx/memory/manager.py
156 157 158 159 160 161 162 163 164 165 166 167 | |
record_tool_execution
¶
record_tool_execution(
tool_name: str,
success: bool,
evidence: str = "",
signal_kind: str = "",
exit_code: int | None = None,
) -> None
Record a tool execution for reflection monitoring.
evidence is the tool's own output text and signal_kind /
exit_code say where the verdict came from. The reflection hint
quotes them back verbatim, which is what makes it worth injecting at
all.
Source code in src/dashscope_agenticx/memory/manager.py
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | |
record_experience
¶
record_experience(
task_summary: str,
tools_used: list[str],
outcome: str,
lesson: str = "",
verified: bool | None = None,
) -> None
Record a task experience to persistent memory.
Source code in src/dashscope_agenticx/memory/manager.py
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | |
log_trace
¶
log_trace(event_type: str, data: dict[str, Any]) -> None
Log a trace event.
Source code in src/dashscope_agenticx/memory/manager.py
209 210 211 | |
reset_session
¶
reset_session() -> None
Reset session memory (called at session start).
Source code in src/dashscope_agenticx/memory/manager.py
213 214 215 | |
SessionMemory
¶
SessionMemory(workspace_dir: Path)
Mid-term memory: per-session persistent state.
Tracks plan, reflection, and tool chains for the current session. Persisted to .agenticx/session/ directory.
Source code in src/dashscope_agenticx/memory/manager.py
38 39 40 41 42 43 44 45 46 47 48 49 50 | |
bind_projection
¶
bind_projection(session_manager, topic_provider) -> None
Persist plan/goal state into the active session event stream.
Source code in src/dashscope_agenticx/memory/manager.py
52 53 54 55 56 57 58 59 60 61 62 | |
restore_projection
¶
restore_projection(topic: str) -> dict[str, Any]
Source code in src/dashscope_agenticx/memory/manager.py
64 65 66 67 68 69 | |
reset
¶
reset() -> None
Reset session memory (called at session start).
Source code in src/dashscope_agenticx/memory/manager.py
71 72 73 74 75 | |
PersistentMemory
¶
PersistentMemory(workspace_dir: Path)
Long-term memory: cross-session persistent memory.
Stores experience and user profile that persist across sessions. Persisted to .agenticx/ directory.
Source code in src/dashscope_agenticx/memory/manager.py
85 86 87 | |
record_experience
¶
record_experience(
task_summary: str,
tools_used: list[str],
outcome: str,
lesson: str = "",
verified: bool | None = None,
) -> None
Record a task experience.
Source code in src/dashscope_agenticx/memory/manager.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |
search_experiences
¶
search_experiences(
query: str, limit: int = 3
) -> list[dict[str, Any]]
Search for relevant experiences.
Source code in src/dashscope_agenticx/memory/manager.py
106 107 108 109 110 111 112 | |
format_for_prompt
¶
format_for_prompt(experiences: list[dict[str, Any]]) -> str
Format experiences for prompt injection.
Source code in src/dashscope_agenticx/memory/manager.py
114 115 116 | |
Sessions¶
SessionManager
¶
SessionManager(workspace_dir: Path = WORKSPACE_DIR)
Manages multi-topic session persistence.
Source code in src/dashscope_agenticx/session.py
72 73 74 75 76 | |
get_scene
¶
get_scene(topic: str | None = None) -> str
Return the scene memory text for a topic (default: current).
Returns an empty string when the file is missing or unreadable.
Source code in src/dashscope_agenticx/session.py
135 136 137 138 139 140 141 142 143 144 145 146 | |
set_scene
¶
set_scene(text: str, topic: str | None = None) -> bool
Replace the scene memory for a topic (default: current).
An empty/whitespace-only text clears the scene file. Returns False when the topic name is unsafe or the write fails.
Source code in src/dashscope_agenticx/session.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | |
append_scene
¶
append_scene(text: str, topic: str | None = None) -> bool
Append a note line to the scene memory of a topic.
Source code in src/dashscope_agenticx/session.py
175 176 177 178 179 180 181 182 183 | |
event_log
¶
event_log(topic: str | None = None) -> SessionEventLog
Return the append-only event log for a safe topic.
Topic validation belongs at this public boundary. Several best-effort
callers accept a topic argument directly; allowing ../ here would
write an event stream outside session/ even though create/switch
correctly reject the same name.
Source code in src/dashscope_agenticx/session.py
185 186 187 188 189 190 191 192 193 194 195 196 197 | |
record_turn_event
¶
record_turn_event(
user_text: str,
assistant_text: str,
tools_used: list[str] | None = None,
outcome: str = "",
topic: str | None = None,
identifiers: dict[str, str] | None = None,
) -> None
Append a turn/end event to the topic's event sidecar.
Records a compact summary of one turn (truncated user/assistant text, tools used, outcome). Best-effort: never raises, so event recording can't break the agent loop. This is a step toward the session-as-event-log direction (later: projection / fork / resume built on the event stream).
Source code in src/dashscope_agenticx/session.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | |
record_messages_snapshot
¶
record_messages_snapshot(
messages: list[dict[str, Any]],
topic: str | None = None,
identifiers: dict[str, str] | None = None,
) -> None
Append a full-fidelity messages/snapshot event.
Stores the complete current message list so the session can later
be reconstructed (resume/fork) from the event log alone. Old
snapshots are pruned once more than _SNAPSHOT_COMPACT_AT
accumulate, keeping the newest _SNAPSHOT_KEEP. Best-effort:
never raises.
Source code in src/dashscope_agenticx/session.py
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | |
resume_from_events
¶
resume_from_events(
topic: str | None = None,
) -> list[dict[str, Any]]
Rebuild the message list from the latest snapshot event.
Returns an empty list when the topic has no snapshot. This is the projection side of the event-sourced session: combined with the append-only log it enables resume / fork / crash recovery.
Source code in src/dashscope_agenticx/session.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | |
project_state
¶
project_state(topic: str | None = None) -> dict[str, Any]
Return messages, plan, goal, artifacts, and the last turn.
Source code in src/dashscope_agenticx/session.py
278 279 280 281 282 283 | |
record_plan_state
¶
record_plan_state(
plan: dict[str, Any] | None, topic: str | None = None
) -> None
Source code in src/dashscope_agenticx/session.py
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 | |
record_artifact
¶
record_artifact(
artifact: dict[str, Any],
topic: str | None = None,
identifiers: dict[str, str] | None = None,
) -> None
Source code in src/dashscope_agenticx/session.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 | |
fork_topic
¶
fork_topic(src: str, dst: str) -> bool
Create topic dst seeded with a copy of src's event log.
The forked topic resumes from the same state as the source. Both names must be safe and the destination must not already exist. Returns False otherwise.
Source code in src/dashscope_agenticx/session.py
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | |
list_topics
¶
list_topics() -> list[SessionMeta]
List all available topics with metadata.
Source code in src/dashscope_agenticx/session.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | |
get_current_topic
¶
get_current_topic() -> str
Get the current active topic.
Source code in src/dashscope_agenticx/session.py
423 424 425 | |
set_current_topic
¶
set_current_topic(topic: str) -> bool
Set the current active topic. Returns True if successful.
Source code in src/dashscope_agenticx/session.py
427 428 429 430 431 432 433 434 435 | |
create_topic
¶
create_topic(topic: str) -> bool
Create a new topic directory. Returns True if created.
Source code in src/dashscope_agenticx/session.py
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 | |
rename_topic
¶
rename_topic(old_name: str, new_name: str) -> bool
Rename a topic. Returns True if successful.
Source code in src/dashscope_agenticx/session.py
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 | |
delete_topic
¶
delete_topic(topic: str) -> bool
Delete a topic and all its files. Returns True if successful.
Source code in src/dashscope_agenticx/session.py
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 | |
get_history_path
¶
get_history_path(topic: str | None = None) -> Path
Get the history path for a safe topic (default: current).
Source code in src/dashscope_agenticx/session.py
520 521 522 523 524 525 526 | |
get_input_history_path
¶
get_input_history_path(topic: str | None = None) -> Path
Get the input-history path for a topic (default: current).
Source code in src/dashscope_agenticx/session.py
528 529 530 531 | |
load_messages
¶
load_messages(
topic: str | None = None,
) -> list[dict[str, Any]]
Load stored chat messages for a topic (default: current).
Returns an empty list when the history file is missing, unreadable, or not a JSON list.
Source code in src/dashscope_agenticx/session.py
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 | |
update_message_count
¶
update_message_count(
count: int, topic: str | None = None
) -> None
Update the message count for a topic.
Source code in src/dashscope_agenticx/session.py
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 | |
should_prompt_archive
¶
should_prompt_archive(
topic: str | None = None, threshold: int = 100
) -> bool
Check if a topic has enough messages to suggest archiving.
Source code in src/dashscope_agenticx/session.py
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 | |
SessionMeta
dataclass
¶
SessionMeta(
topic: str,
created: str,
last_accessed: str,
message_count: int = 0,
)
Metadata for a session topic.
to_dict
¶
to_dict() -> dict
Source code in src/dashscope_agenticx/session.py
53 54 | |
from_dict
classmethod
¶
from_dict(data: dict) -> SessionMeta
Source code in src/dashscope_agenticx/session.py
56 57 58 59 60 61 62 63 64 65 66 | |
get_session_manager
¶
get_session_manager() -> SessionManager
Get the global session manager instance.
Source code in src/dashscope_agenticx/session.py
634 635 636 637 638 639 640 641 642 | |
set_session_manager
¶
set_session_manager(manager: SessionManager) -> None
Set the global session manager instance.
Source code in src/dashscope_agenticx/session.py
645 646 647 648 | |
Session event log¶
SessionEventLog
¶
SessionEventLog(events_file: Path)
Append-only JSONL event log bound to one file.
Events are appended, never edited in place — with one exception:
:meth:compact_snapshots atomically rewrites the file to drop
stale full-history snapshots (all other events are preserved).
seq is a 1-based monotonically increasing position derived
from the current line count, so it stays correct even if another
process appends.
Source code in src/dashscope_agenticx/session_events.py
142 143 | |
append
¶
append(event_type: str, data: dict | None = None) -> None
Append one event. Never raises (best-effort sidecar).
Source code in src/dashscope_agenticx/session_events.py
149 150 151 152 153 154 155 | |
read
¶
read(event_type: str | None = None) -> list[dict[str, Any]]
Return events in order, optionally filtered by type.
Malformed or wrong-schema lines are skipped silently.
Source code in src/dashscope_agenticx/session_events.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
read_raw
¶
read_raw() -> list[dict[str, Any]]
Return every well-formed entry, any schema version.
Unlike :meth:read (which filters to the current schema), this
yields all parseable entries — used when projecting large events
such as messages/snapshot.
Source code in src/dashscope_agenticx/session_events.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
compact_snapshots
¶
compact_snapshots(
keep: int = 2, snapshot_type: str = "messages/snapshot"
) -> bool
Drop all but the newest keep snapshot events, atomically.
Snapshots carry a full copy of the message list, so retaining
every one grows the log quadratically in history length.
Compaction rewrites the file with all non-snapshot events plus
the newest keep snapshots, renumbering seq to stay
line-ordered. The rewrite goes through a tmp file and
os.replace, so a crash mid-compaction leaves the original
log intact. Append and compaction share a stable sidecar lock.
Best-effort: returns True only when the file was rewritten.
Source code in src/dashscope_agenticx/session_events.py
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
project_session_state
¶
project_session_state(
entries: list[dict[str, Any]],
) -> dict[str, Any]
Fold append-only events into the restart/fork session projection.
Source code in src/dashscope_agenticx/session_events.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
latest_snapshot_messages
¶
latest_snapshot_messages(
entries: list[dict[str, Any]],
) -> list[dict[str, Any]]
Return the message list from the newest messages/snapshot.
Scans entries (as produced by :meth:SessionEventLog.read_raw)
backwards; returns an empty list when no snapshot is present.
Source code in src/dashscope_agenticx/session_events.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |
Local platform storage¶
LocalMemoryClient
¶
LocalMemoryClient(
user_id: str = "default", memory_library_id: str = ""
)
File-based memory provider. Implements MemoryProvider Protocol.
Source code in src/dashscope_agenticx/platforms/local/memory.py
43 44 45 46 47 48 49 50 | |
add
async
¶
add(
messages: list[dict[str, str]],
custom_content: str = "",
metadata: dict[str, Any] | None = None,
) -> list[MemoryNode]
Extract key facts from messages and store as memory nodes.
For local mode we do simple extraction: pull out lines that look like user preferences / facts (contains "I", "my", "prefer", etc.) or just store custom_content directly.
Source code in src/dashscope_agenticx/platforms/local/memory.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
search
async
¶
search(
query: str | list[dict[str, str]],
top_k: int = 5,
min_score: float = 0.3,
) -> list[MemoryNode]
Simple keyword-based search (no embedding model available locally).
Source code in src/dashscope_agenticx/platforms/local/memory.py
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | |
list
async
¶
list(
page_num: int = 1, page_size: int = 10
) -> list[MemoryNode]
List all memory nodes with pagination.
Source code in src/dashscope_agenticx/platforms/local/memory.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | |
delete
async
¶
delete(memory_node_id: str) -> bool
Delete a specific memory node.
Source code in src/dashscope_agenticx/platforms/local/memory.py
216 217 218 219 220 221 222 223 224 | |
update
async
¶
update(memory_node_id: str, content: str) -> bool
Update a memory node's content.
Source code in src/dashscope_agenticx/platforms/local/memory.py
226 227 228 229 230 231 232 233 234 235 | |
store_history
¶
store_history(
messages: list[dict[str, str]],
) -> dict[str, Any] | None
Store a conversation summary to history.
Source code in src/dashscope_agenticx/platforms/local/history.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | |
list_history
¶
list_history(limit: int = 20) -> list[dict[str, Any]]
List recent history entries.
Source code in src/dashscope_agenticx/platforms/local/history.py
168 169 170 171 172 173 | |
search_history
¶
search_history(
query: str, limit: int = 10
) -> list[dict[str, Any]]
Search history by keyword.
Source code in src/dashscope_agenticx/platforms/local/history.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | |
export_history
¶
export_history(path: str, fmt: str | None = None) -> str
Export conversation history to a file.
Supported formats: html (default), json, markdown.
When fmt is omitted, the format is auto-detected from the file
extension (.json -> json, .md -> markdown, otherwise html).
Returns the resolved output path.
Source code in src/dashscope_agenticx/platforms/local/history.py
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | |
Context compression¶
compress_messages
async
¶
compress_messages(
messages: list[dict],
chat: _ChatCallable,
context_window: int = DEFAULT_CONTEXT_WINDOW,
keep_recent: int = PRESERVE_RECENT_MESSAGES,
extra_tokens: int = 0,
) -> list[dict] | None
Compress older messages while preserving the most recent ones.
Returns a new message list with a summary of older messages followed by
the preserved recent messages. Returns None only when compression is
not needed; if the summarizer itself fails, an omission marker takes the
summary's place so overflow protection still kicks in.
Source code in src/dashscope_agenticx/compression.py
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 | |
should_compress
¶
should_compress(
messages: list[dict],
context_window: int = DEFAULT_CONTEXT_WINDOW,
extra_tokens: int = 0,
) -> tuple[bool, str]
Return (should_compress, reason).
Compression is triggered when the estimated tokens cross the soft threshold (50% of context window) or forced at the hard threshold (85%). A small minimum message count guards against compressing tiny chats; beyond it the token budget alone decides, so a few very large messages (e.g. huge tool outputs) still compress before overflowing the window.
Source code in src/dashscope_agenticx/compression.py
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
estimate_tokens
¶
estimate_tokens(text: str) -> int
Rough token estimate.
Counts CJK characters separately from ASCII: CJK text is ~1 token per character while ASCII is ~1 token per ~4 characters. Other non-ASCII (accents, emoji, …) sits in between at ~1 token per ~2 characters. This is intentionally conservative (slightly overestimates) for safety.
Source code in src/dashscope_agenticx/compression.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
estimate_message_tokens
¶
estimate_message_tokens(messages: list[dict]) -> int
Sum token estimates for all messages, including overhead per message.
Source code in src/dashscope_agenticx/compression.py
188 189 190 191 192 193 194 | |
preserve_recent_messages
¶
preserve_recent_messages(
messages: list[dict],
keep: int = PRESERVE_RECENT_MESSAGES,
)
Split messages into (older_compressible, recent_preserved).
The split point is advanced past orphaned tool results / dangling tool_calls so the preserved tail never triggers an API 400.
Source code in src/dashscope_agenticx/compression.py
289 290 291 292 293 294 295 296 297 298 299 300 301 | |
shrink_old_tool_messages
¶
shrink_old_tool_messages(
messages: list[dict],
keep_recent: int = PRESERVE_RECENT_MESSAGES,
max_chars: int = OLD_TOOL_MESSAGE_MAX_CHARS,
) -> int
Truncate large tool results outside the recent tail, in place.
Cheaper than full compression (no LLM call): a session full of stale read_file/run_command outputs otherwise re-sends them on every call. Results from RESTORABLE_TOOLS keep a note recording the original call, so the model re-reads instead of reasoning over a hole in its context. Idempotent; returns the number of messages shrunk.
Source code in src/dashscope_agenticx/compression.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |