siopechat-backend 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- siopechat_backend/__init__.py +119 -0
- siopechat_backend/client.py +241 -0
- siopechat_backend/events.py +140 -0
- siopechat_backend/paths.py +113 -0
- siopechat_backend/py.typed +1 -0
- siopechat_backend/services/__init__.py +25 -0
- siopechat_backend/services/_normalize.py +463 -0
- siopechat_backend/services/accounts.py +702 -0
- siopechat_backend/services/chats.py +1085 -0
- siopechat_backend/services/downloads.py +462 -0
- siopechat_backend/services/messages.py +957 -0
- siopechat_backend/services/models.py +214 -0
- siopechat_backend/services/projects.py +392 -0
- siopechat_backend/services/search.py +185 -0
- siopechat_backend/services/settings.py +95 -0
- siopechat_backend/services/tags.py +119 -0
- siopechat_backend/services/updater.py +165 -0
- siopechat_backend/storage/__init__.py +26 -0
- siopechat_backend/storage/cache.py +132 -0
- siopechat_backend/storage/files.py +102 -0
- siopechat_backend/storage/schema.py +149 -0
- siopechat_backend/storage/sqlite.py +166 -0
- siopechat_backend/types.py +418 -0
- siopechat_backend-1.0.0.dist-info/METADATA +142 -0
- siopechat_backend-1.0.0.dist-info/RECORD +29 -0
- siopechat_backend-1.0.0.dist-info/WHEEL +5 -0
- siopechat_backend-1.0.0.dist-info/licenses/COPYRIGHT +7 -0
- siopechat_backend-1.0.0.dist-info/licenses/LICENSE +232 -0
- siopechat_backend-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Pure-asyncio, zero-UI-coupling backend library for SiopeChat."""
|
|
2
|
+
|
|
3
|
+
from webaiprovider import DeepResearchTool, ImageGenerationTool, WebAIProviderType, WebSearchTool
|
|
4
|
+
from webaiprovider.providers.gemini.deep_research import GeminiDeepResearchTool
|
|
5
|
+
|
|
6
|
+
from .client import SiopeBackend
|
|
7
|
+
from .events import BackendEvent, BackendEventDispatcher, EventNames
|
|
8
|
+
from .paths import AppPaths
|
|
9
|
+
from .services import (
|
|
10
|
+
AccountsService,
|
|
11
|
+
ChatsService,
|
|
12
|
+
DownloadsService,
|
|
13
|
+
MessagesService,
|
|
14
|
+
ModelsService,
|
|
15
|
+
ProjectsService,
|
|
16
|
+
SearchService,
|
|
17
|
+
SettingsService,
|
|
18
|
+
TagsService,
|
|
19
|
+
UpdaterService,
|
|
20
|
+
)
|
|
21
|
+
from .storage import SCHEMA_VERSION, AsyncSQLite, BoundedLRUCache, TTLCache
|
|
22
|
+
from .types import (
|
|
23
|
+
AccountAuthError,
|
|
24
|
+
AccountInfo,
|
|
25
|
+
AppSettings,
|
|
26
|
+
ArtifactRecord,
|
|
27
|
+
BackendError,
|
|
28
|
+
BrowserProfileInfo,
|
|
29
|
+
ChatPage,
|
|
30
|
+
ChatSummary,
|
|
31
|
+
ChatWindow,
|
|
32
|
+
DownloadRecord,
|
|
33
|
+
DuplicateSessionError,
|
|
34
|
+
EffortOption,
|
|
35
|
+
ExportFormat,
|
|
36
|
+
FilePreview,
|
|
37
|
+
MessageMetrics,
|
|
38
|
+
MessageRecord,
|
|
39
|
+
ModelInfo,
|
|
40
|
+
NotFoundError,
|
|
41
|
+
PartRecord,
|
|
42
|
+
ProjectAttachmentRecord,
|
|
43
|
+
ProjectRecord,
|
|
44
|
+
ResearchRecord,
|
|
45
|
+
SearchResult,
|
|
46
|
+
SearchResultKind,
|
|
47
|
+
SearchScope,
|
|
48
|
+
SourceRecord,
|
|
49
|
+
StorageError,
|
|
50
|
+
StreamUpdate,
|
|
51
|
+
TagRecord,
|
|
52
|
+
UnsupportedFeatureError,
|
|
53
|
+
UpdateInfo,
|
|
54
|
+
UserAttachmentRecord,
|
|
55
|
+
ValidationError,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
__version__ = "1.0.0"
|
|
59
|
+
|
|
60
|
+
__all__ = [
|
|
61
|
+
"AccountAuthError",
|
|
62
|
+
"AccountInfo",
|
|
63
|
+
"AccountsService",
|
|
64
|
+
"AppPaths",
|
|
65
|
+
"AppSettings",
|
|
66
|
+
"ArtifactRecord",
|
|
67
|
+
"AsyncSQLite",
|
|
68
|
+
"BackendError",
|
|
69
|
+
"BackendEvent",
|
|
70
|
+
"BackendEventDispatcher",
|
|
71
|
+
"BoundedLRUCache",
|
|
72
|
+
"BrowserProfileInfo",
|
|
73
|
+
"ChatPage",
|
|
74
|
+
"ChatSummary",
|
|
75
|
+
"ChatWindow",
|
|
76
|
+
"ChatsService",
|
|
77
|
+
"DeepResearchTool",
|
|
78
|
+
"DownloadRecord",
|
|
79
|
+
"DownloadsService",
|
|
80
|
+
"DuplicateSessionError",
|
|
81
|
+
"EffortOption",
|
|
82
|
+
"EventNames",
|
|
83
|
+
"ExportFormat",
|
|
84
|
+
"FilePreview",
|
|
85
|
+
"GeminiDeepResearchTool",
|
|
86
|
+
"ImageGenerationTool",
|
|
87
|
+
"MessageMetrics",
|
|
88
|
+
"MessageRecord",
|
|
89
|
+
"MessagesService",
|
|
90
|
+
"ModelInfo",
|
|
91
|
+
"ModelsService",
|
|
92
|
+
"NotFoundError",
|
|
93
|
+
"PartRecord",
|
|
94
|
+
"ProjectAttachmentRecord",
|
|
95
|
+
"ProjectRecord",
|
|
96
|
+
"ProjectsService",
|
|
97
|
+
"ResearchRecord",
|
|
98
|
+
"SCHEMA_VERSION",
|
|
99
|
+
"SearchResult",
|
|
100
|
+
"SearchResultKind",
|
|
101
|
+
"SearchScope",
|
|
102
|
+
"SearchService",
|
|
103
|
+
"SettingsService",
|
|
104
|
+
"SiopeBackend",
|
|
105
|
+
"SourceRecord",
|
|
106
|
+
"StorageError",
|
|
107
|
+
"StreamUpdate",
|
|
108
|
+
"TTLCache",
|
|
109
|
+
"TagRecord",
|
|
110
|
+
"TagsService",
|
|
111
|
+
"UnsupportedFeatureError",
|
|
112
|
+
"UpdateInfo",
|
|
113
|
+
"UpdaterService",
|
|
114
|
+
"UserAttachmentRecord",
|
|
115
|
+
"ValidationError",
|
|
116
|
+
"WebAIProviderType",
|
|
117
|
+
"WebSearchTool",
|
|
118
|
+
"__version__",
|
|
119
|
+
]
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Single async entry point (`SiopeBackend`) composing storage, events, and services."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Coroutine, Generator
|
|
8
|
+
from types import TracebackType
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from flowcoord import AsyncTaskScope
|
|
12
|
+
from webaiprovider import AsyncProject
|
|
13
|
+
|
|
14
|
+
from .events import BackendEventDispatcher
|
|
15
|
+
from .paths import AppPaths
|
|
16
|
+
from .services.accounts import AccountsService, ProviderFactory
|
|
17
|
+
from .services.chats import ChatsService
|
|
18
|
+
from .services.downloads import DownloadsService
|
|
19
|
+
from .services.messages import MessagesService
|
|
20
|
+
from .services.models import ModelsService
|
|
21
|
+
from .services.projects import ProjectsService
|
|
22
|
+
from .services.search import SearchService
|
|
23
|
+
from .services.settings import SettingsService
|
|
24
|
+
from .services.tags import TagsService
|
|
25
|
+
from .services.updater import JsonFetcher, UpdaterService
|
|
26
|
+
from .storage.sqlite import AsyncSQLite
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _OpenBackendHandle:
|
|
30
|
+
"""Dual-protocol handle supporting both `async with SiopeBackend.open()` and `await SiopeBackend.open()`."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, coro: Coroutine[Any, Any, SiopeBackend]) -> None:
|
|
33
|
+
self._coro = coro
|
|
34
|
+
self._backend: SiopeBackend | None = None
|
|
35
|
+
|
|
36
|
+
def __await__(self) -> Generator[Any, None, SiopeBackend]:
|
|
37
|
+
return self._coro.__await__()
|
|
38
|
+
|
|
39
|
+
async def __aenter__(self) -> SiopeBackend:
|
|
40
|
+
self._backend = await self._coro
|
|
41
|
+
return self._backend
|
|
42
|
+
|
|
43
|
+
async def __aexit__(
|
|
44
|
+
self,
|
|
45
|
+
exc_type: type[BaseException] | None,
|
|
46
|
+
exc: BaseException | None,
|
|
47
|
+
tb: TracebackType | None,
|
|
48
|
+
) -> None:
|
|
49
|
+
del exc_type, exc, tb
|
|
50
|
+
if self._backend is not None:
|
|
51
|
+
await self._backend.close()
|
|
52
|
+
self._backend = None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class SiopeBackend:
|
|
56
|
+
"""Async embedded backend facade for SiopeChat clients (TUI, CLI, desktop, or API adapters)."""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
*,
|
|
61
|
+
paths: AppPaths,
|
|
62
|
+
db: AsyncSQLite,
|
|
63
|
+
events: BackendEventDispatcher,
|
|
64
|
+
task_scope: AsyncTaskScope,
|
|
65
|
+
settings: SettingsService,
|
|
66
|
+
accounts: AccountsService,
|
|
67
|
+
models: ModelsService,
|
|
68
|
+
chats: ChatsService,
|
|
69
|
+
messages: MessagesService,
|
|
70
|
+
projects: ProjectsService,
|
|
71
|
+
downloads: DownloadsService,
|
|
72
|
+
search: SearchService,
|
|
73
|
+
tags: TagsService,
|
|
74
|
+
updater: UpdaterService,
|
|
75
|
+
) -> None:
|
|
76
|
+
self.paths = paths
|
|
77
|
+
self.db = db
|
|
78
|
+
self.events = events
|
|
79
|
+
self._task_scope = task_scope
|
|
80
|
+
self.settings = settings
|
|
81
|
+
self.accounts = accounts
|
|
82
|
+
self.models = models
|
|
83
|
+
self.chats = chats
|
|
84
|
+
self.messages = messages
|
|
85
|
+
self.projects = projects
|
|
86
|
+
self.downloads = downloads
|
|
87
|
+
self.search = search
|
|
88
|
+
self.tags = tags
|
|
89
|
+
self.updater = updater
|
|
90
|
+
self._closed = False
|
|
91
|
+
|
|
92
|
+
@classmethod
|
|
93
|
+
def open(
|
|
94
|
+
cls,
|
|
95
|
+
root: str | os.PathLike[str] | None = None,
|
|
96
|
+
*,
|
|
97
|
+
downloads_dir: str | os.PathLike[str] | None = None,
|
|
98
|
+
provider_factory: ProviderFactory | None = None,
|
|
99
|
+
update_fetcher: JsonFetcher | None = None,
|
|
100
|
+
max_open_chats: int | None = None,
|
|
101
|
+
history_window_size: int | None = None,
|
|
102
|
+
prepare_accounts: bool = False,
|
|
103
|
+
) -> _OpenBackendHandle:
|
|
104
|
+
"""Open SQLite storage, load settings, initialize services, and manage lifecycle."""
|
|
105
|
+
|
|
106
|
+
async def _create() -> SiopeBackend:
|
|
107
|
+
paths = AppPaths.resolve(root, downloads_dir=downloads_dir).ensure()
|
|
108
|
+
events = BackendEventDispatcher()
|
|
109
|
+
task_scope = AsyncTaskScope(max_pending=128)
|
|
110
|
+
db = AsyncSQLite(paths.db_path)
|
|
111
|
+
await db.open()
|
|
112
|
+
|
|
113
|
+
settings_service = SettingsService(paths, events)
|
|
114
|
+
cfg = await settings_service.load()
|
|
115
|
+
|
|
116
|
+
effective_max_open = (
|
|
117
|
+
max_open_chats if max_open_chats is not None else cfg.max_open_chats
|
|
118
|
+
)
|
|
119
|
+
effective_window = (
|
|
120
|
+
history_window_size if history_window_size is not None else cfg.history_window_size
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
accounts_service = AccountsService(
|
|
124
|
+
db,
|
|
125
|
+
paths,
|
|
126
|
+
events,
|
|
127
|
+
provider_factory=provider_factory,
|
|
128
|
+
)
|
|
129
|
+
models_service = ModelsService(
|
|
130
|
+
accounts_service,
|
|
131
|
+
events,
|
|
132
|
+
db=db,
|
|
133
|
+
ttl_seconds=cfg.model_cache_ttl_seconds,
|
|
134
|
+
)
|
|
135
|
+
chats_service = ChatsService(
|
|
136
|
+
db,
|
|
137
|
+
paths,
|
|
138
|
+
accounts_service,
|
|
139
|
+
events,
|
|
140
|
+
max_open_chats=effective_max_open,
|
|
141
|
+
default_window_size=effective_window,
|
|
142
|
+
)
|
|
143
|
+
messages_service = MessagesService(
|
|
144
|
+
paths,
|
|
145
|
+
accounts_service,
|
|
146
|
+
models_service,
|
|
147
|
+
chats_service,
|
|
148
|
+
events,
|
|
149
|
+
default_tool_timeout=cfg.tool_timeout_seconds,
|
|
150
|
+
)
|
|
151
|
+
projects_service = ProjectsService(db, accounts_service, events)
|
|
152
|
+
downloads_service = DownloadsService(db, paths, chats_service, events)
|
|
153
|
+
search_service = SearchService(db)
|
|
154
|
+
tags_service = TagsService(db, events)
|
|
155
|
+
updater_service = UpdaterService(fetcher=update_fetcher)
|
|
156
|
+
|
|
157
|
+
backend = cls(
|
|
158
|
+
paths=paths,
|
|
159
|
+
db=db,
|
|
160
|
+
events=events,
|
|
161
|
+
task_scope=task_scope,
|
|
162
|
+
settings=settings_service,
|
|
163
|
+
accounts=accounts_service,
|
|
164
|
+
models=models_service,
|
|
165
|
+
chats=chats_service,
|
|
166
|
+
messages=messages_service,
|
|
167
|
+
projects=projects_service,
|
|
168
|
+
downloads=downloads_service,
|
|
169
|
+
search=search_service,
|
|
170
|
+
tags=tags_service,
|
|
171
|
+
updater=updater_service,
|
|
172
|
+
)
|
|
173
|
+
if prepare_accounts:
|
|
174
|
+
await accounts_service.prepare_enabled()
|
|
175
|
+
return backend
|
|
176
|
+
|
|
177
|
+
return _OpenBackendHandle(_create())
|
|
178
|
+
|
|
179
|
+
async def __aenter__(self) -> SiopeBackend:
|
|
180
|
+
return self
|
|
181
|
+
|
|
182
|
+
async def __aexit__(
|
|
183
|
+
self,
|
|
184
|
+
exc_type: type[BaseException] | None,
|
|
185
|
+
exc: BaseException | None,
|
|
186
|
+
tb: TracebackType | None,
|
|
187
|
+
) -> None:
|
|
188
|
+
del exc_type, exc, tb
|
|
189
|
+
await self.close()
|
|
190
|
+
|
|
191
|
+
async def sync_account(self, account_key: str) -> dict[str, bool]:
|
|
192
|
+
"""Concurrently diff-sync models, projects, and chats (incl. project chats) for one account."""
|
|
193
|
+
changed = {"models": False, "projects": False, "chats": False}
|
|
194
|
+
|
|
195
|
+
async def _sync_models() -> None:
|
|
196
|
+
try:
|
|
197
|
+
changed["models"] = await self.models.sync_account(account_key)
|
|
198
|
+
except Exception:
|
|
199
|
+
pass
|
|
200
|
+
|
|
201
|
+
async def _sync_projects() -> list[AsyncProject]:
|
|
202
|
+
try:
|
|
203
|
+
_, changed["projects"], handles = await self.projects._sync_with_handles(
|
|
204
|
+
account_key
|
|
205
|
+
)
|
|
206
|
+
except Exception:
|
|
207
|
+
return []
|
|
208
|
+
return handles
|
|
209
|
+
|
|
210
|
+
async def _sync_chats(project_snapshot: asyncio.Task[list[AsyncProject]]) -> None:
|
|
211
|
+
try:
|
|
212
|
+
_, changed["chats"] = await self.chats._sync_account_diff(
|
|
213
|
+
account_key, project_snapshot=project_snapshot
|
|
214
|
+
)
|
|
215
|
+
except Exception:
|
|
216
|
+
pass
|
|
217
|
+
|
|
218
|
+
project_snapshot = asyncio.create_task(_sync_projects())
|
|
219
|
+
await asyncio.gather(_sync_models(), project_snapshot, _sync_chats(project_snapshot))
|
|
220
|
+
return changed
|
|
221
|
+
|
|
222
|
+
async def sync_all(self) -> dict[str, dict[str, bool]]:
|
|
223
|
+
"""Concurrently diff-sync models, projects, and chats across all enabled accounts."""
|
|
224
|
+
accounts = await self.accounts.list()
|
|
225
|
+
enabled = [a for a in accounts if a.enabled]
|
|
226
|
+
if not enabled:
|
|
227
|
+
return {}
|
|
228
|
+
results = await asyncio.gather(*(self.sync_account(a.key) for a in enabled))
|
|
229
|
+
return {acc.key: res for acc, res in zip(enabled, results, strict=False)}
|
|
230
|
+
|
|
231
|
+
async def close(self) -> None:
|
|
232
|
+
"""Deterministically cancel pending tasks, flush SQLite WAL, and release providers."""
|
|
233
|
+
if self._closed:
|
|
234
|
+
return
|
|
235
|
+
self._closed = True
|
|
236
|
+
await self.messages.close()
|
|
237
|
+
await self.chats.close()
|
|
238
|
+
await self.accounts.close()
|
|
239
|
+
await self._task_scope.aclose()
|
|
240
|
+
await self.events.close()
|
|
241
|
+
await self.db.close()
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Secret-free domain event definitions and flowevent AsyncEventBus wrapper."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from flowevent import AsyncEventBus, AsyncSubscription, AsyncSubscriptionScope, EventEnvelope
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class EventNames:
|
|
13
|
+
"""Canonical event type strings emitted by SiopeBackend services."""
|
|
14
|
+
|
|
15
|
+
SETTINGS_CHANGED = "settings.changed"
|
|
16
|
+
ACCOUNT_ADDED = "account.added"
|
|
17
|
+
ACCOUNT_UPDATED = "account.updated"
|
|
18
|
+
ACCOUNT_REMOVED = "account.removed"
|
|
19
|
+
ACCOUNT_AUTH_CHANGED = "account.auth_changed"
|
|
20
|
+
MODELS_REFRESHED = "models.refreshed"
|
|
21
|
+
CHAT_CREATED = "chat.created"
|
|
22
|
+
CHAT_UPDATED = "chat.updated"
|
|
23
|
+
CHAT_DELETED = "chat.deleted"
|
|
24
|
+
CHAT_SYNCED = "chat.synced"
|
|
25
|
+
CHAT_EVICTED = "chat.evicted"
|
|
26
|
+
MESSAGE_SAVED = "message.saved"
|
|
27
|
+
RESEARCH_UPDATED = "research.updated"
|
|
28
|
+
PROJECT_UPDATED = "project.updated"
|
|
29
|
+
DOWNLOAD_COMPLETED = "download.completed"
|
|
30
|
+
DOWNLOAD_FAILED = "download.failed"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
_FORBIDDEN_FIELDS = frozenset(
|
|
34
|
+
{
|
|
35
|
+
"cookie",
|
|
36
|
+
"cookies",
|
|
37
|
+
"credential",
|
|
38
|
+
"credentials",
|
|
39
|
+
"token",
|
|
40
|
+
"secret",
|
|
41
|
+
"password",
|
|
42
|
+
"authorization",
|
|
43
|
+
"raw_body",
|
|
44
|
+
"message_text",
|
|
45
|
+
"prompt",
|
|
46
|
+
}
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def sanitize_event_payload(payload: Mapping[str, Any] | None) -> dict[str, Any]:
|
|
51
|
+
"""Strip any accidental sensitive keys before dispatching events onto the bus."""
|
|
52
|
+
if not payload:
|
|
53
|
+
return {}
|
|
54
|
+
clean: dict[str, Any] = {}
|
|
55
|
+
for key, value in payload.items():
|
|
56
|
+
lowered = key.lower()
|
|
57
|
+
if any(forbidden in lowered for forbidden in _FORBIDDEN_FIELDS):
|
|
58
|
+
continue
|
|
59
|
+
clean[key] = value
|
|
60
|
+
return clean
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True, slots=True)
|
|
64
|
+
class BackendEvent:
|
|
65
|
+
"""Typed envelope payload emitted through flowevent.AsyncEventBus."""
|
|
66
|
+
|
|
67
|
+
event_type: str
|
|
68
|
+
account_key: str | None = None
|
|
69
|
+
chat_id: str | None = None
|
|
70
|
+
project_id: str | None = None
|
|
71
|
+
data: dict[str, Any] = field(default_factory=dict)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class BackendEventDispatcher:
|
|
75
|
+
"""Thin wrapper over flowevent.AsyncEventBus enforcing sanitized metadata-only events."""
|
|
76
|
+
|
|
77
|
+
def __init__(self) -> None:
|
|
78
|
+
self._bus = AsyncEventBus()
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def bus(self) -> AsyncEventBus:
|
|
82
|
+
"""Expose the underlying flowevent.AsyncEventBus instance."""
|
|
83
|
+
return self._bus
|
|
84
|
+
|
|
85
|
+
def scope(self) -> AsyncSubscriptionScope:
|
|
86
|
+
"""Create a managed AsyncSubscriptionScope for subscribers."""
|
|
87
|
+
return AsyncSubscriptionScope()
|
|
88
|
+
|
|
89
|
+
async def subscribe(
|
|
90
|
+
self,
|
|
91
|
+
callback: Callable[[EventEnvelope[BackendEvent]], Awaitable[None]],
|
|
92
|
+
*,
|
|
93
|
+
event_type: str | None = None,
|
|
94
|
+
account_key: str | None = None,
|
|
95
|
+
once: bool = False,
|
|
96
|
+
replay: int = 0,
|
|
97
|
+
) -> AsyncSubscription:
|
|
98
|
+
"""Subscribe to BackendEvent envelopes filtered by optional event_type/account_key."""
|
|
99
|
+
|
|
100
|
+
def _predicate(envelope: EventEnvelope[BackendEvent]) -> bool:
|
|
101
|
+
payload = envelope.event
|
|
102
|
+
if event_type is not None and payload.event_type != event_type:
|
|
103
|
+
return False
|
|
104
|
+
if account_key is not None and payload.account_key != account_key:
|
|
105
|
+
return False
|
|
106
|
+
return True
|
|
107
|
+
|
|
108
|
+
return await self._bus.subscribe(
|
|
109
|
+
callback,
|
|
110
|
+
predicate=_predicate if (event_type is not None or account_key is not None) else None,
|
|
111
|
+
once=once,
|
|
112
|
+
replay=replay,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
async def emit(
|
|
116
|
+
self,
|
|
117
|
+
event_type: str,
|
|
118
|
+
*,
|
|
119
|
+
account_key: str | None = None,
|
|
120
|
+
chat_id: str | None = None,
|
|
121
|
+
project_id: str | None = None,
|
|
122
|
+
correlation_id: str | None = None,
|
|
123
|
+
data: Mapping[str, Any] | None = None,
|
|
124
|
+
) -> None:
|
|
125
|
+
"""Publish a sanitized BackendEvent wrapped in EventEnvelope."""
|
|
126
|
+
event = BackendEvent(
|
|
127
|
+
event_type=event_type,
|
|
128
|
+
account_key=account_key,
|
|
129
|
+
chat_id=chat_id,
|
|
130
|
+
project_id=project_id,
|
|
131
|
+
data=sanitize_event_payload(data),
|
|
132
|
+
)
|
|
133
|
+
envelope = EventEnvelope(
|
|
134
|
+
event=event, source="siopechat_backend", correlation_id=correlation_id
|
|
135
|
+
)
|
|
136
|
+
await self._bus.publish(envelope)
|
|
137
|
+
|
|
138
|
+
async def close(self) -> None:
|
|
139
|
+
"""Close the underlying flowevent bus."""
|
|
140
|
+
await self._bus.close()
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Application directory layout with platformdirs, overrides, and 0o700 permissions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from platformdirs import user_cache_dir, user_config_dir, user_data_dir, user_downloads_dir
|
|
10
|
+
|
|
11
|
+
APP_NAME = "siopechat"
|
|
12
|
+
APP_AUTHOR = "TahsinCr"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class AppPaths:
|
|
17
|
+
"""Resolved filesystem paths used by SiopeBackend."""
|
|
18
|
+
|
|
19
|
+
config_dir: Path
|
|
20
|
+
data_dir: Path
|
|
21
|
+
cache_dir: Path
|
|
22
|
+
downloads_dir: Path
|
|
23
|
+
artifacts_dir: Path
|
|
24
|
+
sessions_dir: Path
|
|
25
|
+
db_path: Path
|
|
26
|
+
settings_path: Path
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def resolve(
|
|
30
|
+
cls,
|
|
31
|
+
root: str | os.PathLike[str] | None = None,
|
|
32
|
+
*,
|
|
33
|
+
downloads_dir: str | os.PathLike[str] | None = None,
|
|
34
|
+
) -> AppPaths:
|
|
35
|
+
"""Resolve paths from explicit root, SIOPECHAT_* env vars, or OS XDG directories."""
|
|
36
|
+
env_root = os.environ.get("SIOPECHAT_HOME")
|
|
37
|
+
base_root = (
|
|
38
|
+
Path(root).expanduser()
|
|
39
|
+
if root is not None
|
|
40
|
+
else (Path(env_root).expanduser() if env_root else None)
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
if base_root is not None:
|
|
44
|
+
config_dir = base_root / "config"
|
|
45
|
+
data_dir = base_root / "data"
|
|
46
|
+
cache_dir = base_root / "cache"
|
|
47
|
+
else:
|
|
48
|
+
config_env = os.environ.get("SIOPECHAT_CONFIG_DIR")
|
|
49
|
+
data_env = os.environ.get("SIOPECHAT_DATA_DIR")
|
|
50
|
+
cache_env = os.environ.get("SIOPECHAT_CACHE_DIR")
|
|
51
|
+
config_dir = (
|
|
52
|
+
Path(config_env).expanduser()
|
|
53
|
+
if config_env
|
|
54
|
+
else Path(user_config_dir(APP_NAME, APP_AUTHOR))
|
|
55
|
+
)
|
|
56
|
+
data_dir = (
|
|
57
|
+
Path(data_env).expanduser()
|
|
58
|
+
if data_env
|
|
59
|
+
else Path(user_data_dir(APP_NAME, APP_AUTHOR))
|
|
60
|
+
)
|
|
61
|
+
cache_dir = (
|
|
62
|
+
Path(cache_env).expanduser()
|
|
63
|
+
if cache_env
|
|
64
|
+
else Path(user_cache_dir(APP_NAME, APP_AUTHOR))
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
downloads_env = os.environ.get("SIOPECHAT_DOWNLOADS_DIR")
|
|
68
|
+
if downloads_dir is not None:
|
|
69
|
+
resolved_downloads = Path(downloads_dir).expanduser()
|
|
70
|
+
elif downloads_env:
|
|
71
|
+
resolved_downloads = Path(downloads_env).expanduser()
|
|
72
|
+
elif base_root is not None:
|
|
73
|
+
resolved_downloads = base_root / "downloads"
|
|
74
|
+
else:
|
|
75
|
+
resolved_downloads = Path(user_downloads_dir()) / "SiopeChat"
|
|
76
|
+
|
|
77
|
+
artifacts_env = os.environ.get("SIOPECHAT_ARTIFACTS_DIR")
|
|
78
|
+
sessions_env = os.environ.get("SIOPECHAT_SESSIONS_DIR")
|
|
79
|
+
resolved_artifacts = (
|
|
80
|
+
Path(artifacts_env).expanduser() if artifacts_env else data_dir / "artifacts"
|
|
81
|
+
)
|
|
82
|
+
resolved_sessions = (
|
|
83
|
+
Path(sessions_env).expanduser() if sessions_env else data_dir / "sessions"
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
return cls(
|
|
87
|
+
config_dir=config_dir.resolve(),
|
|
88
|
+
data_dir=data_dir.resolve(),
|
|
89
|
+
cache_dir=cache_dir.resolve(),
|
|
90
|
+
downloads_dir=resolved_downloads.resolve(),
|
|
91
|
+
artifacts_dir=resolved_artifacts.resolve(),
|
|
92
|
+
sessions_dir=resolved_sessions.resolve(),
|
|
93
|
+
db_path=(data_dir / "siopechat.sqlite3").resolve(),
|
|
94
|
+
settings_path=(config_dir / "config.json").resolve(),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
def ensure(self) -> AppPaths:
|
|
98
|
+
"""Create required directories, applying 0o700 permissions to internal state dirs on POSIX."""
|
|
99
|
+
for directory in (
|
|
100
|
+
self.config_dir,
|
|
101
|
+
self.data_dir,
|
|
102
|
+
self.cache_dir,
|
|
103
|
+
self.artifacts_dir,
|
|
104
|
+
self.sessions_dir,
|
|
105
|
+
):
|
|
106
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
107
|
+
if os.name == "posix":
|
|
108
|
+
try:
|
|
109
|
+
os.chmod(directory, 0o700)
|
|
110
|
+
except OSError:
|
|
111
|
+
pass
|
|
112
|
+
self.downloads_dir.mkdir(parents=True, exist_ok=True)
|
|
113
|
+
return self
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Async service modules backing SiopeBackend."""
|
|
2
|
+
|
|
3
|
+
from .accounts import AccountsService
|
|
4
|
+
from .chats import ChatsService
|
|
5
|
+
from .downloads import DownloadsService
|
|
6
|
+
from .messages import MessagesService
|
|
7
|
+
from .models import ModelsService
|
|
8
|
+
from .projects import ProjectsService
|
|
9
|
+
from .search import SearchService
|
|
10
|
+
from .settings import SettingsService
|
|
11
|
+
from .tags import TagsService
|
|
12
|
+
from .updater import UpdaterService
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"AccountsService",
|
|
16
|
+
"ChatsService",
|
|
17
|
+
"DownloadsService",
|
|
18
|
+
"MessagesService",
|
|
19
|
+
"ModelsService",
|
|
20
|
+
"ProjectsService",
|
|
21
|
+
"SearchService",
|
|
22
|
+
"SettingsService",
|
|
23
|
+
"TagsService",
|
|
24
|
+
"UpdaterService",
|
|
25
|
+
]
|