cartesia-line 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of cartesia-line might be problematic. Click here for more details.
- cartesia_line-0.0.1.dist-info/METADATA +25 -0
- cartesia_line-0.0.1.dist-info/RECORD +27 -0
- cartesia_line-0.0.1.dist-info/WHEEL +5 -0
- cartesia_line-0.0.1.dist-info/licenses/LICENSE +201 -0
- cartesia_line-0.0.1.dist-info/top_level.txt +1 -0
- line/__init__.py +29 -0
- line/bridge.py +348 -0
- line/bus.py +401 -0
- line/call_request.py +25 -0
- line/events.py +218 -0
- line/harness.py +257 -0
- line/harness_types.py +109 -0
- line/nodes/__init__.py +7 -0
- line/nodes/base.py +60 -0
- line/nodes/conversation_context.py +66 -0
- line/nodes/reasoning.py +223 -0
- line/routes.py +618 -0
- line/tools/__init__.py +9 -0
- line/tools/system_tools.py +120 -0
- line/tools/tool_types.py +39 -0
- line/user_bridge.py +200 -0
- line/utils/__init__.py +0 -0
- line/utils/aio.py +62 -0
- line/utils/gemini_utils.py +152 -0
- line/utils/openai_utils.py +122 -0
- line/voice_agent_app.py +147 -0
- line/voice_agent_system.py +230 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cartesia-line
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Cartesia Voice Agents SDK
|
|
5
|
+
Requires-Python: >=3.9
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Dist: python-dotenv>=1.0.0
|
|
8
|
+
Requires-Dist: loguru>=0.7.0
|
|
9
|
+
Requires-Dist: fastapi>=0.115.0
|
|
10
|
+
Requires-Dist: aiohttp>=3.8.0
|
|
11
|
+
Requires-Dist: pydantic<3,>=2.0.0
|
|
12
|
+
Requires-Dist: uvicorn<1,>=0.35.0
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: pytest; extra == "dev"
|
|
15
|
+
Requires-Dist: pytest-asyncio; extra == "dev"
|
|
16
|
+
Requires-Dist: pre-commit; extra == "dev"
|
|
17
|
+
Requires-Dist: ruff==0.12.8; extra == "dev"
|
|
18
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
19
|
+
Requires-Dist: google-genai<2,>=1.26.0; extra == "dev"
|
|
20
|
+
Provides-Extra: gemini
|
|
21
|
+
Requires-Dist: google-genai<2,>=1.26.0; python_version >= "3.9" and extra == "gemini"
|
|
22
|
+
Requires-Dist: aiohttp>=3.12.0; extra == "gemini"
|
|
23
|
+
Provides-Extra: openai
|
|
24
|
+
Requires-Dist: openai>=1.70.0; extra == "openai"
|
|
25
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
cartesia_line-0.0.1.dist-info/licenses/LICENSE,sha256=ElpXuEGJlZ5XPeLe_tLbAmiEVE79EGxdy-aMw3JxE_Y,11347
|
|
2
|
+
line/__init__.py,sha256=glA0fvCL2xBmgC1cXZbiv6wcXS-yod7ctcL3EnoeEIk,790
|
|
3
|
+
line/bridge.py,sha256=53N5UizGKjrb6iR27OQbTtjgQZ-rNLjEJT0HqQiLa-M,14216
|
|
4
|
+
line/bus.py,sha256=AGMwHCNftVeWDzl0o1Jd2iDm51q1FTBEOlJzGZLub1Q,14324
|
|
5
|
+
line/call_request.py,sha256=JfYS4bAicuwjTHMXdK_PYbvSPj1dht44282yZACGUbU,847
|
|
6
|
+
line/events.py,sha256=d_CtDTGvLyMwFjdO97FtpTwyBO8uSmCzB2CC7hYagiQ,5565
|
|
7
|
+
line/harness.py,sha256=_4TJV3J2Sxdhz5JSuWXlthZLNmhfNlddHANzOLGjtec,8620
|
|
8
|
+
line/harness_types.py,sha256=Lwu1n2fAA5o-b_PjLWDSMu4G-GYEpb3X1CAUy3pvelk,2214
|
|
9
|
+
line/routes.py,sha256=jR_bl96ujx5MYzdVb9YLkcAITCboosM9UM7f4Et9eBc,24446
|
|
10
|
+
line/user_bridge.py,sha256=etnvSMALCDB7JOguW0imd41RSH3sHJ-oBHH2Hr7kSeQ,7620
|
|
11
|
+
line/voice_agent_app.py,sha256=1i-eIeZ3ZM8HHUjDn-WXpqAVfskhhRuESyHQA3AGlAQ,5448
|
|
12
|
+
line/voice_agent_system.py,sha256=8yywrjKdO43s7UkKqIs0jqte27vOF96NYnuGILsJz7k,8002
|
|
13
|
+
line/nodes/__init__.py,sha256=Rp-9gxMZ4hCTjbm6zaiTTBz6lg9d32UwxJgWTJfhnZU,128
|
|
14
|
+
line/nodes/base.py,sha256=HKfv_j3H-E-cwhtK9La1DUNmYdtbGUNeo-c51TGIQKM,1897
|
|
15
|
+
line/nodes/conversation_context.py,sha256=1ytf4q5GGy6tEjVD_KbKAkKLqosCkwi0kVWGymuLJhw,2138
|
|
16
|
+
line/nodes/reasoning.py,sha256=kyXxk6xJHEA4zwkHzriRtOC6cjk13E-N736qDvR5o-A,8567
|
|
17
|
+
line/tools/__init__.py,sha256=mYzcKIk1G_-EFQD6ugoCdcPjgywK_mC4dXu-ZyAtS7U,203
|
|
18
|
+
line/tools/system_tools.py,sha256=Z0tDoaAtZ9GziBLSDklhE6NS91OoHrmGkgToP5nZD_o,3765
|
|
19
|
+
line/tools/tool_types.py,sha256=JJ6mfH9wB-dtaQFHkm8vsJIYsAiW6bIpgAh_nmDn744,1066
|
|
20
|
+
line/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
21
|
+
line/utils/aio.py,sha256=l1YgZ8tf1KtOyq6A-6RA_kE-FKGafDfHERFnDx0-PxM,1899
|
|
22
|
+
line/utils/gemini_utils.py,sha256=6YNyU3-I6Kn95j0qMroelO1WpjIPjIwhiub2lX34-kY,5396
|
|
23
|
+
line/utils/openai_utils.py,sha256=I9nIpHTFC98ChWzRmV-enMSIcicRVF9KYjifsWkoPCE,3596
|
|
24
|
+
cartesia_line-0.0.1.dist-info/METADATA,sha256=sMqD3NiPCOoNfVvbq6_vkllIZmltvvHoY8eoATWc9dA,872
|
|
25
|
+
cartesia_line-0.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
26
|
+
cartesia_line-0.0.1.dist-info/top_level.txt,sha256=xztzr4hR6ekbxrTcEufazgor-5McHQuLNu82cxn1jNE,5
|
|
27
|
+
cartesia_line-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Cartesia AI, Inc.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
line
|
line/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Core agent system components
|
|
2
|
+
# Bus system
|
|
3
|
+
from line.bridge import Bridge
|
|
4
|
+
from line.bus import Bus, Message
|
|
5
|
+
from line.call_request import CallRequest, PreCallResult
|
|
6
|
+
from line.nodes.conversation_context import ConversationContext
|
|
7
|
+
|
|
8
|
+
# Reasoning components
|
|
9
|
+
from line.nodes.reasoning import Node, ReasoningNode
|
|
10
|
+
from line.routes import RouteBuilder, RouteConfig
|
|
11
|
+
from line.user_bridge import register_observability_event
|
|
12
|
+
from line.voice_agent_app import VoiceAgentApp
|
|
13
|
+
from line.voice_agent_system import VoiceAgentSystem
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Bridge",
|
|
17
|
+
"Bus",
|
|
18
|
+
"Message",
|
|
19
|
+
"CallRequest",
|
|
20
|
+
"ConversationContext",
|
|
21
|
+
"Node",
|
|
22
|
+
"PreCallResult",
|
|
23
|
+
"ReasoningNode",
|
|
24
|
+
"RouteBuilder",
|
|
25
|
+
"RouteConfig",
|
|
26
|
+
"VoiceAgentApp",
|
|
27
|
+
"VoiceAgentSystem",
|
|
28
|
+
"register_observability_event",
|
|
29
|
+
]
|
line/bridge.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Bridge - Route events between nodes and bus.
|
|
3
|
+
|
|
4
|
+
Provides stateless routing between node methods and bus events.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
from collections import defaultdict
|
|
9
|
+
from fnmatch import fnmatch
|
|
10
|
+
import inspect
|
|
11
|
+
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type, TypeVar, Union
|
|
12
|
+
|
|
13
|
+
from loguru import logger
|
|
14
|
+
|
|
15
|
+
from line.bus import Bus, Message
|
|
16
|
+
from line.events import EventInstance, EventsRegistry, EventTypeOrAlias
|
|
17
|
+
from line.routes import RouteBuilder, RouteHandler
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from line.nodes.reasoning import Node
|
|
21
|
+
|
|
22
|
+
T = TypeVar("T")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Bridge:
|
|
26
|
+
"""Route bus events to node methods and broadcast results.
|
|
27
|
+
|
|
28
|
+
This class is responsible for managing and executing routes when triggered by bus events.
|
|
29
|
+
When the bus receives an event, it forwards the event to all bridges registered with the bus.
|
|
30
|
+
The bridge determines whether there is a route that should be triggered by the event.
|
|
31
|
+
A route is a sequence of operations that is performed on the message associated with the event.
|
|
32
|
+
|
|
33
|
+
When a route is executed, the bridge will construct the :class:`RouteHandler` corresponding to the
|
|
34
|
+
:class:`RouteBuilder` and execute it.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, node: Union["Node", str]):
|
|
38
|
+
"""Create bridge for node.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
node: Processing node instance.
|
|
42
|
+
"""
|
|
43
|
+
self.node = node # Processing node instance.
|
|
44
|
+
|
|
45
|
+
# Quietly set the node's bridge if possible.
|
|
46
|
+
try:
|
|
47
|
+
node._bridge = self # type: ignore[attr-defined]
|
|
48
|
+
except AttributeError:
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
# event_pattern → (method, broadcast_event).
|
|
52
|
+
self.routes: dict[EventTypeOrAlias, List[RouteHandler]] = defaultdict(list)
|
|
53
|
+
self.scheduled_tasks: List[asyncio.Task] = [] # Background tasks for periodic execution.
|
|
54
|
+
self.bus = None # Bus instance for broadcasting results.
|
|
55
|
+
self._signature_cache = {} # method → takes_parameters for performance.
|
|
56
|
+
self.authorized_nodes = set() # None = open access, set = restricted access.
|
|
57
|
+
|
|
58
|
+
# Input routing state - enables continuous external input → bus event conversion.
|
|
59
|
+
self.input_source = None # Source object with get() method for input messages.
|
|
60
|
+
self.input_task = None # Background task for input routing.
|
|
61
|
+
self.input_shutdown = None # Event to signal input routing shutdown.
|
|
62
|
+
|
|
63
|
+
# Track all active route execution tasks
|
|
64
|
+
self.active_route_tasks: List[asyncio.Task] = []
|
|
65
|
+
self._route_tasks_lock = asyncio.Lock()
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def node_id(self) -> str:
|
|
69
|
+
"""Get the node identifier."""
|
|
70
|
+
if isinstance(self.node, str):
|
|
71
|
+
return self.node
|
|
72
|
+
elif hasattr(self.node, "id"):
|
|
73
|
+
return self.node.id
|
|
74
|
+
elif hasattr(self.node, "__class__"):
|
|
75
|
+
return self.node.__class__.__name__
|
|
76
|
+
return "unknown"
|
|
77
|
+
|
|
78
|
+
def authorize(self, *node_ids) -> "Bridge":
|
|
79
|
+
"""Restrict bridge access to specific nodes.
|
|
80
|
+
|
|
81
|
+
TODO (AD): What does this mean? Every bridge has a node right?
|
|
82
|
+
"""
|
|
83
|
+
self.authorized_nodes = set(node_ids)
|
|
84
|
+
return self
|
|
85
|
+
|
|
86
|
+
def set_bus(self, bus: Bus) -> "Bridge":
|
|
87
|
+
"""Set bus for broadcasting."""
|
|
88
|
+
self.bus = bus
|
|
89
|
+
return self
|
|
90
|
+
|
|
91
|
+
def with_input_routing(self, source: Any = None) -> "Bridge":
|
|
92
|
+
"""
|
|
93
|
+
Enable continuous input routing from external source to bus events.
|
|
94
|
+
|
|
95
|
+
Input routing solves the bidirectional communication problem by automatically
|
|
96
|
+
converting external input streams (WebSocket messages, file changes, etc.) into
|
|
97
|
+
bus events. Without this, you need manual async tasks and coordination.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
source: Object with async get() method. Defaults to self.node.
|
|
101
|
+
Examples: ConversationHarness, FileWatcher, asyncio.Queue.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
Self for method chaining.
|
|
105
|
+
|
|
106
|
+
Examples:
|
|
107
|
+
>>> # Route WebSocket messages to bus events
|
|
108
|
+
>>> bridge.with_input_routing(harness)
|
|
109
|
+
>>>
|
|
110
|
+
>>> # Route file system changes to bus events
|
|
111
|
+
>>> bridge.with_input_routing(file_watcher)
|
|
112
|
+
"""
|
|
113
|
+
self.input_source = source or self.node
|
|
114
|
+
return self
|
|
115
|
+
|
|
116
|
+
def on(
|
|
117
|
+
self,
|
|
118
|
+
event_pattern: Union[str, Type[T]],
|
|
119
|
+
*,
|
|
120
|
+
id: Union[str, Callable[[str], bool]] = None,
|
|
121
|
+
source: Union[str, Callable[[str], bool]] = None,
|
|
122
|
+
timestamp: Union[float, Callable[[float], bool]] = None,
|
|
123
|
+
filter_fn: Optional[Callable[["Message"], bool]] = None,
|
|
124
|
+
**event_property_filters,
|
|
125
|
+
) -> "RouteBuilder":
|
|
126
|
+
"""Start building route for event pattern or typed event with filtering.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
event_pattern: The event type we want to filter on.
|
|
130
|
+
id: The message id to filter by. Can be a string or a callable that returns bool.
|
|
131
|
+
source: The message source to filter by. Can be a string or a callable that returns bool.
|
|
132
|
+
timestamp: The message timestamp to filter by. Can be a float or a callable that returns bool.
|
|
133
|
+
filter_fn: Custom filter function that takes a BusMessage and returns bool.
|
|
134
|
+
**event_property_filters: Additional filters for properties of the event object.
|
|
135
|
+
Keys should be attribute names of the event, values can be the expected value
|
|
136
|
+
or a callable that takes the property value and returns bool.
|
|
137
|
+
|
|
138
|
+
Note:
|
|
139
|
+
When a handler triggers (i.e. the route in .on runs), we spin up a new asyncio.Task.
|
|
140
|
+
Spawning too many tasks will impact the performance of the system.
|
|
141
|
+
We provide filtering directly in the `on` to avoid spawning new asyncio tasks.
|
|
142
|
+
"""
|
|
143
|
+
if not inspect.isclass(event_pattern) and not isinstance(event_pattern, str):
|
|
144
|
+
raise ValueError(f"Event pattern must be a string or a class type: {event_pattern}")
|
|
145
|
+
|
|
146
|
+
logger.debug(f"Bridge {self.node_id}: Adding route for {event_pattern}")
|
|
147
|
+
|
|
148
|
+
# RouteBuilder and RouteHandler have a 1:1 relationship.
|
|
149
|
+
route_builder = RouteBuilder(self)
|
|
150
|
+
route_handler = RouteHandler(route_builder, self)
|
|
151
|
+
|
|
152
|
+
# Set up filtering configuration
|
|
153
|
+
route_handler.route_config.id_filter = id
|
|
154
|
+
route_handler.route_config.source = source
|
|
155
|
+
route_handler.route_config.timestamp_filter = timestamp
|
|
156
|
+
route_handler.route_config.filter_fn = filter_fn
|
|
157
|
+
route_handler.route_config.event_property_filters = event_property_filters
|
|
158
|
+
|
|
159
|
+
self.routes[event_pattern].append(route_handler)
|
|
160
|
+
|
|
161
|
+
return route_builder
|
|
162
|
+
|
|
163
|
+
async def handle_event(self, message: "Message") -> None:
|
|
164
|
+
"""Route incoming event to appropriate handler."""
|
|
165
|
+
# Check authorization first - empty set means open access.
|
|
166
|
+
if self.authorized_nodes and message.source not in self.authorized_nodes:
|
|
167
|
+
return
|
|
168
|
+
|
|
169
|
+
handlers: List[RouteHandler] = self._find_matching_routes(message.event)
|
|
170
|
+
handlers = [handler for handler in handlers if handler.should_process_message(message)]
|
|
171
|
+
if not handlers:
|
|
172
|
+
return
|
|
173
|
+
|
|
174
|
+
# Execute all matching routes concurrently.
|
|
175
|
+
tasks = []
|
|
176
|
+
for handler in handlers:
|
|
177
|
+
tasks.append(asyncio.create_task(handler.handle(message)))
|
|
178
|
+
|
|
179
|
+
# Track the task for cleanup
|
|
180
|
+
async with self._route_tasks_lock:
|
|
181
|
+
self.active_route_tasks.extend(tasks)
|
|
182
|
+
|
|
183
|
+
if tasks:
|
|
184
|
+
# NOTE: We are awaiting here. This is blocking.
|
|
185
|
+
# If you need to run this in the background, make sure to spawn a task and not await that task.
|
|
186
|
+
# See `Bus._route_message` for an example on how this is done.
|
|
187
|
+
results = await asyncio.gather(*tasks, return_exceptions=True)
|
|
188
|
+
|
|
189
|
+
# Log results for each route.
|
|
190
|
+
for route_index, (_, result) in enumerate(zip(tasks, results)): # type: ignore[arg-type]
|
|
191
|
+
if isinstance(result, Exception):
|
|
192
|
+
logger.opt(exception=result).error(
|
|
193
|
+
"Bridge {}: Route {} failed for event {}: {}",
|
|
194
|
+
self.node_id,
|
|
195
|
+
route_index,
|
|
196
|
+
type(message.event).__name__,
|
|
197
|
+
str(result),
|
|
198
|
+
)
|
|
199
|
+
else:
|
|
200
|
+
logger.debug(
|
|
201
|
+
f"Bridge {self.node_id}: Route {route_index} "
|
|
202
|
+
f"completed successfully for event {type(message.event)}"
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
# Cleanup tasks.
|
|
206
|
+
async with self._route_tasks_lock:
|
|
207
|
+
self.active_route_tasks = [t for t in self.active_route_tasks if not t.done()]
|
|
208
|
+
|
|
209
|
+
async def start_input_routing(self) -> None:
|
|
210
|
+
"""
|
|
211
|
+
Start input routing from source to bus events.
|
|
212
|
+
|
|
213
|
+
Creates background task that continuously polls input source and converts
|
|
214
|
+
messages to bus events. Essential for bridging external input streams.
|
|
215
|
+
"""
|
|
216
|
+
if not self.input_source:
|
|
217
|
+
logger.warning(f"Bridge {self.node_id}: No input source configured")
|
|
218
|
+
return
|
|
219
|
+
|
|
220
|
+
if not hasattr(self.input_source, "get"):
|
|
221
|
+
logger.warning(f"Bridge {self.node_id}: Input source missing get() method")
|
|
222
|
+
return
|
|
223
|
+
|
|
224
|
+
self.input_shutdown = asyncio.Event()
|
|
225
|
+
self.input_task = asyncio.create_task(self._input_router())
|
|
226
|
+
logger.debug(f"Bridge {self.node_id}: Input routing started")
|
|
227
|
+
|
|
228
|
+
async def _input_router(self) -> None:
|
|
229
|
+
"""
|
|
230
|
+
Route input from source to bus events continuously.
|
|
231
|
+
|
|
232
|
+
Uses input source's map_to_events method to convert messages to specific events.
|
|
233
|
+
Handles timeouts gracefully to avoid blocking on empty sources.
|
|
234
|
+
"""
|
|
235
|
+
while not self.input_shutdown.is_set():
|
|
236
|
+
try:
|
|
237
|
+
# Get next message from input source - blocks until available.
|
|
238
|
+
message = await asyncio.wait_for(self.input_source.get(), timeout=1.0)
|
|
239
|
+
|
|
240
|
+
# Convert message to events using source's mapping logic.
|
|
241
|
+
if hasattr(self.input_source, "map_to_events"):
|
|
242
|
+
events = self.input_source.map_to_events(message)
|
|
243
|
+
for event in events:
|
|
244
|
+
await self.bus.broadcast(Message(source=self.node_id, event=event))
|
|
245
|
+
else:
|
|
246
|
+
raise ValueError(f"Input source {self.input_source} has no map_to_events method.")
|
|
247
|
+
except asyncio.TimeoutError:
|
|
248
|
+
# No input available - continue polling.
|
|
249
|
+
continue
|
|
250
|
+
except Exception as e:
|
|
251
|
+
logger.exception(f"Bridge {self.node_id}: Input routing error: {e}")
|
|
252
|
+
|
|
253
|
+
async def stop_input_routing(self) -> None:
|
|
254
|
+
"""Stop input routing task and cleanup resources."""
|
|
255
|
+
if self.input_shutdown:
|
|
256
|
+
self.input_shutdown.set()
|
|
257
|
+
|
|
258
|
+
if self.input_task and not self.input_task.done():
|
|
259
|
+
self.input_task.cancel()
|
|
260
|
+
try:
|
|
261
|
+
await self.input_task
|
|
262
|
+
except asyncio.CancelledError:
|
|
263
|
+
pass
|
|
264
|
+
|
|
265
|
+
logger.debug(f"Bridge {self.node_id}: Input routing stopped")
|
|
266
|
+
|
|
267
|
+
async def start(self) -> None:
|
|
268
|
+
"""Start scheduled tasks and input routing if configured."""
|
|
269
|
+
# Start input routing if configured.
|
|
270
|
+
if self.input_source:
|
|
271
|
+
await self.start_input_routing()
|
|
272
|
+
|
|
273
|
+
async def stop(self) -> None:
|
|
274
|
+
"""Stop scheduled tasks and input routing."""
|
|
275
|
+
# Stop input routing first.
|
|
276
|
+
await self.stop_input_routing()
|
|
277
|
+
|
|
278
|
+
# Cancel all active route tasks.
|
|
279
|
+
await self._cancel_all_route_tasks()
|
|
280
|
+
|
|
281
|
+
# Stop scheduled tasks.
|
|
282
|
+
for task in self.scheduled_tasks:
|
|
283
|
+
if not task.done():
|
|
284
|
+
task.cancel()
|
|
285
|
+
|
|
286
|
+
if self.scheduled_tasks:
|
|
287
|
+
await asyncio.gather(*self.scheduled_tasks, return_exceptions=True)
|
|
288
|
+
|
|
289
|
+
self.scheduled_tasks.clear()
|
|
290
|
+
logger.debug("Bridge stopped all scheduled tasks")
|
|
291
|
+
|
|
292
|
+
async def _cancel_all_route_tasks(self):
|
|
293
|
+
"""Cancel all active route execution tasks."""
|
|
294
|
+
async with self._route_tasks_lock:
|
|
295
|
+
if not self.active_route_tasks:
|
|
296
|
+
return
|
|
297
|
+
|
|
298
|
+
logger.info(
|
|
299
|
+
f"Bridge {self.node_id}: Cancelling {len(self.active_route_tasks)} active route tasks"
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
# Cancel all active route tasks
|
|
303
|
+
for task in self.active_route_tasks:
|
|
304
|
+
if not task.done():
|
|
305
|
+
task.cancel()
|
|
306
|
+
|
|
307
|
+
# Wait for all tasks to complete cancellation
|
|
308
|
+
if self.active_route_tasks:
|
|
309
|
+
await asyncio.gather(*self.active_route_tasks, return_exceptions=True)
|
|
310
|
+
|
|
311
|
+
self.active_route_tasks.clear()
|
|
312
|
+
logger.info(f"Bridge {self.node_id}: All route tasks cancelled")
|
|
313
|
+
|
|
314
|
+
# TODO: Do we need this if we are doing the filtering anyway on each event?
|
|
315
|
+
def can_handle(self, event: Any) -> bool:
|
|
316
|
+
"""Check if this bridge can handle the event type."""
|
|
317
|
+
# TODO: This is a very expensive check (maybe?). Just feels too heavy.
|
|
318
|
+
return len(self._find_matching_routes(event)) > 0
|
|
319
|
+
|
|
320
|
+
def _find_matching_routes(self, event: EventInstance) -> List[RouteHandler]:
|
|
321
|
+
"""Find all routes matching event type (supports wildcards)."""
|
|
322
|
+
handlers: List[RouteHandler] = []
|
|
323
|
+
pattern: EventTypeOrAlias
|
|
324
|
+
|
|
325
|
+
# Find all the routes that match the event (glob-style pattern matching).
|
|
326
|
+
for pattern, handler in self.routes.items():
|
|
327
|
+
if inspect.isclass(pattern):
|
|
328
|
+
if isinstance(event, pattern):
|
|
329
|
+
handlers.extend(handler)
|
|
330
|
+
|
|
331
|
+
elif isinstance(pattern, str):
|
|
332
|
+
# This is a catch-all pattern.
|
|
333
|
+
if pattern == "*":
|
|
334
|
+
handlers.extend(handler)
|
|
335
|
+
continue
|
|
336
|
+
|
|
337
|
+
alias = EventsRegistry.get(type(event))
|
|
338
|
+
if not alias:
|
|
339
|
+
continue
|
|
340
|
+
|
|
341
|
+
# Use glob-style pattern matching.
|
|
342
|
+
if fnmatch(alias, pattern):
|
|
343
|
+
handlers.extend(handler)
|
|
344
|
+
else:
|
|
345
|
+
# We should never reach here if we ran `.on` correctly.
|
|
346
|
+
raise AssertionError(f"Invalid pattern: {pattern}")
|
|
347
|
+
|
|
348
|
+
return handlers
|