跳转至内容

记忆与会话

AgenticX 在三个层面保存对话状态:轮内会话历史、 .agenticx/session/<id>/ 下按会话持久化的文件,以及通过所配置平台 (默认百炼,否则本地)实现的长期记忆。上下文压缩使长时运行保持在 模型窗口之内。

面向用户的 /memory、/session 与 /profile 流程参见 子代理、Hooks 与记忆。

记忆管理器

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
def __init__(self, workspace_dir: Path):
    self.workspace_dir = workspace_dir
    self.session = SessionMemory(workspace_dir)
    self.persistent = PersistentMemory(workspace_dir)
    self.trace = TraceLogger(workspace_dir)

workspace_dir instance-attribute

workspace_dir = workspace_dir

session instance-attribute

session = SessionMemory(workspace_dir)

persistent instance-attribute

persistent = PersistentMemory(workspace_dir)

trace instance-attribute

trace = TraceLogger(workspace_dir)

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
@classmethod
def derive_child(cls, 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.
    """
    import uuid

    child = cls.__new__(cls)
    child_workspace = (
        parent.session.session_dir / "children" / uuid.uuid4().hex[:8]
    )
    child.session = SessionMemory(child_workspace)
    child.persistent = parent.persistent
    child.trace = parent.trace
    child._child_workspace = child_workspace
    return child

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
def close(self) -> None:
    """Release ephemeral child state without touching parent stores."""
    child_workspace = getattr(self, "_child_workspace", None)
    if child_workspace is None:
        return
    import shutil

    try:
        shutil.rmtree(child_workspace)
    except OSError:
        pass
    self._child_workspace = None

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
def record_tool_execution(
    self,
    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.
    """
    self.session.reflection.record_tool_execution(
        tool_name,
        success,
        evidence=evidence,
        signal_kind=signal_kind,
        exit_code=exit_code,
    )

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
def record_experience(
    self,
    task_summary: str,
    tools_used: list[str],
    outcome: str,
    lesson: str = "",
    verified: bool | None = None,
) -> None:
    """Record a task experience to persistent memory."""
    self.persistent.record_experience(
        task_summary,
        tools_used,
        outcome,
        lesson,
        verified=verified,
    )

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
def log_trace(self, event_type: str, data: dict[str, Any]) -> None:
    """Log a trace event."""
    self.trace.log(event_type, data)

reset_session

reset_session() -> None

Reset session memory (called at session start).

Source code in src/dashscope_agenticx/memory/manager.py
213
214
215
def reset_session(self) -> None:
    """Reset session memory (called at session start)."""
    self.session.reset()

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
def __init__(self, workspace_dir: Path):
    self.workspace_dir = workspace_dir
    self.session_dir = workspace_dir / "session"
    self.session_dir.mkdir(parents=True, exist_ok=True)

    self.plan = PlanTracker()
    self.reflection = ReflectionTracker()
    self.stagnation = StagnationTracker()
    # Tool sequences are operational runbooks, not learned user memory.
    self.runbooks = ToolChainLibrary(workspace_dir / "runbooks")
    self.tool_chains = self.runbooks  # compatibility alias
    self._session_manager = None
    self._topic_provider: Callable[[], str] | None = None

workspace_dir instance-attribute

workspace_dir = workspace_dir

session_dir instance-attribute

session_dir = workspace_dir / 'session'

plan instance-attribute

plan = PlanTracker()

reflection instance-attribute

reflection = ReflectionTracker()

stagnation instance-attribute

stagnation = StagnationTracker()

runbooks instance-attribute

runbooks = ToolChainLibrary(workspace_dir / 'runbooks')

tool_chains instance-attribute

tool_chains = self.runbooks

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
def bind_projection(self, session_manager, topic_provider) -> None:
    """Persist plan/goal state into the active session event stream."""
    self._session_manager = session_manager
    self._topic_provider = topic_provider

    def _persist(plan: dict[str, Any] | None) -> None:
        topic = topic_provider()
        if topic:
            session_manager.record_plan_state(plan, topic)

    self.plan.set_on_change(_persist)

restore_projection

restore_projection(topic: str) -> dict[str, Any]
Source code in src/dashscope_agenticx/memory/manager.py
64
65
66
67
68
69
def restore_projection(self, topic: str) -> dict[str, Any]:
    if self._session_manager is None:
        return {}
    state = self._session_manager.project_state(topic)
    self.plan.restore(state.get("plan"))
    return state

reset

reset() -> None

Reset session memory (called at session start).

Source code in src/dashscope_agenticx/memory/manager.py
71
72
73
74
75
def reset(self) -> None:
    """Reset session memory (called at session start)."""
    self.plan.clear_plan()
    self.reflection.reset()
    self.stagnation.reset()

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
def __init__(self, workspace_dir: Path):
    self.workspace_dir = workspace_dir
    self.experience = ExperienceTracker(workspace_dir)

workspace_dir instance-attribute

workspace_dir = workspace_dir

experience instance-attribute

experience = ExperienceTracker(workspace_dir)

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
def record_experience(
    self,
    task_summary: str,
    tools_used: list[str],
    outcome: str,
    lesson: str = "",
    verified: bool | None = None,
) -> None:
    """Record a task experience."""
    self.experience.record_experience(
        task_summary,
        tools_used,
        outcome,
        lesson,
        verified=verified,
    )

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
def search_experiences(
    self,
    query: str,
    limit: int = 3,
) -> list[dict[str, Any]]:
    """Search for relevant experiences."""
    return self.experience.search_experiences(query, limit)

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
def format_for_prompt(self, experiences: list[dict[str, Any]]) -> str:
    """Format experiences for prompt injection."""
    return self.experience.format_experiences_for_prompt(experiences)

会话

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
def __init__(self, workspace_dir: Path = WORKSPACE_DIR):
    self.workspace_dir = workspace_dir
    self.session_dir = workspace_dir / "session"
    self.current_topic: str = DEFAULT_TOPIC
    self._ensure_session_dir()

workspace_dir instance-attribute

workspace_dir = workspace_dir

session_dir instance-attribute

session_dir = workspace_dir / 'session'

current_topic instance-attribute

current_topic: str = DEFAULT_TOPIC

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
def get_scene(self, 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.
    """
    path = self._scene_file(topic or self.current_topic)
    if not path.exists():
        return ""
    try:
        return path.read_text(encoding="utf-8").strip()
    except OSError:
        return ""

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
def set_scene(self, 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.
    """
    topic = topic or self.current_topic
    topic_dir = self._safe_topic_dir(topic)
    if topic_dir is None:
        return False
    path = self._scene_file(topic)
    content = text.strip()
    try:
        if not content:
            if path.exists():
                path.unlink()
        else:
            topic_dir.mkdir(parents=True, exist_ok=True)
            path.write_text(content + "\n", encoding="utf-8")
    except OSError:
        return False
    self.event_log(topic).append(
        "scene/updated",
        {"topic": topic, "chars": len(content)},
    )
    return True

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
def append_scene(self, text: str, topic: str | None = None) -> bool:
    """Append a note line to the scene memory of a topic."""
    topic = topic or self.current_topic
    note = text.strip()
    if not note:
        return False
    existing = self.get_scene(topic)
    merged = f"{existing}\n{note}" if existing else note
    return self.set_scene(merged, topic)

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
def event_log(self, 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.
    """
    topic = topic or self.current_topic
    topic_dir = self._safe_topic_dir(topic)
    if topic_dir is None:
        raise ValueError(f"unsafe session topic: {topic!r}")
    return SessionEventLog(topic_dir / EVENTS_FILENAME)

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
def record_turn_event(
    self,
    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).
    """
    try:
        topic = topic or self.current_topic
        self.event_log(topic).append(
            "turn/end",
            {
                "topic": topic,
                "user": (user_text or "")[:200],
                "assistant": (assistant_text or "")[:200],
                "tools": list(tools_used or []),
                "outcome": outcome,
                "ids": dict(identifiers or {}),
            },
        )
    except Exception:
        pass

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
def record_messages_snapshot(
    self,
    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.
    """
    try:
        topic = topic or self.current_topic
        log = self.event_log(topic)
        log.append(
            "messages/snapshot",
            {
                "topic": topic,
                "messages": list(messages or []),
                "ids": dict(identifiers or {}),
            },
        )
        if len(log.read("messages/snapshot")) > _SNAPSHOT_COMPACT_AT:
            log.compact_snapshots(keep=_SNAPSHOT_KEEP)
    except Exception:
        pass

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
def resume_from_events(
    self,
    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.
    """
    try:
        events = self.event_log(topic).read_raw()
    except Exception:
        return []
    return latest_snapshot_messages(events)

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
def project_state(self, topic: str | None = None) -> dict[str, Any]:
    """Return messages, plan, goal, artifacts, and the last turn."""
    try:
        return project_session_state(self.event_log(topic).read_raw())
    except Exception:
        return project_session_state([])

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
def record_plan_state(
    self,
    plan: dict[str, Any] | None,
    topic: str | None = None,
) -> None:
    topic = topic or self.current_topic
    self.event_log(topic).append(
        "plan/updated",
        {"topic": topic, "plan": plan},
    )
    goal = None
    if plan:
        goal = {
            "description": str(plan.get("goal", "")),
            "status": (
                "completed"
                if all(
                    bool(step.get("completed"))
                    for step in plan.get("steps", [])
                    if isinstance(step, dict)
                )
                and bool(plan.get("steps"))
                else "active"
            ),
        }
    self.event_log(topic).append(
        "goal/updated",
        {"topic": topic, "goal": goal},
    )

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
def record_artifact(
    self,
    artifact: dict[str, Any],
    topic: str | None = None,
    identifiers: dict[str, str] | None = None,
) -> None:
    topic = topic or self.current_topic
    self.event_log(topic).append(
        "artifact/recorded",
        {
            "topic": topic,
            **artifact,
            "ids": dict(identifiers or {}),
        },
    )

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
def fork_topic(self, 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.
    """
    src_dir = self._safe_topic_dir(src)
    dst_dir = self._safe_topic_dir(dst)
    if src_dir is None or dst_dir is None:
        return False
    if not src_dir.exists() or dst_dir.exists():
        return False
    try:
        import shutil

        dst_dir.mkdir(parents=True)
        self._save_meta(
            dst,
            SessionMeta(
                topic=dst,
                created=datetime.now().isoformat(),
                last_accessed=datetime.now().isoformat(),
            ),
        )
        src_events = self._events_file(src)
        if src_events.exists():
            shutil.copy2(src_events, self._events_file(dst))
        # Pre-snapshot sessions keep their messages only in
        # history.json; copy it too so the fork restores them.
        src_history = self._history_file(src)
        if src_history.exists():
            shutil.copy2(src_history, self._history_file(dst))
    except OSError:
        return False
    self.event_log(dst).append(
        "topic/forked",
        {"from": src, "to": dst},
    )
    return True

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
def list_topics(self) -> list[SessionMeta]:
    """List all available topics with metadata."""
    topics = []
    if not self.session_dir.exists():
        return topics

    for topic_dir in self.session_dir.iterdir():
        if not topic_dir.is_dir():
            continue
        meta_file = self._meta_file(topic_dir.name)
        if meta_file.exists():
            try:
                data = json.loads(meta_file.read_text(encoding="utf-8"))
                topics.append(SessionMeta.from_dict(data))
            except (json.JSONDecodeError, OSError):
                # Fallback: create meta from directory
                topics.append(
                    SessionMeta(
                        topic=topic_dir.name,
                        created=datetime.now().isoformat(),
                        last_accessed=datetime.now().isoformat(),
                    ),
                )
        else:
            # No meta file — derive timestamps from directory mtime to
            # avoid non-deterministic sort order caused by auto-touching.
            try:
                mtime = topic_dir.stat().st_mtime
                from datetime import timezone as _tz

                ts = (
                    datetime.fromtimestamp(mtime, tz=_tz.utc)
                    .replace(tzinfo=None)
                    .isoformat()
                )
            except OSError:
                ts = datetime.now().isoformat()
            topics.append(
                SessionMeta(
                    topic=topic_dir.name,
                    created=ts,
                    last_accessed=ts,
                ),
            )

    # Sort: default first, then by last_accessed descending.
    # Python sort is stable, so sort by secondary key first.
    topics.sort(key=lambda m: m.last_accessed, reverse=True)
    topics.sort(key=lambda m: m.topic != DEFAULT_TOPIC)
    return topics

get_current_topic

get_current_topic() -> str

Get the current active topic.

Source code in src/dashscope_agenticx/session.py
423
424
425
def get_current_topic(self) -> str:
    """Get the current active topic."""
    return self.current_topic

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
def set_current_topic(self, topic: str) -> bool:
    """Set the current active topic. Returns True if successful."""
    topic_dir = self._safe_topic_dir(topic)
    if topic_dir is None or not topic_dir.exists():
        return False
    self.current_topic = topic
    self._update_last_accessed(topic)
    self.event_log(topic).append("topic/switched", {"topic": topic})
    return True

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
def create_topic(self, topic: str) -> bool:
    """Create a new topic directory. Returns True if created."""
    topic_dir = self._safe_topic_dir(topic)
    if topic_dir is None or topic_dir.exists():
        return False
    topic_dir.mkdir(parents=True)
    meta = SessionMeta(
        topic=topic,
        created=datetime.now().isoformat(),
        last_accessed=datetime.now().isoformat(),
    )
    self._save_meta(topic, meta)
    self.current_topic = topic
    self.event_log(topic).append("topic/created", {"topic": topic})
    return True

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
def rename_topic(self, old_name: str, new_name: str) -> bool:
    """Rename a topic. Returns True if successful."""
    old_dir = self._safe_topic_dir(old_name)
    new_dir = self._safe_topic_dir(new_name)
    if old_dir is None or new_dir is None:
        return False

    if not old_dir.exists() or new_dir.exists():
        return False

    try:
        # Read meta before rename so we can update it after.
        meta_data: dict | None = None
        old_meta_file = old_dir / "meta.json"
        if old_meta_file.exists():
            try:
                meta_data = json.loads(
                    old_meta_file.read_text(encoding="utf-8"),
                )
            except (json.JSONDecodeError, OSError):
                meta_data = None

        old_dir.rename(new_dir)

        # Update meta with new topic name.
        if meta_data is not None:
            meta_data["topic"] = new_name
            new_meta_file = new_dir / "meta.json"
            try:
                new_meta_file.write_text(
                    json.dumps(meta_data, ensure_ascii=False, indent=2),
                    encoding="utf-8",
                )
            except OSError:
                # meta mismatch is tolerable; directory is already
                # renamed
                pass

        if self.current_topic == old_name:
            self.current_topic = new_name
        self.event_log(new_name).append(
            "topic/renamed",
            {"from": old_name, "to": new_name},
        )
        return True
    except OSError:
        return False

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
def delete_topic(self, topic: str) -> bool:
    """Delete a topic and all its files. Returns True if successful."""
    if topic == DEFAULT_TOPIC:
        return False  # Cannot delete default

    topic_dir = self._safe_topic_dir(topic)
    if topic_dir is None or not topic_dir.exists():
        return False

    try:
        import shutil

        shutil.rmtree(topic_dir)
        if self.current_topic == topic:
            self.current_topic = DEFAULT_TOPIC
        return True
    except OSError:
        return False

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
def get_history_path(self, topic: str | None = None) -> Path:
    """Get the history path for a safe topic (default: current)."""
    topic = topic or self.current_topic
    topic_dir = self._safe_topic_dir(topic)
    if topic_dir is None:
        raise ValueError(f"unsafe session topic: {topic!r}")
    return topic_dir / "history.json"

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
def get_input_history_path(self, topic: str | None = None) -> Path:
    """Get the input-history path for a topic (default: current)."""
    topic = topic or self.current_topic
    return self._input_history_file(topic)

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
def load_messages(
    self,
    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.
    """
    path = self._history_file(topic or self.current_topic)
    if not path.exists():
        return []
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except (json.JSONDecodeError, OSError):
        return []
    return data if isinstance(data, list) else []

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
def update_message_count(
    self,
    count: int,
    topic: str | None = None,
) -> None:
    """Update the message count for a topic."""
    topic = topic or self.current_topic
    meta_file = self._meta_file(topic)
    if meta_file.exists():
        try:
            data = json.loads(meta_file.read_text(encoding="utf-8"))
            data["message_count"] = count
            data["last_accessed"] = datetime.now().isoformat()
            meta_file.write_text(
                json.dumps(data, ensure_ascii=False, indent=2),
                encoding="utf-8",
            )
        except (json.JSONDecodeError, OSError):
            pass

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
def should_prompt_archive(
    self,
    topic: str | None = None,
    threshold: int = 100,
) -> bool:
    """Check if a topic has enough messages to suggest archiving."""
    topic = topic or self.current_topic
    if topic != DEFAULT_TOPIC:
        return False  # Only prompt for default topic

    meta_file = self._meta_file(topic)
    if not meta_file.exists():
        return False

    try:
        data = json.loads(meta_file.read_text(encoding="utf-8"))
        return data.get("message_count", 0) >= threshold
    except (json.JSONDecodeError, OSError):
        return False

SessionMeta dataclass

SessionMeta(
    topic: str,
    created: str,
    last_accessed: str,
    message_count: int = 0,
)

Metadata for a session topic.

topic instance-attribute

topic: str

created instance-attribute

created: str

last_accessed instance-attribute

last_accessed: str

message_count class-attribute instance-attribute

message_count: int = 0

to_dict

to_dict() -> dict
Source code in src/dashscope_agenticx/session.py
53
54
def to_dict(self) -> dict:
    return asdict(self)

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
@classmethod
def from_dict(cls, data: dict) -> SessionMeta:
    return cls(
        topic=data.get("topic", DEFAULT_TOPIC),
        created=data.get("created", datetime.now().isoformat()),
        last_accessed=data.get(
            "last_accessed",
            datetime.now().isoformat(),
        ),
        message_count=data.get("message_count", 0),
    )

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
def get_session_manager() -> SessionManager:
    """Get the global session manager instance."""
    global _manager
    bound = _manager_context.get()
    if bound is not None:
        return bound
    if _manager is None:
        _manager = SessionManager()
    return _manager

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
def set_session_manager(manager: SessionManager) -> None:
    """Set the global session manager instance."""
    global _manager
    _manager = manager

会话事件日志

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
def __init__(self, events_file: Path):
    self._file = Path(events_file)

path property

path: Path

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
def append(self, event_type: str, data: dict | None = None) -> None:
    """Append one event. Never raises (best-effort sidecar)."""
    try:
        self._append(event_type, data or {})
    except Exception:
        # The event log is advisory; never break the caller.
        pass

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
def read(
    self,
    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.
    """
    if not self._file.exists():
        return []
    events: list[dict[str, Any]] = []
    with open(self._file, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                entry = json.loads(line)
            except json.JSONDecodeError:
                continue
            if not isinstance(entry, dict):
                continue
            if entry.get("v") != SCHEMA_VERSION:
                continue
            if event_type is not None and entry.get("type") != event_type:
                continue
            events.append(entry)
    return events

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
def read_raw(self) -> 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``.
    """
    if not self._file.exists():
        return []
    entries: list[dict[str, Any]] = []
    with open(self._file, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                entry = json.loads(line)
            except json.JSONDecodeError:
                continue
            if isinstance(entry, dict):
                entries.append(entry)
    return entries

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
def compact_snapshots(
    self,
    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.
    """
    try:
        with _exclusive_lock(self._file):
            return self._compact_snapshots_locked(keep, snapshot_type)
    except OSError:
        return False

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
def project_session_state(entries: list[dict[str, Any]]) -> dict[str, Any]:
    """Fold append-only events into the restart/fork session projection."""
    state: dict[str, Any] = {
        "messages": [],
        "plan": None,
        "goal": None,
        "artifacts": [],
        "last_turn": {},
    }
    artifacts: dict[str, dict[str, Any]] = {}
    for entry in entries:
        event_type = entry.get("type")
        data = entry.get("data") or {}
        if not isinstance(data, dict):
            continue
        if event_type == "messages/snapshot":
            messages = data.get("messages")
            if isinstance(messages, list):
                state["messages"] = messages
        elif event_type == "plan/updated":
            plan = data.get("plan")
            state["plan"] = plan if isinstance(plan, dict) else None
        elif event_type == "goal/updated":
            goal = data.get("goal")
            state["goal"] = goal if isinstance(goal, dict) else None
        elif event_type == "artifact/recorded":
            path = str(data.get("path", ""))
            if path:
                artifacts[path] = dict(data)
        elif event_type == "turn/end":
            state["last_turn"] = dict(data)
    state["artifacts"] = list(artifacts.values())
    return state

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
def 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.
    """
    for entry in reversed(entries):
        if entry.get("type") != "messages/snapshot":
            continue
        data = entry.get("data") or {}
        msgs = data.get("messages")
        if isinstance(msgs, list):
            return msgs
    return []

本地平台存储

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
def __init__(self, user_id: str = "default", memory_library_id: str = ""):
    if not re.fullmatch(r"[A-Za-z0-9._-]+", user_id) or ".." in user_id:
        raise ValueError(f"invalid memory user_id: {user_id}")
    self.user_id = user_id
    self.memory_library_id = memory_library_id  # accepted but unused
    self._dir = _workspace_memory_dir()
    self._dir.mkdir(parents=True, exist_ok=True)
    self._file = self._dir / f"{user_id}.json"

user_id instance-attribute

user_id = user_id

memory_library_id instance-attribute

memory_library_id = memory_library_id

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
async def add(
    self,
    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.
    """
    from dashscope_agenticx.utils import sanitize_text

    nodes = self._load()
    created: list[MemoryNode] = []

    if custom_content:
        clean = sanitize_text(custom_content.strip())
        if not clean or any(n["content"] == clean for n in nodes):
            return []
        node = self._new_node(clean, metadata)
        nodes.append(node)
        created.append(
            MemoryNode(
                id=node["id"],
                content=node["content"],
                metadata=node.get("metadata", {}),
            ),
        )
    else:
        # Extract meaningful lines from conversation
        keywords = re.compile(
            r"(我是|我用|我的|我喜欢|我不|我需要|我的项目|偏好|习惯|"
            r"I am|I use|I prefer|I like|I need|my project|my stack)",
            re.IGNORECASE,
        )
        for msg in messages:
            if msg.get("role") != "user":
                continue
            content = msg.get("content", "")
            for line in content.splitlines():
                line = sanitize_text(line.strip())
                if len(line) < 5 or len(line) > 200:
                    continue
                if keywords.search(line):
                    # De-duplicate
                    if any(n["content"] == line for n in nodes):
                        continue
                    node = self._new_node(line)
                    nodes.append(node)
                    created.append(MemoryNode(id=node["id"], content=line))

    if created:
        self._save(nodes)
    return created

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
async def search(
    self,
    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)."""
    nodes = self._load()
    if not nodes:
        return []

    # Build query text
    if isinstance(query, str):
        query_text = query.lower()
    else:
        query_text = " ".join(m.get("content", "") for m in query).lower()

    keywords = extract_keywords(query_text)
    if not keywords:
        return []

    def _weight(kw: str) -> float:
        return 2.0 if len(kw) >= 2 else 0.5

    max_weight = sum(_weight(kw) for kw in keywords)
    scored: list[tuple[float, int, dict]] = []
    for index, node in enumerate(nodes):
        content_lower = node["content"].lower()
        hit_weight = sum(
            _weight(kw) for kw in keywords if kw in content_lower
        )
        if hit_weight > 0:
            score = min(hit_weight / max_weight, 1.0)
            if score >= min_score:
                scored.append((score, index, node))

    # Highest score first; ties favor the most recently added node.
    scored.sort(key=lambda item: (-item[0], -item[1]))
    results = []
    for score, _, node in scored[:top_k]:
        results.append(
            MemoryNode(
                id=node["id"],
                content=node["content"],
                created_at=node.get("created_at", ""),
                updated_at=node.get("updated_at", ""),
                score=score,
                metadata=node.get("metadata", {}),
            ),
        )
    return results

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
async def list(
    self,
    page_num: int = 1,
    page_size: int = 10,
) -> list[MemoryNode]:
    """List all memory nodes with pagination."""
    nodes = self._load()
    start = (page_num - 1) * page_size
    end = start + page_size
    results = []
    for node in nodes[start:end]:
        results.append(
            MemoryNode(
                id=node["id"],
                content=node["content"],
                created_at=node.get("created_at", ""),
                updated_at=node.get("updated_at", ""),
                metadata=node.get("metadata", {}),
            ),
        )
    return results

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
async def delete(self, memory_node_id: str) -> bool:
    """Delete a specific memory node."""
    nodes = self._load()
    original_len = len(nodes)
    nodes = [n for n in nodes if n["id"] != memory_node_id]
    if len(nodes) < original_len:
        self._save(nodes)
        return True
    return False

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
async def update(self, memory_node_id: str, content: str) -> bool:
    """Update a memory node's content."""
    nodes = self._load()
    for node in nodes:
        if node["id"] == memory_node_id:
            node["content"] = content
            node["updated_at"] = now_iso()
            self._save(nodes)
            return True
    return False

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
def store_history(messages: list[dict[str, str]]) -> dict[str, Any] | None:
    """Store a conversation summary to history."""
    summary = extract_summary(messages)
    if not summary:
        return None

    turns = sum(1 for m in messages if m.get("role") == "user")
    if turns < 1:
        return None

    entry = {
        "id": short_uuid(),
        "summary": summary,
        "created_at": now_iso(),
        "turns": turns,
    }

    entries = _load()
    entries.append(entry)
    _save(entries)
    return entry

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
def list_history(limit: int = 20) -> list[dict[str, Any]]:
    """List recent history entries."""
    if limit <= 0:
        return []
    entries = _load()
    return entries[-limit:]

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
def search_history(query: str, limit: int = 10) -> list[dict[str, Any]]:
    """Search history by keyword."""
    entries = _load()
    if not entries or not query.strip():
        return []

    keywords = extract_keywords(query)
    if not keywords:
        return []

    scored: list[tuple[float, dict]] = []
    for entry in entries:
        summary_lower = entry.get("summary", "").lower()
        hits = sum(1 for kw in keywords if kw in summary_lower)
        if hits > 0:
            score = min(hits / max(len(keywords), 1), 1.0)
            scored.append((score, entry))

    scored.sort(key=lambda x: -x[0])
    return [entry for _, entry in scored[:limit]]

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
def 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.
    """
    entries = _load()
    output = Path(path)

    if fmt is None:
        ext = output.suffix.lower()
        if ext == ".json":
            fmt = "json"
        elif ext == ".md":
            fmt = "markdown"
        else:
            fmt = "html"

    if fmt == "json":
        output.write_text(
            json.dumps(entries, ensure_ascii=False, indent=2),
            encoding="utf-8",
        )
    elif fmt == "markdown":
        lines = ["# Conversation History\n"]
        for e in entries:
            lines.append(f"## {e.get('summary', '(no summary)')}\n")
            lines.append(f"- **Time**: {e.get('created_at', '')}")
            lines.append(f"- **Turns**: {e.get('turns', 0)}\n")
        output.write_text("\n".join(lines), encoding="utf-8")
    else:
        output.write_text(_generate_html(entries), encoding="utf-8")

    return str(output)

上下文压缩

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
async def 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.
    """
    should, _reason = should_compress(messages, context_window, extra_tokens)
    if not should:
        return None

    older, recent = preserve_recent_messages(messages, keep_recent)
    if not older:
        return None

    try:
        summary = await _summarize(older, chat)
        content = (
            "Summary of earlier conversation (auto-compressed, "
            "background context only):\n"
            f"{summary}"
        )
    except Exception:
        content = (
            f"Omitted {len(older)} earlier messages "
            "(auto-compress failed; keeping only recent "
            "messages to bound context)."
        )
    return [{"role": "user", "content": content}, *recent]

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
def 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.
    """

    if len(messages) < MIN_COMPRESS_MESSAGES:
        return False, ""

    estimated = estimate_message_tokens(messages) + extra_tokens
    soft = int(context_window * SOFT_THRESHOLD_RATIO)
    hard = int(context_window * HARD_THRESHOLD_RATIO)

    if estimated >= hard:
        return True, f"token hard threshold ({estimated} >= {hard})"
    if estimated >= soft:
        return True, f"token soft threshold ({estimated} >= {soft})"
    return False, ""

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
def 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.
    """
    if not text:
        return 0
    cjk = ascii_ = other = 0
    for ch in text:
        if ord(ch) < 128:
            ascii_ += 1
        elif _is_cjk(ch):
            cjk += 1
        else:
            other += 1
    return max(cjk + (other + 1) // 2 + (ascii_ + 3) // 4, 1)

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
def estimate_message_tokens(messages: list[dict]) -> int:
    """Sum token estimates for all messages, including overhead per message."""
    total = 0
    for msg in messages:
        text = _estimate_text(msg)
        total += estimate_tokens(text) + 4  # small overhead for role/name keys
    return total

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
def 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.
    """
    if len(messages) <= keep:
        return [], messages
    split = _advance_to_safe_boundary(messages, len(messages) - keep)
    return messages[:split], messages[split:]

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
def 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.
    """
    from dashscope_agenticx.utils.text import (
        has_omitted_marker,
        truncate_head_tail,
    )

    shrunk = 0
    arguments_by_id: dict[str, object] | None = None
    boundary = max(len(messages) - keep_recent, 0)
    for i in range(boundary):
        m = messages[i]
        if m.get("role") != "tool":
            continue
        content = m.get("content")
        if (
            not isinstance(content, str)
            or len(content) <= max_chars
            or has_omitted_marker(content)  # already truncated — idempotent
        ):
            continue
        if arguments_by_id is None:
            arguments_by_id = _tool_call_arguments(messages)
        call_id = m.get("tool_call_id") or m.get("tool_use_id") or ""
        m["content"] = truncate_head_tail(
            content,
            max_chars,
            note=restore_note(m.get("name"), arguments_by_id.get(call_id)),
        )
        shrunk += 1
    return shrunk