meshagent-twilio 0.44.11__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.
- meshagent_twilio-0.44.11/CHANGELOG.md +5 -0
- meshagent_twilio-0.44.11/LICENSE +201 -0
- meshagent_twilio-0.44.11/MANIFEST.in +1 -0
- meshagent_twilio-0.44.11/PKG-INFO +29 -0
- meshagent_twilio-0.44.11/README.md +13 -0
- meshagent_twilio-0.44.11/meshagent/twilio/__init__.py +4 -0
- meshagent_twilio-0.44.11/meshagent/twilio/channel.py +622 -0
- meshagent_twilio-0.44.11/meshagent/twilio/version.py +1 -0
- meshagent_twilio-0.44.11/meshagent_twilio.egg-info/PKG-INFO +29 -0
- meshagent_twilio-0.44.11/meshagent_twilio.egg-info/SOURCES.txt +14 -0
- meshagent_twilio-0.44.11/meshagent_twilio.egg-info/dependency_links.txt +1 -0
- meshagent_twilio-0.44.11/meshagent_twilio.egg-info/requires.txt +3 -0
- meshagent_twilio-0.44.11/meshagent_twilio.egg-info/top_level.txt +1 -0
- meshagent_twilio-0.44.11/pyproject.toml +30 -0
- meshagent_twilio-0.44.11/setup.cfg +4 -0
- meshagent_twilio-0.44.11/tests/test_twilio_channel.py +300 -0
|
@@ -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 [yyyy] [name of copyright owner]
|
|
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
|
+
include CHANGELOG.md
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: meshagent-twilio
|
|
3
|
+
Version: 0.44.11
|
|
4
|
+
Summary: Twilio SMS/MMS channel support for MeshAgent
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Documentation, https://docs.meshagent.com
|
|
7
|
+
Project-URL: Website, https://www.meshagent.com
|
|
8
|
+
Project-URL: Source, https://www.meshagent.com
|
|
9
|
+
Requires-Python: >=3.13
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: meshagent-api==0.44.11
|
|
13
|
+
Requires-Dist: meshagent-agents==0.44.11
|
|
14
|
+
Requires-Dist: aiohttp<4,>=3.12
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# MeshAgent Twilio
|
|
18
|
+
|
|
19
|
+
Twilio SMS/MMS channel support for MeshAgent process agents.
|
|
20
|
+
|
|
21
|
+
This package exports `TwilioChannel` and `create_channel(...)` for use with a
|
|
22
|
+
MeshAgent process channel shim.
|
|
23
|
+
|
|
24
|
+
The channel turns validated Twilio webhook queue messages into trusted
|
|
25
|
+
MeshAgent user turns and sends completed agent responses through Twilio's
|
|
26
|
+
Messages API. Text responses are sent as SMS. File attachments emitted by the
|
|
27
|
+
agent with `attach_file` are sent as MMS media URLs when they are HTTP(S) URLs,
|
|
28
|
+
or when `room:///...` storage URLs can be resolved through
|
|
29
|
+
`room.storage.download_url(path=...)`.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# MeshAgent Twilio
|
|
2
|
+
|
|
3
|
+
Twilio SMS/MMS channel support for MeshAgent process agents.
|
|
4
|
+
|
|
5
|
+
This package exports `TwilioChannel` and `create_channel(...)` for use with a
|
|
6
|
+
MeshAgent process channel shim.
|
|
7
|
+
|
|
8
|
+
The channel turns validated Twilio webhook queue messages into trusted
|
|
9
|
+
MeshAgent user turns and sends completed agent responses through Twilio's
|
|
10
|
+
Messages API. Text responses are sent as SMS. File attachments emitted by the
|
|
11
|
+
agent with `attach_file` are sent as MMS media URLs when they are HTTP(S) URLs,
|
|
12
|
+
or when `room:///...` storage URLs can be resolved through
|
|
13
|
+
`room.storage.download_url(path=...)`.
|
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import contextlib
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import uuid
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import PurePosixPath
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import parse_qs, urlparse
|
|
14
|
+
|
|
15
|
+
from aiohttp import BasicAuth, ClientSession
|
|
16
|
+
from meshagent.agents.adapter import LLMAdapter
|
|
17
|
+
from meshagent.agents.messages import (
|
|
18
|
+
AGENT_MESSAGE_TURN_START,
|
|
19
|
+
AgentFileContentDelta,
|
|
20
|
+
AgentTextContent,
|
|
21
|
+
AgentTextContentDelta,
|
|
22
|
+
ThreadCleared,
|
|
23
|
+
TurnEnded,
|
|
24
|
+
TurnStart,
|
|
25
|
+
TurnStarted,
|
|
26
|
+
TurnStartRejected,
|
|
27
|
+
)
|
|
28
|
+
from meshagent.agents.process import Message
|
|
29
|
+
from meshagent.agents.threaded_channel import ThreadedChannel
|
|
30
|
+
from meshagent.api import Participant, RoomClient
|
|
31
|
+
from meshagent.api.http import new_client_session
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
logger = logging.getLogger("meshagent.twilio_channel")
|
|
35
|
+
|
|
36
|
+
QUEUE_NAME = os.getenv("MESHAGENT_TWILIO_QUEUE_NAME", "twilio-inbound")
|
|
37
|
+
THREAD_PREFIX = os.getenv("MESHAGENT_TWILIO_THREAD_PREFIX", ".threads/twilio")
|
|
38
|
+
MAX_TWILIO_MESSAGE_CHARS = 1500
|
|
39
|
+
MAX_TWILIO_MEDIA_URLS_PER_MESSAGE = 10
|
|
40
|
+
RESPONSE_TIMEOUT_SECONDS = float(os.getenv("MESHAGENT_TWILIO_RESPONSE_TIMEOUT", "300"))
|
|
41
|
+
TWILIO_API_BASE_URL = os.getenv(
|
|
42
|
+
"MESHAGENT_TWILIO_API_BASE_URL",
|
|
43
|
+
"https://api.twilio.com/2010-04-01",
|
|
44
|
+
).rstrip("/")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class TwilioInboundMessage:
|
|
49
|
+
message_sid: str
|
|
50
|
+
from_number: str
|
|
51
|
+
to_number: str
|
|
52
|
+
body: str
|
|
53
|
+
sender_name: str
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True, slots=True)
|
|
57
|
+
class _TwilioTurnResponse:
|
|
58
|
+
text: str
|
|
59
|
+
media_urls: tuple[str, ...] = ()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(slots=True)
|
|
63
|
+
class _PendingTwilioTurn:
|
|
64
|
+
message: TwilioInboundMessage
|
|
65
|
+
response: asyncio.Future[_TwilioTurnResponse]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(slots=True)
|
|
69
|
+
class _ActiveTwilioTurn:
|
|
70
|
+
message: TwilioInboundMessage
|
|
71
|
+
response: asyncio.Future[_TwilioTurnResponse]
|
|
72
|
+
text_parts: list[str] = field(default_factory=list)
|
|
73
|
+
media_urls: list[str] = field(default_factory=list)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def required_env(name: str) -> str:
|
|
77
|
+
value = os.getenv(name, "").strip()
|
|
78
|
+
if value == "":
|
|
79
|
+
raise RuntimeError(f"Set {name} before starting the Twilio channel.")
|
|
80
|
+
return value
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def env_flag(name: str) -> bool:
|
|
84
|
+
value = os.getenv(name, "").strip().lower()
|
|
85
|
+
return value in {"1", "true", "yes", "on"}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def twilio_chunks(text: str) -> list[str]:
|
|
89
|
+
normalized = text.strip()
|
|
90
|
+
if normalized == "":
|
|
91
|
+
return ["The room agent returned an empty response."]
|
|
92
|
+
return [
|
|
93
|
+
normalized[index : index + MAX_TWILIO_MESSAGE_CHARS]
|
|
94
|
+
for index in range(0, len(normalized), MAX_TWILIO_MESSAGE_CHARS)
|
|
95
|
+
]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def twilio_media_batches(media_urls: Sequence[str]) -> list[tuple[str, ...]]:
|
|
99
|
+
return [
|
|
100
|
+
tuple(media_urls[index : index + MAX_TWILIO_MEDIA_URLS_PER_MESSAGE])
|
|
101
|
+
for index in range(0, len(media_urls), MAX_TWILIO_MEDIA_URLS_PER_MESSAGE)
|
|
102
|
+
]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def twilio_message_form_data(
|
|
106
|
+
*,
|
|
107
|
+
from_number: str,
|
|
108
|
+
to_number: str,
|
|
109
|
+
body: str,
|
|
110
|
+
media_urls: Sequence[str] = (),
|
|
111
|
+
) -> list[tuple[str, str]]:
|
|
112
|
+
normalized_body = body.strip()
|
|
113
|
+
if normalized_body == "" and len(media_urls) == 0:
|
|
114
|
+
raise ValueError("Twilio messages require body or media_urls.")
|
|
115
|
+
if len(media_urls) > MAX_TWILIO_MEDIA_URLS_PER_MESSAGE:
|
|
116
|
+
raise ValueError(
|
|
117
|
+
"Twilio messages support at most "
|
|
118
|
+
f"{MAX_TWILIO_MEDIA_URLS_PER_MESSAGE} media URLs."
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
data = [("From", from_number), ("To", to_number)]
|
|
122
|
+
if normalized_body != "":
|
|
123
|
+
data.append(("Body", normalized_body))
|
|
124
|
+
data.extend(("MediaUrl", media_url) for media_url in media_urls)
|
|
125
|
+
return data
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def room_storage_path_from_agent_file_url(*, url: str) -> str | None:
|
|
129
|
+
parsed = urlparse(url.strip())
|
|
130
|
+
if parsed.scheme != "room":
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
raw_path = f"{parsed.netloc}{parsed.path}"
|
|
134
|
+
normalized = PurePosixPath("/" + raw_path).as_posix().strip("/")
|
|
135
|
+
if normalized == "":
|
|
136
|
+
return None
|
|
137
|
+
if any(part in {".", ".."} for part in PurePosixPath(normalized).parts):
|
|
138
|
+
return None
|
|
139
|
+
return normalized
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def is_twilio_fetchable_media_url(*, url: str) -> bool:
|
|
143
|
+
parsed = urlparse(url.strip())
|
|
144
|
+
return parsed.scheme in {"http", "https"} and parsed.netloc != ""
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _slug(value: object) -> str:
|
|
148
|
+
raw = str(value)
|
|
149
|
+
slug = re.sub(r"[^A-Za-z0-9_.-]+", "-", raw).strip("-")
|
|
150
|
+
return slug or "unknown"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _first_form_value(fields: dict[str, list[str]], *names: str) -> str:
|
|
154
|
+
for name in names:
|
|
155
|
+
values = fields.get(name)
|
|
156
|
+
if values is None or len(values) == 0:
|
|
157
|
+
continue
|
|
158
|
+
value = values[0].strip()
|
|
159
|
+
if value != "":
|
|
160
|
+
return value
|
|
161
|
+
return ""
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _queue_body_from_message(message: Any) -> str:
|
|
165
|
+
if not isinstance(message, dict):
|
|
166
|
+
raise ValueError("Twilio queue messages must be JSON objects.")
|
|
167
|
+
body = message.get("body")
|
|
168
|
+
if not isinstance(body, str):
|
|
169
|
+
raise ValueError("Twilio queue messages must include a string body.")
|
|
170
|
+
return body
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def parse_twilio_inbound_message(message: Any) -> TwilioInboundMessage:
|
|
174
|
+
fields = parse_qs(_queue_body_from_message(message), keep_blank_values=True)
|
|
175
|
+
from_number = _first_form_value(fields, "From")
|
|
176
|
+
to_number = _first_form_value(fields, "To")
|
|
177
|
+
body = _first_form_value(fields, "Body")
|
|
178
|
+
if from_number == "" or to_number == "":
|
|
179
|
+
raise ValueError("Twilio queue body must include From and To fields.")
|
|
180
|
+
if body == "":
|
|
181
|
+
raise ValueError("Twilio queue body did not include text in Body.")
|
|
182
|
+
if from_number.lower().startswith("whatsapp:") or to_number.lower().startswith(
|
|
183
|
+
"whatsapp:"
|
|
184
|
+
):
|
|
185
|
+
raise ValueError(
|
|
186
|
+
"Twilio WhatsApp messages are not handled by meshagent-twilio. "
|
|
187
|
+
"Use meshagent-whatsapp for WhatsApp Cloud API messages."
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
message_sid = _first_form_value(
|
|
191
|
+
fields,
|
|
192
|
+
"MessageSid",
|
|
193
|
+
"SmsMessageSid",
|
|
194
|
+
"SmsSid",
|
|
195
|
+
)
|
|
196
|
+
if message_sid == "":
|
|
197
|
+
message_sid = f"local-{uuid.uuid4()}"
|
|
198
|
+
|
|
199
|
+
profile_name = _first_form_value(fields, "ProfileName")
|
|
200
|
+
sender_name = profile_name or from_number
|
|
201
|
+
return TwilioInboundMessage(
|
|
202
|
+
message_sid=message_sid,
|
|
203
|
+
from_number=from_number,
|
|
204
|
+
to_number=to_number,
|
|
205
|
+
body=body,
|
|
206
|
+
sender_name=sender_name,
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class TwilioChannel(ThreadedChannel):
|
|
211
|
+
def __init__(
|
|
212
|
+
self,
|
|
213
|
+
*,
|
|
214
|
+
room: RoomClient,
|
|
215
|
+
account_sid: str,
|
|
216
|
+
auth_token: str,
|
|
217
|
+
queue_name: str = QUEUE_NAME,
|
|
218
|
+
threading_mode: str | None = None,
|
|
219
|
+
thread_dir: str | None = None,
|
|
220
|
+
thread_url_scheme: str | None = None,
|
|
221
|
+
thread_path_extension: str = ".thread",
|
|
222
|
+
thread_list_path: str | None = None,
|
|
223
|
+
llm_adapter: LLMAdapter | None = None,
|
|
224
|
+
thread_prefix: str = THREAD_PREFIX,
|
|
225
|
+
dry_run: bool = False,
|
|
226
|
+
) -> None:
|
|
227
|
+
super().__init__(
|
|
228
|
+
room=room,
|
|
229
|
+
threading_mode=threading_mode,
|
|
230
|
+
thread_dir=thread_dir,
|
|
231
|
+
thread_url_scheme=thread_url_scheme,
|
|
232
|
+
thread_path_extension=thread_path_extension,
|
|
233
|
+
thread_list_path=thread_list_path,
|
|
234
|
+
llm_adapter=llm_adapter,
|
|
235
|
+
)
|
|
236
|
+
normalized_queue_name = queue_name.strip()
|
|
237
|
+
if normalized_queue_name == "":
|
|
238
|
+
raise ValueError("queue_name must not be empty")
|
|
239
|
+
self._queue_name = normalized_queue_name
|
|
240
|
+
self._account_sid = account_sid
|
|
241
|
+
self._auth_token = auth_token
|
|
242
|
+
self._thread_prefix = thread_prefix.rstrip("/") or ".threads/twilio"
|
|
243
|
+
self._dry_run = dry_run
|
|
244
|
+
self._http_session: ClientSession | None = None
|
|
245
|
+
self._receive_task: asyncio.Task[None] | None = None
|
|
246
|
+
self._message_tasks: set[asyncio.Task[None]] = set()
|
|
247
|
+
self._pending_turns_by_message_id: dict[str, _PendingTwilioTurn] = {}
|
|
248
|
+
self._active_turns_by_turn_id: dict[str, _ActiveTwilioTurn] = {}
|
|
249
|
+
self._conversation_locks: dict[str, asyncio.Lock] = {}
|
|
250
|
+
|
|
251
|
+
def _default_thread_dir_fallback_name(self) -> str:
|
|
252
|
+
return "twilio"
|
|
253
|
+
|
|
254
|
+
def handles(self, message: Message) -> bool:
|
|
255
|
+
return isinstance(
|
|
256
|
+
message.data,
|
|
257
|
+
(
|
|
258
|
+
AgentFileContentDelta,
|
|
259
|
+
AgentTextContentDelta,
|
|
260
|
+
ThreadCleared,
|
|
261
|
+
TurnEnded,
|
|
262
|
+
TurnStarted,
|
|
263
|
+
TurnStartRejected,
|
|
264
|
+
),
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
async def on_start(self) -> None:
|
|
268
|
+
await self.publish_thread_attributes()
|
|
269
|
+
await self.open_thread_list_document()
|
|
270
|
+
self._http_session = new_client_session(
|
|
271
|
+
auth=BasicAuth(self._account_sid, self._auth_token),
|
|
272
|
+
)
|
|
273
|
+
await self._room.queues.open(name=self._queue_name)
|
|
274
|
+
self._receive_task = asyncio.create_task(self._receive_loop())
|
|
275
|
+
logger.info("twilio_channel_started queue=%s", self._queue_name)
|
|
276
|
+
|
|
277
|
+
async def on_stop(self) -> None:
|
|
278
|
+
receive_task = self._receive_task
|
|
279
|
+
self._receive_task = None
|
|
280
|
+
if receive_task is not None:
|
|
281
|
+
receive_task.cancel()
|
|
282
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
283
|
+
await receive_task
|
|
284
|
+
|
|
285
|
+
message_tasks = list(self._message_tasks)
|
|
286
|
+
for task in message_tasks:
|
|
287
|
+
task.cancel()
|
|
288
|
+
if message_tasks:
|
|
289
|
+
await asyncio.gather(*message_tasks, return_exceptions=True)
|
|
290
|
+
self._message_tasks.clear()
|
|
291
|
+
|
|
292
|
+
await self._cancel_thread_list_background_tasks()
|
|
293
|
+
await self.close_thread_list_document()
|
|
294
|
+
for pending in self._pending_turns_by_message_id.values():
|
|
295
|
+
if not pending.response.done():
|
|
296
|
+
pending.response.cancel()
|
|
297
|
+
for active in self._active_turns_by_turn_id.values():
|
|
298
|
+
if not active.response.done():
|
|
299
|
+
active.response.cancel()
|
|
300
|
+
self._pending_turns_by_message_id.clear()
|
|
301
|
+
self._active_turns_by_turn_id.clear()
|
|
302
|
+
|
|
303
|
+
http_session = self._http_session
|
|
304
|
+
self._http_session = None
|
|
305
|
+
if http_session is not None:
|
|
306
|
+
await http_session.close()
|
|
307
|
+
|
|
308
|
+
async def on_message(self, message: Message) -> None:
|
|
309
|
+
data = message.data
|
|
310
|
+
if isinstance(data, TurnStarted):
|
|
311
|
+
pending = self._pending_turns_by_message_id.pop(
|
|
312
|
+
data.source_message_id,
|
|
313
|
+
None,
|
|
314
|
+
)
|
|
315
|
+
if pending is None:
|
|
316
|
+
return
|
|
317
|
+
self._active_turns_by_turn_id[data.turn_id] = _ActiveTwilioTurn(
|
|
318
|
+
message=pending.message,
|
|
319
|
+
response=pending.response,
|
|
320
|
+
)
|
|
321
|
+
return
|
|
322
|
+
|
|
323
|
+
if isinstance(data, TurnStartRejected):
|
|
324
|
+
pending = self._pending_turns_by_message_id.pop(
|
|
325
|
+
data.source_message_id,
|
|
326
|
+
None,
|
|
327
|
+
)
|
|
328
|
+
if pending is None or pending.response.done():
|
|
329
|
+
return
|
|
330
|
+
pending.response.set_result(_TwilioTurnResponse(text=data.error.message))
|
|
331
|
+
return
|
|
332
|
+
|
|
333
|
+
if isinstance(data, AgentTextContentDelta):
|
|
334
|
+
active = self._active_turns_by_turn_id.get(data.turn_id)
|
|
335
|
+
if active is None:
|
|
336
|
+
return
|
|
337
|
+
active.text_parts.append(data.text)
|
|
338
|
+
return
|
|
339
|
+
|
|
340
|
+
if isinstance(data, AgentFileContentDelta):
|
|
341
|
+
active = self._active_turns_by_turn_id.get(data.turn_id)
|
|
342
|
+
if active is None:
|
|
343
|
+
return
|
|
344
|
+
media_url = await self._twilio_media_url_for_agent_file_url(url=data.url)
|
|
345
|
+
if media_url is not None:
|
|
346
|
+
active.media_urls.append(media_url)
|
|
347
|
+
return
|
|
348
|
+
|
|
349
|
+
if isinstance(data, ThreadCleared):
|
|
350
|
+
self._clear_thread_state(thread_id=data.thread_id)
|
|
351
|
+
return
|
|
352
|
+
|
|
353
|
+
if not isinstance(data, TurnEnded):
|
|
354
|
+
return
|
|
355
|
+
|
|
356
|
+
active = self._active_turns_by_turn_id.pop(data.turn_id, None)
|
|
357
|
+
if active is None or active.response.done():
|
|
358
|
+
return
|
|
359
|
+
if data.error is not None:
|
|
360
|
+
active.response.set_result(_TwilioTurnResponse(text=data.error.message))
|
|
361
|
+
return
|
|
362
|
+
active.response.set_result(
|
|
363
|
+
_TwilioTurnResponse(
|
|
364
|
+
text="".join(active.text_parts).strip(),
|
|
365
|
+
media_urls=tuple(active.media_urls),
|
|
366
|
+
)
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
async def _receive_loop(self) -> None:
|
|
370
|
+
while not self._stop.is_set():
|
|
371
|
+
try:
|
|
372
|
+
queued_message = await self._room.queues.receive(
|
|
373
|
+
name=self._queue_name,
|
|
374
|
+
create=True,
|
|
375
|
+
wait=True,
|
|
376
|
+
)
|
|
377
|
+
except asyncio.CancelledError:
|
|
378
|
+
raise
|
|
379
|
+
except Exception:
|
|
380
|
+
if self._room.is_closed:
|
|
381
|
+
logger.debug("stopping Twilio receive loop after room close")
|
|
382
|
+
return
|
|
383
|
+
logger.exception(
|
|
384
|
+
"twilio_queue_receive_failed queue=%s", self._queue_name
|
|
385
|
+
)
|
|
386
|
+
await asyncio.sleep(1)
|
|
387
|
+
continue
|
|
388
|
+
|
|
389
|
+
if queued_message is None:
|
|
390
|
+
continue
|
|
391
|
+
|
|
392
|
+
task = asyncio.create_task(self._process_queue_message(queued_message))
|
|
393
|
+
self._message_tasks.add(task)
|
|
394
|
+
task.add_done_callback(self._message_tasks.discard)
|
|
395
|
+
task.add_done_callback(self._log_message_task_failure)
|
|
396
|
+
|
|
397
|
+
async def _process_queue_message(self, queued_message: Any) -> None:
|
|
398
|
+
try:
|
|
399
|
+
twilio_message = parse_twilio_inbound_message(queued_message)
|
|
400
|
+
except ValueError as exc:
|
|
401
|
+
logger.warning("twilio_queue_message_ignored error=%s", exc)
|
|
402
|
+
return
|
|
403
|
+
|
|
404
|
+
conversation_key = f"{twilio_message.to_number}:{twilio_message.from_number}"
|
|
405
|
+
lock = self._conversation_locks.setdefault(
|
|
406
|
+
conversation_key,
|
|
407
|
+
asyncio.Lock(),
|
|
408
|
+
)
|
|
409
|
+
async with lock:
|
|
410
|
+
response = await self._send_twilio_turn(message=twilio_message)
|
|
411
|
+
text_chunks = (
|
|
412
|
+
twilio_chunks(response.text)
|
|
413
|
+
if response.text.strip() != "" or len(response.media_urls) == 0
|
|
414
|
+
else []
|
|
415
|
+
)
|
|
416
|
+
for chunk in text_chunks:
|
|
417
|
+
await self._send_twilio_message(
|
|
418
|
+
from_number=twilio_message.to_number,
|
|
419
|
+
to_number=twilio_message.from_number,
|
|
420
|
+
body=chunk,
|
|
421
|
+
)
|
|
422
|
+
for media_urls in twilio_media_batches(response.media_urls):
|
|
423
|
+
await self._send_twilio_message(
|
|
424
|
+
from_number=twilio_message.to_number,
|
|
425
|
+
to_number=twilio_message.from_number,
|
|
426
|
+
body="",
|
|
427
|
+
media_urls=media_urls,
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
async def _send_twilio_turn(
|
|
431
|
+
self,
|
|
432
|
+
*,
|
|
433
|
+
message: TwilioInboundMessage,
|
|
434
|
+
) -> _TwilioTurnResponse:
|
|
435
|
+
participant_attributes = {
|
|
436
|
+
"name": message.sender_name,
|
|
437
|
+
"role": "user",
|
|
438
|
+
"twilio.channel": "sms",
|
|
439
|
+
"twilio.from": message.from_number,
|
|
440
|
+
"twilio.to": message.to_number,
|
|
441
|
+
"twilio.message_sid": message.message_sid,
|
|
442
|
+
}
|
|
443
|
+
participant = Participant(
|
|
444
|
+
id=f"twilio:{_slug(message.from_number)}",
|
|
445
|
+
attributes=participant_attributes,
|
|
446
|
+
)
|
|
447
|
+
thread_id = self._thread_id_for_conversation(message=message)
|
|
448
|
+
self.bump_thread(path=thread_id, name=message.sender_name)
|
|
449
|
+
|
|
450
|
+
response: asyncio.Future[_TwilioTurnResponse] = (
|
|
451
|
+
asyncio.get_running_loop().create_future()
|
|
452
|
+
)
|
|
453
|
+
turn_start = TurnStart(
|
|
454
|
+
type=AGENT_MESSAGE_TURN_START,
|
|
455
|
+
thread_id=thread_id,
|
|
456
|
+
content=[AgentTextContent(type="text", text=message.body)],
|
|
457
|
+
)
|
|
458
|
+
self._pending_turns_by_message_id[turn_start.message_id] = _PendingTwilioTurn(
|
|
459
|
+
message=message,
|
|
460
|
+
response=response,
|
|
461
|
+
)
|
|
462
|
+
self.emit(sender=participant, payload=turn_start)
|
|
463
|
+
|
|
464
|
+
try:
|
|
465
|
+
return await asyncio.wait_for(response, timeout=RESPONSE_TIMEOUT_SECONDS)
|
|
466
|
+
except asyncio.TimeoutError:
|
|
467
|
+
self._clear_pending_response(response=response)
|
|
468
|
+
logger.warning(
|
|
469
|
+
"twilio_turn_response_timed_out message_sid=%s",
|
|
470
|
+
message.message_sid,
|
|
471
|
+
)
|
|
472
|
+
return _TwilioTurnResponse(
|
|
473
|
+
text="The room agent did not answer before the Twilio channel timed out."
|
|
474
|
+
)
|
|
475
|
+
except Exception:
|
|
476
|
+
self._clear_pending_response(response=response)
|
|
477
|
+
logger.exception("twilio_turn_failed message_sid=%s", message.message_sid)
|
|
478
|
+
return _TwilioTurnResponse(
|
|
479
|
+
text="The room agent could not answer that message."
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
async def _twilio_media_url_for_agent_file_url(self, *, url: str) -> str | None:
|
|
483
|
+
normalized_url = url.strip()
|
|
484
|
+
if is_twilio_fetchable_media_url(url=normalized_url):
|
|
485
|
+
return normalized_url
|
|
486
|
+
|
|
487
|
+
storage_path = room_storage_path_from_agent_file_url(url=normalized_url)
|
|
488
|
+
if storage_path is None:
|
|
489
|
+
logger.warning("twilio_media_url_ignored url=%s", normalized_url)
|
|
490
|
+
return None
|
|
491
|
+
|
|
492
|
+
try:
|
|
493
|
+
media_url = await self._room.storage.download_url(path=storage_path)
|
|
494
|
+
except Exception:
|
|
495
|
+
logger.exception(
|
|
496
|
+
"twilio_media_download_url_failed path=%s",
|
|
497
|
+
storage_path,
|
|
498
|
+
)
|
|
499
|
+
return None
|
|
500
|
+
|
|
501
|
+
if not is_twilio_fetchable_media_url(url=media_url):
|
|
502
|
+
logger.warning(
|
|
503
|
+
"twilio_media_download_url_ignored path=%s url=%s",
|
|
504
|
+
storage_path,
|
|
505
|
+
media_url,
|
|
506
|
+
)
|
|
507
|
+
return None
|
|
508
|
+
return media_url
|
|
509
|
+
|
|
510
|
+
async def _send_twilio_message(
|
|
511
|
+
self,
|
|
512
|
+
*,
|
|
513
|
+
from_number: str,
|
|
514
|
+
to_number: str,
|
|
515
|
+
body: str,
|
|
516
|
+
media_urls: Sequence[str] = (),
|
|
517
|
+
) -> None:
|
|
518
|
+
if self._dry_run:
|
|
519
|
+
logger.info(
|
|
520
|
+
"twilio_dry_run_message from=%s to=%s body=%s media_urls=%s",
|
|
521
|
+
from_number,
|
|
522
|
+
to_number,
|
|
523
|
+
body,
|
|
524
|
+
list(media_urls),
|
|
525
|
+
)
|
|
526
|
+
return
|
|
527
|
+
|
|
528
|
+
http_session = self._http_session
|
|
529
|
+
if http_session is None:
|
|
530
|
+
raise RuntimeError("Twilio HTTP session is not open.")
|
|
531
|
+
|
|
532
|
+
url = f"{TWILIO_API_BASE_URL}/Accounts/{self._account_sid}/Messages.json"
|
|
533
|
+
async with http_session.post(
|
|
534
|
+
url,
|
|
535
|
+
data=twilio_message_form_data(
|
|
536
|
+
from_number=from_number,
|
|
537
|
+
to_number=to_number,
|
|
538
|
+
body=body,
|
|
539
|
+
media_urls=media_urls,
|
|
540
|
+
),
|
|
541
|
+
) as response:
|
|
542
|
+
if response.status < 400:
|
|
543
|
+
logger.info("twilio_message_sent to=%s", to_number)
|
|
544
|
+
return
|
|
545
|
+
response_text = await response.text()
|
|
546
|
+
logger.error(
|
|
547
|
+
"twilio_message_send_failed status=%s body=%s",
|
|
548
|
+
response.status,
|
|
549
|
+
response_text[:500],
|
|
550
|
+
)
|
|
551
|
+
response.raise_for_status()
|
|
552
|
+
|
|
553
|
+
def _thread_id_for_conversation(self, *, message: TwilioInboundMessage) -> str:
|
|
554
|
+
path = f"{self._thread_prefix}/{_slug(message.to_number)}-{_slug(message.from_number)}.thread"
|
|
555
|
+
if "://" in path:
|
|
556
|
+
return path
|
|
557
|
+
return self._thread_url_for_path(path=path)
|
|
558
|
+
|
|
559
|
+
def _clear_thread_state(self, *, thread_id: str) -> None:
|
|
560
|
+
pending_message_ids = [
|
|
561
|
+
message_id
|
|
562
|
+
for message_id, pending in self._pending_turns_by_message_id.items()
|
|
563
|
+
if self._thread_id_for_conversation(message=pending.message) == thread_id
|
|
564
|
+
]
|
|
565
|
+
for message_id in pending_message_ids:
|
|
566
|
+
pending = self._pending_turns_by_message_id.pop(message_id)
|
|
567
|
+
if not pending.response.done():
|
|
568
|
+
pending.response.cancel()
|
|
569
|
+
|
|
570
|
+
active_turn_ids = [
|
|
571
|
+
turn_id
|
|
572
|
+
for turn_id, active in self._active_turns_by_turn_id.items()
|
|
573
|
+
if self._thread_id_for_conversation(message=active.message) == thread_id
|
|
574
|
+
]
|
|
575
|
+
for turn_id in active_turn_ids:
|
|
576
|
+
active = self._active_turns_by_turn_id.pop(turn_id)
|
|
577
|
+
if not active.response.done():
|
|
578
|
+
active.response.cancel()
|
|
579
|
+
|
|
580
|
+
def _clear_pending_response(
|
|
581
|
+
self,
|
|
582
|
+
*,
|
|
583
|
+
response: asyncio.Future[_TwilioTurnResponse],
|
|
584
|
+
) -> None:
|
|
585
|
+
for message_id, pending in list(self._pending_turns_by_message_id.items()):
|
|
586
|
+
if pending.response is response:
|
|
587
|
+
self._pending_turns_by_message_id.pop(message_id, None)
|
|
588
|
+
for turn_id, active in list(self._active_turns_by_turn_id.items()):
|
|
589
|
+
if active.response is response:
|
|
590
|
+
self._active_turns_by_turn_id.pop(turn_id, None)
|
|
591
|
+
|
|
592
|
+
@staticmethod
|
|
593
|
+
def _log_message_task_failure(task: asyncio.Task[None]) -> None:
|
|
594
|
+
if task.cancelled():
|
|
595
|
+
return
|
|
596
|
+
exc = task.exception()
|
|
597
|
+
if exc is not None:
|
|
598
|
+
logger.error("twilio_message_task_failed", exc_info=exc)
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def create_channel(
|
|
602
|
+
*,
|
|
603
|
+
room: RoomClient,
|
|
604
|
+
threading_mode: str | None = None,
|
|
605
|
+
thread_dir: str | None = None,
|
|
606
|
+
thread_url_scheme: str | None = None,
|
|
607
|
+
thread_path_extension: str = ".thread",
|
|
608
|
+
thread_list_path: str | None = None,
|
|
609
|
+
llm_adapter: LLMAdapter | None = None,
|
|
610
|
+
) -> TwilioChannel:
|
|
611
|
+
return TwilioChannel(
|
|
612
|
+
room=room,
|
|
613
|
+
account_sid=required_env("TWILIO_ACCOUNT_SID"),
|
|
614
|
+
auth_token=required_env("TWILIO_AUTH_TOKEN"),
|
|
615
|
+
threading_mode=threading_mode,
|
|
616
|
+
thread_dir=thread_dir,
|
|
617
|
+
thread_url_scheme=thread_url_scheme,
|
|
618
|
+
thread_path_extension=thread_path_extension,
|
|
619
|
+
thread_list_path=thread_list_path,
|
|
620
|
+
llm_adapter=llm_adapter,
|
|
621
|
+
dry_run=env_flag("MESHAGENT_TWILIO_DRY_RUN"),
|
|
622
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.44.11"
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: meshagent-twilio
|
|
3
|
+
Version: 0.44.11
|
|
4
|
+
Summary: Twilio SMS/MMS channel support for MeshAgent
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Documentation, https://docs.meshagent.com
|
|
7
|
+
Project-URL: Website, https://www.meshagent.com
|
|
8
|
+
Project-URL: Source, https://www.meshagent.com
|
|
9
|
+
Requires-Python: >=3.13
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: meshagent-api==0.44.11
|
|
13
|
+
Requires-Dist: meshagent-agents==0.44.11
|
|
14
|
+
Requires-Dist: aiohttp<4,>=3.12
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# MeshAgent Twilio
|
|
18
|
+
|
|
19
|
+
Twilio SMS/MMS channel support for MeshAgent process agents.
|
|
20
|
+
|
|
21
|
+
This package exports `TwilioChannel` and `create_channel(...)` for use with a
|
|
22
|
+
MeshAgent process channel shim.
|
|
23
|
+
|
|
24
|
+
The channel turns validated Twilio webhook queue messages into trusted
|
|
25
|
+
MeshAgent user turns and sends completed agent responses through Twilio's
|
|
26
|
+
Messages API. Text responses are sent as SMS. File attachments emitted by the
|
|
27
|
+
agent with `attach_file` are sent as MMS media URLs when they are HTTP(S) URLs,
|
|
28
|
+
or when `room:///...` storage URLs can be resolved through
|
|
29
|
+
`room.storage.download_url(path=...)`.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
CHANGELOG.md
|
|
2
|
+
LICENSE
|
|
3
|
+
MANIFEST.in
|
|
4
|
+
README.md
|
|
5
|
+
pyproject.toml
|
|
6
|
+
meshagent/twilio/__init__.py
|
|
7
|
+
meshagent/twilio/channel.py
|
|
8
|
+
meshagent/twilio/version.py
|
|
9
|
+
meshagent_twilio.egg-info/PKG-INFO
|
|
10
|
+
meshagent_twilio.egg-info/SOURCES.txt
|
|
11
|
+
meshagent_twilio.egg-info/dependency_links.txt
|
|
12
|
+
meshagent_twilio.egg-info/requires.txt
|
|
13
|
+
meshagent_twilio.egg-info/top_level.txt
|
|
14
|
+
tests/test_twilio_channel.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
meshagent
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "meshagent-twilio"
|
|
7
|
+
description = "Twilio SMS/MMS channel support for MeshAgent"
|
|
8
|
+
dynamic = ["version", "readme"]
|
|
9
|
+
requires-python = ">=3.13"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"meshagent-api==0.44.11",
|
|
13
|
+
"meshagent-agents==0.44.11",
|
|
14
|
+
"aiohttp>=3.12,<4",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Documentation = "https://docs.meshagent.com"
|
|
19
|
+
Website = "https://www.meshagent.com"
|
|
20
|
+
Source = "https://www.meshagent.com"
|
|
21
|
+
|
|
22
|
+
[tool.setuptools.packages.find]
|
|
23
|
+
include = ["meshagent.*"]
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.package-data]
|
|
26
|
+
"meshagent.twilio" = ["py.typed", "*.pyi", "**/*.pyi", "**/*.js"]
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.dynamic]
|
|
29
|
+
version = {attr = "meshagent.twilio.version.__version__"}
|
|
30
|
+
readme = { file = "README.md", content-type = "text/markdown" }
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import cast
|
|
4
|
+
|
|
5
|
+
import meshagent.twilio as twilio
|
|
6
|
+
import pytest
|
|
7
|
+
from meshagent.api import RoomClient
|
|
8
|
+
from meshagent.twilio.channel import (
|
|
9
|
+
MAX_TWILIO_MEDIA_URLS_PER_MESSAGE,
|
|
10
|
+
TwilioChannel,
|
|
11
|
+
TwilioInboundMessage,
|
|
12
|
+
_TwilioTurnResponse,
|
|
13
|
+
create_channel,
|
|
14
|
+
is_twilio_fetchable_media_url,
|
|
15
|
+
parse_twilio_inbound_message,
|
|
16
|
+
room_storage_path_from_agent_file_url,
|
|
17
|
+
twilio_chunks,
|
|
18
|
+
twilio_media_batches,
|
|
19
|
+
twilio_message_form_data,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _FakeStorage:
|
|
24
|
+
def __init__(self, *, download_url: str) -> None:
|
|
25
|
+
self._download_url = download_url
|
|
26
|
+
self.requested_paths: list[str] = []
|
|
27
|
+
|
|
28
|
+
async def download_url(self, *, path: str) -> str:
|
|
29
|
+
self.requested_paths.append(path)
|
|
30
|
+
return self._download_url
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _FakeRoom:
|
|
34
|
+
def __init__(self, *, storage: _FakeStorage) -> None:
|
|
35
|
+
self.storage = storage
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _RecordingTwilioChannel(TwilioChannel):
|
|
39
|
+
def __init__(self, *, response: _TwilioTurnResponse) -> None:
|
|
40
|
+
super().__init__(
|
|
41
|
+
room=cast(
|
|
42
|
+
RoomClient,
|
|
43
|
+
_FakeRoom(storage=_FakeStorage(download_url="https://unused.example")),
|
|
44
|
+
),
|
|
45
|
+
account_sid="AC123",
|
|
46
|
+
auth_token="token",
|
|
47
|
+
)
|
|
48
|
+
self._test_response = response
|
|
49
|
+
self.turn_messages: list[TwilioInboundMessage] = []
|
|
50
|
+
self.sent_messages: list[dict[str, object]] = []
|
|
51
|
+
|
|
52
|
+
async def _send_twilio_turn(
|
|
53
|
+
self,
|
|
54
|
+
*,
|
|
55
|
+
message: TwilioInboundMessage,
|
|
56
|
+
) -> _TwilioTurnResponse:
|
|
57
|
+
self.turn_messages.append(message)
|
|
58
|
+
return self._test_response
|
|
59
|
+
|
|
60
|
+
async def _send_twilio_message(
|
|
61
|
+
self,
|
|
62
|
+
*,
|
|
63
|
+
from_number: str,
|
|
64
|
+
to_number: str,
|
|
65
|
+
body: str,
|
|
66
|
+
media_urls: tuple[str, ...] = (),
|
|
67
|
+
) -> None:
|
|
68
|
+
self.sent_messages.append(
|
|
69
|
+
{
|
|
70
|
+
"from_number": from_number,
|
|
71
|
+
"to_number": to_number,
|
|
72
|
+
"body": body,
|
|
73
|
+
"media_urls": media_urls,
|
|
74
|
+
}
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_package_exports_channel_factory() -> None:
|
|
79
|
+
assert twilio.TwilioChannel is TwilioChannel
|
|
80
|
+
assert twilio.create_channel is create_channel
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_parse_sms_inbound_message() -> None:
|
|
84
|
+
message = parse_twilio_inbound_message(
|
|
85
|
+
{
|
|
86
|
+
"body": (
|
|
87
|
+
"From=%2B15550101000&To=%2B15550102000&Body=hello%20sms"
|
|
88
|
+
"&MessageSid=SMlocal&ProfileName=Local%20SMS%20User"
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
assert message.message_sid == "SMlocal"
|
|
94
|
+
assert message.from_number == "+15550101000"
|
|
95
|
+
assert message.to_number == "+15550102000"
|
|
96
|
+
assert message.body == "hello sms"
|
|
97
|
+
assert message.sender_name == "Local SMS User"
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_parse_inbound_message_rejects_twilio_whatsapp_addresses() -> None:
|
|
101
|
+
try:
|
|
102
|
+
parse_twilio_inbound_message(
|
|
103
|
+
{
|
|
104
|
+
"body": (
|
|
105
|
+
"From=whatsapp%3A%2B15550101000"
|
|
106
|
+
"&To=whatsapp%3A%2B15550102000"
|
|
107
|
+
"&Body=hello%20whatsapp"
|
|
108
|
+
"&MessageSid=SMlocalwhatsapp"
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
)
|
|
112
|
+
except ValueError as exc:
|
|
113
|
+
assert "meshagent-whatsapp" in str(exc)
|
|
114
|
+
else:
|
|
115
|
+
raise AssertionError("Expected ValueError for Twilio WhatsApp message.")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_parse_inbound_message_requires_form_body() -> None:
|
|
119
|
+
try:
|
|
120
|
+
parse_twilio_inbound_message({"body": None})
|
|
121
|
+
except ValueError as exc:
|
|
122
|
+
assert "string body" in str(exc)
|
|
123
|
+
else:
|
|
124
|
+
raise AssertionError("Expected ValueError for non-string Twilio body.")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def test_twilio_chunks_empty_response() -> None:
|
|
128
|
+
assert twilio_chunks(" ") == ["The room agent returned an empty response."]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def test_twilio_media_batches_limits_each_message_to_ten_urls() -> None:
|
|
132
|
+
urls = [f"https://cdn.example/file-{index}.png" for index in range(23)]
|
|
133
|
+
|
|
134
|
+
batches = twilio_media_batches(urls)
|
|
135
|
+
|
|
136
|
+
assert [len(batch) for batch in batches] == [10, 10, 3]
|
|
137
|
+
assert batches[0][0] == "https://cdn.example/file-0.png"
|
|
138
|
+
assert batches[2][-1] == "https://cdn.example/file-22.png"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def test_twilio_message_form_data_repeats_media_url_fields() -> None:
|
|
142
|
+
form_data = twilio_message_form_data(
|
|
143
|
+
from_number="+15550102000",
|
|
144
|
+
to_number="+15550101000",
|
|
145
|
+
body="Here are the files.",
|
|
146
|
+
media_urls=(
|
|
147
|
+
"https://cdn.example/report.pdf",
|
|
148
|
+
"https://cdn.example/chart.png",
|
|
149
|
+
),
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
assert form_data == [
|
|
153
|
+
("From", "+15550102000"),
|
|
154
|
+
("To", "+15550101000"),
|
|
155
|
+
("Body", "Here are the files."),
|
|
156
|
+
("MediaUrl", "https://cdn.example/report.pdf"),
|
|
157
|
+
("MediaUrl", "https://cdn.example/chart.png"),
|
|
158
|
+
]
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def test_twilio_message_form_data_supports_media_only_messages() -> None:
|
|
162
|
+
form_data = twilio_message_form_data(
|
|
163
|
+
from_number="+15550102000",
|
|
164
|
+
to_number="+15550101000",
|
|
165
|
+
body="",
|
|
166
|
+
media_urls=("https://cdn.example/report.pdf",),
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
assert form_data == [
|
|
170
|
+
("From", "+15550102000"),
|
|
171
|
+
("To", "+15550101000"),
|
|
172
|
+
("MediaUrl", "https://cdn.example/report.pdf"),
|
|
173
|
+
]
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def test_twilio_message_form_data_rejects_empty_messages() -> None:
|
|
177
|
+
with pytest.raises(ValueError, match="body or media_urls"):
|
|
178
|
+
twilio_message_form_data(
|
|
179
|
+
from_number="+15550102000",
|
|
180
|
+
to_number="+15550101000",
|
|
181
|
+
body=" ",
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def test_twilio_message_form_data_rejects_oversized_media_batches() -> None:
|
|
186
|
+
media_urls = [
|
|
187
|
+
f"https://cdn.example/file-{index}.png"
|
|
188
|
+
for index in range(MAX_TWILIO_MEDIA_URLS_PER_MESSAGE + 1)
|
|
189
|
+
]
|
|
190
|
+
|
|
191
|
+
with pytest.raises(ValueError, match="at most 10 media URLs"):
|
|
192
|
+
twilio_message_form_data(
|
|
193
|
+
from_number="+15550102000",
|
|
194
|
+
to_number="+15550101000",
|
|
195
|
+
body="",
|
|
196
|
+
media_urls=media_urls,
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def test_room_storage_path_from_agent_file_url_normalizes_room_urls() -> None:
|
|
201
|
+
assert (
|
|
202
|
+
room_storage_path_from_agent_file_url(url="room:///docs/report.pdf")
|
|
203
|
+
== "docs/report.pdf"
|
|
204
|
+
)
|
|
205
|
+
assert (
|
|
206
|
+
room_storage_path_from_agent_file_url(url="room://exports/chart.png")
|
|
207
|
+
== "exports/chart.png"
|
|
208
|
+
)
|
|
209
|
+
assert room_storage_path_from_agent_file_url(url="room:///../secret.txt") is None
|
|
210
|
+
assert (
|
|
211
|
+
room_storage_path_from_agent_file_url(url="https://example.com/file.pdf")
|
|
212
|
+
is None
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def test_is_twilio_fetchable_media_url_requires_http_url() -> None:
|
|
217
|
+
assert is_twilio_fetchable_media_url(url="https://cdn.example/report.pdf")
|
|
218
|
+
assert is_twilio_fetchable_media_url(url="http://localhost:8000/report.pdf")
|
|
219
|
+
assert not is_twilio_fetchable_media_url(url="room:///docs/report.pdf")
|
|
220
|
+
assert not is_twilio_fetchable_media_url(url="https:///missing-host.pdf")
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
@pytest.mark.asyncio
|
|
224
|
+
async def test_twilio_media_url_for_agent_file_url_uses_room_download_url() -> None:
|
|
225
|
+
storage = _FakeStorage(download_url="https://signed.example/docs/report.pdf")
|
|
226
|
+
channel = TwilioChannel(
|
|
227
|
+
room=cast(RoomClient, _FakeRoom(storage=storage)),
|
|
228
|
+
account_sid="AC123",
|
|
229
|
+
auth_token="token",
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
media_url = await channel._twilio_media_url_for_agent_file_url(
|
|
233
|
+
url="room:///docs/report.pdf",
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
assert media_url == "https://signed.example/docs/report.pdf"
|
|
237
|
+
assert storage.requested_paths == ["docs/report.pdf"]
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@pytest.mark.asyncio
|
|
241
|
+
async def test_twilio_media_url_for_agent_file_url_skips_non_http_download_url() -> (
|
|
242
|
+
None
|
|
243
|
+
):
|
|
244
|
+
storage = _FakeStorage(download_url="wss://example.test/download")
|
|
245
|
+
channel = TwilioChannel(
|
|
246
|
+
room=cast(RoomClient, _FakeRoom(storage=storage)),
|
|
247
|
+
account_sid="AC123",
|
|
248
|
+
auth_token="token",
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
media_url = await channel._twilio_media_url_for_agent_file_url(
|
|
252
|
+
url="room:///docs/report.pdf",
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
assert media_url is None
|
|
256
|
+
assert storage.requested_paths == ["docs/report.pdf"]
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@pytest.mark.asyncio
|
|
260
|
+
async def test_process_queue_message_sends_text_before_batched_media() -> None:
|
|
261
|
+
media_urls = tuple(
|
|
262
|
+
f"https://cdn.example/file-{index}.png"
|
|
263
|
+
for index in range(MAX_TWILIO_MEDIA_URLS_PER_MESSAGE + 2)
|
|
264
|
+
)
|
|
265
|
+
channel = _RecordingTwilioChannel(
|
|
266
|
+
response=_TwilioTurnResponse(
|
|
267
|
+
text="Here are the files.",
|
|
268
|
+
media_urls=media_urls,
|
|
269
|
+
)
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
await channel._process_queue_message(
|
|
273
|
+
{
|
|
274
|
+
"body": (
|
|
275
|
+
"From=%2B15550101000&To=%2B15550102000&Body=hello&MessageSid=SMlocal"
|
|
276
|
+
)
|
|
277
|
+
}
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
assert [message.body for message in channel.turn_messages] == ["hello"]
|
|
281
|
+
assert channel.sent_messages == [
|
|
282
|
+
{
|
|
283
|
+
"from_number": "+15550102000",
|
|
284
|
+
"to_number": "+15550101000",
|
|
285
|
+
"body": "Here are the files.",
|
|
286
|
+
"media_urls": (),
|
|
287
|
+
},
|
|
288
|
+
{
|
|
289
|
+
"from_number": "+15550102000",
|
|
290
|
+
"to_number": "+15550101000",
|
|
291
|
+
"body": "",
|
|
292
|
+
"media_urls": media_urls[:MAX_TWILIO_MEDIA_URLS_PER_MESSAGE],
|
|
293
|
+
},
|
|
294
|
+
{
|
|
295
|
+
"from_number": "+15550102000",
|
|
296
|
+
"to_number": "+15550101000",
|
|
297
|
+
"body": "",
|
|
298
|
+
"media_urls": media_urls[MAX_TWILIO_MEDIA_URLS_PER_MESSAGE:],
|
|
299
|
+
},
|
|
300
|
+
]
|