langchain-agentx-python 2.2.3__py3-none-any.whl → 2.2.5__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.
@@ -11,7 +11,7 @@ from langchain_agentx import create_loop_agent
11
11
  ```
12
12
  """
13
13
 
14
- __version__ = "2.2.3"
14
+ __version__ = "2.2.5"
15
15
 
16
16
  from .loop import ( # noqa: F401
17
17
  create_loop_agent,
@@ -6,7 +6,7 @@ tools/grep/backend.py — RipgrepBackend(ripgrep 子进程封装)
6
6
 
7
7
  在整体链路中的位置:
8
8
  GrepRuntimeTool.invoke() -> RipgrepBackend.search() -> run_ripgrep_lines(可选 ctx.cancel_event)
9
- -> RgSubprocessController 或 TextSubprocessRunner
9
+ -> RgSubprocessController(有界 stdout)或 TextSubprocessRunner(测试注入)
10
10
 
11
11
  对应 CC:src/utils/ripgrep.ts + GrepTool.ts call() 中参数拼装。
12
12
  """
@@ -16,7 +16,6 @@ from __future__ import annotations
16
16
  import os
17
17
  import subprocess
18
18
  import threading
19
- from typing import Any
20
19
 
21
20
  from langchain_agentx.tool_runtime.errors import ToolRuntimeError
22
21
  from langchain_agentx.utils.rg_executable import default_rg_executable
@@ -26,6 +25,7 @@ from langchain_agentx.utils.subprocess_text import (
26
25
  )
27
26
 
28
27
  from .models import GrepOutputMode
28
+ from .ripgrep_stdout_cap import RipgrepStdoutCap
29
29
 
30
30
 
31
31
  def resolve_ripgrep_subprocess_cwd(search_path: str) -> str:
@@ -58,6 +58,11 @@ class GrepCancelledError(ToolRuntimeError):
58
58
  super().__init__(message, code="GREP_CANCELLED")
59
59
 
60
60
 
61
+ def _uses_injected_subprocess_run(text_runner: TextSubprocessRunner) -> bool:
62
+ """测试注入自定义 ``subprocess_run`` 时走 text_runner;生产默认走有界 controller。"""
63
+ return getattr(text_runner, "_subprocess_run", None) is not subprocess.run
64
+
65
+
61
66
  def run_ripgrep_lines(
62
67
  rg_path: str,
63
68
  args: list[str],
@@ -70,21 +75,25 @@ def run_ripgrep_lines(
70
75
  ) -> list[str]:
71
76
  """
72
77
  执行 [rg_path, *args, search_path],解析 stdout 为行列表。
73
- 对齐 CC ripgrep.ts:returncode 1 -> [];EAGAIN 时以 -j 1 重试一次。
78
+ 对齐 CC ripgrep.ts:returncode 1 -> [];EAGAIN 时以 -j 1 重试一次;
79
+ stdout 硬顶 ``MAX_STDOUT_BUFFER_SIZE``(20MB)。
74
80
  供 RipgrepBackend 与 Glob 的 rg --files 列文件共用。
75
81
 
76
82
  SDK 补充:``subprocess cwd`` 对齐搜索根目录(目录本身,或文件的父目录)。
77
83
  CC 隐式依赖进程 cwd≈searchDir;编排布局 ``state_root≠repo`` 时须显式设 cwd,
78
84
  否则 Windows 上目录前缀 glob(如 ``alpha/*``)误空。
79
85
 
80
- 若 ``cancel_event`` 非空,使用可中断子进程路径(``RgSubprocessController``),
81
- 不再走 ``text_runner.run``(便于测试 mock 时仅覆盖无取消路径)。
86
+ 生产路径使用 ``RgSubprocessController`` 边收边截;仅当测试注入自定义
87
+ ``text_runner.subprocess_run`` 时走 ``text_runner.run``(事后硬顶)。
82
88
  """
83
89
  search_target = os.path.realpath(search_path)
84
90
  search_cwd = resolve_ripgrep_subprocess_cwd(search_path)
85
91
  cmd = [rg_path, *args, search_target]
86
- if cancel_event is not None:
87
- if cancel_event.is_set():
92
+ stdout_truncated = False
93
+
94
+ use_text_runner = cancel_event is None and _uses_injected_subprocess_run(text_runner)
95
+ if not use_text_runner:
96
+ if cancel_event is not None and cancel_event.is_set():
88
97
  raise GrepCancelledError("ripgrep cancelled before start")
89
98
  from langchain_agentx.tools.grep.rg_subprocess_controller import RgSubprocessController
90
99
 
@@ -100,6 +109,7 @@ def run_ripgrep_lines(
100
109
  raise
101
110
  except GrepCancelledError:
102
111
  raise
112
+ stdout_truncated = bool(getattr(result, "stdout_truncated", False))
103
113
  else:
104
114
  try:
105
115
  result = text_runner.run(
@@ -134,10 +144,7 @@ def run_ripgrep_lines(
134
144
  raise GrepExecutionError(f"ripgrep failed: {stderr or f'exit code {result.returncode}'}")
135
145
 
136
146
  out = result.stdout or ""
137
- if not out.strip():
138
- return []
139
- lines = [ln.rstrip("\r") for ln in out.rstrip("\n").split("\n")]
140
- return [ln for ln in lines if ln]
147
+ return RipgrepStdoutCap.lines_from_text(out, truncated=stdout_truncated)
141
148
 
142
149
 
143
150
  class RipgrepBackend:
@@ -3,10 +3,11 @@ tools/grep/rg_subprocess_controller.py — ripgrep 子进程 timeout + 协作取
3
3
 
4
4
  职责:
5
5
  在无法使用单次 ``subprocess.run(..., timeout=)`` 响应协作取消时,用 Popen + 后台
6
- ``communicate`` 与主线程轮询 ``cancel_event``,对齐 CC ``ripGrep(..., abortSignal)``。
6
+ 有界 stdout/stderr 读取与主线程轮询 ``cancel_event``,对齐 CC ``ripGrep(..., abortSignal)``
7
+ 与 ``MAX_BUFFER_SIZE`` 边收边截。
7
8
 
8
9
  链路位置:
9
- ``grep.backend.run_ripgrep_lines`` 在传入非空 ``cancel_event`` 时委托本类;
10
+ ``grep.backend.run_ripgrep_lines`` 在生产路径(或传入 ``cancel_event``)时委托本类;
10
11
  ``RipgrepBackend.search_stream_limited`` 在读取 stdout 时轮询同一事件。
11
12
 
12
13
  当前裁剪范围:
@@ -24,13 +25,17 @@ from langchain_agentx.tools.grep.backend import (
24
25
  GrepExecutionError,
25
26
  GrepTimeoutError,
26
27
  )
28
+ from langchain_agentx.tools.grep.ripgrep_stdout_cap import RipgrepStdoutCap
27
29
 
28
30
 
29
31
  class RgSubprocessController:
30
- """封装可中断的阻塞式子进程等待(timeout + ``threading.Event``)。"""
32
+ """封装可中断的阻塞式子进程等待(timeout + ``threading.Event`` + stdout 硬顶)。"""
31
33
 
32
34
  _poll_interval_s = 0.05
33
35
 
36
+ def __init__(self, *, stdout_cap_factory: type[RipgrepStdoutCap] = RipgrepStdoutCap) -> None:
37
+ self._stdout_cap_factory = stdout_cap_factory
38
+
34
39
  def run_argv_wait_completed(
35
40
  self,
36
41
  argv: list[str],
@@ -42,8 +47,11 @@ class RgSubprocessController:
42
47
  """
43
48
  启动 ``argv``,在 ``timeout`` 秒内等待结束;若 ``cancel_event`` 被 set 则 terminate/kill。
44
49
 
50
+ stdout/stderr 边收边截(``RipgrepStdoutCap``),避免无界 ``communicate`` 打爆内存。
51
+
45
52
  Returns:
46
53
  ``CompletedProcess``(text stdout/stderr),供上层解析 returncode。
54
+ 额外属性 ``stdout_truncated`` / ``stderr_truncated``(bool)。
47
55
  """
48
56
  if cancel_event is not None and cancel_event.is_set():
49
57
  raise GrepCancelledError("ripgrep cancelled before start")
@@ -64,19 +72,33 @@ class RgSubprocessController:
64
72
  "'rg.exe' is on PATH; on Unix ensure 'rg' is on PATH."
65
73
  ) from e
66
74
 
67
- out_box: list[str | None] = [None]
68
- err_box: list[str | None] = [None]
75
+ stdout_cap = self._stdout_cap_factory()
76
+ stderr_cap = self._stdout_cap_factory()
69
77
  thread_exc: list[BaseException | None] = [None]
70
78
 
71
- def _communicate_worker() -> None:
79
+ def _readers_worker() -> None:
72
80
  try:
73
- o, e = proc.communicate()
74
- out_box[0] = o
75
- err_box[0] = e
81
+ assert proc.stdout is not None
82
+ assert proc.stderr is not None
83
+ out_t = threading.Thread(
84
+ target=stdout_cap.drain_text_stream,
85
+ args=(proc.stdout,),
86
+ daemon=True,
87
+ )
88
+ err_t = threading.Thread(
89
+ target=stderr_cap.drain_text_stream,
90
+ args=(proc.stderr,),
91
+ daemon=True,
92
+ )
93
+ out_t.start()
94
+ err_t.start()
95
+ out_t.join()
96
+ err_t.join()
97
+ proc.wait()
76
98
  except BaseException as ex: # noqa: BLE001 — 必须兜住线程内异常
77
99
  thread_exc[0] = ex
78
100
 
79
- worker = threading.Thread(target=_communicate_worker, daemon=True)
101
+ worker = threading.Thread(target=_readers_worker, daemon=True)
80
102
  worker.start()
81
103
  deadline = time.monotonic() + timeout
82
104
 
@@ -98,12 +120,16 @@ class RgSubprocessController:
98
120
  if thread_exc[0] is not None:
99
121
  raise thread_exc[0]
100
122
 
101
- return subprocess.CompletedProcess(
123
+ result = subprocess.CompletedProcess(
102
124
  args=argv,
103
125
  returncode=proc.returncode if proc.returncode is not None else -1,
104
- stdout=out_box[0] or "",
105
- stderr=err_box[0] or "",
126
+ stdout=stdout_cap.text(),
127
+ stderr=stderr_cap.text(),
106
128
  )
129
+ # 供 run_ripgrep_lines 决定是否丢弃残缺末行
130
+ setattr(result, "stdout_truncated", stdout_cap.truncated)
131
+ setattr(result, "stderr_truncated", stderr_cap.truncated)
132
+ return result
107
133
  finally:
108
134
  if proc.poll() is None:
109
135
  try:
@@ -0,0 +1,93 @@
1
+ """
2
+ tools/grep/ripgrep_stdout_cap.py — ripgrep stdout/stderr 字节硬顶
3
+
4
+ 职责:
5
+ 对齐 CC ``src/utils/ripgrep.ts`` 的 ``MAX_BUFFER_SIZE = 20_000_000``:
6
+ 边收边截,超限停止 append;解析行时若已截断则丢弃可能残缺的末行。
7
+
8
+ 链路位置:
9
+ ``run_ripgrep_lines`` / ``RgSubprocessController`` 共用;Grep 与 Glob 列文件同路径受益。
10
+
11
+ 当前裁剪:
12
+ 按 Unicode 字符长度计量(对齐 CC JS string ``.length``);不在此杀进程。
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ # 对齐 CC ripgrep.ts:large monorepos can have 200k+ files
22
+ MAX_STDOUT_BUFFER_SIZE = 20_000_000
23
+
24
+
25
+ class RipgrepStdoutCap:
26
+ """可复用的有界 stdout/stderr 收集器(feed 后 to_lines / text)。"""
27
+
28
+ def __init__(self, max_size: int = MAX_STDOUT_BUFFER_SIZE) -> None:
29
+ if max_size <= 0:
30
+ raise ValueError("max_size must be positive")
31
+ self._max_size = max_size
32
+ self._parts: list[str] = []
33
+ self._size = 0
34
+ self.truncated = False
35
+
36
+ @property
37
+ def max_size(self) -> int:
38
+ return self._max_size
39
+
40
+ @property
41
+ def size(self) -> int:
42
+ return self._size
43
+
44
+ def feed(self, chunk: str) -> None:
45
+ """追加 chunk;已截断时忽略内容(调用方仍应继续读以排空管道)。"""
46
+ if self.truncated or not chunk:
47
+ return
48
+ remaining = self._max_size - self._size
49
+ if len(chunk) <= remaining:
50
+ self._parts.append(chunk)
51
+ self._size += len(chunk)
52
+ return
53
+ if remaining > 0:
54
+ self._parts.append(chunk[:remaining])
55
+ self._size = self._max_size
56
+ self.truncated = True
57
+
58
+ def text(self) -> str:
59
+ return "".join(self._parts)
60
+
61
+ def to_lines(self) -> list[str]:
62
+ """拆成非空行;截断时丢弃末行(对齐 CC buffer overflow / timeout 处理)。"""
63
+ return self.lines_from_text(self.text(), truncated=self.truncated)
64
+
65
+ @staticmethod
66
+ def lines_from_text(out: str, *, truncated: bool = False) -> list[str]:
67
+ """对已物化字符串做硬顶 + 分行(text_runner / mock 路径)。"""
68
+ if not out:
69
+ return []
70
+ was_truncated = truncated
71
+ if len(out) > MAX_STDOUT_BUFFER_SIZE:
72
+ out = out[:MAX_STDOUT_BUFFER_SIZE]
73
+ was_truncated = True
74
+ if not out.strip():
75
+ return []
76
+ lines = [ln.rstrip("\r") for ln in out.rstrip("\n").split("\n")]
77
+ lines = [ln for ln in lines if ln]
78
+ if was_truncated and lines:
79
+ lines = lines[:-1]
80
+ if was_truncated:
81
+ logger.warning(
82
+ "ripgrep stdout truncated at %s chars (CC MAX_BUFFER_SIZE alignment)",
83
+ MAX_STDOUT_BUFFER_SIZE,
84
+ )
85
+ return lines
86
+
87
+ def drain_text_stream(self, stream) -> None:
88
+ """从文本流按块读取并 feed,超限后继续排空但不入库。"""
89
+ while True:
90
+ chunk = stream.read(64 * 1024)
91
+ if not chunk:
92
+ break
93
+ self.feed(chunk)
@@ -65,7 +65,7 @@ from .execution import (
65
65
  )
66
66
  from .memory_drain_registry import MemoryDrainRegistry
67
67
  from .memory_session_policy import collect_agent_nodes, validate_loop_session_ids
68
- from .state import WorkflowState
68
+ from .state import WorkflowState, project_workflow_node_update
69
69
 
70
70
  # Lazy import for event_adapter(避免循环依赖)
71
71
  # 实际使用时通过 _get_event_adapter() 延迟导入
@@ -453,21 +453,22 @@ class BaseWorkflow(ABC):
453
453
 
454
454
  与 run() 的区别:
455
455
  - run(): 返回完整 WorkflowState(用于顶层调用)
456
- - as_node(): 返回完整 WorkflowState(作为其他 Workflow 的节点)
456
+ - as_node(): 返回相对父 state 的 channel delta(供 LangGraph reducer 合并)
457
457
 
458
458
  实现原理:
459
- - 直接调用 run() 返回完整 state
459
+ - 调用 run() 得到子图终态
460
+ - 经 project_workflow_node_update 将 messages / item_results 投影为增量
460
461
  - 传递 parent_workflow 构建层级关系
461
462
  - 使用 outer_semaphore 控制并发(如果提供)
462
- - LangGraph 的 reducer 会自动处理合并
463
463
 
464
464
  并发控制(问题 19):
465
465
  - 如果 outer_workflow 提供 semaphore,子 workflow 的执行会被限流
466
466
  - 这解决了 DeepSearch 场景下 45 个 sub-workflow 同时启动的问题
467
467
 
468
- 注意(问题 18 - as_node() diff 算法硬 bug):
469
- - ✅ 新设计(正确):直接返回完整 state,让 LangGraph reducer 处理合并
470
- - ❌ 旧设计(错误):手算 diff,硬编码字段名,假设 reducer 是 list append
468
+ 注意(聚合通道契约 · 2026-09-04):
469
+ - 节点必须返回 delta,禁止把父 state 全量回写进 messages / item_results
470
+ - 手写节点请用 delta_messages / delta_item_results
471
+ - as_node 已自动投影,避免嵌套子图 2^N 膨胀
471
472
  """
472
473
  async def node_fn(state: dict) -> dict:
473
474
  # 入口即快照父 _active_run_config,避免 run() 内 set/restore 与父并发时读漂移。
@@ -475,16 +476,18 @@ class BaseWorkflow(ABC):
475
476
  # === 并发控制(问题 19)===
476
477
  if outer_semaphore is not None:
477
478
  async with outer_semaphore:
478
- return await self.run(
479
+ result = await self.run(
479
480
  state,
480
481
  parent_workflow=parent_workflow,
481
482
  run_config=inherited_run_config,
482
483
  )
483
- return await self.run(
484
- state,
485
- parent_workflow=parent_workflow,
486
- run_config=inherited_run_config,
487
- )
484
+ else:
485
+ result = await self.run(
486
+ state,
487
+ parent_workflow=parent_workflow,
488
+ run_config=inherited_run_config,
489
+ )
490
+ return project_workflow_node_update(state, result)
488
491
 
489
492
  return node_fn
490
493
 
@@ -93,16 +93,22 @@ class AgentNode:
93
93
  ctx: WorkflowNodeContext,
94
94
  invocation: LoopInvocation,
95
95
  ) -> dict[str, Any]:
96
- del state, ctx
97
- return {
98
- "messages": graph_result.get("messages", []),
99
- "item_results": [
96
+ from .state import delta_item_results, project_workflow_node_update
97
+
98
+ del ctx
99
+ update = project_workflow_node_update(
100
+ {"messages": state.get("messages", [])},
101
+ {"messages": graph_result.get("messages", [])},
102
+ )
103
+ update.update(
104
+ delta_item_results(
100
105
  {
101
106
  "node": self.name,
102
107
  "session_id": invocation.session_id,
103
108
  }
104
- ],
105
- }
109
+ )
110
+ )
111
+ return update
106
112
 
107
113
  def map_error(
108
114
  self,
@@ -110,16 +116,16 @@ class AgentNode:
110
116
  exc: Exception,
111
117
  ctx: WorkflowNodeContext,
112
118
  ) -> dict[str, Any]:
113
- return {
114
- "messages": state.get("messages", []),
115
- "item_results": [
116
- {
117
- "node": self.name,
118
- "session_id": ctx.loop_session_id,
119
- "error": str(exc),
120
- }
121
- ],
122
- }
119
+ from .state import delta_item_results
120
+
121
+ del state
122
+ return delta_item_results(
123
+ {
124
+ "node": self.name,
125
+ "session_id": ctx.loop_session_id,
126
+ "error": str(exc),
127
+ }
128
+ )
123
129
 
124
130
  def _resolve_graph_factory(
125
131
  self,
@@ -1,10 +1,11 @@
1
1
  """
2
- state.py — Workflow 状态定义
2
+ state.py — Workflow 状态定义与聚合通道契约
3
3
 
4
4
  职责:
5
5
  - 定义 WorkflowState 基类(TypedDict + Annotated reducer)
6
- - 规范 Workflow 状态字段命名与 reducer 使用
7
- - 提供文档模式定义,不强制继承
6
+ - item_results 按身份键幂等合并(防 2^N 全量回写 OOM)
7
+ - 提供 delta_messages / delta_item_results 增量构造接口(防误用)
8
+ - as_node 用 project_workflow_node_update 将终态投影为 delta
8
9
 
9
10
  链路位置:
10
11
  - 被 BaseWorkflow 和所有特殊 Workflow 使用
@@ -13,44 +14,268 @@ state.py — Workflow 状态定义
13
14
  当前裁剪范围:
14
15
  - 仅包含基础字段(messages, item_results, workflow_id 等)
15
16
  - 业务特定字段由具体 Workflow 自行扩展
16
-
17
- 设计说明(问题 10):
18
- - WorkflowState 使用 TypedDict,这是 LangGraph 的最佳实践
19
- - TypedDict + Annotated reducer 是 LangGraph 官方推荐的状态定义方式
20
- - 不要使用普通 dict(没有类型检查和 reducer 支持)
21
- - 不要使用 dataclass(LangGraph StateGraph 不直接支持)
17
+ - 通道预算上限(P2)未做
22
18
  """
23
19
 
24
20
  from __future__ import annotations
25
21
 
26
- from typing import Annotated, TypedDict
27
- from operator import add
22
+ import logging
23
+ import os
24
+ from typing import Annotated, Any, Hashable, Mapping, Sequence, TypedDict
28
25
 
29
26
  from langgraph.graph.message import add_messages
30
27
  from langchain_core.messages import AnyMessage
31
28
 
29
+ logger = logging.getLogger(__name__)
30
+
31
+ _STRICT_DELTA_ENV = "LANGCHAIN_AGENTX_WORKFLOW_STRICT_DELTA"
32
+
33
+ # 显式主键优先;其次 task(编排任务);再 node/repo/session 等复合键
34
+ _EXPLICIT_IDENTITY_KEYS: tuple[str, ...] = ("result_id", "item_key", "id")
35
+ _COMPOSITE_IDENTITY_KEYS: tuple[str, ...] = (
36
+ "node",
37
+ "repo_id",
38
+ "repo",
39
+ "session_id",
40
+ "from",
41
+ )
42
+
43
+
44
+ def item_result_identity(item: Any) -> Hashable | None:
45
+ """提取 item_results 条目的合并身份;无身份则返回 None(走 append)。"""
46
+ if not isinstance(item, dict):
47
+ try:
48
+ hash(item)
49
+ except TypeError:
50
+ return None
51
+ return ("value", item)
52
+
53
+ for key in _EXPLICIT_IDENTITY_KEYS:
54
+ value = item.get(key)
55
+ if value is not None:
56
+ return (key, value)
57
+
58
+ task = item.get("task")
59
+ if task is not None:
60
+ return ("task", task)
61
+
62
+ parts = tuple(
63
+ (key, item[key])
64
+ for key in _COMPOSITE_IDENTITY_KEYS
65
+ if item.get(key) is not None
66
+ )
67
+ if parts:
68
+ return ("composite", parts)
69
+ return None
70
+
71
+
72
+ def _looks_like_full_rewrite(left: Sequence[Any], right: Sequence[Any]) -> bool:
73
+ """检测典型反模式:提交值 = 旧列表前缀 + 增量(state.get(...) + [...])。"""
74
+ if not left or len(right) <= len(left):
75
+ return False
76
+ return list(right[: len(left)]) == list(left)
77
+
78
+
79
+ def _maybe_raise_or_warn_full_rewrite(left: list[Any], right: list[Any]) -> None:
80
+ if not _looks_like_full_rewrite(left, right):
81
+ return
82
+ message = (
83
+ "item_results full-rewrite antipattern detected: "
84
+ f"submitted len={len(right)} looks like prior len={len(left)} + suffix. "
85
+ "Return delta only via delta_item_results(...); "
86
+ "do not submit state.get('item_results', []) + [...]."
87
+ )
88
+ if os.environ.get(_STRICT_DELTA_ENV, "").strip() in {"1", "true", "TRUE", "yes", "YES"}:
89
+ raise ValueError(message)
90
+ logger.warning(message)
91
+
92
+
93
+ class ItemResultsMerge:
94
+ """item_results 通道归约器:按身份键幂等合并,并检测全量回写。"""
95
+
96
+ def __call__(
97
+ self,
98
+ left: list[Any] | None,
99
+ right: list[Any] | None,
100
+ ) -> list[Any]:
101
+ return self.merge(left, right)
102
+
103
+ def merge(
104
+ self,
105
+ left: list[Any] | None,
106
+ right: list[Any] | None,
107
+ ) -> list[Any]:
108
+ left_list = list(left or [])
109
+ right_list = list(right or [])
110
+ if not right_list:
111
+ return left_list
112
+ if not left_list:
113
+ return list(right_list)
114
+
115
+ _maybe_raise_or_warn_full_rewrite(left_list, right_list)
116
+
117
+ keyed: dict[Hashable, int] = {}
118
+ merged: list[Any] = []
119
+ for item in left_list:
120
+ identity = item_result_identity(item)
121
+ if identity is None:
122
+ merged.append(item)
123
+ continue
124
+ if identity in keyed:
125
+ merged[keyed[identity]] = item
126
+ else:
127
+ keyed[identity] = len(merged)
128
+ merged.append(item)
129
+
130
+ for item in right_list:
131
+ identity = item_result_identity(item)
132
+ if identity is None:
133
+ merged.append(item)
134
+ continue
135
+ if identity in keyed:
136
+ merged[keyed[identity]] = item
137
+ else:
138
+ keyed[identity] = len(merged)
139
+ merged.append(item)
140
+ return merged
141
+
142
+
143
+ merge_item_results = ItemResultsMerge()
144
+
145
+
146
+ def _normalize_varargs(items: tuple[Any, ...]) -> list[Any]:
147
+ if len(items) == 1 and isinstance(items[0], list):
148
+ return list(items[0])
149
+ return list(items)
150
+
151
+
152
+ def delta_messages(*messages: Any) -> dict[str, list[Any]]:
153
+ """构造 messages 通道增量(节点应 return 本 dict 或其展开)。
154
+
155
+ 只接收本次新增消息,禁止传入 state['messages'] 全量历史。
156
+ """
157
+ return {"messages": _normalize_varargs(messages)}
158
+
159
+
160
+ def delta_item_results(*items: Any) -> dict[str, list[Any]]:
161
+ """构造 item_results 通道增量(节点应 return 本 dict 或其展开)。
162
+
163
+ 只接收本次新增/更新条目;条目宜带身份键(result_id / item_key / task / node+…)。
164
+ 禁止传入 state.get('item_results', []) + [...] 全量历史。
165
+ """
166
+ return {"item_results": _normalize_varargs(items)}
167
+
168
+
169
+ def _message_identity(message: Any) -> Hashable | None:
170
+ msg_id = getattr(message, "id", None)
171
+ if msg_id is not None:
172
+ return ("id", msg_id)
173
+ return None
174
+
175
+
176
+ def _messages_delta(before: Sequence[Any] | None, after: Sequence[Any] | None) -> list[Any]:
177
+ before_list = list(before or [])
178
+ after_list = list(after or [])
179
+ if not after_list:
180
+ return []
181
+ seen: set[Hashable] = set()
182
+ for message in before_list:
183
+ identity = _message_identity(message)
184
+ if identity is not None:
185
+ seen.add(identity)
186
+ delta: list[Any] = []
187
+ for message in after_list:
188
+ identity = _message_identity(message)
189
+ if identity is None:
190
+ # 无 id:仅当不在 before 相等集合中时纳入(弱 diff)
191
+ if message not in before_list:
192
+ delta.append(message)
193
+ continue
194
+ if identity not in seen:
195
+ seen.add(identity)
196
+ delta.append(message)
197
+ return delta
198
+
199
+
200
+ def _item_results_delta(
201
+ before: Sequence[Any] | None,
202
+ after: Sequence[Any] | None,
203
+ ) -> list[Any]:
204
+ before_list = list(before or [])
205
+ after_list = list(after or [])
206
+ if not after_list:
207
+ return []
208
+
209
+ before_by_key: dict[Hashable, Any] = {}
210
+ before_unkeyed: list[Any] = []
211
+ for item in before_list:
212
+ identity = item_result_identity(item)
213
+ if identity is None:
214
+ before_unkeyed.append(item)
215
+ else:
216
+ before_by_key[identity] = item
217
+
218
+ delta: list[Any] = []
219
+ after_unkeyed: list[Any] = []
220
+ for item in after_list:
221
+ identity = item_result_identity(item)
222
+ if identity is None:
223
+ after_unkeyed.append(item)
224
+ continue
225
+ prior = before_by_key.get(identity)
226
+ if prior is None or prior != item:
227
+ delta.append(item)
228
+
229
+ remaining_unkeyed = list(before_unkeyed)
230
+ for item in after_unkeyed:
231
+ if item in remaining_unkeyed:
232
+ remaining_unkeyed.remove(item)
233
+ else:
234
+ delta.append(item)
235
+ return delta
236
+
237
+
238
+ def project_workflow_node_update(
239
+ before: Mapping[str, Any],
240
+ after: Mapping[str, Any],
241
+ ) -> dict[str, Any]:
242
+ """将子 workflow 终态投影为父图节点应提交的 channel delta。
243
+
244
+ 聚合通道(messages / item_results)只提交相对 before 的增量;
245
+ 其它字段在值变化时原样写入(last-write-wins)。
246
+ """
247
+ update: dict[str, Any] = {}
248
+ for key, value in after.items():
249
+ if key == "messages":
250
+ delta = _messages_delta(before.get("messages"), value)
251
+ if delta:
252
+ update["messages"] = delta
253
+ continue
254
+ if key == "item_results":
255
+ delta = _item_results_delta(before.get("item_results"), value)
256
+ if delta:
257
+ update["item_results"] = delta
258
+ continue
259
+ if before.get(key) != value:
260
+ update[key] = value
261
+ return update
262
+
32
263
 
33
264
  class WorkflowState(TypedDict, total=False):
34
265
  """Workflow 状态 schema,支持并发写入。
35
266
 
36
267
  字段说明:
37
- - messages: 消息列表(所有节点都会追加消息,使用 reducer)
38
- - item_results: 并行任务结果列表(聚合所有 item 的输出,使用 reducer)
39
- - workflow_id: 当前 Workflow ID(单写,由 BaseWorkflow 设置)
40
- - task_key: 当前任务标识符(单写,Phase 2+)
41
- - current_step: 当前步骤(单写,用于顺序 Workflow)
42
- - error: 错误信息(单写,用于错误处理)
43
-
44
- 使用方式:
45
- - 基础类型:WorkflowState(本定义)
46
- - 扩展类型:class MyState(WorkflowState, total=False) 添加业务字段
268
+ - messages: 消息列表(add_messages 按 id 幂等合并)
269
+ - item_results: 并行/叶节点产出(merge_item_results 按身份键幂等合并)
270
+ - workflow_id / task_key / current_step / orchestration_round / error: 单写字段
271
+
272
+ 节点写入约定:
273
+ - 使用 delta_messages / delta_item_results 构造增量,禁止 {**state} 全量回写聚合通道
47
274
  """
48
275
 
49
- # === 并发聚合字段(使用 reducer)===
50
276
  messages: Annotated[list[AnyMessage], add_messages]
51
- item_results: Annotated[list[dict], add]
277
+ item_results: Annotated[list[dict], merge_item_results]
52
278
 
53
- # === 单写字段(无需 reducer)===
54
279
  workflow_id: str
55
280
  task_key: str | None
56
281
  current_step: str | None
@@ -58,4 +283,12 @@ class WorkflowState(TypedDict, total=False):
58
283
  error: str | None
59
284
 
60
285
 
61
- __all__ = ["WorkflowState"]
286
+ __all__ = [
287
+ "WorkflowState",
288
+ "ItemResultsMerge",
289
+ "merge_item_results",
290
+ "item_result_identity",
291
+ "delta_messages",
292
+ "delta_item_results",
293
+ "project_workflow_node_update",
294
+ ]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: langchain-agentx-python
3
- Version: 2.2.3
3
+ Version: 2.2.5
4
4
  Summary: LangChain/LangGraph-based agent utilities for CodeBaseX.
5
5
  Author-email: GoodMood2008 <GoodMood2008@users.noreply.github.com>
6
6
  License: Apache License
@@ -1,4 +1,4 @@
1
- langchain_agentx/__init__.py,sha256=bMHXxvdlfRUJK-ZT43f2Hgef2tNuOs5bc3mv-F4BQRc,1614
1
+ langchain_agentx/__init__.py,sha256=FDi8b0l3oV8v5zS-G33Yb0qoKw5-jje_-Rfu9sxHzOY,1614
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
@@ -581,10 +581,11 @@ langchain_agentx/tools/glob/rg_list_backend.py,sha256=gTyFQE0eYHl-7LkSdah76S8bQn
581
581
  langchain_agentx/tools/glob/rg_pattern.py,sha256=YOV-1gdxC52vzdAwgz27l7mzPJvVuHqpqeWhiEnWQJs,1377
582
582
  langchain_agentx/tools/glob/tool.py,sha256=m746Vl_aI9eFmrXYECkg16zMln9YPVxqjtijPlc5ALA,14868
583
583
  langchain_agentx/tools/grep/__init__.py,sha256=AA9qa42Ap9tw6lPQkNgKzYmr4hu44eP93qVdyP-eFNU,162
584
- langchain_agentx/tools/grep/backend.py,sha256=bzwRUJ_aZjs84oIG3l6IAVygGiLDyNsHPePiMaFMo-4,14539
584
+ langchain_agentx/tools/grep/backend.py,sha256=12BHyDZccr7Hzvfumj3zGpXrSRNV_LiCbYYyG2Y3BCg,15062
585
585
  langchain_agentx/tools/grep/models.py,sha256=6fTSux0COK06weQ7PWYqCGBQx60OaNtqC5q7xKtf5i0,3860
586
586
  langchain_agentx/tools/grep/prompt.py,sha256=Euo1NErphk5WHxaKXwJH-1v7joblfwEFWHIYNthKkzo,1336
587
- langchain_agentx/tools/grep/rg_subprocess_controller.py,sha256=ijMJnKPo7iEDFBz-_YipTiPusrL6OO2XbWxHUuwpMfA,4056
587
+ langchain_agentx/tools/grep/rg_subprocess_controller.py,sha256=A4RGCiZaIo8lrohqftzrOcDmU8VVDlSic1Pqy5ZF5Js,5315
588
+ langchain_agentx/tools/grep/ripgrep_stdout_cap.py,sha256=b7krKaCXYMjkecRwhpB1a8gaJ96BW0oyvxhrlDMQTtA,3149
588
589
  langchain_agentx/tools/grep/tool.py,sha256=S_nGFqFgGHx9UhnXJdNvkdoHCJxLRZBDoPDd-Pxms0g,20513
589
590
  langchain_agentx/tools/plan_mode/__init__.py,sha256=wO5FX24xEB0Dx9h6bysBt1ql3wn0rjPYsg70mbl4S_0,402
590
591
  langchain_agentx/tools/plan_mode/constants.py,sha256=vBjcx9JTSOhU9jfCJ4RKnCxVQPn0HzHapouKxRf2Zns,293
@@ -695,7 +696,7 @@ langchain_agentx/utils/permissions/filesystem.py,sha256=79vRSRPnPadHlDOOYvvbuJaJ
695
696
  langchain_agentx/utils/settings/__init__.py,sha256=UXzHZmrBJsO8ZpDmHfclHXpS7rfpmqRoXEnmTFbtVpE,172
696
697
  langchain_agentx/utils/settings/managed_path.py,sha256=MVcw4F9bTrhKqTLom8ZiiqSqCREMbGcAK9Lt8hkD67M,1155
697
698
  langchain_agentx/workflow/__init__.py,sha256=wgjJM2wW0DbFHjsNbq2bKYgFs3BIPFRuQbH8Ry5kfys,4324
698
- langchain_agentx/workflow/base.py,sha256=rzZTH0ciepTglXfhDMkhl1uiJV4d_bXkOgpHlmu-N0w,33409
699
+ langchain_agentx/workflow/base.py,sha256=g4U7hO4fNRBiwh8Y3yLiU8Rgo1AgahaXV1L7lPob32c,33600
699
700
  langchain_agentx/workflow/batch.py,sha256=rdE9xbQ2-SI3-6yNTsKoSylDoTD5B0djLSKwqy1BdZ8,5474
700
701
  langchain_agentx/workflow/catalog_registry.py,sha256=tYUny5FkHwQU-RRUxOdxaJhiRV_9VRXU636Yn_Gzt-g,2109
701
702
  langchain_agentx/workflow/dag.py,sha256=Y1IR1IwnM79Xuev6HZnOvAE3Q23MRnA9lu4vg2Cie48,4469
@@ -705,7 +706,7 @@ langchain_agentx/workflow/execution.py,sha256=iCEkPgLkaoEM4cB6o7KAqIaBpFuY5HtGGI
705
706
  langchain_agentx/workflow/loop_factory.py,sha256=hCShf_gDnesW2A9JspaUY3upp3NCIguII_wRiXnSIUM,3954
706
707
  langchain_agentx/workflow/memory_drain_registry.py,sha256=Xm_ytbB-BbRIu3-h-KhptsCsmmueOiNZePUuG1hk8zk,1681
707
708
  langchain_agentx/workflow/memory_session_policy.py,sha256=2FI0ZbAA6MnxJexnLYLadQpiqipPQwVnUrTWgl55A74,3333
708
- langchain_agentx/workflow/node.py,sha256=0lFVxCKzCsrN61wBkZpniWwLVXPEwvedmCnqtljIvL8,4891
709
+ langchain_agentx/workflow/node.py,sha256=03DtGBYkpFIv_XWMwLQsgWgS0aK4eHxvMfCI5DiBEmE,5069
709
710
  langchain_agentx/workflow/node_adapter.py,sha256=3ZjXhN-Yqg2JzYpRsvnhOvw8-gvGdzmFYkDG2AFndX4,5330
710
711
  langchain_agentx/workflow/projection_isolation.py,sha256=kx6cM8ZtZAFA2VZ8yBIgVaIQE5o4ZfvSoY3mcxSe3hk,634
711
712
  langchain_agentx/workflow/r8_event_stream_benchmark.py,sha256=VdDOWoK3yoGjYyVpAIN3qoQrChz6Ot8sxDw7Uh8RdhU,6562
@@ -715,7 +716,7 @@ langchain_agentx/workflow/run_session.py,sha256=LuFY52uvYfOBGD_Yi878pO5N2bVWJnVG
715
716
  langchain_agentx/workflow/runtime.py,sha256=DdL66SlcvTyU9KxA-JAS4dFxWuJXlYGQdtmBmZfk3dc,3267
716
717
  langchain_agentx/workflow/runtime_scope_path.py,sha256=k1PLnHK-xFEui6birSCWPZeKKV4_oXIip3mst_xDICo,2687
717
718
  langchain_agentx/workflow/runtime_scope_registry.py,sha256=WgyWAWTuM6xZl6ik2pAZCWBwToeTOaSu94kYqJKY2jU,2945
718
- langchain_agentx/workflow/state.py,sha256=zdtf2x547iAyLKBza2Ye0ROOkeSLoWEkNMUVbLfb1g4,2105
719
+ langchain_agentx/workflow/state.py,sha256=PCSqwlJIP2rMg-TFhDFK2KzWXTC2dEn1q7eVCK1z4SY,9155
719
720
  langchain_agentx/workflow/structure_collector.py,sha256=w2ryitiR9t48DrYGBbR4zlSBOaa7dtrD0XqR23BbSHk,13574
720
721
  langchain_agentx/workflow/structure_errors.py,sha256=yYulfRRc70RU2rKjyJYEIhIspCH5taRa72kAwl3nOAA,941
721
722
  langchain_agentx/workflow/structure_validation.py,sha256=resy8jK_V1mKd_BQykwmpbesg6Yl2QbLavEUEQB2O_w,17698
@@ -760,8 +761,8 @@ langchain_agentx/workspace/root_grant_manager.py,sha256=W3gy8HTevbERbXqIgRcjzOXO
760
761
  langchain_agentx/workspace/tool_boundary.py,sha256=UDwX6swpSLsx9HNkYuuRRiV5o7ZZG_Bru2Yn0c5kNX8,5724
761
762
  langchain_agentx/workspace/validators.py,sha256=tQt-6TOcL8Fw7Ig5ebA9S7vGWh1rby920eFW6x8Tk9E,1439
762
763
  langchain_agentx/workspace/view.py,sha256=PGasqTaqhlD03SXXazHuw4RHfV681AIdlsYqL70pEjc,4774
763
- langchain_agentx_python-2.2.3.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
764
- langchain_agentx_python-2.2.3.dist-info/METADATA,sha256=VcuvJI240NmP2VxSl2xxXD2BTvpnCLxnkXjg5aHzmQE,24250
765
- langchain_agentx_python-2.2.3.dist-info/WHEEL,sha256=51RkbunBAw4BWsgaQWTpPhg4Diwp3c9P5iaLk67Hdtg,92
766
- langchain_agentx_python-2.2.3.dist-info/top_level.txt,sha256=Ge284pniNt8xea0OLk2o9o32GqVpDhOYk20fwE-0xxA,17
767
- langchain_agentx_python-2.2.3.dist-info/RECORD,,
764
+ langchain_agentx_python-2.2.5.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
765
+ langchain_agentx_python-2.2.5.dist-info/METADATA,sha256=H6Y0pRHIIab1cfuQGeOYWKXCW0WcbzoFI3fDduI-uDM,24250
766
+ langchain_agentx_python-2.2.5.dist-info/WHEEL,sha256=51RkbunBAw4BWsgaQWTpPhg4Diwp3c9P5iaLk67Hdtg,92
767
+ langchain_agentx_python-2.2.5.dist-info/top_level.txt,sha256=Ge284pniNt8xea0OLk2o9o32GqVpDhOYk20fwE-0xxA,17
768
+ langchain_agentx_python-2.2.5.dist-info/RECORD,,