agentforge-chat 0.2.2__tar.gz

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.
Files changed (27) hide show
  1. agentforge_chat-0.2.2/.gitignore +49 -0
  2. agentforge_chat-0.2.2/LICENSE +202 -0
  3. agentforge_chat-0.2.2/PKG-INFO +59 -0
  4. agentforge_chat-0.2.2/README.md +32 -0
  5. agentforge_chat-0.2.2/pyproject.toml +70 -0
  6. agentforge_chat-0.2.2/src/agentforge_chat/__init__.py +40 -0
  7. agentforge_chat-0.2.2/src/agentforge_chat/_idempotency.py +38 -0
  8. agentforge_chat-0.2.2/src/agentforge_chat/_locks.py +115 -0
  9. agentforge_chat-0.2.2/src/agentforge_chat/_segment.py +45 -0
  10. agentforge_chat-0.2.2/src/agentforge_chat/_window.py +86 -0
  11. agentforge_chat-0.2.2/src/agentforge_chat/build.py +112 -0
  12. agentforge_chat-0.2.2/src/agentforge_chat/history.py +126 -0
  13. agentforge_chat-0.2.2/src/agentforge_chat/manifest.yaml +32 -0
  14. agentforge_chat-0.2.2/src/agentforge_chat/py.typed +0 -0
  15. agentforge_chat-0.2.2/src/agentforge_chat/session.py +496 -0
  16. agentforge_chat-0.2.2/src/agentforge_chat/sqlite.py +276 -0
  17. agentforge_chat-0.2.2/src/agentforge_chat/tokenisers.py +91 -0
  18. agentforge_chat-0.2.2/src/agentforge_chat/truncation.py +206 -0
  19. agentforge_chat-0.2.2/tests/unit/test_chat_build.py +98 -0
  20. agentforge_chat-0.2.2/tests/unit/test_chat_streaming_per_token.py +104 -0
  21. agentforge_chat-0.2.2/tests/unit/test_in_memory_history.py +19 -0
  22. agentforge_chat-0.2.2/tests/unit/test_sentence_window.py +60 -0
  23. agentforge_chat-0.2.2/tests/unit/test_session.py +243 -0
  24. agentforge_chat-0.2.2/tests/unit/test_session_safety_modes.py +172 -0
  25. agentforge_chat-0.2.2/tests/unit/test_sqlite_history.py +13 -0
  26. agentforge_chat-0.2.2/tests/unit/test_token_budget_tokeniser.py +55 -0
  27. agentforge_chat-0.2.2/tests/unit/test_truncation.py +134 -0
@@ -0,0 +1,49 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+
7
+ # Distribution / packaging
8
+ .Python
9
+ build/
10
+ dist/
11
+ *.egg-info/
12
+ *.egg
13
+ wheels/
14
+ sdist/
15
+ share/python-wheels/
16
+
17
+ # uv
18
+ .venv/
19
+ uv-cache/
20
+
21
+ # Testing
22
+ .pytest_cache/
23
+ .coverage
24
+ .coverage.*
25
+ htmlcov/
26
+ coverage.xml
27
+ .tox/
28
+ .mypy_cache/
29
+ .ruff_cache/
30
+ .hypothesis/
31
+
32
+ # Environment
33
+ .env
34
+ .envrc
35
+
36
+ # Editors
37
+ .vscode/
38
+ .idea/
39
+ *.swp
40
+ *.swo
41
+ *~
42
+
43
+ # OS
44
+ .DS_Store
45
+ Thumbs.db
46
+
47
+ # Project-local
48
+ *.local
49
+ .agentforge-state/.session-cache
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,59 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentforge-chat
3
+ Version: 0.2.2
4
+ Summary: Chat-agent runtime (ChatSession + history drivers + truncation) for AgentForge
5
+ Project-URL: Homepage, https://github.com/Scaffoldic/agentforge-py
6
+ Project-URL: Repository, https://github.com/Scaffoldic/agentforge-py
7
+ Project-URL: Documentation, https://github.com/Scaffoldic/agentforge-py
8
+ Project-URL: Changelog, https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/Scaffoldic/agentforge-py/issues
10
+ Author: The AgentForge Authors
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: agent,ai,chat,chatbot,conversation
14
+ Classifier: Development Status :: 2 - Pre-Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.13
22
+ Requires-Dist: agentforge-core~=0.2.2
23
+ Requires-Dist: agentforge-py~=0.2.2
24
+ Provides-Extra: sqlite
25
+ Requires-Dist: aiosqlite>=0.20; extra == 'sqlite'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # agentforge-chat
29
+
30
+ Chat-agent runtime for AgentForge: `ChatSession`,
31
+ `InMemoryChatHistory` / `SqliteChatHistory` drivers, and four
32
+ truncation strategies (sliding-window, token-budget,
33
+ summarise-oldest, hybrid).
34
+
35
+ See [`docs/features/feat-020-chat-agents.md`](https://github.com/Scaffoldic/agentforge-py/blob/main/docs/features/feat-020-chat-agents.md)
36
+ for the design and runbook.
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install agentforge-chat
42
+ # or, with the SQLite driver pre-pulled:
43
+ pip install "agentforge-chat[sqlite]"
44
+ ```
45
+
46
+ ## Three-line chat from a one-shot agent
47
+
48
+ ```python
49
+ from agentforge import Agent
50
+ from agentforge_chat import ChatSession, SqliteChatHistory
51
+
52
+ agent = Agent(model="anthropic:claude-sonnet-4-6", strategy="react")
53
+ session = ChatSession(
54
+ agent=agent,
55
+ history_store=await SqliteChatHistory.from_path("./chat.db"),
56
+ )
57
+ print((await session.send("Hi")).content)
58
+ print((await session.send("What did I just say?")).content)
59
+ ```
@@ -0,0 +1,32 @@
1
+ # agentforge-chat
2
+
3
+ Chat-agent runtime for AgentForge: `ChatSession`,
4
+ `InMemoryChatHistory` / `SqliteChatHistory` drivers, and four
5
+ truncation strategies (sliding-window, token-budget,
6
+ summarise-oldest, hybrid).
7
+
8
+ See [`docs/features/feat-020-chat-agents.md`](https://github.com/Scaffoldic/agentforge-py/blob/main/docs/features/feat-020-chat-agents.md)
9
+ for the design and runbook.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install agentforge-chat
15
+ # or, with the SQLite driver pre-pulled:
16
+ pip install "agentforge-chat[sqlite]"
17
+ ```
18
+
19
+ ## Three-line chat from a one-shot agent
20
+
21
+ ```python
22
+ from agentforge import Agent
23
+ from agentforge_chat import ChatSession, SqliteChatHistory
24
+
25
+ agent = Agent(model="anthropic:claude-sonnet-4-6", strategy="react")
26
+ session = ChatSession(
27
+ agent=agent,
28
+ history_store=await SqliteChatHistory.from_path("./chat.db"),
29
+ )
30
+ print((await session.send("Hi")).content)
31
+ print((await session.send("What did I just say?")).content)
32
+ ```
@@ -0,0 +1,70 @@
1
+ # agentforge-chat — Chat-agent runtime for AgentForge.
2
+ #
3
+ # `ChatSession` wraps a one-shot `Agent` into a multi-turn,
4
+ # stateful conversation; ships in-memory + sqlite history
5
+ # drivers + four truncation strategies.
6
+ #
7
+ # Per ADR-0003 (three-tier package model — this is Tier 2, a
8
+ # framework runtime extension).
9
+
10
+ [project]
11
+ name = "agentforge-chat"
12
+ version = "0.2.2"
13
+ description = "Chat-agent runtime (ChatSession + history drivers + truncation) for AgentForge"
14
+ readme = "README.md"
15
+ requires-python = ">=3.13"
16
+ license = "Apache-2.0"
17
+ license-files = ["LICENSE"]
18
+ authors = [
19
+ {name = "The AgentForge Authors"},
20
+ ]
21
+ keywords = ["ai", "agent", "chat", "conversation", "chatbot"]
22
+ classifiers = [
23
+ "Development Status :: 2 - Pre-Alpha",
24
+ "Intended Audience :: Developers",
25
+ "License :: OSI Approved :: Apache Software License",
26
+ "Programming Language :: Python :: 3",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Topic :: Software Development :: Libraries :: Python Modules",
29
+ "Typing :: Typed",
30
+ ]
31
+
32
+ dependencies = [
33
+ "agentforge-core ~= 0.2.2",
34
+ "agentforge-py ~= 0.2.2",
35
+ ]
36
+
37
+ [project.optional-dependencies]
38
+ sqlite = ["aiosqlite>=0.20"]
39
+
40
+ [project.urls]
41
+ Homepage = "https://github.com/Scaffoldic/agentforge-py"
42
+ Repository = "https://github.com/Scaffoldic/agentforge-py"
43
+ Documentation = "https://github.com/Scaffoldic/agentforge-py"
44
+ Changelog = "https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md"
45
+ Issues = "https://github.com/Scaffoldic/agentforge-py/issues"
46
+
47
+ [project.entry-points."agentforge.chat.history"]
48
+ memory = "agentforge_chat.history:InMemoryChatHistory"
49
+ sqlite = "agentforge_chat.sqlite:SqliteChatHistory"
50
+
51
+ [project.entry-points."agentforge.chat.truncation"]
52
+ sliding_window = "agentforge_chat.truncation:SlidingWindow"
53
+ token_budget = "agentforge_chat.truncation:TokenBudget"
54
+ summarise_oldest = "agentforge_chat.truncation:SummariseOldest"
55
+ hybrid = "agentforge_chat.truncation:Hybrid"
56
+
57
+ [build-system]
58
+ requires = ["hatchling>=1.27"]
59
+ build-backend = "hatchling.build"
60
+
61
+ [tool.hatch.build.targets.wheel]
62
+ packages = ["src/agentforge_chat"]
63
+
64
+ [tool.hatch.build.targets.sdist]
65
+ include = [
66
+ "src/agentforge_chat",
67
+ "tests",
68
+ "README.md",
69
+ "LICENSE",
70
+ ]
@@ -0,0 +1,40 @@
1
+ """`agentforge-chat` — Chat-agent runtime for AgentForge (feat-020).
2
+
3
+ Public surface: `ChatSession` (chunk 3) + history drivers
4
+ (`InMemoryChatHistory`, `SqliteChatHistory`) + four truncation
5
+ strategies (`SlidingWindow`, `TokenBudget`, `SummariseOldest`,
6
+ `Hybrid`).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from agentforge_chat.build import build_chat_session_from_config
12
+ from agentforge_chat.history import InMemoryChatHistory
13
+ from agentforge_chat.session import ChatSession, SafetyMode
14
+ from agentforge_chat.sqlite import SqliteChatHistory
15
+ from agentforge_chat.tokenisers import (
16
+ Tokeniser,
17
+ anthropic_tokeniser,
18
+ tiktoken_tokeniser,
19
+ )
20
+ from agentforge_chat.truncation import (
21
+ Hybrid,
22
+ SlidingWindow,
23
+ SummariseOldest,
24
+ TokenBudget,
25
+ )
26
+
27
+ __all__ = [
28
+ "ChatSession",
29
+ "Hybrid",
30
+ "InMemoryChatHistory",
31
+ "SafetyMode",
32
+ "SlidingWindow",
33
+ "SqliteChatHistory",
34
+ "SummariseOldest",
35
+ "TokenBudget",
36
+ "Tokeniser",
37
+ "anthropic_tokeniser",
38
+ "build_chat_session_from_config",
39
+ "tiktoken_tokeniser",
40
+ ]
@@ -0,0 +1,38 @@
1
+ """Tiny LRU+TTL cache for per-session idempotency keys (feat-020).
2
+
3
+ Keyed by ``(session_id, key)``; values are the previous
4
+ `ChatResponse`. Entries past TTL are evicted on lookup; entries
5
+ past `max_entries` are evicted oldest-first.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from collections import OrderedDict
12
+
13
+
14
+ class IdempotencyCache[V]:
15
+ def __init__(self, *, ttl_s: float, max_entries: int = 256) -> None:
16
+ self._ttl = ttl_s
17
+ self._max = max_entries
18
+ self._store: OrderedDict[tuple[str, str], tuple[float, V]] = OrderedDict()
19
+
20
+ def get(self, session_id: str, key: str) -> V | None:
21
+ k = (session_id, key)
22
+ entry = self._store.get(k)
23
+ if entry is None:
24
+ return None
25
+ ts, value = entry
26
+ if (time.monotonic() - ts) > self._ttl:
27
+ self._store.pop(k, None)
28
+ return None
29
+ # Mark as recently used.
30
+ self._store.move_to_end(k)
31
+ return value
32
+
33
+ def put(self, session_id: str, key: str, value: V) -> None:
34
+ k = (session_id, key)
35
+ self._store[k] = (time.monotonic(), value)
36
+ self._store.move_to_end(k)
37
+ while len(self._store) > self._max:
38
+ self._store.popitem(last=False)
@@ -0,0 +1,115 @@
1
+ """Per-session lock registry (feat-020).
2
+
3
+ `ChatSession.send` / `stream` acquires a session-scoped lock so
4
+ concurrent calls against the same `session_id` queue. v0.1 shipped
5
+ an in-process `asyncio.Lock` via `WeakValueDictionary`. v0.2 extends
6
+ the surface to support cross-process locks (Redis-backed) via a
7
+ `SessionLock` Protocol that both shapes satisfy.
8
+
9
+ Default factory keeps the in-process behaviour. Multi-worker
10
+ deployments inject `redis_session_lock_factory(...)` from
11
+ `agentforge-chat-history-redis`.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import weakref
18
+ from collections.abc import Callable
19
+ from types import TracebackType
20
+ from typing import Protocol
21
+
22
+
23
+ class SessionLock(Protocol): # pragma: no cover — Protocol method stubs
24
+ """Async-context-manager lock keyed by `session_id`.
25
+
26
+ `ChatSession` calls `async with lock:` once per turn.
27
+ Implementations:
28
+
29
+ - :class:`InMemorySessionLock` — wraps a per-session
30
+ ``asyncio.Lock``. Default; single-process only.
31
+ - ``RedisSessionLock`` (in `agentforge-chat-history-redis`) —
32
+ cross-process; uses Redis ``SET NX PX`` + UUID fencing.
33
+ """
34
+
35
+ async def __aenter__(self) -> SessionLock: ...
36
+
37
+ async def __aexit__(
38
+ self,
39
+ exc_type: type[BaseException] | None,
40
+ exc: BaseException | None,
41
+ tb: TracebackType | None,
42
+ ) -> None: ...
43
+
44
+
45
+ SessionLockFactory = Callable[[str], SessionLock]
46
+ """Build a `SessionLock` for one ``session_id``. v0.2 lets callers
47
+ inject this on `ChatSession` / `ChatServer` construction."""
48
+
49
+
50
+ class InMemorySessionLock:
51
+ """Wraps a per-session `asyncio.Lock` so multiple chat turns on
52
+ the same session_id queue inside one process.
53
+
54
+ Conforms structurally to `SessionLock`.
55
+ """
56
+
57
+ def __init__(self, lock: asyncio.Lock) -> None:
58
+ self._lock = lock
59
+
60
+ async def __aenter__(self) -> InMemorySessionLock:
61
+ await self._lock.acquire()
62
+ return self
63
+
64
+ async def __aexit__(
65
+ self,
66
+ exc_type: type[BaseException] | None,
67
+ exc: BaseException | None,
68
+ tb: TracebackType | None,
69
+ ) -> None:
70
+ self._lock.release()
71
+
72
+
73
+ class _LockRegistry:
74
+ def __init__(self) -> None:
75
+ self._locks: weakref.WeakValueDictionary[str, asyncio.Lock] = weakref.WeakValueDictionary()
76
+
77
+ def get(self, session_id: str) -> asyncio.Lock:
78
+ lock = self._locks.get(session_id)
79
+ if lock is None:
80
+ lock = asyncio.Lock()
81
+ self._locks[session_id] = lock
82
+ return lock
83
+
84
+
85
+ _REGISTRY = _LockRegistry()
86
+
87
+
88
+ def lock_for(session_id: str) -> asyncio.Lock:
89
+ """Return the (shared, weak-referenced) raw `asyncio.Lock`.
90
+
91
+ Retained for backward-compatibility with v0.1 callers that read
92
+ `ChatSession._lock` directly. New code should use
93
+ :func:`default_session_lock_factory` or inject a custom
94
+ `SessionLockFactory`.
95
+ """
96
+ return _REGISTRY.get(session_id)
97
+
98
+
99
+ def default_session_lock_factory(session_id: str) -> SessionLock:
100
+ """Build the default in-process `SessionLock` for ``session_id``.
101
+
102
+ Wraps the shared `asyncio.Lock` from the weak-ref registry so
103
+ multiple `ChatSession` instances bound to the same session_id
104
+ still queue correctly.
105
+ """
106
+ return InMemorySessionLock(_REGISTRY.get(session_id))
107
+
108
+
109
+ __all__ = [
110
+ "InMemorySessionLock",
111
+ "SessionLock",
112
+ "SessionLockFactory",
113
+ "default_session_lock_factory",
114
+ "lock_for",
115
+ ]
@@ -0,0 +1,45 @@
1
+ """Sentence segmenter for the buffer-then-stream path (feat-020).
2
+
3
+ v0.2 ships `ChatSession.stream()` in the spec's
4
+ `safety_mode: "buffer-then-stream"` semantics: the agent runs to
5
+ completion, then the assistant turn is sliced into sentence-ish
6
+ chunks for the wire format. Real per-token streaming follows in a
7
+ later release without changing this surface.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+
14
+ _SENTENCE_BOUNDARY = re.compile(r"(?<=[.!?])\s+")
15
+ _MAX_CHUNK_CHARS = 200
16
+ """Soft cap so a single uninterrupted paragraph still emits as
17
+ multiple chunks."""
18
+
19
+
20
+ def segment_for_stream(text: str) -> list[str]:
21
+ """Split ``text`` into wire-format-friendly chunks.
22
+
23
+ Prefers sentence boundaries (``.!?`` followed by whitespace);
24
+ falls back to paragraph boundaries; falls back to a hard
25
+ `_MAX_CHUNK_CHARS` cap.
26
+ """
27
+ if not text:
28
+ return []
29
+ parts = [p for p in _SENTENCE_BOUNDARY.split(text) if p]
30
+ out: list[str] = []
31
+ for part in parts:
32
+ out.extend(_split_long(part))
33
+ return out
34
+
35
+
36
+ def _split_long(text: str) -> list[str]:
37
+ if len(text) <= _MAX_CHUNK_CHARS:
38
+ return [text]
39
+ pieces: list[str] = []
40
+ cursor = 0
41
+ while cursor < len(text):
42
+ end = min(cursor + _MAX_CHUNK_CHARS, len(text))
43
+ pieces.append(text[cursor:end])
44
+ cursor = end
45
+ return pieces