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.
Files changed (46) hide show
  1. simple_module_chat-0.0.20.dist-info/METADATA +118 -0
  2. simple_module_chat-0.0.20.dist-info/RECORD +46 -0
  3. simple_module_chat-0.0.20.dist-info/WHEEL +4 -0
  4. simple_module_chat-0.0.20.dist-info/entry_points.txt +2 -0
  5. sm_chat/__init__.py +7 -0
  6. sm_chat/agent/__init__.py +3 -0
  7. sm_chat/agent/definition.py +72 -0
  8. sm_chat/agent/instructions.py +101 -0
  9. sm_chat/agent/toolset.py +102 -0
  10. sm_chat/contracts/__init__.py +21 -0
  11. sm_chat/contracts/registry.py +61 -0
  12. sm_chat/contracts/types.py +51 -0
  13. sm_chat/core/__init__.py +3 -0
  14. sm_chat/core/constants.py +55 -0
  15. sm_chat/core/settings.py +104 -0
  16. sm_chat/core/tenancy/__init__.py +125 -0
  17. sm_chat/core/tenancy/_mode.py +207 -0
  18. sm_chat/index.ts +26 -0
  19. sm_chat/locales/de.json +99 -0
  20. sm_chat/locales/en.json +99 -0
  21. sm_chat/module.py +85 -0
  22. sm_chat/package.json +20 -0
  23. sm_chat/pages/Index.tsx +108 -0
  24. sm_chat/ui/components/ApprovalCard.tsx +129 -0
  25. sm_chat/ui/components/ChatDrawerHost.tsx +248 -0
  26. sm_chat/ui/components/ChatExportActions.tsx +87 -0
  27. sm_chat/ui/components/ChatPanel.tsx +225 -0
  28. sm_chat/ui/components/MessageList.tsx +153 -0
  29. sm_chat/ui/components/SuggestedPrompts.tsx +65 -0
  30. sm_chat/ui/components/ThreadSidebar.tsx +222 -0
  31. sm_chat/ui/components/ToolCallPill.tsx +105 -0
  32. sm_chat/ui/hooks/threadMapping.ts +248 -0
  33. sm_chat/ui/hooks/useChatContext.ts +46 -0
  34. sm_chat/ui/hooks/useChatThread.ts +289 -0
  35. sm_chat/ui/hooks/useThreadStream.ts +87 -0
  36. sm_chat/ui/utils/api.ts +133 -0
  37. sm_chat/ui/utils/exportMarkdown.ts +66 -0
  38. sm_chat/ui/utils/i18n.ts +59 -0
  39. sm_chat/ui/utils/markdown.tsx +238 -0
  40. sm_chat/ui/utils/sse.ts +171 -0
  41. sm_chat/ui/utils/types.ts +111 -0
  42. sm_chat/web/__init__.py +3 -0
  43. sm_chat/web/endpoints/__init__.py +3 -0
  44. sm_chat/web/endpoints/api.py +117 -0
  45. sm_chat/web/endpoints/views.py +22 -0
  46. sm_chat/web/shared_props.py +33 -0
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.5
2
+ Name: simple_module_chat
3
+ Version: 0.0.20
4
+ Summary: Generic cross-module workspace chat assistant built on simple_module_ai
5
+ Project-URL: Repository, https://github.com/antosubash/smpy_modules
6
+ Author-email: Anto Subash <antosubash@live.com>
7
+ License-Expression: MIT
8
+ Keywords: ai,chat,simple-module
9
+ Requires-Python: >=3.12
10
+ Requires-Dist: pydantic-settings>=2.0
11
+ Requires-Dist: simple-module-ai<0.1,>=0.0.18
12
+ Requires-Dist: simple-module-core<0.1,>=0.0.50
13
+ Requires-Dist: simple-module-db<0.1,>=0.0.50
14
+ Requires-Dist: simple-module-hosting<0.1,>=0.0.50
15
+ Requires-Dist: simple-module-inertia<0.1,>=0.0.36
16
+ Requires-Dist: simple-module-settings<0.1,>=0.0.44
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
19
+ Requires-Dist: pytest>=8.0; extra == 'dev'
20
+ Requires-Dist: simple-module-test<0.1,>=0.0.36; extra == 'dev'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # simple_module_chat
24
+
25
+ Generic cross-module workspace chat assistant for `simple_module_python`
26
+ applications, built on `simple_module_ai`.
27
+
28
+ Signed-in console users get a dedicated `/chat` workspace and an optional
29
+ slide-over drawer across authenticated console screens. Any module — in-repo or
30
+ host-specific — can plug tools, instructions, suggested prompts, and page
31
+ context resolvers into the assistant through `sm_chat.contracts` without
32
+ coupling `simple_module_chat` to sibling packages.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ uv add simple_module_chat
38
+ ```
39
+
40
+ `simple_module_chat` depends on `simple_module_ai` and reuses its `ai_threads`,
41
+ `ai_messages`, SSE streaming, HITL approval flow, guardrails, and billing
42
+ metering. No additional database tables or Alembic migrations are required.
43
+
44
+ ## Usage
45
+
46
+ The module auto-registers via the `simple_module` entry point (`chat =
47
+ "sm_chat.module:ChatModule"`) and registers the `chat.assistant` agent with
48
+ `simple_module_ai` during startup.
49
+
50
+ ### Registering a chat provider
51
+
52
+ Modules or host applications register tools in `on_startup` (or after
53
+ `create_app()`) regardless of startup order:
54
+
55
+ ```python
56
+ from pydantic_ai.toolsets import FunctionToolset
57
+ from sm_ai.contracts import ToolPolicy
58
+ from sm_chat.contracts import ChatContext, ChatProvider, ChatSuggestedPrompt, register_chat_provider
59
+
60
+ toolset: FunctionToolset[ChatContext] = FunctionToolset()
61
+
62
+
63
+ @toolset.tool
64
+ async def list_items(ctx) -> list[dict[str, str]]:
65
+ return [{"id": "1", "title": "Example"}]
66
+
67
+
68
+ register_chat_provider(
69
+ app,
70
+ ChatProvider(
71
+ id="example",
72
+ title="Example",
73
+ instructions="Use list_items to inspect workspace items.",
74
+ toolset=toolset,
75
+ policies={"list_items": ToolPolicy(permissions=("example.view",))},
76
+ suggested_prompts=(
77
+ ChatSuggestedPrompt(
78
+ id="list-items",
79
+ label="List items",
80
+ prompt="Show me the current items.",
81
+ required_permissions=("example.view",),
82
+ ),
83
+ ),
84
+ ),
85
+ )
86
+ ```
87
+
88
+ Every tool is exposed to the model as `<provider.id>__<tool_name>` and gated
89
+ fail-closed through `PermissionedToolset`.
90
+
91
+ See [docs/extending.md](docs/extending.md) for copy-paste recipes covering
92
+ soft-optional registration, read tools, HITL draft actions, active-screen
93
+ `context_resolver`s, suggested prompts, and the security/privacy checklist.
94
+
95
+ ## Permissions
96
+
97
+ | Permission | Description | Default roles |
98
+ | --- | --- | --- |
99
+ | `chat.use` | Access `/chat`, `/api/chat/context`, and the `chat.assistant` agent | `admin`, `editor`, `viewer` |
100
+
101
+ Underlying module tools continue to enforce their own permissions and HITL
102
+ approval policies.
103
+
104
+ ## Settings
105
+
106
+ Configured via the database-backed `ChatSettings` (`sm_chat`):
107
+
108
+ | Setting | Default | Description |
109
+ | --- | --- | --- |
110
+ | `drawer_enabled` | `true` | Show the floating assistant drawer on authenticated console pages |
111
+ | `system_prompt_extra` | `""` | Optional workspace-specific guidance appended to the assistant prompt |
112
+ | `max_requests` | `12` | Maximum LLM round-trips per turn (clamped to `sm_ai` global limits) |
113
+ | `max_tokens` | `32000` | Maximum tokens per turn (clamped to `sm_ai` global limits) |
114
+
115
+ ## Routes
116
+
117
+ - `GET /chat` — Console chat workspace (Inertia page `Chat/Index`, requires `chat.use`)
118
+ - `GET /api/chat/context` — Permitted providers, suggested prompts, and drawer/AI status (requires `chat.use`)
@@ -0,0 +1,46 @@
1
+ sm_chat/__init__.py,sha256=tGnhSJKBNr0grIZJKHBLEZU0DAabjY1gZAwd5FvmzCU,161
2
+ sm_chat/index.ts,sha256=Ln3c6bJOYUhJd80RouJPSKzCJdmfUFJxFwk3zveTPa4,985
3
+ sm_chat/module.py,sha256=ftxOotEYa_BuRKEyRgS3O7XmqBaDQPzRl8Jt9vZG6KM,3140
4
+ sm_chat/agent/__init__.py,sha256=IWdWw8wU7Xue7fOjZsX7tunaP-8eIBhWOg9wkPhDajs,120
5
+ sm_chat/agent/definition.py,sha256=rvwt_E051sqAYWmRY1S9G4ys0KmlRSBaQL_h2jNgMXw,2676
6
+ sm_chat/agent/instructions.py,sha256=0Lzm_DTFU-y52HioX4KILFYkS1BFvFGBqT3hKw77vX0,3745
7
+ sm_chat/agent/toolset.py,sha256=S_eV4CzDKIu9eNpjCymfr2lY0AA-wpoUs6V9T-4T6pE,3715
8
+ sm_chat/contracts/__init__.py,sha256=Ca9vG5mbsaUYccp_f2qKOK9Now_Kcrt76nIqb8q-GbE,513
9
+ sm_chat/contracts/registry.py,sha256=GR38TYiAnKTLFdl_e3hCedSW-H9_I9K3EChl668jB_A,2113
10
+ sm_chat/contracts/types.py,sha256=asJU1pMbpmx503H5rjPrrpI7SxNGKGyvLlFreAZyJtg,1697
11
+ sm_chat/core/__init__.py,sha256=Da006xQahiHz4e4pgpWBJmEq9ekqlHmNDKhuGmbfp7A,110
12
+ sm_chat/core/constants.py,sha256=pYkry34f0GTqu62WZ9DzUewKByn0D7DgMZOiagquUtE,1553
13
+ sm_chat/core/settings.py,sha256=FBfse2ofu5BCBC4_aiD-8cHzZLIcReaIUtQiAPpznyg,3354
14
+ sm_chat/core/tenancy/__init__.py,sha256=FyyxRFrCmLPBV9qSQhjm5w1HB_hRcF4GWgkaAd8VCXE,4086
15
+ sm_chat/core/tenancy/_mode.py,sha256=DTLKKQ1SN5RyAcxm1q1epOZQ8ItPlw00C1MqiR_nfbs,7451
16
+ sm_chat/locales/de.json,sha256=S4GMySY9IqWsUBOZBY6vpCubvkyE5sOEcmHQ-95i2nM,3829
17
+ sm_chat/locales/en.json,sha256=BymjRFdUcJvTtPFCxzxty7yA8YLY-qyLIMQ13UT70mw,3387
18
+ sm_chat/pages/Index.tsx,sha256=gc5rm75KpHUoDBZv-e46XsTVhQAfvt23IL15fEOre-4,3731
19
+ sm_chat/ui/components/ApprovalCard.tsx,sha256=1S56ck2TDk0lyXpyAsDAAvbuIzXlkEAkJ8USy0iumRI,4854
20
+ sm_chat/ui/components/ChatDrawerHost.tsx,sha256=5p0jPdGIHvGB5AfNWoVeMAaQNccMu1spYsFr7yLcHX0,8450
21
+ sm_chat/ui/components/ChatExportActions.tsx,sha256=KPfVoTAB9ZBGPUMLXVeIEfxVQLaEZjmTs8uGm1DUvNE,2591
22
+ sm_chat/ui/components/ChatPanel.tsx,sha256=jHIpDDjGYZ5TC-w0feGYT-XpeBi7q53ARegHvt6l-h8,7596
23
+ sm_chat/ui/components/MessageList.tsx,sha256=4KNY6Y95fbu-qHIZHRf2WWq7xMkJrI_WOee_mti0I4Q,5657
24
+ sm_chat/ui/components/SuggestedPrompts.tsx,sha256=R2YAbpr4s7BG_Bo9_MZdKhxN3ykYeFEj5T46DzWSqvk,2253
25
+ sm_chat/ui/components/ThreadSidebar.tsx,sha256=qJ5i5ILabu8ZoVEtPxYlEZ7aBw6q47qvJZuX5bnJgcc,8853
26
+ sm_chat/ui/components/ToolCallPill.tsx,sha256=FXo5GCMBRD6j-tKamVb7m49O2QqguOcUN0g93QSwkLg,3678
27
+ sm_chat/ui/hooks/threadMapping.ts,sha256=x7nZnjhljrfEjxfGVpqw_dCXxH5tBhXdRNuOWSsjnF8,7943
28
+ sm_chat/ui/hooks/useChatContext.ts,sha256=rM2dxNNFCZXd1BYxmSzhI-BQJ_9-GftfUqbyVsNAlY0,1262
29
+ sm_chat/ui/hooks/useChatThread.ts,sha256=UfzWS3JGAGX9x4S4HTjncwi0qoCArgMMBg8US1uIcVg,8745
30
+ sm_chat/ui/hooks/useThreadStream.ts,sha256=gA-nGxwdB5v5pAii5gpkGcGRP-TYI_PLfFnyWNPENDU,2689
31
+ sm_chat/ui/utils/api.ts,sha256=VyBNSPgf2Ndu0o1YqMAceZKyHU7z4v12EdvGtE1ER8Q,3957
32
+ sm_chat/ui/utils/exportMarkdown.ts,sha256=vfQJ9gzyglb-iUIYqdkrAiwt01Rhpdb9m-A7toTwmtM,1981
33
+ sm_chat/ui/utils/i18n.ts,sha256=ofxb0Iu93CDQlkkczVi49IUKstBZsqkjLIqAtwD8ApU,1878
34
+ sm_chat/ui/utils/markdown.tsx,sha256=hL1Pdx_O8F3E1ER7FdA6gYiQBJNjC-T9ElR9xv1pKxk,7149
35
+ sm_chat/ui/utils/sse.ts,sha256=uAtcrVR-p5ASPP5Mng7ifVbNSqRNv26IzTthUHCwBW4,5657
36
+ sm_chat/ui/utils/types.ts,sha256=qtDfBZvFXdhynXAQO9ZUPkhCk8OHKpaxZ5eWFbFNwho,2378
37
+ sm_chat/web/__init__.py,sha256=nPODsRGaxRTQIwMJdN6Jn9dgpBI3DftxaaYzCBtr_y0,98
38
+ sm_chat/web/shared_props.py,sha256=R-3JLicmeODQdqZzZDmK1UzuxTkb9gEjNqF5rGM2Ckg,1273
39
+ sm_chat/web/endpoints/__init__.py,sha256=1wuvIIkZ-JLNpyme6wk1zabxl_7APZ9czvvJxhg79l4,88
40
+ sm_chat/web/endpoints/api.py,sha256=2KG_vzyyWcQAEMntOdAtViV0l9ATv-UX7u76OZjuRsg,3727
41
+ sm_chat/web/endpoints/views.py,sha256=Ojw_txnkJEHma7AWVKkRxgoDeRSXHpifmKts76iqsiI,735
42
+ sm_chat/package.json,sha256=h4kOpexHDiwP60GRsSjWJ8vd_ELnpohnINfKULGVR6Y,463
43
+ simple_module_chat-0.0.20.dist-info/METADATA,sha256=t3V2VFeN72vEC-epENui0ao6qtjNcCmGUrmlS6FpzBo,4296
44
+ simple_module_chat-0.0.20.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
45
+ simple_module_chat-0.0.20.dist-info/entry_points.txt,sha256=YRVtQsDAlPNNaecJzsFECTDO2Ye-Em5gBMtTbHOwKys,49
46
+ simple_module_chat-0.0.20.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [simple_module]
2
+ chat = sm_chat.module:ChatModule
sm_chat/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Generic cross-module workspace chat assistant module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sm_chat.module import ChatModule
6
+
7
+ __all__ = ["ChatModule"]
@@ -0,0 +1,3 @@
1
+ """Agent definition, composite toolset, and instructions for ``chat.assistant``."""
2
+
3
+ from __future__ import annotations
@@ -0,0 +1,72 @@
1
+ """Builds the ``chat.assistant`` ``AgentDefinition`` registered with ``sm_ai``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import FastAPI
6
+ from pydantic_ai import Agent, RunContext
7
+ from sm_ai.contracts import AgentDefinition, AiRequestContext
8
+
9
+ from sm_chat.agent.instructions import build_instructions
10
+ from sm_chat.agent.toolset import CompositeChatToolset
11
+ from sm_chat.contracts import ChatContext, list_chat_providers
12
+ from sm_chat.core import constants
13
+ from sm_chat.core.settings import current_settings
14
+
15
+
16
+ def sanitize_current_path(raw: object) -> str | None:
17
+ """Validate an untrusted ``current_path`` hint from ``request_metadata``.
18
+
19
+ Accepts only relative paths starting with a single ``/``, no ``//``, no
20
+ scheme, no control characters, and at most ``MAX_CURRENT_PATH_LENGTH`` chars.
21
+ """
22
+ if not isinstance(raw, str):
23
+ return None
24
+ path = raw.strip()
25
+ if not path or len(path) > constants.MAX_CURRENT_PATH_LENGTH:
26
+ return None
27
+ if not path.startswith("/") or path.startswith("//"):
28
+ return None
29
+ if "://" in path or any(ord(ch) < 32 or ord(ch) == 127 for ch in path):
30
+ return None
31
+ return path
32
+
33
+
34
+ def sanitize_locale(raw: object) -> str:
35
+ """Normalize an untrusted locale hint to a supported console locale."""
36
+ if not isinstance(raw, str):
37
+ return constants.DEFAULT_LOCALE
38
+ code = raw.strip().lower().split("-", 1)[0].split("_", 1)[0]
39
+ return code if code in constants.SUPPORTED_LOCALES else constants.DEFAULT_LOCALE
40
+
41
+
42
+ def build_chat_agent_definition(app: FastAPI) -> AgentDefinition[ChatContext]:
43
+ """Create the app-scoped ``AgentDefinition`` for ``chat.assistant``."""
44
+ agent: Agent[ChatContext, str] = Agent(
45
+ deps_type=ChatContext,
46
+ toolsets=[CompositeChatToolset(app=app)],
47
+ )
48
+
49
+ @agent.instructions
50
+ async def _instructions(ctx: RunContext[ChatContext]) -> str:
51
+ return await build_instructions(app, ctx)
52
+
53
+ def _deps_factory(ai_ctx: AiRequestContext) -> ChatContext:
54
+ metadata = ai_ctx.request_metadata or {}
55
+ return ChatContext(
56
+ ai_context=ai_ctx,
57
+ current_path=sanitize_current_path(metadata.get("current_path")),
58
+ locale=sanitize_locale(metadata.get("locale")),
59
+ providers=list_chat_providers(app),
60
+ )
61
+
62
+ settings = current_settings(app)
63
+ return AgentDefinition(
64
+ id=constants.AGENT_ID,
65
+ title=constants.AGENT_TITLE,
66
+ agent=agent,
67
+ deps_factory=_deps_factory,
68
+ tier=constants.AGENT_TIER,
69
+ required_permissions=(constants.PERM_USE,),
70
+ max_requests=settings.max_requests,
71
+ max_tokens=settings.max_tokens,
72
+ )
@@ -0,0 +1,101 @@
1
+ """Single combined ``@agent.instructions`` builder for ``chat.assistant``.
2
+
3
+ vLLM / Qwen3 chat templates reject multiple system messages, so every rule,
4
+ workspace override, provider instruction block, and resolved page context is
5
+ joined into one instruction string per turn.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import inspect
11
+ import logging
12
+
13
+ from fastapi import FastAPI
14
+ from pydantic_ai import RunContext
15
+
16
+ from sm_chat.agent.toolset import provider_has_permitted_tools
17
+ from sm_chat.contracts import ChatContext, ChatProvider
18
+ from sm_chat.core.settings import current_settings
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ _BASE_RULES = (
23
+ "You are the Workspace Assistant for signed-in console users.\n"
24
+ "- Answer questions using the available tools. Never fabricate IDs, metrics, counts, "
25
+ "URLs, or records.\n"
26
+ "- When referencing workspace items, include clickable relative markdown links to their "
27
+ "admin screens when returned by tools.\n"
28
+ "- Draft-creating tools only create drafts and require explicit user approval; never "
29
+ "claim to have published, deleted, or sent content.\n"
30
+ "- Respect privacy boundaries: only work with editorial, operational, and aggregate "
31
+ "data exposed by your tools.\n"
32
+ "- If a user asks about something no available tool covers, explain plainly what you "
33
+ "can help with instead."
34
+ )
35
+
36
+
37
+ async def _resolve_provider_instructions(provider: ChatProvider, ctx: ChatContext) -> str:
38
+ raw = provider.instructions
39
+ if callable(raw):
40
+ result = raw(ctx)
41
+ if inspect.isawaitable(result):
42
+ result = await result
43
+ return str(result).strip()
44
+ return raw.strip()
45
+
46
+
47
+ async def build_instructions(app: FastAPI, run_ctx: RunContext[ChatContext]) -> str:
48
+ """Build the single system prompt string for one ``chat.assistant`` turn."""
49
+ chat_ctx = run_ctx.deps
50
+ language_name = "German" if chat_ctx.locale == "de" else "English"
51
+ sections: list[str] = [
52
+ _BASE_RULES,
53
+ f"Always reply in {language_name} unless the user explicitly writes in another language.",
54
+ ]
55
+
56
+ extra = current_settings(app).system_prompt_extra.strip()
57
+ if extra:
58
+ sections.append(f"## Workspace guidance\n{extra}")
59
+
60
+ permitted = [
61
+ provider
62
+ for provider in chat_ctx.providers
63
+ if provider_has_permitted_tools(provider, chat_ctx.ai_context)
64
+ ]
65
+
66
+ for provider in permitted:
67
+ try:
68
+ text = await _resolve_provider_instructions(provider, chat_ctx)
69
+ except Exception:
70
+ logger.warning(
71
+ "Chat provider %r instructions failed; skipping provider guidance.",
72
+ provider.id,
73
+ exc_info=True,
74
+ )
75
+ continue
76
+ if text:
77
+ sections.append(f"## {provider.title}\n{text}")
78
+
79
+ if chat_ctx.current_path:
80
+ context_parts: list[str] = []
81
+ for provider in permitted:
82
+ if provider.context_resolver is None:
83
+ continue
84
+ try:
85
+ resolved = await provider.context_resolver(chat_ctx, chat_ctx.current_path)
86
+ except Exception:
87
+ logger.warning(
88
+ "Chat provider %r context_resolver failed for path %r.",
89
+ provider.id,
90
+ chat_ctx.current_path,
91
+ exc_info=True,
92
+ )
93
+ continue
94
+ if resolved and resolved.strip():
95
+ context_parts.append(resolved.strip())
96
+ if context_parts:
97
+ sections.append("## Current page context\n" + "\n\n".join(context_parts))
98
+ else:
99
+ sections.append(f"## Current page\nThe user is viewing {chat_ctx.current_path}.")
100
+
101
+ return "\n\n".join(sections)
@@ -0,0 +1,102 @@
1
+ """Composite toolset that namespaces and fail-closed-gates all ``ChatProvider`` toolsets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, replace
6
+ from typing import Any
7
+
8
+ from fastapi import FastAPI
9
+ from pydantic_ai import RunContext
10
+ from pydantic_ai.toolsets import AbstractToolset, ToolsetTool
11
+ from sm_ai.contracts import AiRequestContext, PermissionedToolset, ToolPermissionError, ToolPolicy
12
+
13
+ from sm_chat.contracts import ChatContext, ChatProvider, list_chat_providers
14
+
15
+ TOOL_NAMESPACE_SEP = "__"
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class _DenyAllPolicy(ToolPolicy):
20
+ """Fail-closed fallback policy denying every unlisted tool, even for superusers."""
21
+
22
+ def is_allowed(self, context: AiRequestContext) -> bool:
23
+ return False
24
+
25
+
26
+ _DENY_ALL = _DenyAllPolicy()
27
+
28
+
29
+ def provider_has_permitted_tools(provider: ChatProvider, ai_ctx: AiRequestContext) -> bool:
30
+ """Return True when ``ai_ctx`` is permitted to invoke at least one tool of ``provider``."""
31
+ if any(policy.is_allowed(ai_ctx) for policy in provider.policies.values()):
32
+ return True
33
+ return provider.default_policy is not None and provider.default_policy.is_allowed(ai_ctx)
34
+
35
+
36
+ def _wrap_provider(
37
+ provider: ChatProvider,
38
+ chat_ctx: ChatContext,
39
+ ) -> PermissionedToolset[ChatContext]:
40
+ raw_toolset = provider.toolset(chat_ctx) if callable(provider.toolset) else provider.toolset
41
+ return PermissionedToolset(
42
+ wrapped=raw_toolset,
43
+ policies=provider.policies,
44
+ context=lambda rc: rc.deps.ai_context,
45
+ default_policy=provider.default_policy
46
+ if provider.default_policy is not None
47
+ else _DENY_ALL,
48
+ )
49
+
50
+
51
+ def _resolve_providers(app: FastAPI, chat_ctx: ChatContext) -> tuple[ChatProvider, ...]:
52
+ return chat_ctx.providers or list_chat_providers(app)
53
+
54
+
55
+ @dataclass
56
+ class CompositeChatToolset(AbstractToolset[ChatContext]):
57
+ """Exposes every registered ``ChatProvider``'s permitted tools under ``<id>__<tool>``."""
58
+
59
+ app: FastAPI
60
+
61
+ @property
62
+ def id(self) -> str:
63
+ return "sm_chat.composite"
64
+
65
+ async def get_tools(self, ctx: RunContext[ChatContext]) -> dict[str, ToolsetTool[ChatContext]]:
66
+ combined: dict[str, ToolsetTool[ChatContext]] = {}
67
+ for provider in _resolve_providers(self.app, ctx.deps):
68
+ wrapped = _wrap_provider(provider, ctx.deps)
69
+ tools = await wrapped.get_tools(ctx)
70
+ for tool_name, tool in tools.items():
71
+ prefixed = f"{provider.id}{TOOL_NAMESPACE_SEP}{tool_name}"
72
+ combined[prefixed] = replace(
73
+ tool,
74
+ toolset=self,
75
+ tool_def=replace(tool.tool_def, name=prefixed),
76
+ )
77
+ return combined
78
+
79
+ async def call_tool(
80
+ self,
81
+ name: str,
82
+ tool_args: dict[str, Any],
83
+ ctx: RunContext[ChatContext],
84
+ tool: ToolsetTool[ChatContext],
85
+ ) -> Any:
86
+ if TOOL_NAMESPACE_SEP not in name:
87
+ raise ToolPermissionError(f"Unknown chat tool {name!r}.")
88
+ provider_id, original_name = name.split(TOOL_NAMESPACE_SEP, 1)
89
+ provider = next(
90
+ (p for p in _resolve_providers(self.app, ctx.deps) if p.id == provider_id),
91
+ None,
92
+ )
93
+ if provider is None:
94
+ raise ToolPermissionError(f"Unknown chat provider {provider_id!r}.")
95
+ wrapped = _wrap_provider(provider, ctx.deps)
96
+ inner_ctx = replace(ctx, tool_name=original_name)
97
+ inner_tool = replace(
98
+ tool,
99
+ toolset=wrapped,
100
+ tool_def=replace(tool.tool_def, name=original_name),
101
+ )
102
+ return await wrapped.call_tool(original_name, tool_args, inner_ctx, inner_tool)
@@ -0,0 +1,21 @@
1
+ """Public Python contract for ``simple_module_chat``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sm_chat.contracts.registry import (
6
+ clear_chat_providers,
7
+ get_chat_provider,
8
+ list_chat_providers,
9
+ register_chat_provider,
10
+ )
11
+ from sm_chat.contracts.types import ChatContext, ChatProvider, ChatSuggestedPrompt
12
+
13
+ __all__ = [
14
+ "ChatContext",
15
+ "ChatProvider",
16
+ "ChatSuggestedPrompt",
17
+ "clear_chat_providers",
18
+ "get_chat_provider",
19
+ "list_chat_providers",
20
+ "register_chat_provider",
21
+ ]
@@ -0,0 +1,61 @@
1
+ """Startup-order-independent app-scoped registry of ``ChatProvider`` instances."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Final
7
+
8
+ from fastapi import FastAPI
9
+
10
+ from sm_chat.contracts.types import ChatProvider
11
+
12
+ _STATE_ATTR: Final = "sm_chat_providers"
13
+ _PROVIDER_ID_RE: Final = re.compile(r"^[a-z](?:[a-z0-9_-]{0,46}[a-z0-9])?$")
14
+
15
+
16
+ def _providers_map(app: FastAPI) -> dict[str, ChatProvider]:
17
+ providers = getattr(app.state, _STATE_ATTR, None)
18
+ if not isinstance(providers, dict):
19
+ providers = {}
20
+ setattr(app.state, _STATE_ATTR, providers)
21
+ return providers
22
+
23
+
24
+ def register_chat_provider(
25
+ app: FastAPI,
26
+ provider: ChatProvider,
27
+ *,
28
+ replace: bool = False,
29
+ ) -> None:
30
+ """Register a ``ChatProvider`` on ``app.state`` regardless of module startup order."""
31
+ if "__" in provider.id or not _PROVIDER_ID_RE.fullmatch(provider.id):
32
+ raise ValueError(
33
+ f"Invalid chat provider id {provider.id!r}: must match {_PROVIDER_ID_RE.pattern!r} "
34
+ "and must not contain '__'."
35
+ )
36
+ providers = _providers_map(app)
37
+ if provider.id in providers and not replace:
38
+ raise ValueError(f"Chat provider {provider.id!r} is already registered.")
39
+ providers[provider.id] = provider
40
+
41
+
42
+ def list_chat_providers(app: FastAPI) -> tuple[ChatProvider, ...]:
43
+ """Return all ``ChatProvider`` instances registered on ``app`` in registration order."""
44
+ providers = getattr(app.state, _STATE_ATTR, None)
45
+ if not isinstance(providers, dict):
46
+ return ()
47
+ return tuple(providers.values())
48
+
49
+
50
+ def get_chat_provider(app: FastAPI, provider_id: str) -> ChatProvider | None:
51
+ """Look up a registered ``ChatProvider`` on ``app`` by ``provider_id``."""
52
+ providers = getattr(app.state, _STATE_ATTR, None)
53
+ if not isinstance(providers, dict):
54
+ return None
55
+ return providers.get(provider_id)
56
+
57
+
58
+ def clear_chat_providers(app: FastAPI) -> None:
59
+ """Remove all registered ``ChatProvider`` instances from ``app`` (test helper)."""
60
+ if hasattr(app.state, _STATE_ATTR):
61
+ setattr(app.state, _STATE_ATTR, {})
@@ -0,0 +1,51 @@
1
+ """Public contract types for modules registering tools with ``simple_module_chat``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Callable, Mapping
6
+ from dataclasses import dataclass
7
+ from typing import TYPE_CHECKING
8
+
9
+ from sm_ai.contracts import AiRequestContext, ToolPolicy
10
+
11
+ if TYPE_CHECKING:
12
+ from pydantic_ai.toolsets import AbstractToolset
13
+
14
+
15
+ @dataclass(slots=True)
16
+ class ChatContext:
17
+ """Per-turn dependency context passed to ``chat.assistant`` tools and instructions."""
18
+
19
+ ai_context: AiRequestContext
20
+ current_path: str | None = None
21
+ locale: str = "en"
22
+ providers: tuple[ChatProvider, ...] = ()
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class ChatSuggestedPrompt:
27
+ """One starter prompt chip exposed to users who hold ``required_permissions``."""
28
+
29
+ id: str
30
+ label: str
31
+ prompt: str
32
+ required_permissions: tuple[str, ...] = ()
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class ChatProvider:
37
+ """Descriptor registered by a module or host app to extend ``chat.assistant``.
38
+
39
+ Tool names are automatically prefixed as ``<provider.id>__<tool_name>`` by
40
+ ``CompositeChatToolset`` and wrapped in ``PermissionedToolset`` with a
41
+ fail-closed default policy whenever ``default_policy`` is ``None``.
42
+ """
43
+
44
+ id: str
45
+ title: str
46
+ instructions: str | Callable[[ChatContext], str | Awaitable[str]]
47
+ toolset: AbstractToolset[ChatContext] | Callable[[ChatContext], AbstractToolset[ChatContext]]
48
+ policies: Mapping[str, ToolPolicy]
49
+ default_policy: ToolPolicy | None = None
50
+ suggested_prompts: tuple[ChatSuggestedPrompt, ...] = ()
51
+ context_resolver: Callable[[ChatContext, str], Awaitable[str | None]] | None = None
@@ -0,0 +1,3 @@
1
+ """Core configuration, constants, and tenancy helpers for ``sm_chat``."""
2
+
3
+ from __future__ import annotations
@@ -0,0 +1,55 @@
1
+ """Chat module constants.
2
+
3
+ Kept out of call sites so no module name, route, role, Inertia page, or
4
+ permission appears as a bare literal (see ``scripts/check_hardcoded_strings.py``).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Final
10
+
11
+ PACKAGE: Final = "sm_chat"
12
+ LOCALE_NAMESPACE: Final = "chat"
13
+ MODULE_NAME: Final = "Chat"
14
+ DISPLAY_NAME: Final = "Chat"
15
+
16
+ AGENT_ID: Final = "chat.assistant"
17
+ AGENT_TITLE: Final = "Workspace Assistant"
18
+ AGENT_TIER: Final = "chat"
19
+
20
+ ROUTE_PREFIX_API: Final = "/api/chat"
21
+ ROUTE_CONTEXT: Final = "/context"
22
+ VIEW_PREFIX: Final = "/chat"
23
+ VIEW_INDEX: Final = "/"
24
+
25
+ MENU_URL: Final = f"{VIEW_PREFIX}/"
26
+ MENU_LABEL: Final = "Assistant"
27
+ MENU_LABEL_KEY: Final = "chat.menu.assistant"
28
+ MENU_ICON: Final = "message-square"
29
+ MENU_ORDER: Final = 15
30
+
31
+ # Modules this one depends on (value = that module's ModuleMeta.name).
32
+ _MODULE_AI: Final = "Ai"
33
+ _MODULE_SETTINGS: Final = "Settings"
34
+
35
+ # Inertia page identifier for ``modules/chat/sm_chat/pages/Index.tsx``.
36
+ _PAGE_INDEX: Final = f"{MODULE_NAME}/Index"
37
+
38
+ PERM_GROUP: Final = "chat"
39
+ PERM_GROUP_KEY: Final = "chat.permission_group"
40
+ PERM_USE: Final = "chat.use"
41
+ PERMISSIONS: Final = (PERM_USE,)
42
+
43
+ ROLE_ADMIN: Final = "admin"
44
+ ROLE_EDITOR: Final = "editor"
45
+ ROLE_VIEWER: Final = "viewer"
46
+ DEFAULT_ROLES: Final = (ROLE_ADMIN, ROLE_EDITOR, ROLE_VIEWER)
47
+
48
+ DEFAULT_MAX_REQUESTS: Final = 12
49
+ MIN_MAX_REQUESTS: Final = 1
50
+ DEFAULT_MAX_TOKENS: Final = 32_000
51
+ MIN_MAX_TOKENS: Final = 1
52
+
53
+ MAX_CURRENT_PATH_LENGTH: Final = 256
54
+ SUPPORTED_LOCALES: Final = frozenset({"en", "de"})
55
+ DEFAULT_LOCALE: Final = "en"