langchain-agentx-python 2.5.0__py3-none-any.whl → 2.5.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- langchain_agentx/__init__.py +1 -1
- langchain_agentx/loop/graph/factory.py +37 -6
- langchain_agentx/loop/subagent/context.py +10 -1
- langchain_agentx/memory/instruction/read_state_seeder.py +6 -1
- langchain_agentx/session/agent_session.py +34 -0
- langchain_agentx/session/conversation_factory.py +6 -0
- langchain_agentx/session/conversation_session.py +36 -1
- langchain_agentx/tool_runtime/post_compact_restore.py +462 -0
- langchain_agentx/tool_runtime/read_state_lifecycle.py +165 -0
- langchain_agentx/tool_runtime/session_store.py +32 -8
- {langchain_agentx_python-2.5.0.dist-info → langchain_agentx_python-2.5.1.dist-info}/METADATA +1 -1
- {langchain_agentx_python-2.5.0.dist-info → langchain_agentx_python-2.5.1.dist-info}/RECORD +15 -13
- {langchain_agentx_python-2.5.0.dist-info → langchain_agentx_python-2.5.1.dist-info}/LICENSE +0 -0
- {langchain_agentx_python-2.5.0.dist-info → langchain_agentx_python-2.5.1.dist-info}/WHEEL +0 -0
- {langchain_agentx_python-2.5.0.dist-info → langchain_agentx_python-2.5.1.dist-info}/top_level.txt +0 -0
langchain_agentx/__init__.py
CHANGED
|
@@ -1593,17 +1593,48 @@ class LoopGraphBuilder:
|
|
|
1593
1593
|
patch["compaction_pipeline_meta"] = meta
|
|
1594
1594
|
meta["compact_progress"] = progress_events
|
|
1595
1595
|
|
|
1596
|
+
@staticmethod
|
|
1597
|
+
def _messages_truly_evaporated(patch: dict[str, Any]) -> bool:
|
|
1598
|
+
"""委托 ``read_state_lifecycle.messages_truly_evaporated``(供单测/外部复用)。"""
|
|
1599
|
+
from langchain_agentx.tool_runtime.read_state_lifecycle import (
|
|
1600
|
+
messages_truly_evaporated,
|
|
1601
|
+
)
|
|
1602
|
+
|
|
1603
|
+
return messages_truly_evaporated(patch)
|
|
1604
|
+
|
|
1596
1605
|
def _clear_file_reads_after_message_compaction(self, patch: dict[str, Any]) -> None:
|
|
1597
|
-
"""
|
|
1606
|
+
"""真·蒸发后清空 last_read(对齐 CC ``readFileState.clear()`` on compact)。
|
|
1598
1607
|
|
|
1599
1608
|
防止 Read dedup 返回 file_unchanged 却断言「内容仍在本会话」(A2)。
|
|
1609
|
+
常驻裁剪(snip 等)不动读状态(BUG-20261109-32 / CC microCompact)。
|
|
1600
1610
|
"""
|
|
1601
|
-
|
|
1602
|
-
|
|
1611
|
+
from langchain_agentx.tool_runtime.read_state_lifecycle import (
|
|
1612
|
+
clear_file_reads_if_evaporated,
|
|
1613
|
+
)
|
|
1614
|
+
from langchain_agentx.workspace.plans import resolve_plans_directory
|
|
1615
|
+
|
|
1603
1616
|
store = getattr(self, "_session_store", None)
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1617
|
+
if store is None:
|
|
1618
|
+
return
|
|
1619
|
+
workspace_cfg = getattr(self, "_workspace_cfg", None)
|
|
1620
|
+
plans_dir = None
|
|
1621
|
+
memory_paths: list[str] = []
|
|
1622
|
+
if workspace_cfg is not None:
|
|
1623
|
+
try:
|
|
1624
|
+
plans_dir = resolve_plans_directory(workspace_cfg)
|
|
1625
|
+
except Exception:
|
|
1626
|
+
plans_dir = None
|
|
1627
|
+
entry = getattr(workspace_cfg, "memory_entrypoint", None)
|
|
1628
|
+
if entry is not None:
|
|
1629
|
+
memory_paths.append(str(entry))
|
|
1630
|
+
clear_file_reads_if_evaporated(
|
|
1631
|
+
store,
|
|
1632
|
+
patch,
|
|
1633
|
+
plans_dir=plans_dir,
|
|
1634
|
+
memory_paths=memory_paths or None,
|
|
1635
|
+
session_id=getattr(self, "_session_id", None),
|
|
1636
|
+
workspace_cfg=workspace_cfg,
|
|
1637
|
+
)
|
|
1607
1638
|
|
|
1608
1639
|
def _apply_prune_and_compress(self, state: dict[str, Any]) -> dict[str, Any]:
|
|
1609
1640
|
if self._session_memory_compact_bridge is not None:
|
|
@@ -427,10 +427,19 @@ class ForkedParentRuntime:
|
|
|
427
427
|
|
|
428
428
|
|
|
429
429
|
def _clone_parent_session_store(parent_store: Any) -> Any:
|
|
430
|
+
"""后台 fork 专用:继承父读缓存(调用方必带父消息,见 ``build_for_background``)。
|
|
431
|
+
|
|
432
|
+
显式 ``inherit_file_reads=True``,禁止依赖 clone 默认值——plain/Skill 路径
|
|
433
|
+
不得复用本函数(须走 ``create_subagent_context(fork_from_parent=…)``)。
|
|
434
|
+
"""
|
|
430
435
|
from langchain_agentx.tool_runtime.session_store import AgentSessionStore
|
|
431
436
|
|
|
432
437
|
if isinstance(parent_store, AgentSessionStore):
|
|
433
|
-
return parent_store.clone(
|
|
438
|
+
return parent_store.clone(
|
|
439
|
+
file_state_only=True,
|
|
440
|
+
inherit_grants=True,
|
|
441
|
+
inherit_file_reads=True,
|
|
442
|
+
)
|
|
434
443
|
return parent_store
|
|
435
444
|
|
|
436
445
|
|
|
@@ -3,7 +3,8 @@ memory/instruction/read_state_seeder.py — 指令注入 read-state 播种
|
|
|
3
3
|
|
|
4
4
|
职责:
|
|
5
5
|
将 Layer 1 规则文件注入 prompt 时同步写入 ``AgentSessionStore.file_read_state``;
|
|
6
|
-
注入内容与磁盘不一致时标记 ``is_partial_view``(对齐 CC attachments memoryFilesToAttachments
|
|
6
|
+
注入内容与磁盘不一致时标记 ``is_partial_view``(对齐 CC attachments memoryFilesToAttachments);
|
|
7
|
+
同步 ``loaded_nested_memory_paths.add``(对齐 CC 非淘汰去重轨)。
|
|
7
8
|
|
|
8
9
|
链路位置:
|
|
9
10
|
LoopGraphBuilder 初始化 → InstructionMemoryBootstrap.seed_injected_read_state()。
|
|
@@ -53,6 +54,9 @@ class InstructionReadStateSeeder:
|
|
|
53
54
|
injected_content: str,
|
|
54
55
|
) -> None:
|
|
55
56
|
path = str(file_path.resolve())
|
|
57
|
+
# 对齐 CC memoryFilesToAttachments:nested Set 或 readFileState 命中则跳过
|
|
58
|
+
if session_store.has_nested_memory_loaded(path):
|
|
59
|
+
return
|
|
56
60
|
if session_store.has_been_read(path):
|
|
57
61
|
return
|
|
58
62
|
try:
|
|
@@ -76,3 +80,4 @@ class InstructionReadStateSeeder:
|
|
|
76
80
|
if content_differs:
|
|
77
81
|
entry["is_partial_view"] = True
|
|
78
82
|
session_store.upsert_last_read_from_bridge_entry(path, entry)
|
|
83
|
+
session_store.mark_nested_memory_loaded(path)
|
|
@@ -408,7 +408,15 @@ class AgentSession:
|
|
|
408
408
|
return self._dispatcher
|
|
409
409
|
|
|
410
410
|
def clear_context(self) -> None:
|
|
411
|
+
"""清空对话消息,并对齐 CC /clear 清读状态与 skill 去重集合。"""
|
|
411
412
|
self._messages.clear()
|
|
413
|
+
store = self._resolve_session_store()
|
|
414
|
+
if store is not None:
|
|
415
|
+
from ..tool_runtime.read_state_lifecycle import (
|
|
416
|
+
clear_tool_state_on_conversation_reset,
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
clear_tool_state_on_conversation_reset(store)
|
|
412
420
|
|
|
413
421
|
async def compact_context(
|
|
414
422
|
self, *, progress_callback: Any = None
|
|
@@ -420,7 +428,13 @@ class AgentSession:
|
|
|
420
428
|
|
|
421
429
|
返回:
|
|
422
430
|
(before_tokens, after_tokens) 元组
|
|
431
|
+
|
|
432
|
+
真·蒸发(autocompact / session_memory)时清空 last_read,对齐 CC
|
|
433
|
+
``compact.ts`` ``readFileState.clear()``;常驻 snip 等不清。
|
|
423
434
|
"""
|
|
435
|
+
from ..tool_runtime.read_state_lifecycle import clear_file_reads_if_evaporated
|
|
436
|
+
from ..workspace.plans import resolve_plans_directory
|
|
437
|
+
|
|
424
438
|
before_tokens = total_estimated_tokens_for_messages(self._messages, num_chars_per_token=4)
|
|
425
439
|
# 注意:model=None 表示不使用 LLM 摘要,仅走 prune 路径
|
|
426
440
|
# 如果需要 LLM 摘要,调用方需要通过其他方式提供 model
|
|
@@ -429,6 +443,26 @@ class AgentSession:
|
|
|
429
443
|
model=None,
|
|
430
444
|
progress_callback=progress_callback,
|
|
431
445
|
)
|
|
446
|
+
store = self._resolve_session_store()
|
|
447
|
+
if store is not None:
|
|
448
|
+
# 须在写入 self._messages 前执行:真蒸发会追加 post-compact 合成 Read
|
|
449
|
+
plans_dir = None
|
|
450
|
+
memory_paths: list[str] = []
|
|
451
|
+
try:
|
|
452
|
+
plans_dir = resolve_plans_directory(self._workspace_cfg)
|
|
453
|
+
except Exception:
|
|
454
|
+
plans_dir = None
|
|
455
|
+
entry = getattr(self._workspace_cfg, "memory_entrypoint", None)
|
|
456
|
+
if entry is not None:
|
|
457
|
+
memory_paths.append(str(entry))
|
|
458
|
+
clear_file_reads_if_evaporated(
|
|
459
|
+
store,
|
|
460
|
+
patch,
|
|
461
|
+
plans_dir=plans_dir,
|
|
462
|
+
memory_paths=memory_paths or None,
|
|
463
|
+
session_id=self._session_id,
|
|
464
|
+
workspace_cfg=self._workspace_cfg,
|
|
465
|
+
)
|
|
432
466
|
if isinstance(patch.get("messages"), list):
|
|
433
467
|
self._messages = list(patch["messages"])
|
|
434
468
|
after_tokens = total_estimated_tokens_for_messages(self._messages, num_chars_per_token=4)
|
|
@@ -28,6 +28,7 @@ from langchain_agentx.loop.config.loop_config import AgentLoopConfig, LoopServic
|
|
|
28
28
|
from langchain_agentx.loop.config.loop_runtime_overlay import LoopRuntimeOverlay
|
|
29
29
|
from langchain_agentx.loop.graph.factory import create_loop_agent
|
|
30
30
|
from langchain_agentx.loop.hook import HookEngine, HooksConfigSnapshot, HookRegistry, WorkspaceTrustChecker
|
|
31
|
+
from langchain_agentx.tool_runtime.session_store import AgentSessionStore
|
|
31
32
|
from langchain_agentx.workspace import resolve_agent_state_config
|
|
32
33
|
from .conversation_session import ConversationSession
|
|
33
34
|
|
|
@@ -65,6 +66,9 @@ def create_conversation_session(
|
|
|
65
66
|
cfg = replace(cfg, workspace=replace(cfg.workspace, workspace_trust_accepted=workspace_trust_accepted))
|
|
66
67
|
|
|
67
68
|
resolved_id = conversation_id or f"conv-{uuid4().hex}"
|
|
69
|
+
# graph 每轮新建,但 read 状态须跨 turn;与 AgentSession 一样持有共享 store
|
|
70
|
+
session_store = svcs.session_store or AgentSessionStore(session_id=resolved_id)
|
|
71
|
+
svcs = replace(svcs, session_store=session_store)
|
|
68
72
|
|
|
69
73
|
if hook_engine is None:
|
|
70
74
|
snapshot = svcs.hooks.build_snapshot() if svcs.hooks is not None else HooksConfigSnapshot()
|
|
@@ -84,6 +88,7 @@ def create_conversation_session(
|
|
|
84
88
|
svcs,
|
|
85
89
|
capabilities=overlay.capabilities if overlay.capabilities is not None else svcs.capabilities,
|
|
86
90
|
command_registry=command_registry,
|
|
91
|
+
session_store=session_store,
|
|
87
92
|
)
|
|
88
93
|
return create_loop_agent(model, config=runtime_cfg, services=final_svcs)
|
|
89
94
|
|
|
@@ -96,6 +101,7 @@ def create_conversation_session(
|
|
|
96
101
|
capabilities=svcs.capabilities,
|
|
97
102
|
command_registry=command_registry,
|
|
98
103
|
mcp_plugin_sink=plugin_mcp,
|
|
104
|
+
session_store=session_store,
|
|
99
105
|
)
|
|
100
106
|
|
|
101
107
|
|
|
@@ -70,6 +70,7 @@ class ConversationSession:
|
|
|
70
70
|
capabilities: RuntimeCapabilities | None = None,
|
|
71
71
|
command_registry: CommandRegistry | None = None,
|
|
72
72
|
mcp_plugin_sink: list[Any] | None = None,
|
|
73
|
+
session_store: Any | None = None,
|
|
73
74
|
) -> None:
|
|
74
75
|
self._graph_factory = graph_factory
|
|
75
76
|
self._conversation_id = conversation_id
|
|
@@ -80,6 +81,8 @@ class ConversationSession:
|
|
|
80
81
|
self._container_type = "conversation"
|
|
81
82
|
self._session_memory_manager: Any | None = None
|
|
82
83
|
self._capabilities = capabilities
|
|
84
|
+
# 跨 turn 共享 store(graph 每轮新建);供 /clear · /compact 清读状态
|
|
85
|
+
self._session_store = session_store
|
|
83
86
|
self._skill_registry = SkillRegistry(workspace_root=workspace_cfg.workspace_root)
|
|
84
87
|
self._command_registry = PluginCommandRegistry()
|
|
85
88
|
self._agent_registry = AgentRegistry()
|
|
@@ -361,11 +364,42 @@ class ConversationSession:
|
|
|
361
364
|
return self._dispatcher
|
|
362
365
|
|
|
363
366
|
def clear_context(self) -> None:
|
|
367
|
+
"""清空对话消息;若能解析到 session_store 则对齐 CC /clear 清工具状态。"""
|
|
364
368
|
self._messages.clear()
|
|
369
|
+
store = self._resolve_session_store()
|
|
370
|
+
if store is not None:
|
|
371
|
+
from ..tool_runtime.read_state_lifecycle import (
|
|
372
|
+
clear_tool_state_on_conversation_reset,
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
clear_tool_state_on_conversation_reset(store)
|
|
365
376
|
|
|
366
377
|
async def compact_context(self) -> tuple[int, int]:
|
|
378
|
+
"""压缩上下文;真·蒸发时清空 last_read(对齐 CC compact.ts)。"""
|
|
379
|
+
from ..tool_runtime.read_state_lifecycle import clear_file_reads_if_evaporated
|
|
380
|
+
from ..workspace.plans import resolve_plans_directory
|
|
381
|
+
|
|
367
382
|
before_tokens = total_estimated_tokens_for_messages(self._messages, num_chars_per_token=4)
|
|
368
383
|
patch = default_loop_context_compaction().run({"messages": self._messages})
|
|
384
|
+
store = self._resolve_session_store()
|
|
385
|
+
if store is not None:
|
|
386
|
+
plans_dir = None
|
|
387
|
+
memory_paths: list[str] = []
|
|
388
|
+
try:
|
|
389
|
+
plans_dir = resolve_plans_directory(self._workspace_cfg)
|
|
390
|
+
except Exception:
|
|
391
|
+
plans_dir = None
|
|
392
|
+
entry = getattr(self._workspace_cfg, "memory_entrypoint", None)
|
|
393
|
+
if entry is not None:
|
|
394
|
+
memory_paths.append(str(entry))
|
|
395
|
+
clear_file_reads_if_evaporated(
|
|
396
|
+
store,
|
|
397
|
+
patch,
|
|
398
|
+
plans_dir=plans_dir,
|
|
399
|
+
memory_paths=memory_paths or None,
|
|
400
|
+
session_id=self._conversation_id,
|
|
401
|
+
workspace_cfg=self._workspace_cfg,
|
|
402
|
+
)
|
|
369
403
|
if isinstance(patch.get("messages"), list):
|
|
370
404
|
self._messages = list(patch["messages"])
|
|
371
405
|
after_tokens = total_estimated_tokens_for_messages(self._messages, num_chars_per_token=4)
|
|
@@ -421,7 +455,8 @@ class ConversationSession:
|
|
|
421
455
|
return catalog.list_skills_menu(dynamic_catalog=dynamic)
|
|
422
456
|
|
|
423
457
|
def _resolve_session_store(self) -> Any | None:
|
|
424
|
-
|
|
458
|
+
"""跨 turn 共享的 AgentSessionStore(工厂注入;无则 None)。"""
|
|
459
|
+
return self._session_store
|
|
425
460
|
|
|
426
461
|
async def _execute_hook(self, event: HookEvent) -> None:
|
|
427
462
|
ctx = HookContext(event=event, state={}, session_id=self._conversation_id)
|
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
"""
|
|
2
|
+
tool_runtime/post_compact_restore.py — 真·蒸发后恢复最近读文件(对齐 CC)
|
|
3
|
+
|
|
4
|
+
职责:
|
|
5
|
+
对齐 ``createPostCompactFileAttachments`` + ``messages.ts`` ``case 'file'``:
|
|
6
|
+
clear 前快照 → ≤N 读盘(失败回落快照)→ 重注册 last_read
|
|
7
|
+
→ 注入合成 Read tool_use + tool_result(system-reminder 包裹);
|
|
8
|
+
另可选追加 ``plan_file_reference``(对齐 CC ``createPlanAttachmentIfNeeded``)。
|
|
9
|
+
|
|
10
|
+
链路位置:
|
|
11
|
+
``read_state_lifecycle.clear_file_reads_if_evaporated`` 在 clear 后调用,
|
|
12
|
+
并把 ``messages`` 追加进 compaction patch。
|
|
13
|
+
|
|
14
|
+
当前裁剪范围:
|
|
15
|
+
仅 text 文件路径;跳过 ``is_partial_view`` / plan / memory 路径 / 保留尾部非 stub Read;
|
|
16
|
+
不含 skill listing / async agent / nested_memory 其它 post-compact 附件
|
|
17
|
+
(SDK 尚无 invoked-skills 登记表)。
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import time
|
|
23
|
+
import uuid
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any, Collection
|
|
27
|
+
|
|
28
|
+
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
|
|
29
|
+
|
|
30
|
+
from langchain_agentx.tools.read.prompt import FILE_UNCHANGED_STUB, TOOL_NAME
|
|
31
|
+
from langchain_agentx.utils.file_mtime import FileModificationTimeReader
|
|
32
|
+
|
|
33
|
+
# CC compact.ts
|
|
34
|
+
POST_COMPACT_MAX_FILES_TO_RESTORE = 5
|
|
35
|
+
POST_COMPACT_MAX_TOKENS_PER_FILE = 5_000
|
|
36
|
+
POST_COMPACT_TOKEN_BUDGET = 50_000
|
|
37
|
+
_CHARS_PER_TOKEN = 4
|
|
38
|
+
|
|
39
|
+
# 对齐 CC shouldExcludeFromPostCompactRestore 的 memory 文件名面
|
|
40
|
+
_EXCLUDED_MEMORY_BASENAMES = frozenset(
|
|
41
|
+
{
|
|
42
|
+
"CLAUDE.md",
|
|
43
|
+
"CLAUDE.local.md",
|
|
44
|
+
"AGENT.md",
|
|
45
|
+
"AGENT.local.md",
|
|
46
|
+
".cursorrules",
|
|
47
|
+
".cursorrules.local",
|
|
48
|
+
"MEMORY.md",
|
|
49
|
+
}
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
_TRUNCATION_NOTE = (
|
|
53
|
+
"Note: The file {filename} was too large and has been truncated. "
|
|
54
|
+
"Don't tell the user about this truncation. Use {tool} to read more "
|
|
55
|
+
"of the file if you need."
|
|
56
|
+
)
|
|
57
|
+
_TOO_LARGE_REFERENCE = (
|
|
58
|
+
"Note: {filename} was read before the last conversation was summarized, "
|
|
59
|
+
"but the contents are too large to include. Use {tool} tool if you need "
|
|
60
|
+
"to access it."
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class PostCompactRestoreResult:
|
|
66
|
+
restored: tuple[str, ...]
|
|
67
|
+
skipped_preserved: tuple[str, ...]
|
|
68
|
+
skipped_partial: tuple[str, ...]
|
|
69
|
+
skipped_excluded: tuple[str, ...]
|
|
70
|
+
skipped_budget: tuple[str, ...]
|
|
71
|
+
failed: tuple[str, ...]
|
|
72
|
+
messages: tuple[Any, ...] = field(default_factory=tuple)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def should_exclude_from_post_compact_restore(
|
|
76
|
+
path: str,
|
|
77
|
+
*,
|
|
78
|
+
plans_dir: Path | str | None = None,
|
|
79
|
+
memory_paths: Collection[str] | None = None,
|
|
80
|
+
) -> bool:
|
|
81
|
+
"""对齐 CC ``shouldExcludeFromPostCompactRestore``:排除 plan / memory 路径。"""
|
|
82
|
+
try:
|
|
83
|
+
resolved = Path(path).resolve()
|
|
84
|
+
except OSError:
|
|
85
|
+
resolved = Path(path)
|
|
86
|
+
name = resolved.name
|
|
87
|
+
if name in _EXCLUDED_MEMORY_BASENAMES:
|
|
88
|
+
return True
|
|
89
|
+
if memory_paths:
|
|
90
|
+
for raw in memory_paths:
|
|
91
|
+
try:
|
|
92
|
+
if resolved == Path(raw).resolve():
|
|
93
|
+
return True
|
|
94
|
+
except OSError:
|
|
95
|
+
if str(resolved) == str(raw):
|
|
96
|
+
return True
|
|
97
|
+
if plans_dir is not None:
|
|
98
|
+
try:
|
|
99
|
+
plans = Path(plans_dir).resolve()
|
|
100
|
+
resolved.relative_to(plans)
|
|
101
|
+
return True
|
|
102
|
+
except (OSError, ValueError):
|
|
103
|
+
pass
|
|
104
|
+
# 无 plans_dir 时的启发式:路径段落含 plans 目录名
|
|
105
|
+
if any(part == "plans" for part in resolved.parts):
|
|
106
|
+
return True
|
|
107
|
+
return False
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class PostCompactReadStateRestorer:
|
|
111
|
+
"""清前快照 → 选最近文件 → 读盘/回落 → 重注册 + 注入合成 Read 消息。"""
|
|
112
|
+
|
|
113
|
+
def __init__(
|
|
114
|
+
self,
|
|
115
|
+
*,
|
|
116
|
+
max_files: int = POST_COMPACT_MAX_FILES_TO_RESTORE,
|
|
117
|
+
max_tokens_per_file: int = POST_COMPACT_MAX_TOKENS_PER_FILE,
|
|
118
|
+
token_budget: int = POST_COMPACT_TOKEN_BUDGET,
|
|
119
|
+
mtime_reader: FileModificationTimeReader | None = None,
|
|
120
|
+
plans_dir: Path | str | None = None,
|
|
121
|
+
memory_paths: Collection[str] | None = None,
|
|
122
|
+
) -> None:
|
|
123
|
+
self._max_files = max(0, max_files)
|
|
124
|
+
self._max_chars_per_file = max_tokens_per_file * _CHARS_PER_TOKEN
|
|
125
|
+
self._char_budget = token_budget * _CHARS_PER_TOKEN
|
|
126
|
+
self._mtime = mtime_reader or FileModificationTimeReader()
|
|
127
|
+
self._plans_dir = plans_dir
|
|
128
|
+
self._memory_paths = tuple(memory_paths) if memory_paths else ()
|
|
129
|
+
|
|
130
|
+
def restore(
|
|
131
|
+
self,
|
|
132
|
+
store: Any,
|
|
133
|
+
pre_clear: dict[str, dict[str, Any]],
|
|
134
|
+
*,
|
|
135
|
+
preserved_messages: list[Any] | None = None,
|
|
136
|
+
) -> PostCompactRestoreResult:
|
|
137
|
+
preserved = collect_preserved_read_paths(preserved_messages or [])
|
|
138
|
+
skipped_excluded = tuple(
|
|
139
|
+
p
|
|
140
|
+
for p, entry in pre_clear.items()
|
|
141
|
+
if isinstance(entry, dict)
|
|
142
|
+
and should_exclude_from_post_compact_restore(
|
|
143
|
+
p,
|
|
144
|
+
plans_dir=self._plans_dir,
|
|
145
|
+
memory_paths=self._memory_paths,
|
|
146
|
+
)
|
|
147
|
+
)
|
|
148
|
+
candidates = self._select_candidates(pre_clear, preserved)
|
|
149
|
+
|
|
150
|
+
restored: list[str] = []
|
|
151
|
+
skipped_partial: list[str] = []
|
|
152
|
+
skipped_budget: list[str] = []
|
|
153
|
+
failed: list[str] = []
|
|
154
|
+
out_messages: list[Any] = []
|
|
155
|
+
skipped_preserved = tuple(p for p in pre_clear if _norm(p) in preserved)
|
|
156
|
+
used_chars = 0
|
|
157
|
+
|
|
158
|
+
for path, entry in candidates:
|
|
159
|
+
if bool(entry.get("is_partial_view")):
|
|
160
|
+
skipped_partial.append(path)
|
|
161
|
+
continue
|
|
162
|
+
content = self._load_content(path, entry)
|
|
163
|
+
if content is None:
|
|
164
|
+
failed.append(path)
|
|
165
|
+
continue
|
|
166
|
+
|
|
167
|
+
truncated = False
|
|
168
|
+
if len(content) > self._max_chars_per_file:
|
|
169
|
+
content = content[: self._max_chars_per_file]
|
|
170
|
+
truncated = True
|
|
171
|
+
|
|
172
|
+
if used_chars + len(content) > self._char_budget:
|
|
173
|
+
# CC compact_file_reference:太大放不进预算时只留提示
|
|
174
|
+
skipped_budget.append(path)
|
|
175
|
+
out_messages.append(
|
|
176
|
+
HumanMessage(
|
|
177
|
+
content=_wrap_system_reminder(
|
|
178
|
+
_TOO_LARGE_REFERENCE.format(
|
|
179
|
+
filename=path, tool=TOOL_NAME
|
|
180
|
+
)
|
|
181
|
+
),
|
|
182
|
+
additional_kwargs={
|
|
183
|
+
"metadata": {
|
|
184
|
+
"attachment": {
|
|
185
|
+
"type": "compact_file_reference",
|
|
186
|
+
"filename": path,
|
|
187
|
+
},
|
|
188
|
+
"is_meta": True,
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
)
|
|
192
|
+
)
|
|
193
|
+
continue
|
|
194
|
+
|
|
195
|
+
self._register(store, path, content, entry)
|
|
196
|
+
used_chars += len(content)
|
|
197
|
+
restored.append(path)
|
|
198
|
+
out_messages.extend(
|
|
199
|
+
build_post_compact_file_messages(
|
|
200
|
+
path, content, truncated=truncated
|
|
201
|
+
)
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
return PostCompactRestoreResult(
|
|
205
|
+
restored=tuple(restored),
|
|
206
|
+
skipped_preserved=skipped_preserved,
|
|
207
|
+
skipped_partial=tuple(skipped_partial),
|
|
208
|
+
skipped_excluded=skipped_excluded,
|
|
209
|
+
skipped_budget=tuple(skipped_budget),
|
|
210
|
+
failed=tuple(failed),
|
|
211
|
+
messages=tuple(out_messages),
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
def _select_candidates(
|
|
215
|
+
self,
|
|
216
|
+
pre_clear: dict[str, dict[str, Any]],
|
|
217
|
+
preserved: set[str],
|
|
218
|
+
) -> list[tuple[str, dict[str, Any]]]:
|
|
219
|
+
"""先排除 plan/memory / preserved,再按 ts 取最近 max_files(对齐 CC)。"""
|
|
220
|
+
items: list[tuple[str, dict[str, Any], float]] = []
|
|
221
|
+
for path, entry in pre_clear.items():
|
|
222
|
+
if not isinstance(entry, dict):
|
|
223
|
+
continue
|
|
224
|
+
if _norm(path) in preserved:
|
|
225
|
+
continue
|
|
226
|
+
if should_exclude_from_post_compact_restore(
|
|
227
|
+
path,
|
|
228
|
+
plans_dir=self._plans_dir,
|
|
229
|
+
memory_paths=self._memory_paths,
|
|
230
|
+
):
|
|
231
|
+
continue
|
|
232
|
+
ts = entry.get("ts")
|
|
233
|
+
try:
|
|
234
|
+
score = float(ts) if ts is not None else 0.0
|
|
235
|
+
except (TypeError, ValueError):
|
|
236
|
+
score = 0.0
|
|
237
|
+
items.append((path, entry, score))
|
|
238
|
+
items.sort(key=lambda x: x[2], reverse=True)
|
|
239
|
+
return [(p, e) for p, e, _ in items[: self._max_files]]
|
|
240
|
+
|
|
241
|
+
def _load_content(self, path: str, entry: dict[str, Any]) -> str | None:
|
|
242
|
+
try:
|
|
243
|
+
return Path(path).read_text(encoding="utf-8")
|
|
244
|
+
except OSError:
|
|
245
|
+
snap = entry.get("content")
|
|
246
|
+
return snap if isinstance(snap, str) else None
|
|
247
|
+
|
|
248
|
+
def _register(
|
|
249
|
+
self,
|
|
250
|
+
store: Any,
|
|
251
|
+
path: str,
|
|
252
|
+
content: str,
|
|
253
|
+
entry: dict[str, Any],
|
|
254
|
+
) -> None:
|
|
255
|
+
mtime_ms = self._mtime.read_ms(path)
|
|
256
|
+
payload = {
|
|
257
|
+
"tool_call_id": None,
|
|
258
|
+
"ts": time.time(),
|
|
259
|
+
"offset": None,
|
|
260
|
+
"limit": None,
|
|
261
|
+
"mtime_ms": mtime_ms,
|
|
262
|
+
"line_start": None,
|
|
263
|
+
"line_end": None,
|
|
264
|
+
"content": content,
|
|
265
|
+
}
|
|
266
|
+
upsert = getattr(store, "upsert_last_read_from_bridge_entry", None)
|
|
267
|
+
if callable(upsert):
|
|
268
|
+
upsert(path, payload)
|
|
269
|
+
return
|
|
270
|
+
record = getattr(store, "record_file_read", None)
|
|
271
|
+
if callable(record):
|
|
272
|
+
record(path, tool_call_id=None, content=content, mtime_ms=mtime_ms)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def build_post_compact_file_messages(
|
|
276
|
+
path: str,
|
|
277
|
+
content: str,
|
|
278
|
+
*,
|
|
279
|
+
truncated: bool = False,
|
|
280
|
+
) -> list[Any]:
|
|
281
|
+
"""对齐 CC ``messages.ts`` ``case 'file'`` / text:合成 Read tool_use + result。"""
|
|
282
|
+
tool_call_id = f"postcompact_{uuid.uuid4().hex[:16]}"
|
|
283
|
+
tool_content = _wrap_system_reminder(content)
|
|
284
|
+
msgs: list[Any] = [
|
|
285
|
+
AIMessage(
|
|
286
|
+
content="",
|
|
287
|
+
tool_calls=[
|
|
288
|
+
{
|
|
289
|
+
"name": TOOL_NAME,
|
|
290
|
+
"args": {"file_path": path},
|
|
291
|
+
"id": tool_call_id,
|
|
292
|
+
"type": "tool_call",
|
|
293
|
+
}
|
|
294
|
+
],
|
|
295
|
+
additional_kwargs={
|
|
296
|
+
"metadata": {
|
|
297
|
+
"attachment": {"type": "file", "filename": path},
|
|
298
|
+
"post_compact_restore": True,
|
|
299
|
+
}
|
|
300
|
+
},
|
|
301
|
+
),
|
|
302
|
+
ToolMessage(
|
|
303
|
+
content=tool_content,
|
|
304
|
+
tool_call_id=tool_call_id,
|
|
305
|
+
name=TOOL_NAME,
|
|
306
|
+
additional_kwargs={
|
|
307
|
+
"metadata": {
|
|
308
|
+
"attachment": {"type": "file", "filename": path},
|
|
309
|
+
"post_compact_restore": True,
|
|
310
|
+
}
|
|
311
|
+
},
|
|
312
|
+
),
|
|
313
|
+
]
|
|
314
|
+
if truncated:
|
|
315
|
+
msgs.append(
|
|
316
|
+
HumanMessage(
|
|
317
|
+
content=_wrap_system_reminder(
|
|
318
|
+
_TRUNCATION_NOTE.format(filename=path, tool=TOOL_NAME)
|
|
319
|
+
),
|
|
320
|
+
additional_kwargs={
|
|
321
|
+
"metadata": {
|
|
322
|
+
"attachment": {
|
|
323
|
+
"type": "file",
|
|
324
|
+
"filename": path,
|
|
325
|
+
"truncated": True,
|
|
326
|
+
},
|
|
327
|
+
"is_meta": True,
|
|
328
|
+
"post_compact_restore": True,
|
|
329
|
+
}
|
|
330
|
+
},
|
|
331
|
+
)
|
|
332
|
+
)
|
|
333
|
+
return msgs
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def collect_preserved_read_paths(messages: list[Any]) -> set[str]:
|
|
337
|
+
"""保留尾部中「非 stub」Read 的 file_path(对齐 CC collectReadToolFilePaths)。"""
|
|
338
|
+
stub_ids: set[str] = set()
|
|
339
|
+
for msg in messages:
|
|
340
|
+
content = getattr(msg, "content", None)
|
|
341
|
+
tool_call_id = getattr(msg, "tool_call_id", None)
|
|
342
|
+
if (
|
|
343
|
+
tool_call_id
|
|
344
|
+
and isinstance(content, str)
|
|
345
|
+
and (
|
|
346
|
+
content.startswith(FILE_UNCHANGED_STUB)
|
|
347
|
+
or FILE_UNCHANGED_STUB in content
|
|
348
|
+
)
|
|
349
|
+
):
|
|
350
|
+
stub_ids.add(str(tool_call_id))
|
|
351
|
+
|
|
352
|
+
paths: set[str] = set()
|
|
353
|
+
for msg in messages:
|
|
354
|
+
tool_calls = getattr(msg, "tool_calls", None)
|
|
355
|
+
if not isinstance(tool_calls, list):
|
|
356
|
+
ak = getattr(msg, "additional_kwargs", None)
|
|
357
|
+
if isinstance(ak, dict) and isinstance(ak.get("tool_calls"), list):
|
|
358
|
+
tool_calls = ak["tool_calls"]
|
|
359
|
+
if not isinstance(tool_calls, list):
|
|
360
|
+
continue
|
|
361
|
+
for tc in tool_calls:
|
|
362
|
+
if not isinstance(tc, dict):
|
|
363
|
+
tc_name = getattr(tc, "name", None)
|
|
364
|
+
tc_id = getattr(tc, "id", None)
|
|
365
|
+
tc_args = getattr(tc, "args", None) or getattr(tc, "arguments", None)
|
|
366
|
+
else:
|
|
367
|
+
tc_name = tc.get("name") or (tc.get("function") or {}).get("name")
|
|
368
|
+
tc_id = tc.get("id")
|
|
369
|
+
tc_args = tc.get("args") or tc.get("arguments")
|
|
370
|
+
if isinstance(tc.get("function"), dict) and tc_args is None:
|
|
371
|
+
tc_args = tc["function"].get("arguments")
|
|
372
|
+
if tc_name != TOOL_NAME:
|
|
373
|
+
continue
|
|
374
|
+
if tc_id is not None and str(tc_id) in stub_ids:
|
|
375
|
+
continue
|
|
376
|
+
path = _file_path_from_args(tc_args)
|
|
377
|
+
if path:
|
|
378
|
+
paths.add(_norm(path))
|
|
379
|
+
return paths
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _wrap_system_reminder(content: str) -> str:
|
|
383
|
+
"""对齐 CC ``wrapInSystemReminder``。"""
|
|
384
|
+
return f"<system-reminder>\n{content}\n</system-reminder>"
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _file_path_from_args(args: Any) -> str | None:
|
|
388
|
+
if isinstance(args, str):
|
|
389
|
+
import json
|
|
390
|
+
|
|
391
|
+
try:
|
|
392
|
+
args = json.loads(args)
|
|
393
|
+
except (TypeError, ValueError, json.JSONDecodeError):
|
|
394
|
+
return None
|
|
395
|
+
if not isinstance(args, dict):
|
|
396
|
+
return None
|
|
397
|
+
raw = args.get("file_path")
|
|
398
|
+
return raw if isinstance(raw, str) and raw else None
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _norm(path: str) -> str:
|
|
402
|
+
try:
|
|
403
|
+
return str(Path(path).resolve())
|
|
404
|
+
except OSError:
|
|
405
|
+
return path
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def build_post_compact_plan_reference_message(
|
|
409
|
+
session_id: str,
|
|
410
|
+
workspace_cfg: Any,
|
|
411
|
+
*,
|
|
412
|
+
agent_id: str | None = None,
|
|
413
|
+
) -> HumanMessage | None:
|
|
414
|
+
"""对齐 CC ``createPlanAttachmentIfNeeded``:有 plan 内容则注入 plan_file_reference。"""
|
|
415
|
+
if not session_id or workspace_cfg is None:
|
|
416
|
+
return None
|
|
417
|
+
try:
|
|
418
|
+
from langchain_agentx.workspace.plans import get_plan_content, get_plan_file_path
|
|
419
|
+
except ImportError:
|
|
420
|
+
return None
|
|
421
|
+
content = get_plan_content(session_id, workspace_cfg)
|
|
422
|
+
if not content:
|
|
423
|
+
return None
|
|
424
|
+
plan_path = str(get_plan_file_path(session_id, workspace_cfg, agent_id=agent_id))
|
|
425
|
+
return HumanMessage(
|
|
426
|
+
content=_wrap_system_reminder(
|
|
427
|
+
f"Current plan file ({plan_path}):\n\n{content}"
|
|
428
|
+
),
|
|
429
|
+
additional_kwargs={
|
|
430
|
+
"metadata": {
|
|
431
|
+
"attachment": {
|
|
432
|
+
"type": "plan_file_reference",
|
|
433
|
+
"planFilePath": plan_path,
|
|
434
|
+
"planContent": content,
|
|
435
|
+
},
|
|
436
|
+
"is_meta": True,
|
|
437
|
+
"post_compact_restore": True,
|
|
438
|
+
}
|
|
439
|
+
},
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def append_post_compact_plan_to_patch(
|
|
444
|
+
patch: dict[str, Any],
|
|
445
|
+
*,
|
|
446
|
+
session_id: str | None,
|
|
447
|
+
workspace_cfg: Any,
|
|
448
|
+
agent_id: str | None = None,
|
|
449
|
+
) -> bool:
|
|
450
|
+
"""若真蒸发且有 plan,将 plan_file_reference 追加到 ``patch['messages']``。"""
|
|
451
|
+
if not session_id or "messages" not in patch:
|
|
452
|
+
return False
|
|
453
|
+
msg = build_post_compact_plan_reference_message(
|
|
454
|
+
session_id, workspace_cfg, agent_id=agent_id
|
|
455
|
+
)
|
|
456
|
+
if msg is None:
|
|
457
|
+
return False
|
|
458
|
+
base = patch.get("messages")
|
|
459
|
+
msgs = list(base) if isinstance(base, list) else []
|
|
460
|
+
msgs.append(msg)
|
|
461
|
+
patch["messages"] = msgs
|
|
462
|
+
return True
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""
|
|
2
|
+
tool_runtime/read_state_lifecycle.py — 读状态清空边界(对齐 CC readFileState)
|
|
3
|
+
|
|
4
|
+
职责:
|
|
5
|
+
判定「真·蒸发」与 /clear 会话重置时应清哪些工具状态。
|
|
6
|
+
供 LoopGraphBuilder.prune_and_compress 与 AgentSession.clear/compact 共用。
|
|
7
|
+
|
|
8
|
+
链路位置:
|
|
9
|
+
factory._clear_file_reads_after_message_compaction
|
|
10
|
+
· AgentSession.clear_context / compact_context
|
|
11
|
+
|
|
12
|
+
当前裁剪范围:
|
|
13
|
+
post-compact 恢复含 last_read 重注册 + 合成 Read + 可选 plan_file_reference;
|
|
14
|
+
/clear 与真蒸发同时清 ``loaded_nested_memory_paths``;
|
|
15
|
+
seeder 已接 nested ``.has``/``.add``;
|
|
16
|
+
不含 skill listing / async agent 其它 post-compact 附件。
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from langchain_agentx.tool_runtime.post_compact_restore import (
|
|
24
|
+
PostCompactReadStateRestorer,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def messages_truly_evaporated(patch: dict[str, Any]) -> bool:
|
|
29
|
+
"""是否发生「真·蒸发」——对齐 CC 仅在 compact/clear/fork 清 readFileState。
|
|
30
|
+
|
|
31
|
+
snip / microcompact / tool_result_budget / collapse 等常驻裁剪会改 messages,
|
|
32
|
+
但内容仍在上下文;此时清空 last_read 会让跨轮 Write/Edit 误报未读
|
|
33
|
+
(BUG-20261109-32)。仅 session_memory 全量摘要或 autocompact 折叠/摘要时为真。
|
|
34
|
+
"""
|
|
35
|
+
meta = patch.get("compaction_pipeline_meta")
|
|
36
|
+
if not isinstance(meta, dict):
|
|
37
|
+
return False
|
|
38
|
+
if meta.get("session_memory_compaction") == "applied":
|
|
39
|
+
return True
|
|
40
|
+
if meta.get("autocompact_mode") == "session_memory":
|
|
41
|
+
return True
|
|
42
|
+
stages = meta.get("stages")
|
|
43
|
+
if not isinstance(stages, list):
|
|
44
|
+
return False
|
|
45
|
+
for stage in stages:
|
|
46
|
+
if not isinstance(stage, dict) or stage.get("name") != "autocompact":
|
|
47
|
+
continue
|
|
48
|
+
extra = stage.get("extra")
|
|
49
|
+
if not isinstance(extra, dict):
|
|
50
|
+
extra = {}
|
|
51
|
+
if extra.get("autocompact_skipped"):
|
|
52
|
+
continue
|
|
53
|
+
if int(stage.get("tokens_freed") or 0) > 0:
|
|
54
|
+
return True
|
|
55
|
+
if int(extra.get("folded_messages") or 0) > 0:
|
|
56
|
+
return True
|
|
57
|
+
if extra.get("autocompact_mode") in {
|
|
58
|
+
"llm",
|
|
59
|
+
"prune",
|
|
60
|
+
"prune_blocked_llm",
|
|
61
|
+
}:
|
|
62
|
+
return True
|
|
63
|
+
return False
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _clear_loaded_nested_memory_paths(store: Any) -> None:
|
|
67
|
+
clearer = getattr(store, "clear_loaded_nested_memory_paths", None)
|
|
68
|
+
if callable(clearer):
|
|
69
|
+
clearer()
|
|
70
|
+
return
|
|
71
|
+
nested = getattr(store, "loaded_nested_memory_paths", None)
|
|
72
|
+
if isinstance(nested, set):
|
|
73
|
+
nested.clear()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def clear_tool_state_on_conversation_reset(store: Any) -> None:
|
|
77
|
+
"""对齐 CC ``/clear``:``readFileState.clear`` + skill/nested 去重集合。
|
|
78
|
+
|
|
79
|
+
CC: ``commands/clear/conversation.ts`` —
|
|
80
|
+
``readFileState.clear(); discoveredSkillNames?.clear(); loadedNestedMemoryPaths?.clear()``。
|
|
81
|
+
SDK:``clear_file_read_state`` + ``loaded_nested_memory_paths`` +
|
|
82
|
+
``dynamic_skill_catalog.discoverer.seen_dirs``。
|
|
83
|
+
"""
|
|
84
|
+
clearer = getattr(store, "clear_file_read_state", None)
|
|
85
|
+
if callable(clearer):
|
|
86
|
+
clearer()
|
|
87
|
+
_clear_loaded_nested_memory_paths(store)
|
|
88
|
+
catalog = getattr(store, "dynamic_skill_catalog", None)
|
|
89
|
+
if catalog is None:
|
|
90
|
+
return
|
|
91
|
+
discoverer = getattr(catalog, "discoverer", None)
|
|
92
|
+
seen = getattr(discoverer, "seen_dirs", None)
|
|
93
|
+
if isinstance(seen, set):
|
|
94
|
+
seen.clear()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def clear_file_reads_if_evaporated(
|
|
98
|
+
store: Any,
|
|
99
|
+
patch: dict[str, Any],
|
|
100
|
+
*,
|
|
101
|
+
restorer: PostCompactReadStateRestorer | None = None,
|
|
102
|
+
plans_dir: Any = None,
|
|
103
|
+
memory_paths: Any = None,
|
|
104
|
+
session_id: str | None = None,
|
|
105
|
+
workspace_cfg: Any = None,
|
|
106
|
+
agent_id: str | None = None,
|
|
107
|
+
) -> bool:
|
|
108
|
+
"""若 patch 含 messages 且真·蒸发:快照 → clear → ≤5 重注册 + 注入合成 Read。
|
|
109
|
+
|
|
110
|
+
对齐 CC compact:``readFileState.clear(); loadedNestedMemoryPaths?.clear()``,
|
|
111
|
+
再 ``createPostCompactFileAttachments`` + ``createPlanAttachmentIfNeeded``。
|
|
112
|
+
恢复消息追加到 ``patch["messages"]``。返回是否执行了 clear。
|
|
113
|
+
"""
|
|
114
|
+
if "messages" not in patch:
|
|
115
|
+
return False
|
|
116
|
+
if not messages_truly_evaporated(patch):
|
|
117
|
+
return False
|
|
118
|
+
clearer = getattr(store, "clear_file_read_state", None)
|
|
119
|
+
if not callable(clearer):
|
|
120
|
+
return False
|
|
121
|
+
|
|
122
|
+
pre: dict[str, dict[str, Any]] = {}
|
|
123
|
+
snap = getattr(store, "get_last_read_map_bridge_view", None)
|
|
124
|
+
if callable(snap):
|
|
125
|
+
raw = snap()
|
|
126
|
+
if isinstance(raw, dict):
|
|
127
|
+
pre = {
|
|
128
|
+
str(k): dict(v)
|
|
129
|
+
for k, v in raw.items()
|
|
130
|
+
if isinstance(v, dict)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
clearer()
|
|
134
|
+
_clear_loaded_nested_memory_paths(store)
|
|
135
|
+
|
|
136
|
+
active = restorer
|
|
137
|
+
if active is None and (plans_dir is not None or memory_paths is not None):
|
|
138
|
+
active = PostCompactReadStateRestorer(
|
|
139
|
+
plans_dir=plans_dir,
|
|
140
|
+
memory_paths=memory_paths,
|
|
141
|
+
)
|
|
142
|
+
elif active is None:
|
|
143
|
+
active = PostCompactReadStateRestorer()
|
|
144
|
+
|
|
145
|
+
if pre:
|
|
146
|
+
preserved = patch.get("messages")
|
|
147
|
+
msgs = preserved if isinstance(preserved, list) else None
|
|
148
|
+
result = active.restore(store, pre, preserved_messages=msgs)
|
|
149
|
+
if result.messages:
|
|
150
|
+
base = list(msgs) if msgs is not None else []
|
|
151
|
+
base.extend(result.messages)
|
|
152
|
+
patch["messages"] = base
|
|
153
|
+
|
|
154
|
+
if session_id and workspace_cfg is not None:
|
|
155
|
+
from langchain_agentx.tool_runtime.post_compact_restore import (
|
|
156
|
+
append_post_compact_plan_to_patch,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
append_post_compact_plan_to_patch(
|
|
160
|
+
patch,
|
|
161
|
+
session_id=session_id,
|
|
162
|
+
workspace_cfg=workspace_cfg,
|
|
163
|
+
agent_id=agent_id,
|
|
164
|
+
)
|
|
165
|
+
return True
|
|
@@ -7,6 +7,7 @@ runtime/session_store.py — 会话级状态存储
|
|
|
7
7
|
负责跨 turn 持久化的会话状态:
|
|
8
8
|
|
|
9
9
|
file_read_state — 文件读取记录(为 read-before-write / Edit staleness 服务)
|
|
10
|
+
loaded_nested_memory_paths — 嵌套 memory 附件去重(非淘汰 Set;对齐 CC)
|
|
10
11
|
file_history — 文件写入/编辑历史
|
|
11
12
|
audit_log — 工具调用审计日志(含权限窗口事件与工具框架审计)
|
|
12
13
|
permissions_cache — 权限决策缓存(避免重复询问)
|
|
@@ -24,7 +25,8 @@ runtime/session_store.py — 会话级状态存储
|
|
|
24
25
|
→ ToolExecutionContext.session_store;ToolStateBridge **仅**读写本对象。
|
|
25
26
|
|
|
26
27
|
当前裁剪范围:
|
|
27
|
-
不做磁盘持久化;grant 随 session 生命周期;enable_dynamic_root_grant 默认 False(workflow
|
|
28
|
+
不做磁盘持久化;grant 随 session 生命周期;enable_dynamic_root_grant 默认 False(workflow);
|
|
29
|
+
nested Set 的附件 ``.has``/``.add`` 热路径待 attachment 接线(BUG-34 最小切片仅字段+重置)。
|
|
28
30
|
"""
|
|
29
31
|
|
|
30
32
|
from __future__ import annotations
|
|
@@ -115,6 +117,9 @@ class AgentSessionStore:
|
|
|
115
117
|
self.session_id: str = session_id or str(uuid.uuid4())
|
|
116
118
|
self._created_at: float = time.time()
|
|
117
119
|
self._file_read_state: dict[str, FileReadRecord] = {}
|
|
120
|
+
# 对齐 CC ToolUseContext.loadedNestedMemoryPaths:永不淘汰的附件去重轨,
|
|
121
|
+
# 与 LRU 式 _file_read_state 分轨;fork /clear /compact 时重置。
|
|
122
|
+
self.loaded_nested_memory_paths: set[str] = set()
|
|
118
123
|
self._file_history: list[FileWriteRecord] = []
|
|
119
124
|
self._audit_log: list[dict[str, Any]] = []
|
|
120
125
|
self._permissions_cache: dict[str, Any] = {}
|
|
@@ -164,13 +169,26 @@ class AgentSessionStore:
|
|
|
164
169
|
self._file_read_state[path] = FileReadRecord.from_bridge_dict(path, entry)
|
|
165
170
|
|
|
166
171
|
def clear_file_read_state(self) -> None:
|
|
167
|
-
"""清空文件读缓存(对齐 CC ``readFileState.clear()
|
|
172
|
+
"""清空文件读缓存(对齐 CC ``readFileState.clear()``)。
|
|
168
173
|
|
|
169
|
-
|
|
170
|
-
|
|
174
|
+
调用边界:真·蒸发(autocompact / session_memory)、``/clear``、fork 隔离;
|
|
175
|
+
常驻 snip/microcompact 不得触发(BUG-20261109-32)。蒸发后若不清理,
|
|
176
|
+
Read dedup 会返回 ``file_unchanged`` stub 却断言「内容仍在本会话」
|
|
177
|
+
(BUG-20261107-28 A2)。
|
|
171
178
|
"""
|
|
172
179
|
self._file_read_state.clear()
|
|
173
180
|
|
|
181
|
+
def mark_nested_memory_loaded(self, path: str) -> None:
|
|
182
|
+
"""标记嵌套 memory 附件已注入(对齐 CC ``loadedNestedMemoryPaths.add``)。"""
|
|
183
|
+
self.loaded_nested_memory_paths.add(path)
|
|
184
|
+
|
|
185
|
+
def has_nested_memory_loaded(self, path: str) -> bool:
|
|
186
|
+
return path in self.loaded_nested_memory_paths
|
|
187
|
+
|
|
188
|
+
def clear_loaded_nested_memory_paths(self) -> None:
|
|
189
|
+
"""清空嵌套 memory 去重轨(对齐 CC ``loadedNestedMemoryPaths.clear()``)。"""
|
|
190
|
+
self.loaded_nested_memory_paths.clear()
|
|
191
|
+
|
|
174
192
|
def replace_all_file_reads_from_bridge_map(self, data: dict[str, Any]) -> None:
|
|
175
193
|
"""整体替换文件读映射(对应 ToolStateBridge.set_last_read_map)。"""
|
|
176
194
|
self._file_read_state.clear()
|
|
@@ -398,19 +416,25 @@ class AgentSessionStore:
|
|
|
398
416
|
*,
|
|
399
417
|
file_state_only: bool = True,
|
|
400
418
|
inherit_grants: bool = False,
|
|
401
|
-
inherit_file_reads: bool =
|
|
419
|
+
inherit_file_reads: bool = False,
|
|
402
420
|
) -> AgentSessionStore:
|
|
403
421
|
"""克隆会话存储。
|
|
404
422
|
|
|
405
|
-
``inherit_file_reads``
|
|
406
|
-
|
|
407
|
-
|
|
423
|
+
``inherit_file_reads`` 默认 ``False``(对齐 CC ``runAgent.ts``:仅当
|
|
424
|
+
``forkContextMessages !== undefined`` 才 ``cloneFileStateCache``)。
|
|
425
|
+
真 Fork / 后台 fork(已带父消息)须**显式**传 ``True``;plain / Skill
|
|
426
|
+
fork 保持默认空读缓存,避免 ``file_unchanged`` 假 stub。
|
|
427
|
+
|
|
428
|
+
``loaded_nested_memory_paths`` 恒空(对齐 CC ``forkedAgent.ts``
|
|
429
|
+
``loadedNestedMemoryPaths: new Set()``),与是否继承读缓存无关。
|
|
408
430
|
"""
|
|
409
431
|
new = AgentSessionStore(session_id=str(uuid.uuid4()))
|
|
410
432
|
if inherit_file_reads:
|
|
411
433
|
new._file_read_state = {
|
|
412
434
|
k: copy.deepcopy(v) for k, v in self._file_read_state.items()
|
|
413
435
|
}
|
|
436
|
+
# 显式重置:勿从父拷贝 nested 去重轨(__init__ 已空;防后续误继承)
|
|
437
|
+
new.loaded_nested_memory_paths = set()
|
|
414
438
|
if inherit_grants:
|
|
415
439
|
new._granted_roots = copy.deepcopy(self._granted_roots)
|
|
416
440
|
new.enable_dynamic_root_grant = self.enable_dynamic_root_grant
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
langchain_agentx/__init__.py,sha256=
|
|
1
|
+
langchain_agentx/__init__.py,sha256=IbtGZcLMlOyEzzdTvIPnPCQ-ODVGrD8ApebZRCEur7Y,2014
|
|
2
2
|
langchain_agentx/command/__init__.py,sha256=Ej260S5uFQcmEtGZQG_NH7BYjHoStrpBLtGUsBTxyZk,631
|
|
3
3
|
langchain_agentx/command/allowed_tools.py,sha256=TVA0VM8rm98H-QbLK_GRiX5RhEAZFxKawliMi4kk96A,3359
|
|
4
4
|
langchain_agentx/command/context.py,sha256=DIGOGPBw5UGDBm0WNNJlKx1h_9rCRmcdROv4DT61Qug,731
|
|
@@ -71,7 +71,7 @@ langchain_agentx/loop/exit/terminal.py,sha256=_DAZk-kS4Xd0nxMlayLo60-uj1Y5ozgBjL
|
|
|
71
71
|
langchain_agentx/loop/exit/withheld_error.py,sha256=LfX3j7Rgd9VoMzlz7GOs9TPuRe7RXr_Gxweyotx3tqQ,1846
|
|
72
72
|
langchain_agentx/loop/graph/__init__.py,sha256=9pUUqn7G87n3lV45iYIU24j0wcTHyCD--SSdtv3urh4,136
|
|
73
73
|
langchain_agentx/loop/graph/builtin_loop_control.py,sha256=31o4H6SDGC_vECSliXecuVEnzlD1ahlVZ5JzEpxYY04,9248
|
|
74
|
-
langchain_agentx/loop/graph/factory.py,sha256=
|
|
74
|
+
langchain_agentx/loop/graph/factory.py,sha256=KXSdgTRZM_UpqT4gL9JgSNoeT-Wa5R4iZ2K2n2NFpkA,115795
|
|
75
75
|
langchain_agentx/loop/graph/graph_edges.py,sha256=kW6Npx-nMIPzcaisCxVPkTwf5Y9GOKy1NWCNkJWeJBQ,47370
|
|
76
76
|
langchain_agentx/loop/graph/reactive_compact_node.py,sha256=633b5hTnR3BK8GBEKWhzOwGB0BQrVRKozNxDomWFjLo,8762
|
|
77
77
|
langchain_agentx/loop/graph/runtime_tools_node.py,sha256=wQkbc0ophyefpPZEc0q1vKoJOIdS4S6d6hSsrkdRLDk,7387
|
|
@@ -146,7 +146,7 @@ langchain_agentx/loop/subagent/active_run_registry.py,sha256=KurhAMDTBnRkdxNidaM
|
|
|
146
146
|
langchain_agentx/loop/subagent/async_runner.py,sha256=ZJu6DztRmg0SNEapEuPyQbsk8SprXiMKWDWDHb9L7yQ,14124
|
|
147
147
|
langchain_agentx/loop/subagent/boundary_snapshot.py,sha256=9cQuqN29nJDRnHnx9c8b09KRmODE2zv15Z06QyjVJps,10008
|
|
148
148
|
langchain_agentx/loop/subagent/cache_safe_params.py,sha256=-qcgdazEYRy6s4ILQuttpxraE3gsxq17Ro7LYBnuv3E,4460
|
|
149
|
-
langchain_agentx/loop/subagent/context.py,sha256=
|
|
149
|
+
langchain_agentx/loop/subagent/context.py,sha256=35sY4iWQIZPylO243yNz4MrVZerzq4-G5gCemAhFg-M,25778
|
|
150
150
|
langchain_agentx/loop/subagent/definition_permission.py,sha256=_Y30FA0EDTgqpqjw5luIiwbpABLo17myC3aY4NWbGIw,2188
|
|
151
151
|
langchain_agentx/loop/subagent/display_projector.py,sha256=AKsGWS1c9reH0kuD5u4oQ24KsBgyt7X10iZM3ere6Fs,3504
|
|
152
152
|
langchain_agentx/loop/subagent/fork_boilerplate.py,sha256=2Uh3cwegL7V-DvtLIxjX7ik5uW5mXfY2NBzP-biREso,5005
|
|
@@ -211,7 +211,7 @@ langchain_agentx/memory/instruction/__init__.py,sha256=ucQQMDX9B1h_FbsnX5D9fd-Uw
|
|
|
211
211
|
langchain_agentx/memory/instruction/exclusion.py,sha256=bUPJS6Hx7ONUdPOTQmMxNDTUBqnQBVgCnxF-jrAlmcw,2457
|
|
212
212
|
langchain_agentx/memory/instruction/external_includes.py,sha256=7yequcy-agxONzYqLx5YfIHi0EpY6u0yDGb-QLOqYok,1947
|
|
213
213
|
langchain_agentx/memory/instruction/loader.py,sha256=0xwVTbDKVNp19q51pNRaUgcsl2S7L_WhubThbbEDxR4,13762
|
|
214
|
-
langchain_agentx/memory/instruction/read_state_seeder.py,sha256=
|
|
214
|
+
langchain_agentx/memory/instruction/read_state_seeder.py,sha256=1fhG_Mlxw1Io_n67WcaT7ESQYKq_qmiwLxEYPYlKnE4,3278
|
|
215
215
|
langchain_agentx/memory/instruction/resolver.py,sha256=oFW8_qbDUQVk4h_qINaksFk7nCnn8qM2PSJbMpFi9Wg,781
|
|
216
216
|
langchain_agentx/memory/instruction/runtime.py,sha256=Pjb8dSQLa58YDoDj67ZnKDL9WqntTlTIJZ570IptT0Q,4137
|
|
217
217
|
langchain_agentx/memory/instruction/sections.py,sha256=7aHJbp48JIdTD8P7PuJlPuzJgnSQrN0BXg6bMgVSiUY,2809
|
|
@@ -352,11 +352,11 @@ langchain_agentx/provider/semantics/families/openai_finish_reason.py,sha256=t5eb
|
|
|
352
352
|
langchain_agentx/provider/semantics/families/openai_interpreter.py,sha256=zT7EFfHJ5fmYZ_F59vDfyrYdEwcMJANxkoW1Pt3iocI,1915
|
|
353
353
|
langchain_agentx/provider/semantics/families/openai_normalizer.py,sha256=oaf2Riz8EY6VQpc6SNKtsb-naMELw3gYV3IsnZoRBYU,2155
|
|
354
354
|
langchain_agentx/session/__init__.py,sha256=uXxjBzhW1FtvSfDTTaGZPbyeSFRzRQb2MfxDumKViug,1234
|
|
355
|
-
langchain_agentx/session/agent_session.py,sha256=
|
|
355
|
+
langchain_agentx/session/agent_session.py,sha256=L9Zvmc1jEjNHdQWNRq9PiwSCDHSbhx-pFDoU10o_kUk,26775
|
|
356
356
|
langchain_agentx/session/cleanup_registry.py,sha256=aaPUn9psCwgZ27fB1qW7lzc1TeKaBvQAxhcHDiNs2Rs,4137
|
|
357
|
-
langchain_agentx/session/conversation_factory.py,sha256=
|
|
357
|
+
langchain_agentx/session/conversation_factory.py,sha256=ophUDNIIJS9gVb0g1Y-8CndoCA6OAON92IR1sO-MLgQ,6747
|
|
358
358
|
langchain_agentx/session/conversation_recovery.py,sha256=OXzaxywRmqRwNA2Q1UNOpUvMlIjBzgdbsNPxPGHwoaA,5803
|
|
359
|
-
langchain_agentx/session/conversation_session.py,sha256=
|
|
359
|
+
langchain_agentx/session/conversation_session.py,sha256=Iuxuidu26MhtMUCmIdKw3yG7bsLnDWpfwt3kjhMeOrU,19677
|
|
360
360
|
langchain_agentx/session/factory.py,sha256=bwvkIppJS52_CVJ6RIjao6Kv7FDolR4-0-c5q0R_e6Y,6661
|
|
361
361
|
langchain_agentx/session/plan_mode.py,sha256=GjPLBG6eVrTB7M-CeMwLqkHCQDdD93cCgwIAvOF0wRM,4710
|
|
362
362
|
langchain_agentx/session/plan_mode_attachments.py,sha256=byIJC2F3RTJ9BTWVhpbE1e1rRwahAH5anPKsMXFvUE8,13861
|
|
@@ -483,13 +483,15 @@ langchain_agentx/tool_runtime/permission_snapshot.py,sha256=xFoi9fIcZjSw_zrIoygl
|
|
|
483
483
|
langchain_agentx/tool_runtime/pipeline.py,sha256=cNC8FzeBtfNo8I02wXsaBbbpwxbVXu67eRnr_OfEU3Y,53104
|
|
484
484
|
langchain_agentx/tool_runtime/policy.py,sha256=CZvkFS9m28q1txTz5MTltKGouMQZJnRVyz8DEfRewYA,30892
|
|
485
485
|
langchain_agentx/tool_runtime/policy_decorator.py,sha256=XWbgh_TRlPJ-J-RFo1FKjIN_n_Z9rtLTfSwBQoyLTTg,2264
|
|
486
|
+
langchain_agentx/tool_runtime/post_compact_restore.py,sha256=8Zqlx2GNKEC-jNdKGWPcoA-f_YgXnyEt32FkwDgQGbs,15815
|
|
486
487
|
langchain_agentx/tool_runtime/process_loader.py,sha256=NwflLSdAs44fpMs4Y1vYRZEN3OmIAcGOgp0Eb90K5WA,6960
|
|
487
488
|
langchain_agentx/tool_runtime/prompt_context.py,sha256=Dw3Qs8yWwT7dv-ZVHKnQxtPPKQXGySOQpwH4sstfsjE,3233
|
|
488
489
|
langchain_agentx/tool_runtime/read_ignore_patterns.py,sha256=l4kNulVDaOdQxcs4FeC2DT6k3172D4hgeafEbqGGvTw,3034
|
|
489
490
|
langchain_agentx/tool_runtime/read_permission.py,sha256=rwH7NEtL57aUKXVjSf6hMOOvEWOayNFyvI_SNoNCHPA,9284
|
|
491
|
+
langchain_agentx/tool_runtime/read_state_lifecycle.py,sha256=PsxQOM7vo0Ho06u5T2TC9T3F2kviSGVQVpwH_RUZZN4,5755
|
|
490
492
|
langchain_agentx/tool_runtime/registry.py,sha256=cvdMRz5cyAqLjM0MWWp6wu1DgqtZeMoiR2vgyAVHlb8,3358
|
|
491
493
|
langchain_agentx/tool_runtime/session_hints.py,sha256=TyoNdSw5GsE5AvYDPHJKsrto9YXZtbAdihI8YKHdRxA,3004
|
|
492
|
-
langchain_agentx/tool_runtime/session_store.py,sha256=
|
|
494
|
+
langchain_agentx/tool_runtime/session_store.py,sha256=TXexgL5K91EjbX6YtLMvBr1vHBtP1Bka_BPCdvisSSk,19485
|
|
493
495
|
langchain_agentx/tool_runtime/shell_error.py,sha256=gi2i0sc4qHcUiLD5B2yk-wIvyVaOpLFKyf4ZnnKmAuE,2198
|
|
494
496
|
langchain_agentx/tool_runtime/smoke_test_runtime.py,sha256=vOdoYdFwsWjq8k7rHD7hkgtgM5noGr9a6Wn1hHZ7354,11846
|
|
495
497
|
langchain_agentx/tool_runtime/state_bridge.py,sha256=8F7jG8Uk4EVJaAB8rwKpNmbWrNZtIHYJO5RFBiwSRhs,6011
|
|
@@ -888,8 +890,8 @@ langchain_agentx/workspace/root_grant_manager.py,sha256=W3gy8HTevbERbXqIgRcjzOXO
|
|
|
888
890
|
langchain_agentx/workspace/tool_boundary.py,sha256=UDwX6swpSLsx9HNkYuuRRiV5o7ZZG_Bru2Yn0c5kNX8,5724
|
|
889
891
|
langchain_agentx/workspace/validators.py,sha256=tQt-6TOcL8Fw7Ig5ebA9S7vGWh1rby920eFW6x8Tk9E,1439
|
|
890
892
|
langchain_agentx/workspace/view.py,sha256=PGasqTaqhlD03SXXazHuw4RHfV681AIdlsYqL70pEjc,4774
|
|
891
|
-
langchain_agentx_python-2.5.
|
|
892
|
-
langchain_agentx_python-2.5.
|
|
893
|
-
langchain_agentx_python-2.5.
|
|
894
|
-
langchain_agentx_python-2.5.
|
|
895
|
-
langchain_agentx_python-2.5.
|
|
893
|
+
langchain_agentx_python-2.5.1.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
894
|
+
langchain_agentx_python-2.5.1.dist-info/METADATA,sha256=0ByV5PMUotTDFtHI1dNip0lAoQY0AYOmzhEdY9YXGbo,23971
|
|
895
|
+
langchain_agentx_python-2.5.1.dist-info/WHEEL,sha256=51RkbunBAw4BWsgaQWTpPhg4Diwp3c9P5iaLk67Hdtg,92
|
|
896
|
+
langchain_agentx_python-2.5.1.dist-info/top_level.txt,sha256=Ge284pniNt8xea0OLk2o9o32GqVpDhOYk20fwE-0xxA,17
|
|
897
|
+
langchain_agentx_python-2.5.1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
{langchain_agentx_python-2.5.0.dist-info → langchain_agentx_python-2.5.1.dist-info}/top_level.txt
RENAMED
|
File without changes
|