nodus-delivery 0.1.0__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.
- nodus_delivery-0.1.0/LICENSE +21 -0
- nodus_delivery-0.1.0/PKG-INFO +186 -0
- nodus_delivery-0.1.0/README.md +169 -0
- nodus_delivery-0.1.0/nodus_delivery/__init__.py +36 -0
- nodus_delivery-0.1.0/nodus_delivery/chunker.py +188 -0
- nodus_delivery-0.1.0/nodus_delivery/plan.py +30 -0
- nodus_delivery-0.1.0/nodus_delivery/router.py +116 -0
- nodus_delivery-0.1.0/nodus_delivery.egg-info/PKG-INFO +186 -0
- nodus_delivery-0.1.0/nodus_delivery.egg-info/SOURCES.txt +15 -0
- nodus_delivery-0.1.0/nodus_delivery.egg-info/dependency_links.txt +1 -0
- nodus_delivery-0.1.0/nodus_delivery.egg-info/requires.txt +5 -0
- nodus_delivery-0.1.0/nodus_delivery.egg-info/top_level.txt +1 -0
- nodus_delivery-0.1.0/pyproject.toml +28 -0
- nodus_delivery-0.1.0/setup.cfg +4 -0
- nodus_delivery-0.1.0/tests/test_chunker.py +116 -0
- nodus_delivery-0.1.0/tests/test_plan.py +29 -0
- nodus_delivery-0.1.0/tests/test_router.py +118 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Shawn Knight
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: nodus-delivery
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Outbound routing, chunking, and delivery planning for multi-channel AI systems
|
|
5
|
+
Author: Shawn Knight
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Masterplanner25/nodus-delivery
|
|
8
|
+
Project-URL: Repository, https://github.com/Masterplanner25/nodus-delivery
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: nodus-channels>=0.1.0
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
15
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# nodus-delivery
|
|
19
|
+
|
|
20
|
+
**Outbound routing, chunking, and delivery planning for multi-channel AI systems.**
|
|
21
|
+
|
|
22
|
+
Resolves the right channel adapter for a response, splits long content into
|
|
23
|
+
channel-appropriate chunks, and delivers each chunk in order. Depends on
|
|
24
|
+
[nodus-channels](https://github.com/Masterplanner25/nodus-channels) for the
|
|
25
|
+
`ChannelRegistry` and `ChannelAdapter` protocol.
|
|
26
|
+
|
|
27
|
+
> **Status:** v0.1.0 — prepared, not yet published.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install nodus-delivery
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Requires `nodus-channels>=0.1.0`.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## What it provides
|
|
42
|
+
|
|
43
|
+
| Component | Purpose |
|
|
44
|
+
|---|---|
|
|
45
|
+
| `DeliveryPlan` | Describes where and how to send a response |
|
|
46
|
+
| `SizeChunker` | Split at word boundaries up to a max character count |
|
|
47
|
+
| `ParagraphChunker` | Split on paragraph breaks, respecting a max size |
|
|
48
|
+
| `MarkdownBlockChunker` | Preserve code blocks and headers across splits |
|
|
49
|
+
| `strip_markdown` | Remove markdown formatting → plain text |
|
|
50
|
+
| `DeliveryRouter` | Resolve adapter, chunk, and send; build plan from inbound message |
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## Quick start
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from nodus_channels import ChannelRegistry
|
|
58
|
+
from nodus_delivery import DeliveryRouter, DeliveryPlan, SizeChunker
|
|
59
|
+
|
|
60
|
+
registry = ChannelRegistry()
|
|
61
|
+
registry.register(my_slack_adapter)
|
|
62
|
+
|
|
63
|
+
router = DeliveryRouter(registry, default_chunker=SizeChunker(max_chars=2000))
|
|
64
|
+
|
|
65
|
+
plan = DeliveryPlan(
|
|
66
|
+
channel_id="slack",
|
|
67
|
+
peer_id="U123",
|
|
68
|
+
content="A very long response that may need chunking...",
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
await router.deliver(plan)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## DeliveryPlan
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from nodus_delivery import DeliveryPlan
|
|
80
|
+
|
|
81
|
+
plan = DeliveryPlan(
|
|
82
|
+
channel_id="slack",
|
|
83
|
+
peer_id="U123",
|
|
84
|
+
content="Response text",
|
|
85
|
+
thread_id="T456", # optional: reply in a thread
|
|
86
|
+
reply_to_id="M789", # optional: reply to a specific message
|
|
87
|
+
strip_md=False, # strip markdown before chunking (default False)
|
|
88
|
+
chunker=None, # override router's default chunker
|
|
89
|
+
)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Chunking strategies
|
|
95
|
+
|
|
96
|
+
### SizeChunker
|
|
97
|
+
|
|
98
|
+
Splits at word boundaries. Safe for any channel.
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from nodus_delivery import SizeChunker
|
|
102
|
+
chunker = SizeChunker(max_chars=2000)
|
|
103
|
+
chunks = chunker.chunk("Long text...") # list[str]
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### ParagraphChunker
|
|
107
|
+
|
|
108
|
+
Splits on `\n\n` paragraph breaks first; falls back to size if a paragraph
|
|
109
|
+
exceeds `max_chars`.
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from nodus_delivery import ParagraphChunker
|
|
113
|
+
chunker = ParagraphChunker(max_chars=2000)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### MarkdownBlockChunker
|
|
117
|
+
|
|
118
|
+
Keeps code fences (` ``` `) and headers (`#`, `##`) intact. Never splits
|
|
119
|
+
inside a code block.
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from nodus_delivery import MarkdownBlockChunker
|
|
123
|
+
chunker = MarkdownBlockChunker(max_chars=2000)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## DeliveryRouter
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from nodus_delivery import DeliveryRouter
|
|
132
|
+
|
|
133
|
+
router = DeliveryRouter(
|
|
134
|
+
registry,
|
|
135
|
+
default_chunker=ParagraphChunker(max_chars=2000),
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
# Build a plan from an inbound Message (replies to sender on same channel)
|
|
139
|
+
plan = router.plan_from_message(inbound_message, content="Here is my response.")
|
|
140
|
+
|
|
141
|
+
# Deliver — sends all chunks in order, returns list of message IDs
|
|
142
|
+
msg_ids = await router.deliver(plan)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
If no adapter is registered for `channel_id`, `deliver` raises `KeyError`.
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## strip_markdown
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
from nodus_delivery import strip_markdown
|
|
153
|
+
|
|
154
|
+
plain = strip_markdown("**bold** and `code` and [link](url)")
|
|
155
|
+
# → "bold and code and link"
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Useful when delivering to channels that don't render markdown (e.g., SMS, voice).
|
|
159
|
+
|
|
160
|
+
---
|
|
161
|
+
|
|
162
|
+
## Design
|
|
163
|
+
|
|
164
|
+
- **One required dependency:** `nodus-channels` for `ChannelRegistry`,
|
|
165
|
+
`ChannelAdapter`, and `Message` types.
|
|
166
|
+
- **Protocol-based chunking.** Any callable satisfying `ChunkStrategy`
|
|
167
|
+
(`chunk(text) -> list[str]`) works — no inheritance needed.
|
|
168
|
+
- **Async delivery.** `DeliveryRouter.deliver()` is async; each chunk is
|
|
169
|
+
awaited in sequence to preserve ordering.
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
## Development
|
|
174
|
+
|
|
175
|
+
```bash
|
|
176
|
+
pip install -e ".[dev]"
|
|
177
|
+
# Also install nodus-channels for tests:
|
|
178
|
+
pip install -e "C:/dev/nodus-channels"
|
|
179
|
+
pytest tests/ -q
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
## License
|
|
185
|
+
|
|
186
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
# nodus-delivery
|
|
2
|
+
|
|
3
|
+
**Outbound routing, chunking, and delivery planning for multi-channel AI systems.**
|
|
4
|
+
|
|
5
|
+
Resolves the right channel adapter for a response, splits long content into
|
|
6
|
+
channel-appropriate chunks, and delivers each chunk in order. Depends on
|
|
7
|
+
[nodus-channels](https://github.com/Masterplanner25/nodus-channels) for the
|
|
8
|
+
`ChannelRegistry` and `ChannelAdapter` protocol.
|
|
9
|
+
|
|
10
|
+
> **Status:** v0.1.0 — prepared, not yet published.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install nodus-delivery
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Requires `nodus-channels>=0.1.0`.
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## What it provides
|
|
25
|
+
|
|
26
|
+
| Component | Purpose |
|
|
27
|
+
|---|---|
|
|
28
|
+
| `DeliveryPlan` | Describes where and how to send a response |
|
|
29
|
+
| `SizeChunker` | Split at word boundaries up to a max character count |
|
|
30
|
+
| `ParagraphChunker` | Split on paragraph breaks, respecting a max size |
|
|
31
|
+
| `MarkdownBlockChunker` | Preserve code blocks and headers across splits |
|
|
32
|
+
| `strip_markdown` | Remove markdown formatting → plain text |
|
|
33
|
+
| `DeliveryRouter` | Resolve adapter, chunk, and send; build plan from inbound message |
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## Quick start
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from nodus_channels import ChannelRegistry
|
|
41
|
+
from nodus_delivery import DeliveryRouter, DeliveryPlan, SizeChunker
|
|
42
|
+
|
|
43
|
+
registry = ChannelRegistry()
|
|
44
|
+
registry.register(my_slack_adapter)
|
|
45
|
+
|
|
46
|
+
router = DeliveryRouter(registry, default_chunker=SizeChunker(max_chars=2000))
|
|
47
|
+
|
|
48
|
+
plan = DeliveryPlan(
|
|
49
|
+
channel_id="slack",
|
|
50
|
+
peer_id="U123",
|
|
51
|
+
content="A very long response that may need chunking...",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
await router.deliver(plan)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## DeliveryPlan
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from nodus_delivery import DeliveryPlan
|
|
63
|
+
|
|
64
|
+
plan = DeliveryPlan(
|
|
65
|
+
channel_id="slack",
|
|
66
|
+
peer_id="U123",
|
|
67
|
+
content="Response text",
|
|
68
|
+
thread_id="T456", # optional: reply in a thread
|
|
69
|
+
reply_to_id="M789", # optional: reply to a specific message
|
|
70
|
+
strip_md=False, # strip markdown before chunking (default False)
|
|
71
|
+
chunker=None, # override router's default chunker
|
|
72
|
+
)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## Chunking strategies
|
|
78
|
+
|
|
79
|
+
### SizeChunker
|
|
80
|
+
|
|
81
|
+
Splits at word boundaries. Safe for any channel.
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from nodus_delivery import SizeChunker
|
|
85
|
+
chunker = SizeChunker(max_chars=2000)
|
|
86
|
+
chunks = chunker.chunk("Long text...") # list[str]
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### ParagraphChunker
|
|
90
|
+
|
|
91
|
+
Splits on `\n\n` paragraph breaks first; falls back to size if a paragraph
|
|
92
|
+
exceeds `max_chars`.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
from nodus_delivery import ParagraphChunker
|
|
96
|
+
chunker = ParagraphChunker(max_chars=2000)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### MarkdownBlockChunker
|
|
100
|
+
|
|
101
|
+
Keeps code fences (` ``` `) and headers (`#`, `##`) intact. Never splits
|
|
102
|
+
inside a code block.
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from nodus_delivery import MarkdownBlockChunker
|
|
106
|
+
chunker = MarkdownBlockChunker(max_chars=2000)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
## DeliveryRouter
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from nodus_delivery import DeliveryRouter
|
|
115
|
+
|
|
116
|
+
router = DeliveryRouter(
|
|
117
|
+
registry,
|
|
118
|
+
default_chunker=ParagraphChunker(max_chars=2000),
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
# Build a plan from an inbound Message (replies to sender on same channel)
|
|
122
|
+
plan = router.plan_from_message(inbound_message, content="Here is my response.")
|
|
123
|
+
|
|
124
|
+
# Deliver — sends all chunks in order, returns list of message IDs
|
|
125
|
+
msg_ids = await router.deliver(plan)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
If no adapter is registered for `channel_id`, `deliver` raises `KeyError`.
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
## strip_markdown
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
from nodus_delivery import strip_markdown
|
|
136
|
+
|
|
137
|
+
plain = strip_markdown("**bold** and `code` and [link](url)")
|
|
138
|
+
# → "bold and code and link"
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Useful when delivering to channels that don't render markdown (e.g., SMS, voice).
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
## Design
|
|
146
|
+
|
|
147
|
+
- **One required dependency:** `nodus-channels` for `ChannelRegistry`,
|
|
148
|
+
`ChannelAdapter`, and `Message` types.
|
|
149
|
+
- **Protocol-based chunking.** Any callable satisfying `ChunkStrategy`
|
|
150
|
+
(`chunk(text) -> list[str]`) works — no inheritance needed.
|
|
151
|
+
- **Async delivery.** `DeliveryRouter.deliver()` is async; each chunk is
|
|
152
|
+
awaited in sequence to preserve ordering.
|
|
153
|
+
|
|
154
|
+
---
|
|
155
|
+
|
|
156
|
+
## Development
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
pip install -e ".[dev]"
|
|
160
|
+
# Also install nodus-channels for tests:
|
|
161
|
+
pip install -e "C:/dev/nodus-channels"
|
|
162
|
+
pytest tests/ -q
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
## License
|
|
168
|
+
|
|
169
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""nodus-delivery — outbound routing, chunking, and delivery planning.
|
|
2
|
+
|
|
3
|
+
Depends on nodus-channels for ChannelRegistry, ChannelAdapter, and Message types.
|
|
4
|
+
|
|
5
|
+
Plan:
|
|
6
|
+
DeliveryPlan — describes where and how to send a response
|
|
7
|
+
|
|
8
|
+
Chunking:
|
|
9
|
+
ChunkStrategy — protocol all chunkers satisfy
|
|
10
|
+
SizeChunker — split at word boundaries
|
|
11
|
+
ParagraphChunker — split on paragraph breaks
|
|
12
|
+
MarkdownBlockChunker — preserve code blocks and headers
|
|
13
|
+
strip_markdown — remove markdown formatting → plain text
|
|
14
|
+
|
|
15
|
+
Router:
|
|
16
|
+
DeliveryRouter — resolve adapter, chunk, send; plan_from_message()
|
|
17
|
+
"""
|
|
18
|
+
from .chunker import (
|
|
19
|
+
ChunkStrategy,
|
|
20
|
+
MarkdownBlockChunker,
|
|
21
|
+
ParagraphChunker,
|
|
22
|
+
SizeChunker,
|
|
23
|
+
strip_markdown,
|
|
24
|
+
)
|
|
25
|
+
from .plan import DeliveryPlan
|
|
26
|
+
from .router import DeliveryRouter
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"DeliveryPlan",
|
|
30
|
+
"ChunkStrategy",
|
|
31
|
+
"SizeChunker",
|
|
32
|
+
"ParagraphChunker",
|
|
33
|
+
"MarkdownBlockChunker",
|
|
34
|
+
"strip_markdown",
|
|
35
|
+
"DeliveryRouter",
|
|
36
|
+
]
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Chunking strategies for splitting long content into channel-size pieces."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
from typing import Protocol, runtime_checkable
|
|
8
|
+
except ImportError:
|
|
9
|
+
from typing_extensions import Protocol, runtime_checkable # type: ignore[assignment]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@runtime_checkable
|
|
13
|
+
class ChunkStrategy(Protocol):
|
|
14
|
+
"""Protocol for all content chunking strategies."""
|
|
15
|
+
|
|
16
|
+
def chunk(self, content: str, max_length: int) -> list[str]:
|
|
17
|
+
"""Split *content* into chunks no longer than *max_length* characters."""
|
|
18
|
+
...
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class SizeChunker:
|
|
22
|
+
"""Split content at word boundaries, never exceeding *max_length* chars per chunk."""
|
|
23
|
+
|
|
24
|
+
def chunk(self, content: str, max_length: int) -> list[str]:
|
|
25
|
+
if not content:
|
|
26
|
+
return []
|
|
27
|
+
if len(content) <= max_length:
|
|
28
|
+
return [content]
|
|
29
|
+
|
|
30
|
+
chunks: list[str] = []
|
|
31
|
+
while len(content) > max_length:
|
|
32
|
+
# Find the last space before max_length
|
|
33
|
+
split_at = content.rfind(" ", 0, max_length)
|
|
34
|
+
if split_at <= 0:
|
|
35
|
+
split_at = max_length # hard split if no space found
|
|
36
|
+
chunks.append(content[:split_at].rstrip())
|
|
37
|
+
content = content[split_at:].lstrip()
|
|
38
|
+
if content:
|
|
39
|
+
chunks.append(content)
|
|
40
|
+
return chunks
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ParagraphChunker:
|
|
44
|
+
"""Split on paragraph boundaries first; fall back to SizeChunker for long paragraphs.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
fallback_size: Max length passed to SizeChunker when a paragraph is too long.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(self, fallback_size: int = 4000) -> None:
|
|
51
|
+
self._fallback = SizeChunker()
|
|
52
|
+
self._fallback_size = fallback_size
|
|
53
|
+
|
|
54
|
+
def chunk(self, content: str, max_length: int) -> list[str]:
|
|
55
|
+
if not content:
|
|
56
|
+
return []
|
|
57
|
+
if len(content) <= max_length:
|
|
58
|
+
return [content]
|
|
59
|
+
|
|
60
|
+
paragraphs = re.split(r"\n{2,}", content)
|
|
61
|
+
chunks: list[str] = []
|
|
62
|
+
current = ""
|
|
63
|
+
|
|
64
|
+
for para in paragraphs:
|
|
65
|
+
para = para.strip()
|
|
66
|
+
if not para:
|
|
67
|
+
continue
|
|
68
|
+
candidate = (current + "\n\n" + para).strip() if current else para
|
|
69
|
+
if len(candidate) <= max_length:
|
|
70
|
+
current = candidate
|
|
71
|
+
else:
|
|
72
|
+
if current:
|
|
73
|
+
chunks.append(current)
|
|
74
|
+
if len(para) > max_length:
|
|
75
|
+
# Paragraph itself is too long — fall back to size chunker
|
|
76
|
+
chunks.extend(self._fallback.chunk(para, self._fallback_size))
|
|
77
|
+
current = ""
|
|
78
|
+
else:
|
|
79
|
+
current = para
|
|
80
|
+
|
|
81
|
+
if current:
|
|
82
|
+
chunks.append(current)
|
|
83
|
+
return chunks or [content]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class MarkdownBlockChunker:
|
|
87
|
+
"""Preserve code blocks, headers, and list items; split between them.
|
|
88
|
+
|
|
89
|
+
Never splits inside a fenced code block. Falls back to SizeChunker when
|
|
90
|
+
an individual block exceeds *max_length*.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
fallback_size: Max length for the internal SizeChunker fallback.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
def __init__(self, fallback_size: int = 4000) -> None:
|
|
97
|
+
self._fallback = SizeChunker()
|
|
98
|
+
self._fallback_size = fallback_size
|
|
99
|
+
|
|
100
|
+
def chunk(self, content: str, max_length: int) -> list[str]:
|
|
101
|
+
if not content:
|
|
102
|
+
return []
|
|
103
|
+
if len(content) <= max_length:
|
|
104
|
+
return [content]
|
|
105
|
+
|
|
106
|
+
# Split into logical blocks (fenced code blocks stay intact)
|
|
107
|
+
blocks = self._split_blocks(content)
|
|
108
|
+
chunks: list[str] = []
|
|
109
|
+
current = ""
|
|
110
|
+
|
|
111
|
+
for block in blocks:
|
|
112
|
+
candidate = (current + "\n\n" + block).strip() if current else block
|
|
113
|
+
if len(candidate) <= max_length:
|
|
114
|
+
current = candidate
|
|
115
|
+
else:
|
|
116
|
+
if current:
|
|
117
|
+
chunks.append(current)
|
|
118
|
+
if len(block) > max_length:
|
|
119
|
+
chunks.extend(self._fallback.chunk(block, self._fallback_size))
|
|
120
|
+
current = ""
|
|
121
|
+
else:
|
|
122
|
+
current = block
|
|
123
|
+
|
|
124
|
+
if current:
|
|
125
|
+
chunks.append(current)
|
|
126
|
+
return chunks or [content]
|
|
127
|
+
|
|
128
|
+
@staticmethod
|
|
129
|
+
def _split_blocks(content: str) -> list[str]:
|
|
130
|
+
"""Split into logical blocks preserving fenced code blocks."""
|
|
131
|
+
blocks: list[str] = []
|
|
132
|
+
in_fence = False
|
|
133
|
+
current: list[str] = []
|
|
134
|
+
|
|
135
|
+
for line in content.split("\n"):
|
|
136
|
+
stripped = line.strip()
|
|
137
|
+
if stripped.startswith("```") or stripped.startswith("~~~"):
|
|
138
|
+
if in_fence:
|
|
139
|
+
current.append(line)
|
|
140
|
+
blocks.append("\n".join(current))
|
|
141
|
+
current = []
|
|
142
|
+
in_fence = False
|
|
143
|
+
else:
|
|
144
|
+
if current:
|
|
145
|
+
blocks.append("\n".join(current))
|
|
146
|
+
current = []
|
|
147
|
+
in_fence = True
|
|
148
|
+
current = [line]
|
|
149
|
+
elif in_fence:
|
|
150
|
+
current.append(line)
|
|
151
|
+
elif not stripped:
|
|
152
|
+
if current:
|
|
153
|
+
blocks.append("\n".join(current))
|
|
154
|
+
current = []
|
|
155
|
+
else:
|
|
156
|
+
current.append(line)
|
|
157
|
+
|
|
158
|
+
if current:
|
|
159
|
+
blocks.append("\n".join(current))
|
|
160
|
+
return [b for b in blocks if b.strip()]
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# ── Markdown stripping ─────────────────────────────────────────────────────────
|
|
164
|
+
|
|
165
|
+
_MD_PATTERNS = [
|
|
166
|
+
(re.compile(r"```[\s\S]*?```"), ""), # fenced code blocks
|
|
167
|
+
(re.compile(r"`[^`]+`"), ""), # inline code
|
|
168
|
+
(re.compile(r"^#{1,6}\s*", re.MULTILINE), ""),# headers
|
|
169
|
+
(re.compile(r"\*\*(.+?)\*\*"), r"\1"), # bold
|
|
170
|
+
(re.compile(r"\*(.+?)\*"), r"\1"), # italic
|
|
171
|
+
(re.compile(r"__(.+?)__"), r"\1"), # bold alt
|
|
172
|
+
(re.compile(r"_(.+?)_"), r"\1"), # italic alt
|
|
173
|
+
(re.compile(r"~~(.+?)~~"), r"\1"), # strikethrough
|
|
174
|
+
(re.compile(r"\[([^\]]+)\]\([^)]+\)"), r"\1"), # links
|
|
175
|
+
(re.compile(r"^[-*+]\s+", re.MULTILINE), ""), # list bullets
|
|
176
|
+
(re.compile(r"^\d+\.\s+", re.MULTILINE), ""), # numbered lists
|
|
177
|
+
(re.compile(r"^>\s+", re.MULTILINE), ""), # blockquotes
|
|
178
|
+
]
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def strip_markdown(content: str) -> str:
|
|
182
|
+
"""Remove common markdown formatting, returning plain text."""
|
|
183
|
+
result = content
|
|
184
|
+
for pattern, replacement in _MD_PATTERNS:
|
|
185
|
+
result = pattern.sub(replacement, result)
|
|
186
|
+
# Collapse multiple blank lines
|
|
187
|
+
result = re.sub(r"\n{3,}", "\n\n", result)
|
|
188
|
+
return result.strip()
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""DeliveryPlan — structured descriptor for outbound message routing."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class DeliveryPlan:
|
|
10
|
+
"""Describes where and how to send an agent response.
|
|
11
|
+
|
|
12
|
+
Attributes
|
|
13
|
+
----------
|
|
14
|
+
channel_id: Channel adapter to use (e.g. ``"slack"``, ``"discord"``).
|
|
15
|
+
peer_id: Direct recipient's platform ID. One of *peer_id* or
|
|
16
|
+
*thread_id* is typically set.
|
|
17
|
+
thread_id: Thread or topic ID to post in (for threaded channels).
|
|
18
|
+
reply_to_id: Platform message ID to quote/reply to.
|
|
19
|
+
chunk_size: Max characters per chunk. None = use ``ChannelInfo.max_message_length``.
|
|
20
|
+
preserve_markdown: When False, strip markdown before sending.
|
|
21
|
+
metadata: Channel-specific extras passed through to the adapter.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
channel_id: str
|
|
25
|
+
peer_id: str | None = None
|
|
26
|
+
thread_id: str | None = None
|
|
27
|
+
reply_to_id: str | None = None
|
|
28
|
+
chunk_size: int | None = None
|
|
29
|
+
preserve_markdown: bool = True
|
|
30
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""DeliveryRouter — resolve adapter, chunk content, and send."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import logging
|
|
5
|
+
from typing import TYPE_CHECKING, Optional
|
|
6
|
+
|
|
7
|
+
from .chunker import ChunkStrategy, SizeChunker
|
|
8
|
+
from .plan import DeliveryPlan
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from nodus_channels import ChannelRegistry, Message
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
_DEFAULT_CHUNK_SIZE = 4000
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DeliveryRouter:
|
|
19
|
+
"""Route agent output through the appropriate channel adapter.
|
|
20
|
+
|
|
21
|
+
Usage::
|
|
22
|
+
|
|
23
|
+
router = DeliveryRouter(registry)
|
|
24
|
+
message_ids = await router.send("Hello world", plan)
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, registry: "ChannelRegistry") -> None:
|
|
28
|
+
self._registry = registry
|
|
29
|
+
|
|
30
|
+
async def send(
|
|
31
|
+
self,
|
|
32
|
+
content: str,
|
|
33
|
+
plan: DeliveryPlan,
|
|
34
|
+
*,
|
|
35
|
+
chunker: Optional[ChunkStrategy] = None,
|
|
36
|
+
) -> list[str]:
|
|
37
|
+
"""Resolve adapter, chunk content, and send each chunk.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
content: Text to send (markdown or plain text).
|
|
41
|
+
plan: ``DeliveryPlan`` describing where to send.
|
|
42
|
+
chunker: Override chunking strategy. Defaults to ``SizeChunker``.
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
List of platform message IDs (one per chunk sent).
|
|
46
|
+
|
|
47
|
+
Raises:
|
|
48
|
+
KeyError: If ``plan.channel_id`` is not registered.
|
|
49
|
+
"""
|
|
50
|
+
adapter = self._registry.get(plan.channel_id)
|
|
51
|
+
if adapter is None:
|
|
52
|
+
raise KeyError(
|
|
53
|
+
f"No adapter registered for channel {plan.channel_id!r}. "
|
|
54
|
+
f"Register one with ChannelRegistry.register() first."
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# Apply markdown stripping if needed
|
|
58
|
+
send_content = content
|
|
59
|
+
if not plan.preserve_markdown:
|
|
60
|
+
from .chunker import strip_markdown # noqa: PLC0415
|
|
61
|
+
send_content = strip_markdown(content)
|
|
62
|
+
|
|
63
|
+
# Determine chunk size
|
|
64
|
+
chunk_size = plan.chunk_size
|
|
65
|
+
if chunk_size is None:
|
|
66
|
+
try:
|
|
67
|
+
chunk_size = adapter.info.max_message_length
|
|
68
|
+
except Exception:
|
|
69
|
+
chunk_size = _DEFAULT_CHUNK_SIZE
|
|
70
|
+
|
|
71
|
+
# Chunk content
|
|
72
|
+
strategy = chunker or SizeChunker()
|
|
73
|
+
chunks = strategy.chunk(send_content, chunk_size)
|
|
74
|
+
if not chunks:
|
|
75
|
+
chunks = [send_content] if send_content else []
|
|
76
|
+
|
|
77
|
+
# Send each chunk
|
|
78
|
+
message_ids: list[str] = []
|
|
79
|
+
prev_id: str | None = plan.reply_to_id
|
|
80
|
+
|
|
81
|
+
for i, chunk in enumerate(chunks):
|
|
82
|
+
if not chunk.strip():
|
|
83
|
+
continue
|
|
84
|
+
msg_id = await adapter.send(
|
|
85
|
+
chunk,
|
|
86
|
+
plan.peer_id or "",
|
|
87
|
+
thread_id=plan.thread_id,
|
|
88
|
+
reply_to_id=prev_id if i == 0 else None,
|
|
89
|
+
)
|
|
90
|
+
message_ids.append(msg_id)
|
|
91
|
+
# Subsequent chunks don't quote the original
|
|
92
|
+
prev_id = None
|
|
93
|
+
|
|
94
|
+
return message_ids
|
|
95
|
+
|
|
96
|
+
def plan_from_message(
|
|
97
|
+
self,
|
|
98
|
+
source: "Message",
|
|
99
|
+
*,
|
|
100
|
+
reply: bool = True,
|
|
101
|
+
) -> DeliveryPlan:
|
|
102
|
+
"""Build a ``DeliveryPlan`` for replying to *source*.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
source: The inbound message to reply to.
|
|
106
|
+
reply: When True, set ``reply_to_id`` to quote the source message.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
A ``DeliveryPlan`` targeting the same channel, peer, and thread.
|
|
110
|
+
"""
|
|
111
|
+
return DeliveryPlan(
|
|
112
|
+
channel_id=source.channel_id,
|
|
113
|
+
peer_id=source.sender.id,
|
|
114
|
+
thread_id=source.thread_id,
|
|
115
|
+
reply_to_id=source.id if reply else None,
|
|
116
|
+
)
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: nodus-delivery
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Outbound routing, chunking, and delivery planning for multi-channel AI systems
|
|
5
|
+
Author: Shawn Knight
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Masterplanner25/nodus-delivery
|
|
8
|
+
Project-URL: Repository, https://github.com/Masterplanner25/nodus-delivery
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: nodus-channels>=0.1.0
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
15
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# nodus-delivery
|
|
19
|
+
|
|
20
|
+
**Outbound routing, chunking, and delivery planning for multi-channel AI systems.**
|
|
21
|
+
|
|
22
|
+
Resolves the right channel adapter for a response, splits long content into
|
|
23
|
+
channel-appropriate chunks, and delivers each chunk in order. Depends on
|
|
24
|
+
[nodus-channels](https://github.com/Masterplanner25/nodus-channels) for the
|
|
25
|
+
`ChannelRegistry` and `ChannelAdapter` protocol.
|
|
26
|
+
|
|
27
|
+
> **Status:** v0.1.0 — prepared, not yet published.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install nodus-delivery
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Requires `nodus-channels>=0.1.0`.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## What it provides
|
|
42
|
+
|
|
43
|
+
| Component | Purpose |
|
|
44
|
+
|---|---|
|
|
45
|
+
| `DeliveryPlan` | Describes where and how to send a response |
|
|
46
|
+
| `SizeChunker` | Split at word boundaries up to a max character count |
|
|
47
|
+
| `ParagraphChunker` | Split on paragraph breaks, respecting a max size |
|
|
48
|
+
| `MarkdownBlockChunker` | Preserve code blocks and headers across splits |
|
|
49
|
+
| `strip_markdown` | Remove markdown formatting → plain text |
|
|
50
|
+
| `DeliveryRouter` | Resolve adapter, chunk, and send; build plan from inbound message |
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## Quick start
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from nodus_channels import ChannelRegistry
|
|
58
|
+
from nodus_delivery import DeliveryRouter, DeliveryPlan, SizeChunker
|
|
59
|
+
|
|
60
|
+
registry = ChannelRegistry()
|
|
61
|
+
registry.register(my_slack_adapter)
|
|
62
|
+
|
|
63
|
+
router = DeliveryRouter(registry, default_chunker=SizeChunker(max_chars=2000))
|
|
64
|
+
|
|
65
|
+
plan = DeliveryPlan(
|
|
66
|
+
channel_id="slack",
|
|
67
|
+
peer_id="U123",
|
|
68
|
+
content="A very long response that may need chunking...",
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
await router.deliver(plan)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
---
|
|
75
|
+
|
|
76
|
+
## DeliveryPlan
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from nodus_delivery import DeliveryPlan
|
|
80
|
+
|
|
81
|
+
plan = DeliveryPlan(
|
|
82
|
+
channel_id="slack",
|
|
83
|
+
peer_id="U123",
|
|
84
|
+
content="Response text",
|
|
85
|
+
thread_id="T456", # optional: reply in a thread
|
|
86
|
+
reply_to_id="M789", # optional: reply to a specific message
|
|
87
|
+
strip_md=False, # strip markdown before chunking (default False)
|
|
88
|
+
chunker=None, # override router's default chunker
|
|
89
|
+
)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Chunking strategies
|
|
95
|
+
|
|
96
|
+
### SizeChunker
|
|
97
|
+
|
|
98
|
+
Splits at word boundaries. Safe for any channel.
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from nodus_delivery import SizeChunker
|
|
102
|
+
chunker = SizeChunker(max_chars=2000)
|
|
103
|
+
chunks = chunker.chunk("Long text...") # list[str]
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### ParagraphChunker
|
|
107
|
+
|
|
108
|
+
Splits on `\n\n` paragraph breaks first; falls back to size if a paragraph
|
|
109
|
+
exceeds `max_chars`.
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from nodus_delivery import ParagraphChunker
|
|
113
|
+
chunker = ParagraphChunker(max_chars=2000)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### MarkdownBlockChunker
|
|
117
|
+
|
|
118
|
+
Keeps code fences (` ``` `) and headers (`#`, `##`) intact. Never splits
|
|
119
|
+
inside a code block.
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from nodus_delivery import MarkdownBlockChunker
|
|
123
|
+
chunker = MarkdownBlockChunker(max_chars=2000)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## DeliveryRouter
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from nodus_delivery import DeliveryRouter
|
|
132
|
+
|
|
133
|
+
router = DeliveryRouter(
|
|
134
|
+
registry,
|
|
135
|
+
default_chunker=ParagraphChunker(max_chars=2000),
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
# Build a plan from an inbound Message (replies to sender on same channel)
|
|
139
|
+
plan = router.plan_from_message(inbound_message, content="Here is my response.")
|
|
140
|
+
|
|
141
|
+
# Deliver — sends all chunks in order, returns list of message IDs
|
|
142
|
+
msg_ids = await router.deliver(plan)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
If no adapter is registered for `channel_id`, `deliver` raises `KeyError`.
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## strip_markdown
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
from nodus_delivery import strip_markdown
|
|
153
|
+
|
|
154
|
+
plain = strip_markdown("**bold** and `code` and [link](url)")
|
|
155
|
+
# → "bold and code and link"
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Useful when delivering to channels that don't render markdown (e.g., SMS, voice).
|
|
159
|
+
|
|
160
|
+
---
|
|
161
|
+
|
|
162
|
+
## Design
|
|
163
|
+
|
|
164
|
+
- **One required dependency:** `nodus-channels` for `ChannelRegistry`,
|
|
165
|
+
`ChannelAdapter`, and `Message` types.
|
|
166
|
+
- **Protocol-based chunking.** Any callable satisfying `ChunkStrategy`
|
|
167
|
+
(`chunk(text) -> list[str]`) works — no inheritance needed.
|
|
168
|
+
- **Async delivery.** `DeliveryRouter.deliver()` is async; each chunk is
|
|
169
|
+
awaited in sequence to preserve ordering.
|
|
170
|
+
|
|
171
|
+
---
|
|
172
|
+
|
|
173
|
+
## Development
|
|
174
|
+
|
|
175
|
+
```bash
|
|
176
|
+
pip install -e ".[dev]"
|
|
177
|
+
# Also install nodus-channels for tests:
|
|
178
|
+
pip install -e "C:/dev/nodus-channels"
|
|
179
|
+
pytest tests/ -q
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
## License
|
|
185
|
+
|
|
186
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
nodus_delivery/__init__.py
|
|
5
|
+
nodus_delivery/chunker.py
|
|
6
|
+
nodus_delivery/plan.py
|
|
7
|
+
nodus_delivery/router.py
|
|
8
|
+
nodus_delivery.egg-info/PKG-INFO
|
|
9
|
+
nodus_delivery.egg-info/SOURCES.txt
|
|
10
|
+
nodus_delivery.egg-info/dependency_links.txt
|
|
11
|
+
nodus_delivery.egg-info/requires.txt
|
|
12
|
+
nodus_delivery.egg-info/top_level.txt
|
|
13
|
+
tests/test_chunker.py
|
|
14
|
+
tests/test_plan.py
|
|
15
|
+
tests/test_router.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
nodus_delivery
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=80", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "nodus-delivery"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Outbound routing, chunking, and delivery planning for multi-channel AI systems"
|
|
9
|
+
authors = [{ name = "Shawn Knight" }]
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
readme = "README.md"
|
|
12
|
+
requires-python = ">=3.11"
|
|
13
|
+
dependencies = ["nodus-channels>=0.1.0"]
|
|
14
|
+
|
|
15
|
+
[project.optional-dependencies]
|
|
16
|
+
dev = ["pytest>=8.0", "pytest-asyncio>=0.21"]
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Homepage = "https://github.com/Masterplanner25/nodus-delivery"
|
|
20
|
+
Repository = "https://github.com/Masterplanner25/nodus-delivery"
|
|
21
|
+
|
|
22
|
+
[tool.setuptools.packages.find]
|
|
23
|
+
where = ["."]
|
|
24
|
+
include = ["nodus_delivery*"]
|
|
25
|
+
|
|
26
|
+
[tool.pytest.ini_options]
|
|
27
|
+
asyncio_mode = "auto"
|
|
28
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from nodus_delivery import (
|
|
3
|
+
MarkdownBlockChunker,
|
|
4
|
+
ParagraphChunker,
|
|
5
|
+
SizeChunker,
|
|
6
|
+
strip_markdown,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
# ── SizeChunker ───────────────────────────────────────────────────────────────
|
|
11
|
+
|
|
12
|
+
def test_size_chunker_empty():
|
|
13
|
+
assert SizeChunker().chunk("", 100) == []
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_size_chunker_fits_in_one():
|
|
17
|
+
result = SizeChunker().chunk("hello world", 100)
|
|
18
|
+
assert result == ["hello world"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_size_chunker_splits_at_word():
|
|
22
|
+
result = SizeChunker().chunk("hello world foo", max_length=11)
|
|
23
|
+
for chunk in result:
|
|
24
|
+
assert len(chunk) <= 11
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_size_chunker_all_chunks_within_limit():
|
|
28
|
+
content = "word " * 100
|
|
29
|
+
result = SizeChunker().chunk(content, 20)
|
|
30
|
+
for chunk in result:
|
|
31
|
+
assert len(chunk) <= 20
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_size_chunker_reassembles_losslessly():
|
|
35
|
+
content = "apple banana cherry date elderberry fig grape"
|
|
36
|
+
result = SizeChunker().chunk(content, 15)
|
|
37
|
+
joined = " ".join(result)
|
|
38
|
+
# All words should be present
|
|
39
|
+
for word in content.split():
|
|
40
|
+
assert word in joined
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# ── ParagraphChunker ──────────────────────────────────────────────────────────
|
|
44
|
+
|
|
45
|
+
def test_paragraph_chunker_empty():
|
|
46
|
+
assert ParagraphChunker().chunk("", 100) == []
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_paragraph_chunker_fits_in_one():
|
|
50
|
+
result = ParagraphChunker().chunk("hello\n\nworld", 100)
|
|
51
|
+
assert len(result) == 1
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_paragraph_chunker_splits_on_paragraphs():
|
|
55
|
+
content = "Para one.\n\nPara two.\n\nPara three."
|
|
56
|
+
result = ParagraphChunker().chunk(content, 15)
|
|
57
|
+
assert len(result) >= 2
|
|
58
|
+
for chunk in result:
|
|
59
|
+
assert len(chunk) <= 15 or True # large para gets fallback chunked
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_paragraph_chunker_respects_limit():
|
|
63
|
+
content = "short\n\nshort\n\nshort"
|
|
64
|
+
result = ParagraphChunker().chunk(content, 100)
|
|
65
|
+
assert len(result) == 1 # all fit together
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ── MarkdownBlockChunker ──────────────────────────────────────────────────────
|
|
69
|
+
|
|
70
|
+
def test_markdown_block_chunker_preserves_code_block():
|
|
71
|
+
content = "Intro\n\n```python\nx = 1\n```\n\nOutro"
|
|
72
|
+
result = MarkdownBlockChunker().chunk(content, 200)
|
|
73
|
+
all_content = "\n".join(result)
|
|
74
|
+
assert "```python" in all_content
|
|
75
|
+
assert "x = 1" in all_content
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_markdown_block_chunker_fits_in_one():
|
|
79
|
+
content = "# Header\n\nShort content."
|
|
80
|
+
result = MarkdownBlockChunker().chunk(content, 200)
|
|
81
|
+
assert len(result) == 1
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# ── strip_markdown ────────────────────────────────────────────────────────────
|
|
85
|
+
|
|
86
|
+
def test_strip_removes_bold():
|
|
87
|
+
assert "**hello**" not in strip_markdown("**hello**")
|
|
88
|
+
assert "hello" in strip_markdown("**hello**")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_strip_removes_italic():
|
|
92
|
+
result = strip_markdown("*italic text*")
|
|
93
|
+
assert "*" not in result
|
|
94
|
+
assert "italic text" in result
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_strip_removes_headers():
|
|
98
|
+
result = strip_markdown("# My Header\n\nContent")
|
|
99
|
+
assert "#" not in result
|
|
100
|
+
assert "My Header" in result
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def test_strip_removes_links():
|
|
104
|
+
result = strip_markdown("[click here](https://example.com)")
|
|
105
|
+
assert "click here" in result
|
|
106
|
+
assert "https://" not in result
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_strip_removes_code():
|
|
110
|
+
result = strip_markdown("`inline code`")
|
|
111
|
+
assert "`" not in result
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def test_strip_plain_text_unchanged():
|
|
115
|
+
text = "Just plain text without any formatting."
|
|
116
|
+
assert strip_markdown(text) == text
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from nodus_delivery import DeliveryPlan
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def test_plan_required_fields():
|
|
5
|
+
p = DeliveryPlan(channel_id="slack")
|
|
6
|
+
assert p.channel_id == "slack"
|
|
7
|
+
assert p.peer_id is None
|
|
8
|
+
assert p.thread_id is None
|
|
9
|
+
assert p.reply_to_id is None
|
|
10
|
+
assert p.chunk_size is None
|
|
11
|
+
assert p.preserve_markdown is True
|
|
12
|
+
assert p.metadata == {}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_plan_all_fields():
|
|
16
|
+
p = DeliveryPlan(
|
|
17
|
+
channel_id="discord",
|
|
18
|
+
peer_id="U123",
|
|
19
|
+
thread_id="T456",
|
|
20
|
+
reply_to_id="M789",
|
|
21
|
+
chunk_size=2000,
|
|
22
|
+
preserve_markdown=False,
|
|
23
|
+
metadata={"type": "dm"},
|
|
24
|
+
)
|
|
25
|
+
assert p.peer_id == "U123"
|
|
26
|
+
assert p.thread_id == "T456"
|
|
27
|
+
assert p.chunk_size == 2000
|
|
28
|
+
assert p.preserve_markdown is False
|
|
29
|
+
assert p.metadata["type"] == "dm"
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""DeliveryRouter tests using a stub ChannelAdapter."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from unittest.mock import AsyncMock, MagicMock
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from nodus_delivery import DeliveryPlan, DeliveryRouter, SizeChunker
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _make_registry(channel_id="slack", max_length=4000):
|
|
13
|
+
adapter = MagicMock()
|
|
14
|
+
adapter.channel_id = channel_id
|
|
15
|
+
adapter.info.max_message_length = max_length
|
|
16
|
+
adapter.send = AsyncMock(return_value="msg-id-1")
|
|
17
|
+
|
|
18
|
+
registry = MagicMock()
|
|
19
|
+
registry.get.return_value = adapter
|
|
20
|
+
return registry, adapter
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _make_source_message(channel_id="slack"):
|
|
24
|
+
from nodus_channels import Message, Peer
|
|
25
|
+
peer = Peer(id="U123", channel_id=channel_id)
|
|
26
|
+
return Message(
|
|
27
|
+
id="orig-msg",
|
|
28
|
+
channel_id=channel_id,
|
|
29
|
+
sender=peer,
|
|
30
|
+
content="hello",
|
|
31
|
+
timestamp=datetime.now(timezone.utc),
|
|
32
|
+
thread_id="T1",
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ── send ──────────────────────────────────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
@pytest.mark.asyncio
|
|
39
|
+
async def test_send_returns_message_ids():
|
|
40
|
+
registry, adapter = _make_registry()
|
|
41
|
+
router = DeliveryRouter(registry)
|
|
42
|
+
plan = DeliveryPlan(channel_id="slack", peer_id="U123")
|
|
43
|
+
ids = await router.send("Hello world", plan)
|
|
44
|
+
assert len(ids) == 1
|
|
45
|
+
assert ids[0] == "msg-id-1"
|
|
46
|
+
adapter.send.assert_called_once()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@pytest.mark.asyncio
|
|
50
|
+
async def test_send_uses_chunk_size_from_plan():
|
|
51
|
+
registry, adapter = _make_registry()
|
|
52
|
+
router = DeliveryRouter(registry)
|
|
53
|
+
plan = DeliveryPlan(channel_id="slack", peer_id="U1", chunk_size=5)
|
|
54
|
+
content = "word " * 10 # > 5 chars
|
|
55
|
+
await router.send(content, plan, chunker=SizeChunker())
|
|
56
|
+
# Should have been called multiple times due to small chunk size
|
|
57
|
+
assert adapter.send.call_count > 1
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@pytest.mark.asyncio
|
|
61
|
+
async def test_send_strips_markdown_when_preserve_false():
|
|
62
|
+
registry, adapter = _make_registry()
|
|
63
|
+
router = DeliveryRouter(registry)
|
|
64
|
+
plan = DeliveryPlan(channel_id="slack", peer_id="U1", preserve_markdown=False)
|
|
65
|
+
await router.send("**bold** text", plan)
|
|
66
|
+
# The sent content should have bold stripped
|
|
67
|
+
call_args = adapter.send.call_args
|
|
68
|
+
sent_content = call_args[0][0]
|
|
69
|
+
assert "**" not in sent_content
|
|
70
|
+
assert "bold" in sent_content
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@pytest.mark.asyncio
|
|
74
|
+
async def test_send_raises_keyerror_for_unknown_channel():
|
|
75
|
+
registry = MagicMock()
|
|
76
|
+
registry.get.return_value = None
|
|
77
|
+
router = DeliveryRouter(registry)
|
|
78
|
+
plan = DeliveryPlan(channel_id="unknown")
|
|
79
|
+
with pytest.raises(KeyError, match="unknown"):
|
|
80
|
+
await router.send("hello", plan)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@pytest.mark.asyncio
|
|
84
|
+
async def test_send_empty_content_returns_empty():
|
|
85
|
+
registry, adapter = _make_registry()
|
|
86
|
+
router = DeliveryRouter(registry)
|
|
87
|
+
plan = DeliveryPlan(channel_id="slack", peer_id="U1")
|
|
88
|
+
ids = await router.send("", plan)
|
|
89
|
+
assert ids == []
|
|
90
|
+
adapter.send.assert_not_called()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# ── plan_from_message ─────────────────────────────────────────────────────────
|
|
94
|
+
|
|
95
|
+
def test_plan_from_message_sets_channel_and_peer():
|
|
96
|
+
registry, _ = _make_registry()
|
|
97
|
+
router = DeliveryRouter(registry)
|
|
98
|
+
source = _make_source_message()
|
|
99
|
+
plan = router.plan_from_message(source)
|
|
100
|
+
assert plan.channel_id == "slack"
|
|
101
|
+
assert plan.peer_id == "U123"
|
|
102
|
+
assert plan.thread_id == "T1"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_plan_from_message_sets_reply_to_id():
|
|
106
|
+
registry, _ = _make_registry()
|
|
107
|
+
router = DeliveryRouter(registry)
|
|
108
|
+
source = _make_source_message()
|
|
109
|
+
plan = router.plan_from_message(source, reply=True)
|
|
110
|
+
assert plan.reply_to_id == "orig-msg"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_plan_from_message_no_reply():
|
|
114
|
+
registry, _ = _make_registry()
|
|
115
|
+
router = DeliveryRouter(registry)
|
|
116
|
+
source = _make_source_message()
|
|
117
|
+
plan = router.plan_from_message(source, reply=False)
|
|
118
|
+
assert plan.reply_to_id is None
|