simple-module-chat 0.0.20__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.
- simple_module_chat-0.0.20.dist-info/METADATA +118 -0
- simple_module_chat-0.0.20.dist-info/RECORD +46 -0
- simple_module_chat-0.0.20.dist-info/WHEEL +4 -0
- simple_module_chat-0.0.20.dist-info/entry_points.txt +2 -0
- sm_chat/__init__.py +7 -0
- sm_chat/agent/__init__.py +3 -0
- sm_chat/agent/definition.py +72 -0
- sm_chat/agent/instructions.py +101 -0
- sm_chat/agent/toolset.py +102 -0
- sm_chat/contracts/__init__.py +21 -0
- sm_chat/contracts/registry.py +61 -0
- sm_chat/contracts/types.py +51 -0
- sm_chat/core/__init__.py +3 -0
- sm_chat/core/constants.py +55 -0
- sm_chat/core/settings.py +104 -0
- sm_chat/core/tenancy/__init__.py +125 -0
- sm_chat/core/tenancy/_mode.py +207 -0
- sm_chat/index.ts +26 -0
- sm_chat/locales/de.json +99 -0
- sm_chat/locales/en.json +99 -0
- sm_chat/module.py +85 -0
- sm_chat/package.json +20 -0
- sm_chat/pages/Index.tsx +108 -0
- sm_chat/ui/components/ApprovalCard.tsx +129 -0
- sm_chat/ui/components/ChatDrawerHost.tsx +248 -0
- sm_chat/ui/components/ChatExportActions.tsx +87 -0
- sm_chat/ui/components/ChatPanel.tsx +225 -0
- sm_chat/ui/components/MessageList.tsx +153 -0
- sm_chat/ui/components/SuggestedPrompts.tsx +65 -0
- sm_chat/ui/components/ThreadSidebar.tsx +222 -0
- sm_chat/ui/components/ToolCallPill.tsx +105 -0
- sm_chat/ui/hooks/threadMapping.ts +248 -0
- sm_chat/ui/hooks/useChatContext.ts +46 -0
- sm_chat/ui/hooks/useChatThread.ts +289 -0
- sm_chat/ui/hooks/useThreadStream.ts +87 -0
- sm_chat/ui/utils/api.ts +133 -0
- sm_chat/ui/utils/exportMarkdown.ts +66 -0
- sm_chat/ui/utils/i18n.ts +59 -0
- sm_chat/ui/utils/markdown.tsx +238 -0
- sm_chat/ui/utils/sse.ts +171 -0
- sm_chat/ui/utils/types.ts +111 -0
- sm_chat/web/__init__.py +3 -0
- sm_chat/web/endpoints/__init__.py +3 -0
- sm_chat/web/endpoints/api.py +117 -0
- sm_chat/web/endpoints/views.py +22 -0
- sm_chat/web/shared_props.py +33 -0
sm_chat/core/settings.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""DB-backed settings and module-scoped state container for ``sm_chat``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from pydantic import Field, ValidationInfo, field_validator
|
|
10
|
+
from simple_module_core.settings.settings_base import DbBackedSettings
|
|
11
|
+
|
|
12
|
+
from sm_chat.core import constants
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
_GUARDRAIL_BOUNDS: dict[str, tuple[int, int]] = {
|
|
17
|
+
"max_requests": (constants.MIN_MAX_REQUESTS, constants.DEFAULT_MAX_REQUESTS),
|
|
18
|
+
"max_tokens": (constants.MIN_MAX_TOKENS, constants.DEFAULT_MAX_TOKENS),
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ChatSettings(DbBackedSettings):
|
|
23
|
+
"""Workspace chat assistant settings (stored in the shared settings DB)."""
|
|
24
|
+
|
|
25
|
+
drawer_enabled: bool = Field(
|
|
26
|
+
default=True,
|
|
27
|
+
description="Show the floating assistant drawer on authenticated console pages.",
|
|
28
|
+
)
|
|
29
|
+
system_prompt_extra: str = Field(
|
|
30
|
+
default="",
|
|
31
|
+
description="Optional workspace-specific guidance appended to the assistant prompt.",
|
|
32
|
+
)
|
|
33
|
+
max_requests: int = Field(
|
|
34
|
+
default=constants.DEFAULT_MAX_REQUESTS,
|
|
35
|
+
description="Maximum LLM round-trips per assistant turn (clamped to AI global limits).",
|
|
36
|
+
json_schema_extra={"requires_restart": True},
|
|
37
|
+
)
|
|
38
|
+
max_tokens: int = Field(
|
|
39
|
+
default=constants.DEFAULT_MAX_TOKENS,
|
|
40
|
+
description="Maximum total tokens per assistant turn (clamped to AI global limits).",
|
|
41
|
+
json_schema_extra={"requires_restart": True},
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
@field_validator(*_GUARDRAIL_BOUNDS)
|
|
45
|
+
@classmethod
|
|
46
|
+
def _stored_guardrail_tolerated(cls, value: int, info: ValidationInfo) -> int:
|
|
47
|
+
field_name = info.field_name or ""
|
|
48
|
+
minimum, default = _GUARDRAIL_BOUNDS[field_name]
|
|
49
|
+
if value < minimum:
|
|
50
|
+
logger.warning(
|
|
51
|
+
"Ignoring stored %s=%d: it must be >= %d; using default %d.",
|
|
52
|
+
field_name,
|
|
53
|
+
value,
|
|
54
|
+
minimum,
|
|
55
|
+
default,
|
|
56
|
+
)
|
|
57
|
+
return default
|
|
58
|
+
return value
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class ChatServices:
|
|
63
|
+
"""Chat module singletons stored on ``app.state.sm_chat``."""
|
|
64
|
+
|
|
65
|
+
settings: ChatSettings
|
|
66
|
+
tenancy: Any = None
|
|
67
|
+
tenant_header: str | None = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
_current: ChatServices | None = None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def install(services: ChatServices) -> ChatServices:
|
|
74
|
+
"""Record the host's ``ChatServices`` instance and return it."""
|
|
75
|
+
global _current
|
|
76
|
+
_current = services
|
|
77
|
+
return services
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def reset() -> None:
|
|
81
|
+
"""Drop the installed instance (tests only)."""
|
|
82
|
+
global _current
|
|
83
|
+
_current = None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def get_app_services(app: Any) -> ChatServices:
|
|
87
|
+
"""Return ``app.state.sm_chat``, creating a default container if absent."""
|
|
88
|
+
existing = getattr(app.state, constants.PACKAGE, None)
|
|
89
|
+
if isinstance(existing, ChatServices):
|
|
90
|
+
return existing
|
|
91
|
+
created = ChatServices(settings=current_settings())
|
|
92
|
+
setattr(app.state, constants.PACKAGE, created)
|
|
93
|
+
return created
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def current_settings(app: Any | None = None) -> ChatSettings:
|
|
97
|
+
"""Return the hydrated ``ChatSettings`` for ``app`` or the installed host."""
|
|
98
|
+
if app is not None:
|
|
99
|
+
services = getattr(app.state, constants.PACKAGE, None)
|
|
100
|
+
if isinstance(services, ChatServices):
|
|
101
|
+
return services.settings
|
|
102
|
+
if _current is not None:
|
|
103
|
+
return _current.settings
|
|
104
|
+
return ChatSettings()
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Which tenant a chat request runs in, and the refusal when there is none.
|
|
2
|
+
|
|
3
|
+
Mirrors ``sm_ai.core.tenancy`` (records' tenancy plan, §A). ``sm_chat`` owns no
|
|
4
|
+
database tables of its own (it reuses ``sm_ai``'s thread tables), so it binds
|
|
5
|
+
the request tenant at every entry point without needing a separate ORM guard.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from collections.abc import AsyncIterator, Iterator
|
|
12
|
+
from contextlib import contextmanager
|
|
13
|
+
from typing import Any, Final
|
|
14
|
+
|
|
15
|
+
from fastapi import HTTPException, Request
|
|
16
|
+
from simple_module_db import is_valid_tenant_id, tenant_context
|
|
17
|
+
from simple_module_db.models.listeners import TenantIsolationError, current_tenant_id
|
|
18
|
+
|
|
19
|
+
from sm_chat.core.tenancy._mode import (
|
|
20
|
+
DEFAULT_TENANT,
|
|
21
|
+
TenancyMode,
|
|
22
|
+
configure,
|
|
23
|
+
detect_mode,
|
|
24
|
+
mode_of,
|
|
25
|
+
request_mode,
|
|
26
|
+
tenant_header,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"DEFAULT_TENANT",
|
|
31
|
+
"TENANT_RE",
|
|
32
|
+
"TenancyMode",
|
|
33
|
+
"TenantRequired",
|
|
34
|
+
"TenantUnbound",
|
|
35
|
+
"bind_admin",
|
|
36
|
+
"bound_tenant",
|
|
37
|
+
"configure",
|
|
38
|
+
"detect_mode",
|
|
39
|
+
"mode_of",
|
|
40
|
+
"resolve_admin",
|
|
41
|
+
"tenant_header",
|
|
42
|
+
"tenant_scope",
|
|
43
|
+
"valid_tenant",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
TENANT_RE: Final = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,49}$")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class TenantUnbound(RuntimeError): # noqa: N818 - matches cross-module tenancy parity
|
|
50
|
+
"""A chat operation ran with no tenant bound."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class TenantRequired(HTTPException):
|
|
54
|
+
"""A multi-tenant host, and a signed-in request with no active organisation."""
|
|
55
|
+
|
|
56
|
+
code: Final = "tenant_required"
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
detail: str = "No organisation is active for this account",
|
|
61
|
+
) -> None:
|
|
62
|
+
super().__init__(status_code=403, detail=detail)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def valid_tenant(value: object) -> bool:
|
|
66
|
+
"""The framework's own check (``fullmatch``, and never ``"platform"``)."""
|
|
67
|
+
return is_valid_tenant_id(value)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@contextmanager
|
|
71
|
+
def tenant_scope(tenant_id: str) -> Iterator[str]:
|
|
72
|
+
"""Bind ``tenant_id`` for the block, and always unbind it.
|
|
73
|
+
|
|
74
|
+
Re-entering the tenant already bound is a no-op. Binding a *different* one
|
|
75
|
+
is refused with ``TenantIsolationError``.
|
|
76
|
+
"""
|
|
77
|
+
if not valid_tenant(tenant_id):
|
|
78
|
+
raise ValueError(f"not a valid tenant id: {tenant_id!r}")
|
|
79
|
+
current = current_tenant_id.get()
|
|
80
|
+
if current is not None and current != tenant_id:
|
|
81
|
+
raise TenantIsolationError(
|
|
82
|
+
f"cannot bind tenant {tenant_id!r} inside a scope bound to {current!r}"
|
|
83
|
+
)
|
|
84
|
+
with tenant_context(tenant_id):
|
|
85
|
+
yield tenant_id
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def bound_tenant() -> str:
|
|
89
|
+
"""The tenant this code runs in; :class:`TenantUnbound` if there is none."""
|
|
90
|
+
tenant = current_tenant_id.get()
|
|
91
|
+
if tenant is None:
|
|
92
|
+
raise TenantUnbound("no tenant is bound for this chat operation")
|
|
93
|
+
return tenant
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _resolved(request: Any) -> str | None:
|
|
97
|
+
"""The tenant something upstream already chose for this request, or ``None``."""
|
|
98
|
+
tenant = getattr(request.state, "tenant_id", None)
|
|
99
|
+
if valid_tenant(tenant):
|
|
100
|
+
return tenant
|
|
101
|
+
bound = current_tenant_id.get()
|
|
102
|
+
return bound if valid_tenant(bound) else None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def resolve_admin(request: Any) -> str:
|
|
106
|
+
"""The authenticated surface's tenant (single-tenant defaults to ``default``;
|
|
107
|
+
multi-tenant requires an authenticated user with an active organisation)."""
|
|
108
|
+
single = mode_of(request.app) is TenancyMode.SINGLE
|
|
109
|
+
if not single and getattr(request.state, "user", None) is None:
|
|
110
|
+
raise HTTPException(status_code=401, detail="Not authenticated")
|
|
111
|
+
tenant = _resolved(request)
|
|
112
|
+
if tenant is None and request_mode(request, mode_of(request.app)) is TenancyMode.SINGLE:
|
|
113
|
+
return DEFAULT_TENANT
|
|
114
|
+
if tenant is None:
|
|
115
|
+
raise TenantRequired(
|
|
116
|
+
"no organisation is active for this account; pick one (or have an "
|
|
117
|
+
"administrator assign one) before using chat on a multi-tenant host"
|
|
118
|
+
)
|
|
119
|
+
return tenant
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
async def bind_admin(request: Request) -> AsyncIterator[str]:
|
|
123
|
+
"""Router dependency: binds the request's tenant for the whole request."""
|
|
124
|
+
with tenant_scope(resolve_admin(request)) as tenant:
|
|
125
|
+
yield tenant
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Whether chat runs single- or multi-tenant, read off the built stack.
|
|
2
|
+
|
|
3
|
+
Split out of :mod:`sm_chat.core.tenancy`, which re-exports every name here.
|
|
4
|
+
Mirrors ``sm_images.core.tenancy._mode`` (records' tenancy plan, §A.3).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
from typing import Any, Final
|
|
13
|
+
|
|
14
|
+
from simple_module_hosting.pipeline.tenancy import single_tenant_id, tenancy_mode
|
|
15
|
+
|
|
16
|
+
from sm_chat.core import constants
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"DEFAULT_TENANT",
|
|
20
|
+
"TenancyMode",
|
|
21
|
+
"configure",
|
|
22
|
+
"detect_mode",
|
|
23
|
+
"mode_of",
|
|
24
|
+
"mounted",
|
|
25
|
+
"request_mode",
|
|
26
|
+
"scope_mode",
|
|
27
|
+
"tenant_header",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger("sm_chat.core.tenancy")
|
|
31
|
+
|
|
32
|
+
_PACKAGE: Final = "chat"
|
|
33
|
+
"""The prefix of this file's messages."""
|
|
34
|
+
|
|
35
|
+
DEFAULT_TENANT: Final = "default"
|
|
36
|
+
"""The tenant of a single-tenant host, and of every row that predates tenancy."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class TenancyMode(StrEnum):
|
|
40
|
+
SINGLE = "single"
|
|
41
|
+
MULTI = "multi"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_KNOWN_KWARGS: Final = frozenset({"fixed", "header"})
|
|
45
|
+
|
|
46
|
+
_UNREADABLE: Final = (
|
|
47
|
+
"{pkg}: cannot read the app's middleware stack (app.user_middleware, or "
|
|
48
|
+
"its entries' .cls, is gone), so it cannot tell a single-tenant host from "
|
|
49
|
+
"a multi-tenant one. Refusing to guess: a wrong 'single' leaves every "
|
|
50
|
+
"read unfiltered (#125)"
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _tenant_middleware(app: Any) -> Any:
|
|
55
|
+
"""The ``TenantMiddleware`` entry of the built stack, or ``None``."""
|
|
56
|
+
from simple_module_hosting.pipeline.middleware import TenantMiddleware
|
|
57
|
+
from starlette.applications import Starlette
|
|
58
|
+
|
|
59
|
+
entries = getattr(app, "user_middleware", None)
|
|
60
|
+
if entries is None or any(not hasattr(e, "cls") for e in entries):
|
|
61
|
+
if isinstance(app, Starlette):
|
|
62
|
+
raise RuntimeError(_UNREADABLE.format(pkg=_PACKAGE))
|
|
63
|
+
return None
|
|
64
|
+
return next(
|
|
65
|
+
(e for e in entries if isinstance(e.cls, type) and issubclass(e.cls, TenantMiddleware)),
|
|
66
|
+
None,
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _kwargs(entry: Any) -> dict[str, Any] | None:
|
|
71
|
+
"""*entry*'s keywords, or ``None`` when their shape is not one read here."""
|
|
72
|
+
kwargs = getattr(entry, "kwargs", None)
|
|
73
|
+
if not isinstance(kwargs, Mapping) or getattr(entry, "args", ()):
|
|
74
|
+
return None
|
|
75
|
+
return dict(kwargs) if set(kwargs) <= _KNOWN_KWARGS else None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _fixed_tenant(entry: Any) -> str | None:
|
|
79
|
+
"""The tenant a single-tenant host pins every request to, or ``None``."""
|
|
80
|
+
return (_kwargs(entry) or {}).get("fixed") if entry else None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _opaque_middleware(app: Any) -> bool:
|
|
84
|
+
"""Whether the stack has an entry built by a factory rather than a class."""
|
|
85
|
+
return any(not isinstance(e.cls, type) for e in getattr(app, "user_middleware", None) or ())
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _framework_mode(app: Any) -> TenancyMode | None:
|
|
89
|
+
"""The framework's own public answer, or ``None`` without one."""
|
|
90
|
+
if str(tenancy_mode(app)) == TenancyMode.MULTI:
|
|
91
|
+
return TenancyMode.MULTI
|
|
92
|
+
return TenancyMode.SINGLE if getattr(app.state, "sm", None) is not None else None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def mounted(scope: Mapping[str, Any]) -> bool:
|
|
96
|
+
"""Whether this request reached the app through a parent's ``Mount``."""
|
|
97
|
+
outer = scope.get("app_root_path")
|
|
98
|
+
return outer is not None and scope.get("root_path", "") != outer
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def scope_mode(app: Any, scope: Mapping[str, Any], stored: TenancyMode) -> TenancyMode:
|
|
102
|
+
"""*stored* (the app's mode), unless it says ``SINGLE`` for a mounted app
|
|
103
|
+
the framework has no answer for."""
|
|
104
|
+
ambiguous = mounted(scope) and _framework_mode(app) is None
|
|
105
|
+
return TenancyMode.MULTI if stored is TenancyMode.SINGLE and ambiguous else stored
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def request_mode(request: Any, stored: TenancyMode) -> TenancyMode:
|
|
109
|
+
""":func:`scope_mode` for a ``Request``."""
|
|
110
|
+
return scope_mode(request.app, getattr(request, "scope", None) or {}, stored)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def pinned_tenants(app: Any) -> dict[str, str]:
|
|
114
|
+
"""Every tenant the host pins its requests to, keyed by where the pin is."""
|
|
115
|
+
pins = (
|
|
116
|
+
{"default_tenant": single_tenant_id(app)}
|
|
117
|
+
if _framework_mode(app) is TenancyMode.SINGLE
|
|
118
|
+
else {}
|
|
119
|
+
)
|
|
120
|
+
fixed = _fixed_tenant(_tenant_middleware(app))
|
|
121
|
+
if fixed is not None:
|
|
122
|
+
pins["fixed"] = fixed
|
|
123
|
+
return pins
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
_PIN_SHOWN: Final = {
|
|
127
|
+
"default_tenant": "default_tenant={!r}",
|
|
128
|
+
"fixed": "TenantMiddleware(fixed={!r})",
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def stray_pins(app: Any) -> str | None:
|
|
133
|
+
"""The host's pins to a tenant other than ``DEFAULT_TENANT``, or ``None``."""
|
|
134
|
+
stray = [
|
|
135
|
+
_PIN_SHOWN[source].format(tenant)
|
|
136
|
+
for source, tenant in pinned_tenants(app).items()
|
|
137
|
+
if tenant != DEFAULT_TENANT
|
|
138
|
+
]
|
|
139
|
+
return " and ".join(stray) or None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def detect_mode(app: Any) -> TenancyMode:
|
|
143
|
+
"""``MULTI`` iff ``TenantMiddleware`` is in the stack and resolves tenants
|
|
144
|
+
per request; a ``fixed`` one is a single-tenant host."""
|
|
145
|
+
entry = _tenant_middleware(app)
|
|
146
|
+
framework = _framework_mode(app)
|
|
147
|
+
if framework is TenancyMode.MULTI:
|
|
148
|
+
return TenancyMode.MULTI
|
|
149
|
+
if entry is not None:
|
|
150
|
+
if _kwargs(entry) is None:
|
|
151
|
+
return TenancyMode.MULTI
|
|
152
|
+
return TenancyMode.SINGLE if _fixed_tenant(entry) else TenancyMode.MULTI
|
|
153
|
+
if framework is None and _opaque_middleware(app):
|
|
154
|
+
return TenancyMode.MULTI
|
|
155
|
+
return TenancyMode.SINGLE
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _warn_if_unrecognised(app: Any) -> None:
|
|
159
|
+
entry = _tenant_middleware(app)
|
|
160
|
+
if entry is not None and _kwargs(entry) is None:
|
|
161
|
+
logger.warning(
|
|
162
|
+
"%s: TenantMiddleware was installed with arguments this version does not "
|
|
163
|
+
"recognise (args=%r, kwargs=%r); running multi-tenant so reads stay filtered",
|
|
164
|
+
_PACKAGE,
|
|
165
|
+
getattr(entry, "args", None),
|
|
166
|
+
getattr(entry, "kwargs", None),
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def tenant_header(app: Any) -> str | None:
|
|
171
|
+
"""The header that middleware resolves a tenant from, or ``None``."""
|
|
172
|
+
kwargs = getattr(_tenant_middleware(app), "kwargs", None)
|
|
173
|
+
header = kwargs.get("header") if isinstance(kwargs, Mapping) else None
|
|
174
|
+
return header or None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def configure(app: Any) -> TenancyMode:
|
|
178
|
+
"""Detect the mode once, store it on the services container, and warn on drift."""
|
|
179
|
+
stray = stray_pins(app)
|
|
180
|
+
if stray is not None:
|
|
181
|
+
raise RuntimeError(
|
|
182
|
+
f"chat: the host pins every request to {stray}, but chat "
|
|
183
|
+
f"runs a single-tenant host in {DEFAULT_TENANT!r}. Unset default_tenant and any "
|
|
184
|
+
f"TenantMiddleware(fixed=...), set them "
|
|
185
|
+
f"to {DEFAULT_TENANT!r}, or turn multi_tenant on"
|
|
186
|
+
)
|
|
187
|
+
mode = detect_mode(app)
|
|
188
|
+
_warn_if_unrecognised(app)
|
|
189
|
+
services = getattr(app.state, constants.PACKAGE, None)
|
|
190
|
+
if services is not None:
|
|
191
|
+
services.tenancy = mode
|
|
192
|
+
services.tenant_header = tenant_header(app)
|
|
193
|
+
host = getattr(getattr(app.state, "host", None), "settings", None)
|
|
194
|
+
if getattr(host, "multi_tenant", False) is True and mode is TenancyMode.SINGLE:
|
|
195
|
+
logger.warning(
|
|
196
|
+
"chat: the host setting multi_tenant is on but the middleware stack has no "
|
|
197
|
+
"TenantMiddleware, so chat runs single-tenant. The stack is built once, when "
|
|
198
|
+
"the process starts: restart it to apply the setting"
|
|
199
|
+
)
|
|
200
|
+
return mode
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def mode_of(app: Any) -> TenancyMode:
|
|
204
|
+
"""The stored mode, or a fresh detection before ``on_startup`` has run."""
|
|
205
|
+
services = getattr(app.state, constants.PACKAGE, None)
|
|
206
|
+
mode = getattr(services, "tenancy", None)
|
|
207
|
+
return mode if isinstance(mode, TenancyMode) else detect_mode(app)
|
sm_chat/index.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public frontend exports of `@simple-module-py/chat`.
|
|
3
|
+
*
|
|
4
|
+
* Host apps mount `<ChatDrawerHost initialPage={props.initialPage} />`
|
|
5
|
+
* alongside Inertia's `<App />`, or embed `<ChatPanel />` directly.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export type { ChatDrawerHostProps, InertiaPageLike } from './ui/components/ChatDrawerHost';
|
|
9
|
+
export { ChatDrawerHost } from './ui/components/ChatDrawerHost';
|
|
10
|
+
export type { ChatPanelProps } from './ui/components/ChatPanel';
|
|
11
|
+
export { ChatPanel } from './ui/components/ChatPanel';
|
|
12
|
+
export type { UseChatContextResult } from './ui/hooks/useChatContext';
|
|
13
|
+
export { useChatContext } from './ui/hooks/useChatContext';
|
|
14
|
+
export type { UseChatThreadOptions, UseChatThreadResult } from './ui/hooks/useChatThread';
|
|
15
|
+
export { useChatThread } from './ui/hooks/useChatThread';
|
|
16
|
+
export type {
|
|
17
|
+
ChatContextData,
|
|
18
|
+
ChatMessage,
|
|
19
|
+
ChatProviderInfo,
|
|
20
|
+
ChatRequestMetadata,
|
|
21
|
+
ChatSharedProp,
|
|
22
|
+
ChatSuggestedPrompt,
|
|
23
|
+
PendingApprovalItem,
|
|
24
|
+
ThreadSummary,
|
|
25
|
+
ToolCallActivity,
|
|
26
|
+
} from './ui/utils/types';
|
sm_chat/locales/de.json
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
{
|
|
2
|
+
"menu": {
|
|
3
|
+
"assistant": "Assistent"
|
|
4
|
+
},
|
|
5
|
+
"permission_group": "Chat",
|
|
6
|
+
"page": {
|
|
7
|
+
"head_title": "Workspace-Assistent",
|
|
8
|
+
"title": "Workspace-Assistent",
|
|
9
|
+
"subtitle": "Stellen Sie Fragen oder erstellen Sie Entwürfe für Ihren Arbeitsbereich."
|
|
10
|
+
},
|
|
11
|
+
"drawer": {
|
|
12
|
+
"open": "Assistent öffnen",
|
|
13
|
+
"close": "Assistent schließen",
|
|
14
|
+
"open_full_page": "Vollbild öffnen",
|
|
15
|
+
"title": "Assistent",
|
|
16
|
+
"shortcut_hint": "{shortcut} zum Umschalten drücken"
|
|
17
|
+
},
|
|
18
|
+
"sidebar": {
|
|
19
|
+
"title": "Unterhaltungen",
|
|
20
|
+
"new_chat": "Neuer Chat",
|
|
21
|
+
"empty": "Noch keine Unterhaltungen.",
|
|
22
|
+
"delete": "Unterhaltung löschen",
|
|
23
|
+
"delete_confirm": "Diese Unterhaltung löschen?",
|
|
24
|
+
"untitled": "Unbenannte Unterhaltung",
|
|
25
|
+
"loading": "Unterhaltungen werden geladen…",
|
|
26
|
+
"search_placeholder": "Unterhaltungen filtern…",
|
|
27
|
+
"clear_search": "Filter zurücksetzen",
|
|
28
|
+
"no_matches": "Keine passenden Unterhaltungen.",
|
|
29
|
+
"rename": "Unterhaltung umbenennen",
|
|
30
|
+
"rename_placeholder": "Titel der Unterhaltung",
|
|
31
|
+
"save_rename": "Titel speichern",
|
|
32
|
+
"cancel_rename": "Umbenennen abbrechen"
|
|
33
|
+
},
|
|
34
|
+
"composer": {
|
|
35
|
+
"placeholder": "Fragen Sie nach Ihrem Arbeitsbereich oder fordern Sie einen Entwurf an…",
|
|
36
|
+
"send": "Senden",
|
|
37
|
+
"stop": "Stopp",
|
|
38
|
+
"hint": "Eingabe zum Senden, Umschalt+Eingabe für eine neue Zeile."
|
|
39
|
+
},
|
|
40
|
+
"messages": {
|
|
41
|
+
"you": "Sie",
|
|
42
|
+
"assistant": "Assistent",
|
|
43
|
+
"thinking": "Denkt nach…",
|
|
44
|
+
"streaming": "Antwortet…",
|
|
45
|
+
"copy": "Nachricht kopieren",
|
|
46
|
+
"copied": "Kopiert",
|
|
47
|
+
"cancelled": "Antwort gestoppt.",
|
|
48
|
+
"copy_markdown": "Als Markdown kopieren",
|
|
49
|
+
"copied_markdown": "Kopiert",
|
|
50
|
+
"download_markdown": ".md herunterladen"
|
|
51
|
+
},
|
|
52
|
+
"tools": {
|
|
53
|
+
"running": "Führt {tool} aus…",
|
|
54
|
+
"completed": "{tool} verwendet",
|
|
55
|
+
"failed": "{tool} fehlgeschlagen",
|
|
56
|
+
"show_details": "Details anzeigen",
|
|
57
|
+
"hide_details": "Details ausblenden"
|
|
58
|
+
},
|
|
59
|
+
"approval": {
|
|
60
|
+
"title": "Freigabe erforderlich",
|
|
61
|
+
"subtitle": "Prüfen Sie diesen Entwurf, bevor fortgefahren wird.",
|
|
62
|
+
"provider_label": "Modul",
|
|
63
|
+
"action_label": "Aktion",
|
|
64
|
+
"approve": "Genehmigen",
|
|
65
|
+
"deny": "Ablehnen",
|
|
66
|
+
"approving": "Wird genehmigt…",
|
|
67
|
+
"denying": "Wird abgelehnt…",
|
|
68
|
+
"approved": "Genehmigt",
|
|
69
|
+
"denied": "Abgelehnt",
|
|
70
|
+
"denial_reason_placeholder": "Optionaler Grund für die Ablehnung…"
|
|
71
|
+
},
|
|
72
|
+
"prompts": {
|
|
73
|
+
"title": "Vorschläge",
|
|
74
|
+
"empty": "Stellen Sie eine Frage zu Ihrem Arbeitsbereich, um zu beginnen."
|
|
75
|
+
},
|
|
76
|
+
"empty": {
|
|
77
|
+
"title": "Wie kann ich helfen?",
|
|
78
|
+
"description": "Stellen Sie Fragen zu Seiten, Artikeln, Medien, Analysen, Newslettern oder Veranstaltungen — oder lassen Sie einen Entwurf vorbereiten.",
|
|
79
|
+
"no_providers": "Für Ihre Kontoberechtigungen sind derzeit keine Arbeitsbereich-Werkzeuge verfügbar."
|
|
80
|
+
},
|
|
81
|
+
"errors": {
|
|
82
|
+
"not_configured_title": "KI ist nicht konfiguriert",
|
|
83
|
+
"not_configured_body": "Konfigurieren Sie einen KI-Anbieter in den KI-Einstellungen, um zu chatten.",
|
|
84
|
+
"open_ai_settings": "KI-Einstellungen öffnen",
|
|
85
|
+
"load_context_failed": "Assistent-Kontext konnte nicht geladen werden.",
|
|
86
|
+
"load_threads_failed": "Unterhaltungen konnten nicht geladen werden.",
|
|
87
|
+
"send_failed": "Nachricht konnte nicht gesendet werden. Bitte erneut versuchen.",
|
|
88
|
+
"cancel_failed": "Die laufende Antwort konnte nicht gestoppt werden.",
|
|
89
|
+
"approval_failed": "Ihre Entscheidung konnte nicht übermittelt werden.",
|
|
90
|
+
"delete_failed": "Unterhaltung konnte nicht gelöscht werden.",
|
|
91
|
+
"rename_failed": "Unterhaltung konnte nicht umbenannt werden."
|
|
92
|
+
},
|
|
93
|
+
"settings": {
|
|
94
|
+
"drawer_enabled": "Schwebenden Assistent-Drawer aktivieren",
|
|
95
|
+
"system_prompt_extra": "Zusätzliche Hinweise für den Arbeitsbereich",
|
|
96
|
+
"max_requests": "Max. Anfragen pro Zug",
|
|
97
|
+
"max_tokens": "Max. Tokens pro Zug"
|
|
98
|
+
}
|
|
99
|
+
}
|
sm_chat/locales/en.json
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
{
|
|
2
|
+
"menu": {
|
|
3
|
+
"assistant": "Assistant"
|
|
4
|
+
},
|
|
5
|
+
"permission_group": "Chat",
|
|
6
|
+
"page": {
|
|
7
|
+
"head_title": "Workspace Assistant",
|
|
8
|
+
"title": "Workspace Assistant",
|
|
9
|
+
"subtitle": "Ask questions or draft content across your workspace."
|
|
10
|
+
},
|
|
11
|
+
"drawer": {
|
|
12
|
+
"open": "Open assistant",
|
|
13
|
+
"close": "Close assistant",
|
|
14
|
+
"open_full_page": "Open full page",
|
|
15
|
+
"title": "Assistant",
|
|
16
|
+
"shortcut_hint": "Press {shortcut} to toggle"
|
|
17
|
+
},
|
|
18
|
+
"sidebar": {
|
|
19
|
+
"title": "Conversations",
|
|
20
|
+
"new_chat": "New chat",
|
|
21
|
+
"empty": "No conversations yet.",
|
|
22
|
+
"delete": "Delete conversation",
|
|
23
|
+
"delete_confirm": "Delete this conversation?",
|
|
24
|
+
"untitled": "Untitled conversation",
|
|
25
|
+
"loading": "Loading conversations…",
|
|
26
|
+
"search_placeholder": "Filter conversations…",
|
|
27
|
+
"clear_search": "Clear filter",
|
|
28
|
+
"no_matches": "No matching conversations.",
|
|
29
|
+
"rename": "Rename conversation",
|
|
30
|
+
"rename_placeholder": "Conversation title",
|
|
31
|
+
"save_rename": "Save title",
|
|
32
|
+
"cancel_rename": "Cancel rename"
|
|
33
|
+
},
|
|
34
|
+
"composer": {
|
|
35
|
+
"placeholder": "Ask about your workspace or request a draft…",
|
|
36
|
+
"send": "Send",
|
|
37
|
+
"stop": "Stop",
|
|
38
|
+
"hint": "Press Enter to send, Shift+Enter for a new line."
|
|
39
|
+
},
|
|
40
|
+
"messages": {
|
|
41
|
+
"you": "You",
|
|
42
|
+
"assistant": "Assistant",
|
|
43
|
+
"thinking": "Thinking…",
|
|
44
|
+
"streaming": "Responding…",
|
|
45
|
+
"copy": "Copy message",
|
|
46
|
+
"copied": "Copied",
|
|
47
|
+
"cancelled": "Response stopped.",
|
|
48
|
+
"copy_markdown": "Copy Markdown",
|
|
49
|
+
"copied_markdown": "Copied",
|
|
50
|
+
"download_markdown": "Download .md"
|
|
51
|
+
},
|
|
52
|
+
"tools": {
|
|
53
|
+
"running": "Running {tool}…",
|
|
54
|
+
"completed": "Used {tool}",
|
|
55
|
+
"failed": "{tool} failed",
|
|
56
|
+
"show_details": "Show details",
|
|
57
|
+
"hide_details": "Hide details"
|
|
58
|
+
},
|
|
59
|
+
"approval": {
|
|
60
|
+
"title": "Approval required",
|
|
61
|
+
"subtitle": "Review this draft action before continuing.",
|
|
62
|
+
"provider_label": "Module",
|
|
63
|
+
"action_label": "Action",
|
|
64
|
+
"approve": "Approve",
|
|
65
|
+
"deny": "Deny",
|
|
66
|
+
"approving": "Approving…",
|
|
67
|
+
"denying": "Denying…",
|
|
68
|
+
"approved": "Approved",
|
|
69
|
+
"denied": "Denied",
|
|
70
|
+
"denial_reason_placeholder": "Optional reason for denying…"
|
|
71
|
+
},
|
|
72
|
+
"prompts": {
|
|
73
|
+
"title": "Suggested prompts",
|
|
74
|
+
"empty": "Ask anything about your workspace to get started."
|
|
75
|
+
},
|
|
76
|
+
"empty": {
|
|
77
|
+
"title": "How can I help?",
|
|
78
|
+
"description": "Ask questions about your pages, articles, media, analytics, newsletters, or events — or ask me to prepare a draft.",
|
|
79
|
+
"no_providers": "No workspace tools are available for your account permissions yet."
|
|
80
|
+
},
|
|
81
|
+
"errors": {
|
|
82
|
+
"not_configured_title": "AI is not configured",
|
|
83
|
+
"not_configured_body": "Configure an AI provider in AI settings to start chatting.",
|
|
84
|
+
"open_ai_settings": "Open AI settings",
|
|
85
|
+
"load_context_failed": "Could not load assistant context.",
|
|
86
|
+
"load_threads_failed": "Could not load conversations.",
|
|
87
|
+
"send_failed": "Could not send message. Try again.",
|
|
88
|
+
"cancel_failed": "Could not stop the current response.",
|
|
89
|
+
"approval_failed": "Could not submit your approval decision.",
|
|
90
|
+
"delete_failed": "Could not delete conversation.",
|
|
91
|
+
"rename_failed": "Could not rename conversation."
|
|
92
|
+
},
|
|
93
|
+
"settings": {
|
|
94
|
+
"drawer_enabled": "Enable floating assistant drawer",
|
|
95
|
+
"system_prompt_extra": "Additional workspace guidance",
|
|
96
|
+
"max_requests": "Max requests per turn",
|
|
97
|
+
"max_tokens": "Max tokens per turn"
|
|
98
|
+
}
|
|
99
|
+
}
|