chatom 0.2.1__tar.gz → 0.2.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {chatom-0.2.1 → chatom-0.2.2}/PKG-INFO +9 -1
- {chatom-0.2.1 → chatom-0.2.2}/chatom/__init__.py +1 -1
- chatom-0.2.2/chatom/agent/files.py +185 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/agent/toolset.py +139 -9
- {chatom-0.2.1 → chatom-0.2.2}/chatom/csp/adapter.py +9 -4
- {chatom-0.2.1 → chatom-0.2.2}/chatom/csp/nodes.py +5 -2
- {chatom-0.2.1 → chatom-0.2.2}/chatom/slack/message.py +8 -4
- {chatom-0.2.1 → chatom-0.2.2}/chatom/symphony/backend.py +52 -4
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/conversion/test_message_conversion_slack.py +26 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_agent.py +45 -4
- chatom-0.2.2/chatom/tests/test_attachment_files.py +92 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_csp.py +32 -1
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_incoming_attachments.py +69 -4
- {chatom-0.2.1 → chatom-0.2.2}/pyproject.toml +11 -2
- {chatom-0.2.1 → chatom-0.2.2}/.gitignore +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/LICENSE +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/README.md +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/agent/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/agent/context.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/backend/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/backend/backend.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/backend/backend_config.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/backend/backend_registry.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/attachment.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/authorization.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/base.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/capabilities.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/channel.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/connection.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/conversion.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/embed.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/interaction.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/mention.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/message.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/organization.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/presence.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/reaction.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/testing.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/thread.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/base/user.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/bridge/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/bridge/identity.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/bridge/relay.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/csp/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/csp/interactions.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/discord/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/discord/backend.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/discord/channel.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/discord/config.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/discord/guild.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/discord/mention.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/discord/message.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/discord/presence.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/discord/testing.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/discord/user.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/enums.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/examples/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/examples/basic_connection.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/examples/cross_platform_bot.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/examples/direct_messages.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/examples/formatted_messages.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/examples/listen_for_messages.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/examples/mentions_and_reactions.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/examples/message_history.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/examples/send_message.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/examples/threads_and_replies.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/examples/unified_frontend.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/format/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/format/attachment.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/format/components.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/format/embed.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/format/message.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/format/parse.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/format/spec/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/format/spec/symphony.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/format/table.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/format/telegram.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/format/text.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/format/variant.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/handlers.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/mcp/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/mcp/cli.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/mcp/config/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/mcp/config/config.yaml +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/mcp/config/gateway/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/mcp/config/gateway/discord.yaml +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/mcp/config/gateway/slack.yaml +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/mcp/config/gateway/symphony.yaml +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/mcp/config/gateway/symphony_dev.yaml +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/mcp/config/gateway/telegram.yaml +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/mcp/server.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/slack/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/slack/backend.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/slack/channel.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/slack/config.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/slack/mention.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/slack/presence.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/slack/testing.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/slack/user.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/symphony/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/symphony/channel.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/symphony/config.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/symphony/mention.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/symphony/message.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/symphony/presence.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/symphony/testing.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/symphony/user.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/telegram/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/telegram/backend.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/telegram/channel.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/telegram/config.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/telegram/mention.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/telegram/message.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/telegram/presence.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/telegram/testing.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/telegram/user.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/combined_e2e.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/conversion/test_message_conversion.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/conversion/test_message_conversion_cross.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/conversion/test_message_conversion_discord.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/conversion/test_message_conversion_symphony.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/conversion/test_symphony_messageml_compliance.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/conversion/test_telegram_html.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/integration/__init__.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/integration/test_discord_integration.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/integration/test_slack_integration.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/integration/test_symphony_integration.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/integration/test_telegram_integration.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_access_policy.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_all.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_backend.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_backend_registry.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_backends.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_base_models.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_bot_features.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_bridge.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_config.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_connection.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_conversion.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_discord_channel_conversion.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_enums.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_format.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_interactions.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_mcp.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_mention.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_mock_backends.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_symphony_fetch_messages.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_testing.py +0 -0
- {chatom-0.2.1 → chatom-0.2.2}/chatom/tests/test_threads.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: chatom
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: Minimum viable chat components
|
|
5
5
|
Project-URL: Repository, https://github.com/1kbgz/chatom
|
|
6
6
|
Project-URL: Homepage, https://github.com/1kbgz/chatom
|
|
@@ -22,7 +22,11 @@ Requires-Dist: mistune>=3
|
|
|
22
22
|
Requires-Dist: pydantic>=2
|
|
23
23
|
Requires-Dist: singledispatch
|
|
24
24
|
Provides-Extra: agent
|
|
25
|
+
Requires-Dist: openpyxl<4,>=3.1; extra == 'agent'
|
|
25
26
|
Requires-Dist: pydantic-ai>=0.4; extra == 'agent'
|
|
27
|
+
Requires-Dist: pypdf<7,>=6; extra == 'agent'
|
|
28
|
+
Requires-Dist: python-docx<2,>=1; extra == 'agent'
|
|
29
|
+
Requires-Dist: reportlab<6,>=4; extra == 'agent'
|
|
26
30
|
Provides-Extra: develop
|
|
27
31
|
Requires-Dist: build; extra == 'develop'
|
|
28
32
|
Requires-Dist: bump-my-version; extra == 'develop'
|
|
@@ -35,12 +39,16 @@ Requires-Dist: hatchling; extra == 'develop'
|
|
|
35
39
|
Requires-Dist: hydra-core>=1.3; extra == 'develop'
|
|
36
40
|
Requires-Dist: mdformat; extra == 'develop'
|
|
37
41
|
Requires-Dist: mdformat-tables>=1; extra == 'develop'
|
|
42
|
+
Requires-Dist: openpyxl<4,>=3.1; extra == 'develop'
|
|
38
43
|
Requires-Dist: pydantic-ai>=0.4; extra == 'develop'
|
|
44
|
+
Requires-Dist: pypdf<7,>=6; extra == 'develop'
|
|
39
45
|
Requires-Dist: pytest; extra == 'develop'
|
|
40
46
|
Requires-Dist: pytest-asyncio; extra == 'develop'
|
|
41
47
|
Requires-Dist: pytest-cov; extra == 'develop'
|
|
42
48
|
Requires-Dist: pytest-mock; extra == 'develop'
|
|
49
|
+
Requires-Dist: python-docx<2,>=1; extra == 'develop'
|
|
43
50
|
Requires-Dist: python-telegram-bot; extra == 'develop'
|
|
51
|
+
Requires-Dist: reportlab<6,>=4; extra == 'develop'
|
|
44
52
|
Requires-Dist: ruff; extra == 'develop'
|
|
45
53
|
Requires-Dist: slack-sdk; extra == 'develop'
|
|
46
54
|
Requires-Dist: symphony-bdk-python; extra == 'develop'
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import io
|
|
5
|
+
import mimetypes
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
from xml.sax.saxutils import escape
|
|
9
|
+
from zipfile import ZipFile
|
|
10
|
+
|
|
11
|
+
MAX_BYTES = 5_000_000
|
|
12
|
+
MAX_CHARS = 50_000
|
|
13
|
+
MAX_CELLS = 10_000
|
|
14
|
+
MAX_PAGES = 100
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _format(filename: str) -> str:
|
|
18
|
+
extension = Path(filename).suffix.lower()
|
|
19
|
+
if extension not in {".txt", ".csv", ".xlsx", ".pdf", ".docx"}:
|
|
20
|
+
raise ValueError("Unsupported document format. Use TXT, CSV, XLSX, PDF, or DOCX.")
|
|
21
|
+
return extension
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _check_table(columns: list[str], rows: list[list[Any]]) -> None:
|
|
25
|
+
if len(columns) + sum(len(row) for row in rows) > MAX_CELLS:
|
|
26
|
+
raise ValueError("Document exceeds the cell limit.")
|
|
27
|
+
if columns and any(len(row) != len(columns) for row in rows):
|
|
28
|
+
raise ValueError("Every row must match the number of columns.")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def create_document(
|
|
32
|
+
filename: str,
|
|
33
|
+
*,
|
|
34
|
+
text: str = "",
|
|
35
|
+
columns: list[str] | None = None,
|
|
36
|
+
rows: list[list[Any]] | None = None,
|
|
37
|
+
sheet_name: str = "Data",
|
|
38
|
+
) -> tuple[bytes, str]:
|
|
39
|
+
extension = _format(filename)
|
|
40
|
+
columns, rows = columns or [], rows or []
|
|
41
|
+
_check_table(columns, rows)
|
|
42
|
+
if len(text) + sum(len(str(value)) for row in [columns, *rows] for value in row) > MAX_CHARS:
|
|
43
|
+
raise ValueError("Document exceeds the text limit.")
|
|
44
|
+
output = io.BytesIO()
|
|
45
|
+
if extension == ".txt":
|
|
46
|
+
data = text.encode("utf-8")
|
|
47
|
+
elif extension == ".csv":
|
|
48
|
+
stream = io.StringIO(newline="")
|
|
49
|
+
writer = csv.writer(stream)
|
|
50
|
+
for row in ([columns] if columns else []) + rows:
|
|
51
|
+
writer.writerow(["'" + value if isinstance(value, str) and value.startswith(("=", "+", "-", "@")) else value for value in row])
|
|
52
|
+
data = stream.getvalue().encode("utf-8")
|
|
53
|
+
elif extension == ".xlsx":
|
|
54
|
+
from openpyxl import Workbook
|
|
55
|
+
|
|
56
|
+
workbook = Workbook()
|
|
57
|
+
worksheet = workbook.active
|
|
58
|
+
worksheet.title = sheet_name
|
|
59
|
+
for row in ([columns] if columns else []) + rows:
|
|
60
|
+
worksheet.append(row)
|
|
61
|
+
for cell in worksheet[worksheet.max_row]:
|
|
62
|
+
if isinstance(cell.value, str):
|
|
63
|
+
cell.data_type = "s"
|
|
64
|
+
workbook.save(output)
|
|
65
|
+
workbook.close()
|
|
66
|
+
data = output.getvalue()
|
|
67
|
+
elif extension == ".docx":
|
|
68
|
+
from docx import Document
|
|
69
|
+
|
|
70
|
+
document = Document()
|
|
71
|
+
document.add_paragraph(text)
|
|
72
|
+
table_rows = ([columns] if columns else []) + rows
|
|
73
|
+
if table_rows:
|
|
74
|
+
table = document.add_table(rows=0, cols=max(len(row) for row in table_rows))
|
|
75
|
+
for row in table_rows:
|
|
76
|
+
cells = table.add_row().cells
|
|
77
|
+
for index, value in enumerate(row):
|
|
78
|
+
cells[index].text = str(value)
|
|
79
|
+
document.save(output)
|
|
80
|
+
data = output.getvalue()
|
|
81
|
+
else:
|
|
82
|
+
from reportlab.lib.styles import getSampleStyleSheet
|
|
83
|
+
from reportlab.platypus import Paragraph, SimpleDocTemplate, Table
|
|
84
|
+
|
|
85
|
+
styles = getSampleStyleSheet()
|
|
86
|
+
items = [Paragraph(escape(text).replace("\n", "<br/>"), styles["BodyText"])]
|
|
87
|
+
table_rows = ([columns] if columns else []) + rows
|
|
88
|
+
if table_rows:
|
|
89
|
+
items.append(Table([[Paragraph(escape(str(value)), styles["BodyText"]) for value in row] for row in table_rows]))
|
|
90
|
+
SimpleDocTemplate(output).build(items)
|
|
91
|
+
data = output.getvalue()
|
|
92
|
+
if len(data) > MAX_BYTES:
|
|
93
|
+
raise ValueError("Document exceeds the byte limit.")
|
|
94
|
+
office_types = {
|
|
95
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
96
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
97
|
+
}
|
|
98
|
+
return data, office_types.get(extension) or mimetypes.guess_type(filename)[0] or "application/octet-stream"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def read_document(
|
|
102
|
+
data: bytes,
|
|
103
|
+
filename: str,
|
|
104
|
+
content_type: str = "",
|
|
105
|
+
*,
|
|
106
|
+
max_bytes: int = MAX_BYTES,
|
|
107
|
+
max_chars: int = MAX_CHARS,
|
|
108
|
+
) -> dict[str, Any]:
|
|
109
|
+
extension = _format(filename)
|
|
110
|
+
if len(data) > max_bytes or max_bytes < 1 or max_chars < 1:
|
|
111
|
+
raise ValueError("Document exceeds the byte limit or has invalid limits.")
|
|
112
|
+
if extension in {".xlsx", ".docx"}:
|
|
113
|
+
with ZipFile(io.BytesIO(data)) as archive:
|
|
114
|
+
if len(archive.infolist()) > 2_000 or sum(item.file_size for item in archive.infolist()) > max_bytes:
|
|
115
|
+
raise ValueError("Document expanded archive exceeds the byte limit.")
|
|
116
|
+
result: dict[str, Any] = {"filename": filename, "content_type": content_type or mimetypes.guess_type(filename)[0], "truncated": False}
|
|
117
|
+
text = ""
|
|
118
|
+
if extension == ".txt":
|
|
119
|
+
text = data.decode("utf-8-sig")
|
|
120
|
+
elif extension == ".csv":
|
|
121
|
+
table = []
|
|
122
|
+
cells = 0
|
|
123
|
+
for row in csv.reader(io.StringIO(data.decode("utf-8-sig"))):
|
|
124
|
+
cells += len(row)
|
|
125
|
+
if cells > MAX_CELLS or sum(len(str(value)) for value in row) + len(text) > max_chars:
|
|
126
|
+
result["truncated"] = True
|
|
127
|
+
break
|
|
128
|
+
table.append(row)
|
|
129
|
+
text += "\t".join(row) + "\n"
|
|
130
|
+
result["rows"] = table
|
|
131
|
+
elif extension == ".xlsx":
|
|
132
|
+
from openpyxl import load_workbook
|
|
133
|
+
|
|
134
|
+
workbook = load_workbook(io.BytesIO(data), read_only=True, data_only=False, keep_links=False)
|
|
135
|
+
sheets: dict[str, list[list[Any]]] = {}
|
|
136
|
+
cells = 0
|
|
137
|
+
try:
|
|
138
|
+
for sheet in workbook:
|
|
139
|
+
values = []
|
|
140
|
+
for row in sheet.iter_rows(values_only=True):
|
|
141
|
+
cells += len(row)
|
|
142
|
+
row_text = "\t".join(str(value) if value is not None else "" for value in row) + "\n"
|
|
143
|
+
if cells > MAX_CELLS or len(text) + len(row_text) > max_chars:
|
|
144
|
+
result["truncated"] = True
|
|
145
|
+
break
|
|
146
|
+
values.append([value.isoformat() if hasattr(value, "isoformat") else value for value in row])
|
|
147
|
+
text += row_text
|
|
148
|
+
sheets[sheet.title] = values
|
|
149
|
+
if result["truncated"]:
|
|
150
|
+
break
|
|
151
|
+
finally:
|
|
152
|
+
workbook.close()
|
|
153
|
+
result["sheets"] = sheets
|
|
154
|
+
elif extension == ".docx":
|
|
155
|
+
from docx import Document
|
|
156
|
+
|
|
157
|
+
document = Document(io.BytesIO(data))
|
|
158
|
+
text = "\n".join(paragraph.text for paragraph in document.paragraphs)
|
|
159
|
+
for table in document.tables:
|
|
160
|
+
for row in table.rows:
|
|
161
|
+
text += "\n" + "\t".join(cell.text for cell in row.cells)
|
|
162
|
+
if len(text) > max_chars:
|
|
163
|
+
break
|
|
164
|
+
if len(text) > max_chars:
|
|
165
|
+
break
|
|
166
|
+
else:
|
|
167
|
+
from pypdf import PdfReader
|
|
168
|
+
|
|
169
|
+
document = PdfReader(io.BytesIO(data))
|
|
170
|
+
if document.is_encrypted:
|
|
171
|
+
raise ValueError("Encrypted PDF documents are unsupported.")
|
|
172
|
+
result["pages"] = len(document.pages)
|
|
173
|
+
image_pages = []
|
|
174
|
+
for index, page in enumerate(document.pages[:MAX_PAGES]):
|
|
175
|
+
page_text = page.extract_text() or ""
|
|
176
|
+
if not page_text.strip():
|
|
177
|
+
image_pages.append(index + 1)
|
|
178
|
+
text += page_text + "\n"
|
|
179
|
+
if len(text) > max_chars:
|
|
180
|
+
break
|
|
181
|
+
result["needs_ocr_pages"] = image_pages
|
|
182
|
+
result["truncated"] = len(document.pages) > MAX_PAGES
|
|
183
|
+
result["text"] = text[:max_chars]
|
|
184
|
+
result["truncated"] = result["truncated"] or len(text) > max_chars
|
|
185
|
+
return result
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import asyncio
|
|
3
4
|
import logging
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
4
6
|
from dataclasses import dataclass, field
|
|
5
7
|
from datetime import UTC, datetime, timedelta
|
|
6
8
|
from typing import Any, cast
|
|
9
|
+
from zipfile import BadZipFile
|
|
7
10
|
|
|
8
11
|
from pydantic import BaseModel as PydanticBaseModel, Field, TypeAdapter
|
|
9
12
|
from pydantic_ai._run_context import RunContext
|
|
@@ -230,6 +233,27 @@ class UploadFileParams(PydanticBaseModel):
|
|
|
230
233
|
content: str = Field(default="", description="Optional message text to accompany the file.")
|
|
231
234
|
|
|
232
235
|
|
|
236
|
+
class CreateFileParams(PydanticBaseModel):
|
|
237
|
+
channel: ChannelRef
|
|
238
|
+
filename: str = Field(description="Filename ending in .txt, .csv, .xlsx, .pdf, or .docx.", max_length=200)
|
|
239
|
+
text: str = Field(default="", max_length=50_000)
|
|
240
|
+
columns: list[str] = Field(default_factory=list, max_length=100)
|
|
241
|
+
rows: list[list[str | int | float | bool | None]] = Field(default_factory=list, max_length=10_000)
|
|
242
|
+
sheet_name: str = Field(default="Data", max_length=31)
|
|
243
|
+
content: str = Field(default="", description="Optional caption.")
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class ReadFileParams(DownloadAttachmentParams):
|
|
247
|
+
max_chars: int = Field(default=50_000, ge=1, le=200_000)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
class GenerateImageParams(PydanticBaseModel):
|
|
251
|
+
channel: ChannelRef
|
|
252
|
+
prompt: str = Field(description="Describe the image to generate. This tool generates and attaches the PNG directly.", max_length=8_000)
|
|
253
|
+
filename: str = Field(default="generated.png", max_length=200)
|
|
254
|
+
content: str = Field(default="")
|
|
255
|
+
|
|
256
|
+
|
|
233
257
|
class GetBotInfoParams(PydanticBaseModel):
|
|
234
258
|
"""Parameters for retrieving the bot's own profile (none required)."""
|
|
235
259
|
|
|
@@ -408,6 +432,27 @@ _TOOL_DESCRIPTORS: list[dict[str, Any]] = [
|
|
|
408
432
|
"capability": Capability.FILES,
|
|
409
433
|
"write": True,
|
|
410
434
|
},
|
|
435
|
+
{
|
|
436
|
+
"name": "create_file",
|
|
437
|
+
"description": "Create and attach a real TXT, CSV, XLSX, PDF, or DOCX file from text and structured rows. Do not invent binary data or give the user code to run.",
|
|
438
|
+
"params_model": CreateFileParams,
|
|
439
|
+
"capability": Capability.FILES,
|
|
440
|
+
"write": True,
|
|
441
|
+
},
|
|
442
|
+
{
|
|
443
|
+
"name": "read_file",
|
|
444
|
+
"description": "Read an attached TXT, CSV, XLSX, PDF, or DOCX into text and tables. Use attachment/message IDs from the incoming message or list_recent_attachments.",
|
|
445
|
+
"params_model": ReadFileParams,
|
|
446
|
+
"capability": Capability.FILES,
|
|
447
|
+
"write": False,
|
|
448
|
+
},
|
|
449
|
+
{
|
|
450
|
+
"name": "generate_image",
|
|
451
|
+
"description": "Generate an image using the image provider and attach its PNG here. Choose defaults when unspecified; use this instead of SVG/HTML code or fabricated base64.",
|
|
452
|
+
"params_model": GenerateImageParams,
|
|
453
|
+
"capability": Capability.FILES,
|
|
454
|
+
"write": True,
|
|
455
|
+
},
|
|
411
456
|
]
|
|
412
457
|
|
|
413
458
|
|
|
@@ -452,12 +497,14 @@ class BackendToolset(AbstractToolset[Any]):
|
|
|
452
497
|
disabled_tools: set[str] | None = None,
|
|
453
498
|
max_tool_calls: int = 0,
|
|
454
499
|
per_tool_limits: dict[str, int] | None = None,
|
|
500
|
+
image_generator: Callable[[str], Awaitable[bytes]] | None = None,
|
|
455
501
|
) -> None:
|
|
456
502
|
self._backend = backend
|
|
457
503
|
self._read_only = read_only
|
|
458
504
|
self._max_retries = max_retries
|
|
459
505
|
self._policy = access_policy or AccessPolicy()
|
|
460
506
|
self._disabled_tools = disabled_tools or set()
|
|
507
|
+
self._image_generator = image_generator
|
|
461
508
|
# Per-run tool call budget. 0 disables the total cap; per-tool limits
|
|
462
509
|
# may still apply. A single BackendToolset instance is expected to back
|
|
463
510
|
# exactly one agent run, so these counters scope naturally to a run.
|
|
@@ -556,6 +603,8 @@ class BackendToolset(AbstractToolset[Any]):
|
|
|
556
603
|
"""Decide whether a tool descriptor should be exposed."""
|
|
557
604
|
if desc["name"] in self._disabled_tools:
|
|
558
605
|
return False
|
|
606
|
+
if desc["name"] == "generate_image" and self._image_generator is None:
|
|
607
|
+
return False
|
|
559
608
|
if desc["write"] and self._read_only:
|
|
560
609
|
return False
|
|
561
610
|
cap = desc.get("capability")
|
|
@@ -889,13 +938,22 @@ class BackendToolset(AbstractToolset[Any]):
|
|
|
889
938
|
return {"ok": True}
|
|
890
939
|
|
|
891
940
|
async def _call_delete_message(self, args: dict[str, Any]) -> Any:
|
|
892
|
-
channel = self._channel(args)
|
|
941
|
+
channel = await self._resolve_channel_full(self._channel(args))
|
|
893
942
|
await self._check_channel_access(channel)
|
|
943
|
+
messages = await self._backend.fetch_messages(channel=channel, limit=self._policy.max_messages_per_request)
|
|
944
|
+
target = next((message for message in messages or [] if message.id == args["message_id"]), None)
|
|
945
|
+
if target is None:
|
|
946
|
+
return {"error": "not_found", "message": "Cannot verify the target message in this channel's recent history."}
|
|
947
|
+
identity = await self._backend.get_bot_info()
|
|
948
|
+
if identity is None or not identity.id or target.author_id != identity.id:
|
|
949
|
+
return {"error": "access_denied", "message": "Only messages authored by this bot can be deleted."}
|
|
950
|
+
if target.channel_id and self._backend.normalize_channel_id(target.channel_id) != self._backend.normalize_channel_id(channel.id):
|
|
951
|
+
return {"error": "access_denied", "message": "Target message belongs to another channel."}
|
|
894
952
|
await self._backend.delete_message(
|
|
895
953
|
message=args["message_id"],
|
|
896
954
|
channel=channel,
|
|
897
955
|
)
|
|
898
|
-
return {"ok": True}
|
|
956
|
+
return {"ok": True, "message_id": args["message_id"]}
|
|
899
957
|
|
|
900
958
|
async def _call_set_presence(self, args: dict[str, Any]) -> Any:
|
|
901
959
|
await self._backend.set_presence(
|
|
@@ -1016,11 +1074,83 @@ class BackendToolset(AbstractToolset[Any]):
|
|
|
1016
1074
|
|
|
1017
1075
|
content_type = mimetypes.guess_type(args["filename"])[0] or ""
|
|
1018
1076
|
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1077
|
+
try:
|
|
1078
|
+
sent = await self._backend.upload_file(
|
|
1079
|
+
channel=channel,
|
|
1080
|
+
data=data,
|
|
1081
|
+
filename=args["filename"],
|
|
1082
|
+
content_type=content_type,
|
|
1083
|
+
content=args.get("content", ""),
|
|
1084
|
+
)
|
|
1085
|
+
except ValueError as exc:
|
|
1086
|
+
return {"error": "invalid_file", "message": str(exc)}
|
|
1026
1087
|
return {"ok": True, "message_id": getattr(sent, "id", "") or ""}
|
|
1088
|
+
|
|
1089
|
+
async def _call_create_file(self, args: dict[str, Any]) -> Any:
|
|
1090
|
+
from pathlib import Path
|
|
1091
|
+
|
|
1092
|
+
from .files import create_document
|
|
1093
|
+
|
|
1094
|
+
channel = await self._resolve_channel_full(self._channel(args))
|
|
1095
|
+
await self._check_channel_access(channel)
|
|
1096
|
+
if Path(args["filename"]).name != args["filename"]:
|
|
1097
|
+
return {"error": "invalid_file", "message": "Use a filename without a directory path."}
|
|
1098
|
+
try:
|
|
1099
|
+
data, media_type = await asyncio.to_thread(
|
|
1100
|
+
create_document,
|
|
1101
|
+
args["filename"],
|
|
1102
|
+
text=args["text"],
|
|
1103
|
+
columns=args["columns"],
|
|
1104
|
+
rows=args["rows"],
|
|
1105
|
+
sheet_name=args["sheet_name"],
|
|
1106
|
+
)
|
|
1107
|
+
sent = await self._backend.upload_file(channel, data, filename=args["filename"], content_type=media_type, content=args["content"])
|
|
1108
|
+
except (ValueError, ImportError) as exc:
|
|
1109
|
+
return {"error": "invalid_file", "message": str(exc)}
|
|
1110
|
+
except (RuntimeError, OSError) as exc:
|
|
1111
|
+
logger.warning("File creation/upload failed: %s", type(exc).__name__)
|
|
1112
|
+
return {"error": "file_failed", "message": f"File creation or upload failed ({type(exc).__name__})."}
|
|
1113
|
+
return {"ok": True, "message_id": sent.id, "filename": args["filename"], "content_type": media_type, "size": len(data)}
|
|
1114
|
+
|
|
1115
|
+
async def _call_read_file(self, args: dict[str, Any]) -> Any:
|
|
1116
|
+
import base64
|
|
1117
|
+
|
|
1118
|
+
from .files import read_document
|
|
1119
|
+
|
|
1120
|
+
downloaded = await self._call_download_attachment(args)
|
|
1121
|
+
if "error" in downloaded:
|
|
1122
|
+
return downloaded
|
|
1123
|
+
try:
|
|
1124
|
+
return await asyncio.to_thread(
|
|
1125
|
+
read_document,
|
|
1126
|
+
base64.b64decode(downloaded["data_base64"], validate=True),
|
|
1127
|
+
downloaded["filename"],
|
|
1128
|
+
downloaded["content_type"],
|
|
1129
|
+
max_bytes=args["max_bytes"],
|
|
1130
|
+
max_chars=args["max_chars"],
|
|
1131
|
+
)
|
|
1132
|
+
except (ValueError, ImportError) as exc:
|
|
1133
|
+
return {"error": "invalid_file", "message": str(exc)}
|
|
1134
|
+
except (RuntimeError, OSError, BadZipFile, KeyError) as exc:
|
|
1135
|
+
return {"error": "read_failed", "message": f"File reading failed ({type(exc).__name__})."}
|
|
1136
|
+
|
|
1137
|
+
async def _call_generate_image(self, args: dict[str, Any]) -> Any:
|
|
1138
|
+
from pathlib import Path
|
|
1139
|
+
|
|
1140
|
+
channel = await self._resolve_channel_full(self._channel(args))
|
|
1141
|
+
await self._check_channel_access(channel)
|
|
1142
|
+
if Path(args["filename"]).name != args["filename"] or not args["filename"].lower().endswith(".png"):
|
|
1143
|
+
return {"error": "invalid_file", "message": "Use a PNG filename without a directory path."}
|
|
1144
|
+
try:
|
|
1145
|
+
assert self._image_generator is not None
|
|
1146
|
+
data = await self._image_generator(args["prompt"])
|
|
1147
|
+
if not data.startswith(b"\x89PNG\r\n\x1a\n") or len(data) > 5_000_000:
|
|
1148
|
+
raise ValueError("The image provider must return PNG bytes within the file limit.")
|
|
1149
|
+
sent = await self._backend.upload_file(channel, data, filename=args["filename"], content_type="image/png", content=args["content"])
|
|
1150
|
+
except (ValueError, RuntimeError, OSError) as exc:
|
|
1151
|
+
logger.warning("Image generation/upload failed: %s", type(exc).__name__)
|
|
1152
|
+
return {
|
|
1153
|
+
"error": "generation_failed",
|
|
1154
|
+
"message": str(exc) if isinstance(exc, ValueError) else f"Image generation or upload failed ({type(exc).__name__}).",
|
|
1155
|
+
}
|
|
1156
|
+
return {"ok": True, "message_id": sent.id, "filename": args["filename"], "content_type": "image/png", "size": len(data)}
|
|
@@ -94,7 +94,7 @@ class BackendAdapter:
|
|
|
94
94
|
)
|
|
95
95
|
|
|
96
96
|
@csp.node
|
|
97
|
-
def _write_message(self, msg: ts[Message]):
|
|
97
|
+
def _write_message(self, msg: ts[Message], on_sent: object = None):
|
|
98
98
|
"""Internal node for writing messages."""
|
|
99
99
|
with csp.state():
|
|
100
100
|
s_queue: Queue | None = None
|
|
@@ -104,7 +104,7 @@ class BackendAdapter:
|
|
|
104
104
|
s_queue = Queue(maxsize=0)
|
|
105
105
|
s_thread = threading.Thread(
|
|
106
106
|
target=_send_messages_thread,
|
|
107
|
-
args=(s_queue, self._backend),
|
|
107
|
+
args=(s_queue, self._backend, on_sent),
|
|
108
108
|
daemon=True,
|
|
109
109
|
)
|
|
110
110
|
s_thread.start()
|
|
@@ -119,7 +119,7 @@ class BackendAdapter:
|
|
|
119
119
|
s_queue.put(msg)
|
|
120
120
|
|
|
121
121
|
@csp.graph
|
|
122
|
-
def publish(self, msg: ts[Message]):
|
|
122
|
+
def publish(self, msg: ts[Message], on_sent: object = None):
|
|
123
123
|
"""Publish messages to the backend.
|
|
124
124
|
|
|
125
125
|
Args:
|
|
@@ -134,7 +134,12 @@ class BackendAdapter:
|
|
|
134
134
|
... ))
|
|
135
135
|
... adapter.publish(response)
|
|
136
136
|
"""
|
|
137
|
-
self
|
|
137
|
+
callback = on_sent if on_sent is not None else getattr(self, "_message_sent_callback", None)
|
|
138
|
+
self._write_message(msg=msg, on_sent=callback)
|
|
139
|
+
|
|
140
|
+
def set_message_callback(self, callback) -> None:
|
|
141
|
+
"""Observe posted messages without changing platform publish overrides."""
|
|
142
|
+
self._message_sent_callback = callback
|
|
138
143
|
|
|
139
144
|
@csp.node
|
|
140
145
|
def _set_presence(self, presence: ts[str], timeout: float = 5.0):
|
|
@@ -8,6 +8,7 @@ import asyncio
|
|
|
8
8
|
import contextlib
|
|
9
9
|
import logging
|
|
10
10
|
import threading
|
|
11
|
+
from collections.abc import Callable
|
|
11
12
|
from queue import Queue
|
|
12
13
|
|
|
13
14
|
import csp
|
|
@@ -328,7 +329,7 @@ def message_reader(
|
|
|
328
329
|
)
|
|
329
330
|
|
|
330
331
|
|
|
331
|
-
def _send_messages_thread(msg_queue: Queue, backend: BackendBase):
|
|
332
|
+
def _send_messages_thread(msg_queue: Queue, backend: BackendBase, on_sent: Callable[[Message, Message], None] | None = None):
|
|
332
333
|
"""Thread function to send messages from queue using the backend.
|
|
333
334
|
|
|
334
335
|
Uses asyncio.run() which properly sets up the task context
|
|
@@ -389,11 +390,13 @@ def _send_messages_thread(msg_queue: Queue, backend: BackendBase):
|
|
|
389
390
|
content_to_send = str(kwargs.pop("content"))
|
|
390
391
|
else:
|
|
391
392
|
content_to_send = msg.content
|
|
392
|
-
await thread_backend.send_message(
|
|
393
|
+
sent = await thread_backend.send_message(
|
|
393
394
|
channel=msg.channel_id,
|
|
394
395
|
content=content_to_send,
|
|
395
396
|
**kwargs,
|
|
396
397
|
)
|
|
398
|
+
if on_sent is not None:
|
|
399
|
+
on_sent(msg, sent)
|
|
397
400
|
|
|
398
401
|
# Upload any attachments with binary data
|
|
399
402
|
for att in upload_attachments:
|
|
@@ -6,6 +6,8 @@ This module provides the Slack-specific Message class.
|
|
|
6
6
|
from enum import Enum
|
|
7
7
|
from typing import TYPE_CHECKING, Any
|
|
8
8
|
|
|
9
|
+
from pydantic import model_validator
|
|
10
|
+
|
|
9
11
|
from chatom.base import Field, Message, Organization, Thread, User
|
|
10
12
|
|
|
11
13
|
from .user import SlackUser
|
|
@@ -183,10 +185,12 @@ class SlackMessage(Message):
|
|
|
183
185
|
"""Check if this message is from a bot."""
|
|
184
186
|
return self.bot_id is not None or self.subtype == SlackMessageSubtype.BOT_MESSAGE
|
|
185
187
|
|
|
186
|
-
@
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
188
|
+
@model_validator(mode="before")
|
|
189
|
+
@classmethod
|
|
190
|
+
def _set_edit_status(cls, data: Any) -> Any:
|
|
191
|
+
if isinstance(data, dict) and "is_edited" not in data and data.get("edited") is not None:
|
|
192
|
+
return {**data, "is_edited": True}
|
|
193
|
+
return data
|
|
190
194
|
|
|
191
195
|
@property
|
|
192
196
|
def has_blocks(self) -> bool:
|
|
@@ -914,6 +914,7 @@ class SymphonyBackend(BackendBase):
|
|
|
914
914
|
Sends the file as an attachment via the Symphony BDK message API.
|
|
915
915
|
The binary data is written to a temporary file and its open binary
|
|
916
916
|
handle is passed to the BDK's attachment parameter.
|
|
917
|
+
Images require matching PNG, JPEG, or GIF filenames, MIME types, and signatures.
|
|
917
918
|
"""
|
|
918
919
|
import mimetypes
|
|
919
920
|
import os
|
|
@@ -925,6 +926,15 @@ class SymphonyBackend(BackendBase):
|
|
|
925
926
|
if self._bdk is None:
|
|
926
927
|
raise RuntimeError("Symphony not connected")
|
|
927
928
|
|
|
929
|
+
filename_type = mimetypes.guess_type(filename)[0] or ""
|
|
930
|
+
media_type = (content_type or filename_type).partition(";")[0].strip().lower()
|
|
931
|
+
log.info("Symphony upload filename=%r content_type=%r size=%d", filename, media_type, len(data))
|
|
932
|
+
if media_type.startswith("image/") or filename_type.startswith("image/"):
|
|
933
|
+
signatures = {"image/png": b"\x89PNG\r\n\x1a\n", "image/jpeg": b"\xff\xd8\xff", "image/gif": (b"GIF87a", b"GIF89a")}
|
|
934
|
+
if media_type not in signatures or filename_type != media_type or not data.startswith(signatures[media_type]):
|
|
935
|
+
log.warning("Symphony upload rejected filename=%r content_type=%r size=%d", filename, media_type, len(data))
|
|
936
|
+
raise ValueError("Use PNG or JPEG, or GIF, with a matching filename, MIME type, and file signature for Symphony image uploads.")
|
|
937
|
+
|
|
928
938
|
channel_id = await self._resolve_channel_id(channel)
|
|
929
939
|
|
|
930
940
|
fd, tmp_path = tempfile.mkstemp(suffix=f"_{filename}")
|
|
@@ -936,7 +946,6 @@ class SymphonyBackend(BackendBase):
|
|
|
936
946
|
body = content or title or filename
|
|
937
947
|
if not body.strip().startswith("<messageML>"):
|
|
938
948
|
body = f"<messageML>{body}</messageML>"
|
|
939
|
-
media_type = content_type or mimetypes.guess_type(filename)[0] or ""
|
|
940
949
|
if media_type.startswith("image/"):
|
|
941
950
|
root = fromstring(body)
|
|
942
951
|
ElementTree.SubElement(root, "img", {"src": f"cid:{os.path.basename(tmp_path)}"})
|
|
@@ -960,6 +969,14 @@ class SymphonyBackend(BackendBase):
|
|
|
960
969
|
channel=SymphonyChannel(id=channel_id),
|
|
961
970
|
)
|
|
962
971
|
except Exception as e:
|
|
972
|
+
log.warning(
|
|
973
|
+
"Symphony upload failed filename=%r content_type=%r size=%d status=%r error_type=%s",
|
|
974
|
+
filename,
|
|
975
|
+
media_type,
|
|
976
|
+
len(data),
|
|
977
|
+
getattr(e, "status", None),
|
|
978
|
+
type(e).__name__,
|
|
979
|
+
)
|
|
963
980
|
raise RuntimeError(f"Failed to upload file: {e}") from e
|
|
964
981
|
finally:
|
|
965
982
|
with contextlib.suppress(OSError):
|
|
@@ -988,9 +1005,6 @@ class SymphonyBackend(BackendBase):
|
|
|
988
1005
|
if attachment.data is not None:
|
|
989
1006
|
return await super().download_attachment(attachment, message=message, max_bytes=max_bytes)
|
|
990
1007
|
|
|
991
|
-
if max_bytes is not None:
|
|
992
|
-
raise AttachmentDownloadLimitError(max_bytes, getattr(attachment, "size", None))
|
|
993
|
-
|
|
994
1008
|
if self._bdk is None:
|
|
995
1009
|
raise RuntimeError("Symphony not connected")
|
|
996
1010
|
|
|
@@ -1006,6 +1020,40 @@ class SymphonyBackend(BackendBase):
|
|
|
1006
1020
|
)
|
|
1007
1021
|
|
|
1008
1022
|
message_service = self._bdk.messages()
|
|
1023
|
+
if max_bytes is not None:
|
|
1024
|
+
size = getattr(attachment, "size", None)
|
|
1025
|
+
if size is not None and size > max_bytes:
|
|
1026
|
+
raise AttachmentDownloadLimitError(max_bytes, size)
|
|
1027
|
+
api = getattr(message_service, "_attachment_api", None)
|
|
1028
|
+
if api is None or not hasattr(self._bdk, "bot_session"):
|
|
1029
|
+
raise AttachmentDownloadLimitError(max_bytes, size)
|
|
1030
|
+
session = self._bdk.bot_session()
|
|
1031
|
+
response = await api.v1_stream_sid_attachment_get(
|
|
1032
|
+
sid=stream_id,
|
|
1033
|
+
file_id=attachment_id,
|
|
1034
|
+
message_id=message_id,
|
|
1035
|
+
session_token=await session.session_token,
|
|
1036
|
+
key_manager_token=await session.key_manager_token,
|
|
1037
|
+
_preload_content=False,
|
|
1038
|
+
)
|
|
1039
|
+
try:
|
|
1040
|
+
if response.status != 200:
|
|
1041
|
+
raise RuntimeError(f"Symphony attachment download returned HTTP {response.status}.")
|
|
1042
|
+
encoded_limit = 4 * ((max_bytes + 2) // 3) + 2
|
|
1043
|
+
encoded_data = bytearray()
|
|
1044
|
+
while chunk := await response.content.read(65_536):
|
|
1045
|
+
encoded_data.extend(chunk)
|
|
1046
|
+
if len(encoded_data) > encoded_limit:
|
|
1047
|
+
raise AttachmentDownloadLimitError(max_bytes)
|
|
1048
|
+
encoded_value = bytes(encoded_data)
|
|
1049
|
+
if encoded_value.startswith(b'"'):
|
|
1050
|
+
encoded_value = json.loads(encoded_value)
|
|
1051
|
+
data = base64.b64decode(encoded_value, validate=True)
|
|
1052
|
+
if len(data) > max_bytes:
|
|
1053
|
+
raise AttachmentDownloadLimitError(max_bytes, len(data))
|
|
1054
|
+
return data
|
|
1055
|
+
finally:
|
|
1056
|
+
response.release()
|
|
1009
1057
|
encoded = await message_service.get_attachment(
|
|
1010
1058
|
stream_id=stream_id,
|
|
1011
1059
|
message_id=message_id,
|
|
@@ -137,6 +137,32 @@ class TestSlackMessageConversion:
|
|
|
137
137
|
class TestSlackMessageProperties:
|
|
138
138
|
"""Tests for SlackMessage computed properties."""
|
|
139
139
|
|
|
140
|
+
def test_edit_status_defaults_to_false_and_is_writable(self):
|
|
141
|
+
from chatom.slack import SlackMessage
|
|
142
|
+
|
|
143
|
+
message = SlackMessage(id="m1")
|
|
144
|
+
assert message.is_edited is False
|
|
145
|
+
message.is_edited = True
|
|
146
|
+
assert message.is_edited is True
|
|
147
|
+
message.is_edited = False
|
|
148
|
+
assert message.is_edited is False
|
|
149
|
+
|
|
150
|
+
def test_edit_status_preserves_explicit_flag(self):
|
|
151
|
+
from chatom.slack import SlackMessage
|
|
152
|
+
|
|
153
|
+
message = SlackMessage(id="m1", is_edited=True)
|
|
154
|
+
assert message.is_edited is True
|
|
155
|
+
|
|
156
|
+
def test_edit_status_uses_slack_metadata(self):
|
|
157
|
+
from chatom.slack import SlackMessage
|
|
158
|
+
|
|
159
|
+
edited = {"user": "U12345", "ts": "1234567890.123456"}
|
|
160
|
+
message = SlackMessage(id="m1", edited=edited)
|
|
161
|
+
assert message.is_edited is True
|
|
162
|
+
parsed = SlackMessage.from_api_response({"ts": "m1", "edited": edited})
|
|
163
|
+
assert parsed.is_edited is True
|
|
164
|
+
assert parsed.model_dump()["is_edited"] is True
|
|
165
|
+
|
|
140
166
|
def test_is_thread_reply_true(self):
|
|
141
167
|
"""Test is_thread_reply returns True when in a thread."""
|
|
142
168
|
from chatom.slack import SlackMessage
|