simple-module-chat 0.0.20__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.
Files changed (59) hide show
  1. simple_module_chat-0.0.20/.gitignore +61 -0
  2. simple_module_chat-0.0.20/PKG-INFO +118 -0
  3. simple_module_chat-0.0.20/README.md +96 -0
  4. simple_module_chat-0.0.20/docs/extending.md +314 -0
  5. simple_module_chat-0.0.20/hatch_build.py +60 -0
  6. simple_module_chat-0.0.20/package.json +20 -0
  7. simple_module_chat-0.0.20/pyproject.toml +57 -0
  8. simple_module_chat-0.0.20/sm_chat/__init__.py +7 -0
  9. simple_module_chat-0.0.20/sm_chat/agent/__init__.py +3 -0
  10. simple_module_chat-0.0.20/sm_chat/agent/definition.py +72 -0
  11. simple_module_chat-0.0.20/sm_chat/agent/instructions.py +101 -0
  12. simple_module_chat-0.0.20/sm_chat/agent/toolset.py +102 -0
  13. simple_module_chat-0.0.20/sm_chat/contracts/__init__.py +21 -0
  14. simple_module_chat-0.0.20/sm_chat/contracts/registry.py +61 -0
  15. simple_module_chat-0.0.20/sm_chat/contracts/types.py +51 -0
  16. simple_module_chat-0.0.20/sm_chat/core/__init__.py +3 -0
  17. simple_module_chat-0.0.20/sm_chat/core/constants.py +55 -0
  18. simple_module_chat-0.0.20/sm_chat/core/settings.py +104 -0
  19. simple_module_chat-0.0.20/sm_chat/core/tenancy/__init__.py +125 -0
  20. simple_module_chat-0.0.20/sm_chat/core/tenancy/_mode.py +207 -0
  21. simple_module_chat-0.0.20/sm_chat/index.ts +26 -0
  22. simple_module_chat-0.0.20/sm_chat/locales/de.json +99 -0
  23. simple_module_chat-0.0.20/sm_chat/locales/en.json +99 -0
  24. simple_module_chat-0.0.20/sm_chat/module.py +85 -0
  25. simple_module_chat-0.0.20/sm_chat/pages/Index.tsx +108 -0
  26. simple_module_chat-0.0.20/sm_chat/ui/components/ApprovalCard.tsx +129 -0
  27. simple_module_chat-0.0.20/sm_chat/ui/components/ChatDrawerHost.test.tsx +261 -0
  28. simple_module_chat-0.0.20/sm_chat/ui/components/ChatDrawerHost.tsx +248 -0
  29. simple_module_chat-0.0.20/sm_chat/ui/components/ChatExportActions.tsx +87 -0
  30. simple_module_chat-0.0.20/sm_chat/ui/components/ChatPanel.test.tsx +209 -0
  31. simple_module_chat-0.0.20/sm_chat/ui/components/ChatPanel.tsx +225 -0
  32. simple_module_chat-0.0.20/sm_chat/ui/components/MessageList.tsx +153 -0
  33. simple_module_chat-0.0.20/sm_chat/ui/components/SuggestedPrompts.tsx +65 -0
  34. simple_module_chat-0.0.20/sm_chat/ui/components/ThreadSidebar.test.tsx +133 -0
  35. simple_module_chat-0.0.20/sm_chat/ui/components/ThreadSidebar.tsx +222 -0
  36. simple_module_chat-0.0.20/sm_chat/ui/components/ToolCallPill.tsx +105 -0
  37. simple_module_chat-0.0.20/sm_chat/ui/hooks/threadMapping.ts +248 -0
  38. simple_module_chat-0.0.20/sm_chat/ui/hooks/useChatContext.ts +46 -0
  39. simple_module_chat-0.0.20/sm_chat/ui/hooks/useChatThread.test.tsx +158 -0
  40. simple_module_chat-0.0.20/sm_chat/ui/hooks/useChatThread.ts +289 -0
  41. simple_module_chat-0.0.20/sm_chat/ui/hooks/useThreadStream.ts +87 -0
  42. simple_module_chat-0.0.20/sm_chat/ui/utils/api.ts +133 -0
  43. simple_module_chat-0.0.20/sm_chat/ui/utils/exportMarkdown.test.ts +48 -0
  44. simple_module_chat-0.0.20/sm_chat/ui/utils/exportMarkdown.ts +66 -0
  45. simple_module_chat-0.0.20/sm_chat/ui/utils/i18n.ts +59 -0
  46. simple_module_chat-0.0.20/sm_chat/ui/utils/markdown.tsx +238 -0
  47. simple_module_chat-0.0.20/sm_chat/ui/utils/sse.test.ts +184 -0
  48. simple_module_chat-0.0.20/sm_chat/ui/utils/sse.ts +171 -0
  49. simple_module_chat-0.0.20/sm_chat/ui/utils/types.ts +111 -0
  50. simple_module_chat-0.0.20/sm_chat/web/__init__.py +3 -0
  51. simple_module_chat-0.0.20/sm_chat/web/endpoints/__init__.py +3 -0
  52. simple_module_chat-0.0.20/sm_chat/web/endpoints/api.py +117 -0
  53. simple_module_chat-0.0.20/sm_chat/web/endpoints/views.py +22 -0
  54. simple_module_chat-0.0.20/sm_chat/web/shared_props.py +33 -0
  55. simple_module_chat-0.0.20/tests/agent/test_chat_agent.py +220 -0
  56. simple_module_chat-0.0.20/tests/agent/test_composite_toolset.py +184 -0
  57. simple_module_chat-0.0.20/tests/contracts/test_registry.py +86 -0
  58. simple_module_chat-0.0.20/tests/web/test_chat_web.py +201 -0
  59. simple_module_chat-0.0.20/tsconfig.json +11 -0
@@ -0,0 +1,61 @@
1
+ .claude/settings.local.json
2
+
3
+ # Python
4
+ .venv/
5
+ __pycache__/
6
+ *.pyc
7
+ *.egg-info/
8
+
9
+ # Node
10
+ node_modules/
11
+ dist/
12
+
13
+ # Built module frontend bundles (force-included into wheels at build time)
14
+ modules/*/*/static/dist/
15
+
16
+ # Host build output and the module-pages manifest regenerated by `make gen-pages`
17
+ host/static/dist/
18
+ host/client_app/modules.manifest.json
19
+ host/client_app/modules.generated.ts
20
+ host/client_app/modules.generated.css
21
+ host/client_app/modules.assets.json
22
+ host/client_app/.module-tsconfig/
23
+ host/client_app/i18n/
24
+ modules/*/*/pages/i18n.generated.ts
25
+
26
+ # Local databases. `make migrate` resolves alembic's script_location relative
27
+ # to the repo root, so running it the documented way leaves ./app.db here —
28
+ # not under host/ — and it must never be committed.
29
+ host/*.db
30
+ app.db*
31
+ # SQLite runs in WAL mode since framework 0.0.35 (#339): its sidecar files.
32
+ host/*.db-wal
33
+ host/*.db-shm
34
+ # `make beat` keeps Celery beat's schedule state in the repo root.
35
+ celerybeat-schedule*
36
+
37
+ # Runtime upload storage (PagebuilderSettings.media_root)
38
+ var/
39
+ # file_storage's local backend (DEFAULT_FS_ROOT = ./uploads), which the dev
40
+ # host creates in the repo root
41
+ uploads/
42
+
43
+ # Env
44
+ .env
45
+
46
+ # Playwright
47
+ playwright-report/
48
+ test-results/
49
+ .e2e-shards/
50
+ blob-report/
51
+ .playwright-mcp/
52
+ .playwright-cli/
53
+
54
+ # macOS
55
+ .DS_Store
56
+
57
+ # QA / verify pipeline artifacts (/qa, /vf)
58
+ .qa/
59
+ .verify/
60
+ # Scratch database a /qa run boots against, so it never touches host/app.db.
61
+ qa.db*
@@ -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,96 @@
1
+ # simple_module_chat
2
+
3
+ Generic cross-module workspace chat assistant for `simple_module_python`
4
+ applications, built on `simple_module_ai`.
5
+
6
+ Signed-in console users get a dedicated `/chat` workspace and an optional
7
+ slide-over drawer across authenticated console screens. Any module — in-repo or
8
+ host-specific — can plug tools, instructions, suggested prompts, and page
9
+ context resolvers into the assistant through `sm_chat.contracts` without
10
+ coupling `simple_module_chat` to sibling packages.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ uv add simple_module_chat
16
+ ```
17
+
18
+ `simple_module_chat` depends on `simple_module_ai` and reuses its `ai_threads`,
19
+ `ai_messages`, SSE streaming, HITL approval flow, guardrails, and billing
20
+ metering. No additional database tables or Alembic migrations are required.
21
+
22
+ ## Usage
23
+
24
+ The module auto-registers via the `simple_module` entry point (`chat =
25
+ "sm_chat.module:ChatModule"`) and registers the `chat.assistant` agent with
26
+ `simple_module_ai` during startup.
27
+
28
+ ### Registering a chat provider
29
+
30
+ Modules or host applications register tools in `on_startup` (or after
31
+ `create_app()`) regardless of startup order:
32
+
33
+ ```python
34
+ from pydantic_ai.toolsets import FunctionToolset
35
+ from sm_ai.contracts import ToolPolicy
36
+ from sm_chat.contracts import ChatContext, ChatProvider, ChatSuggestedPrompt, register_chat_provider
37
+
38
+ toolset: FunctionToolset[ChatContext] = FunctionToolset()
39
+
40
+
41
+ @toolset.tool
42
+ async def list_items(ctx) -> list[dict[str, str]]:
43
+ return [{"id": "1", "title": "Example"}]
44
+
45
+
46
+ register_chat_provider(
47
+ app,
48
+ ChatProvider(
49
+ id="example",
50
+ title="Example",
51
+ instructions="Use list_items to inspect workspace items.",
52
+ toolset=toolset,
53
+ policies={"list_items": ToolPolicy(permissions=("example.view",))},
54
+ suggested_prompts=(
55
+ ChatSuggestedPrompt(
56
+ id="list-items",
57
+ label="List items",
58
+ prompt="Show me the current items.",
59
+ required_permissions=("example.view",),
60
+ ),
61
+ ),
62
+ ),
63
+ )
64
+ ```
65
+
66
+ Every tool is exposed to the model as `<provider.id>__<tool_name>` and gated
67
+ fail-closed through `PermissionedToolset`.
68
+
69
+ See [docs/extending.md](docs/extending.md) for copy-paste recipes covering
70
+ soft-optional registration, read tools, HITL draft actions, active-screen
71
+ `context_resolver`s, suggested prompts, and the security/privacy checklist.
72
+
73
+ ## Permissions
74
+
75
+ | Permission | Description | Default roles |
76
+ | --- | --- | --- |
77
+ | `chat.use` | Access `/chat`, `/api/chat/context`, and the `chat.assistant` agent | `admin`, `editor`, `viewer` |
78
+
79
+ Underlying module tools continue to enforce their own permissions and HITL
80
+ approval policies.
81
+
82
+ ## Settings
83
+
84
+ Configured via the database-backed `ChatSettings` (`sm_chat`):
85
+
86
+ | Setting | Default | Description |
87
+ | --- | --- | --- |
88
+ | `drawer_enabled` | `true` | Show the floating assistant drawer on authenticated console pages |
89
+ | `system_prompt_extra` | `""` | Optional workspace-specific guidance appended to the assistant prompt |
90
+ | `max_requests` | `12` | Maximum LLM round-trips per turn (clamped to `sm_ai` global limits) |
91
+ | `max_tokens` | `32000` | Maximum tokens per turn (clamped to `sm_ai` global limits) |
92
+
93
+ ## Routes
94
+
95
+ - `GET /chat` — Console chat workspace (Inertia page `Chat/Index`, requires `chat.use`)
96
+ - `GET /api/chat/context` — Permitted providers, suggested prompts, and drawer/AI status (requires `chat.use`)
@@ -0,0 +1,314 @@
1
+ # Extending `simple_module_chat` — Extension Points & Best Practices
2
+
3
+ This guide documents how sibling SimpleModules and downstream host applications
4
+ extend the generic `chat.assistant` workspace assistant through `sm_chat.contracts`,
5
+ along with production security and privacy invariants.
6
+
7
+ ---
8
+
9
+ ## Extension map
10
+
11
+ | # | Extension point | Contract import (`sm_chat.contracts` / `sm_ai.contracts`) | Purpose |
12
+ |---|---|---|---|
13
+ | 1 | Soft-optional startup registration | `register_chat_provider`, `ChatProvider` | Plug tools into `chat.assistant` without requiring `simple_module_chat` at install time |
14
+ | 2 | Read-only workspace tools | `FunctionToolset(sequential=True)`, `ChatContext`, `ToolPolicy` | Expose tenant-scoped, permission-gated reads to the model |
15
+ | 3 | HITL draft-creating tools | `ToolPolicy(requires_approval=True, approval_metadata=...)` | Pause before creating drafts until the user explicitly approves |
16
+ | 4 | Active-screen context | `ChatProvider.context_resolver` | Inject safe metadata about the item currently open in the console |
17
+ | 5 | Starter prompt chips | `ChatSuggestedPrompt` | Surface permission-filtered quick prompts in the empty state |
18
+ | 6 | Security & privacy guardrails | `tenant_scope`, `ResourcePolicy`, `PermissionedToolset` | Fail-closed multi-tenancy, zero PII exposure, and single-session safety |
19
+
20
+ ---
21
+
22
+ ## 1. Register a custom `ChatProvider` in `on_startup`
23
+
24
+ Always import `simple_module_chat` inside a soft-optional helper so your module or
25
+ host app continues to boot cleanly when the `[chat]` extra is not installed.
26
+ `register_chat_provider(app, provider, replace=True)` stores providers on
27
+ `app.state` and works regardless of module startup order.
28
+
29
+ ```python
30
+ from fastapi import FastAPI
31
+ from simple_module_core.modules.module import ModuleBase, ModuleMeta
32
+
33
+
34
+ def register_chat_provider_if_installed(app: FastAPI) -> None:
35
+ """Register the Inventory chat provider when ``simple_module_chat`` is installed."""
36
+ try:
37
+ from sm_ai.contracts import ToolPolicy as _ToolPolicy # noqa: F401
38
+ from sm_chat.contracts import register_chat_provider
39
+ except ImportError:
40
+ return
41
+ register_chat_provider(app, build_chat_provider(), replace=True)
42
+
43
+
44
+ class InventoryModule(ModuleBase):
45
+ meta = ModuleMeta(
46
+ name="Inventory",
47
+ route_prefix="/api/inventory",
48
+ view_prefix="/admin/inventory",
49
+ version="0.1.0",
50
+ i18n_audience="admin",
51
+ requires_framework=">=1.0,<2.0",
52
+ )
53
+
54
+ async def on_startup(self, app: FastAPI) -> None:
55
+ register_chat_provider_if_installed(app)
56
+ ```
57
+
58
+ For a host-specific provider that does not belong to a reusable module, call
59
+ `register_chat_provider_if_installed(app)` right after `create_app()` in your
60
+ host entrypoint.
61
+
62
+ **Best practices:**
63
+ - Never store providers or database state in module-level globals —
64
+ `register_chat_provider(app, ...)` scopes registrations to `app.state`.
65
+ - Use a short, lowercase `provider.id` (e.g. `"inventory"`). Every tool is
66
+ exposed to the LLM as `<provider.id>__<tool_name>` (for example,
67
+ `inventory__list_items`).
68
+ - Always import sibling modules exclusively through their `.contracts` package.
69
+
70
+ ---
71
+
72
+ ## 2. Build read-only tools with `FunctionToolset(sequential=True)`
73
+
74
+ Use `FunctionToolset(sequential=True)` whenever tools share the request's
75
+ `AsyncSession` (`ctx.deps.ai_context.session`). SQLAlchemy's async session does
76
+ not allow concurrent queries on the same connection; `sequential=True` ensures
77
+ Pydantic AI executes tool calls one after another even when the model emits
78
+ parallel tool calls.
79
+
80
+ ```python
81
+ from typing import Any
82
+
83
+ from pydantic_ai import RunContext
84
+ from pydantic_ai.toolsets import FunctionToolset
85
+ from sm_ai.contracts import ToolPolicy
86
+ from sm_chat.contracts import ChatContext, ChatProvider
87
+ from sqlalchemy.ext.asyncio import AsyncSession
88
+ from sqlmodel import col, select
89
+
90
+ from my_app.inventory.models import InventoryItem
91
+ from my_app.inventory.tenancy import tenant_scope
92
+
93
+
94
+ def _require_session(ctx: RunContext[ChatContext]) -> AsyncSession:
95
+ session = ctx.deps.ai_context.session
96
+ if session is None:
97
+ raise RuntimeError("Inventory chat tools require an active database session.")
98
+ return session
99
+
100
+
101
+ def build_chat_provider() -> ChatProvider:
102
+ toolset: FunctionToolset[ChatContext] = FunctionToolset(sequential=True)
103
+
104
+ @toolset.tool
105
+ async def list_items(
106
+ ctx: RunContext[ChatContext],
107
+ status: str | None = None,
108
+ limit: int = 20,
109
+ ) -> list[dict[str, Any]]:
110
+ """List inventory items in the current tenant."""
111
+ db = _require_session(ctx)
112
+ clamped = 20 if limit <= 0 else min(limit, 50)
113
+ stmt = select(InventoryItem).order_by(col(InventoryItem.updated_at).desc()).limit(clamped)
114
+ if status and status.strip():
115
+ stmt = stmt.where(col(InventoryItem.status) == status.strip().lower())
116
+ with tenant_scope(ctx.deps.ai_context.tenant_id):
117
+ rows = list((await db.execute(stmt)).scalars().all())
118
+ return [
119
+ {
120
+ "id": str(item.id),
121
+ "name": item.name,
122
+ "status": item.status,
123
+ "admin_url": f"/admin/inventory/items/{item.id}",
124
+ }
125
+ for item in rows
126
+ ]
127
+
128
+ read_policy = ToolPolicy(permissions=("inventory.view",))
129
+ return ChatProvider(
130
+ id="inventory",
131
+ title="Inventory",
132
+ instructions=(
133
+ "You can inspect Inventory items and propose new draft items. "
134
+ "Always include the clickable admin_url when referring to an item."
135
+ ),
136
+ toolset=toolset,
137
+ policies={"list_items": read_policy},
138
+ )
139
+ ```
140
+
141
+ **Best practices:**
142
+ - Clamp every `limit` argument (e.g. `1..50`) and truncate long text fields
143
+ before returning them to the model.
144
+ - Return a relative `admin_url` on each item so the assistant can render
145
+ clickable Markdown links to the console screen.
146
+ - Leave `default_policy=None` on `ChatProvider` — `CompositeChatToolset` wraps
147
+ every provider in a fail-closed `PermissionedToolset`, so any tool omitted
148
+ from `policies` is hidden and denied automatically.
149
+
150
+ ---
151
+
152
+ ## 3. Add HITL draft-creating tools (`requires_approval=True`)
153
+
154
+ State-mutating tools must create **drafts only** (never publish, send, or
155
+ delete) and require explicit human approval via `ToolPolicy(requires_approval=True)`.
156
+
157
+ ```python
158
+ @toolset.tool
159
+ async def create_draft_item(
160
+ ctx: RunContext[ChatContext],
161
+ name: str,
162
+ summary: str = "",
163
+ ) -> dict[str, Any]:
164
+ """Create a new DRAFT inventory item (never published)."""
165
+ db = _require_session(ctx)
166
+ with tenant_scope(ctx.deps.ai_context.tenant_id):
167
+ item = InventoryItem(name=name.strip(), summary=summary.strip(), status="draft")
168
+ db.add(item)
169
+ await db.flush()
170
+ await db.refresh(item)
171
+ return {
172
+ "id": str(item.id),
173
+ "name": item.name,
174
+ "status": "draft",
175
+ "admin_url": f"/admin/inventory/items/{item.id}",
176
+ }
177
+ ```
178
+
179
+ Bind it with an approval policy in `ChatProvider.policies`:
180
+
181
+ ```python
182
+ draft_policy = ToolPolicy(
183
+ permissions=("inventory.edit",),
184
+ requires_approval=True,
185
+ approval_metadata={"module": "inventory", "action": "create_draft_item"},
186
+ )
187
+ policies = {
188
+ "list_items": read_policy,
189
+ "create_draft_item": draft_policy,
190
+ }
191
+ ```
192
+
193
+ When the model calls `inventory__create_draft_item`, `simple_module_ai` pauses
194
+ the run, persists `pending_approval` server-side, and renders an **Approve /
195
+ Deny** card in `<ChatPanel />`. Resuming after approval costs **0** extra
196
+ `ai.requests` units.
197
+
198
+ ---
199
+
200
+ ## 4. Add a `context_resolver` for active-screen awareness
201
+
202
+ When a user opens the floating `<ChatDrawerHost />` while viewing a specific
203
+ item in the console, `chat.assistant` passes `current_path` (from Inertia's
204
+ `page.url`) to each permitted provider's `context_resolver(chat_ctx, current_path)`.
205
+
206
+ Return a concise, safe plain-text summary when the path matches one of your
207
+ screens, or `None` otherwise:
208
+
209
+ ```python
210
+ import re
211
+ from urllib.parse import urlsplit
212
+
213
+ from sm_ai.contracts import ToolPolicy
214
+ from sm_chat.contracts import ChatContext
215
+
216
+ _ITEM_PATH_RE = re.compile(r"^/admin/inventory/items/(\d+)(?:/edit)?/?$")
217
+
218
+
219
+ async def resolve_item_context(chat_ctx: ChatContext, current_path: str) -> str | None:
220
+ match = _ITEM_PATH_RE.match(urlsplit(current_path).path)
221
+ if match is None:
222
+ return None
223
+ ai_ctx = chat_ctx.ai_context
224
+ if (
225
+ ai_ctx.session is None
226
+ or not ai_ctx.tenant_id
227
+ or not ToolPolicy(permissions=("inventory.view",)).is_allowed(ai_ctx)
228
+ ):
229
+ return None
230
+ with tenant_scope(ai_ctx.tenant_id):
231
+ item = await ai_ctx.session.get(InventoryItem, int(match.group(1)))
232
+ if item is None:
233
+ return None
234
+ return (
235
+ f"The user is currently viewing Inventory item #{item.id} "
236
+ f"(item_id={item.id}, name={item.name!r}, status={item.status})."
237
+ )
238
+ ```
239
+
240
+ Attach it to your `ChatProvider`:
241
+
242
+ ```python
243
+ ChatProvider(
244
+ ...,
245
+ context_resolver=resolve_item_context,
246
+ )
247
+ ```
248
+
249
+ **Rules for `context_resolver`:**
250
+ - Parse `current_path` with `urllib.parse.urlsplit(...)` so query parameters do
251
+ not break path matching (or read query parameters explicitly when your screen
252
+ identifies resources via `?property=...`).
253
+ - Re-check permissions, `ResourcePolicy` / ownership filters, and tenant scope
254
+ inside the resolver — never assume `current_path` is trustworthy.
255
+ - Return `None` on non-matching routes, missing rows, or unauthorized access.
256
+ - Never include PII, secrets, or raw file storage keys in the returned string.
257
+
258
+ ---
259
+
260
+ ## 5. Add `suggested_prompts`
261
+
262
+ `ChatSuggestedPrompt` chips appear in the empty state of `/chat/` and the
263
+ drawer. `GET /api/chat/context` filters them server-side against the user's
264
+ effective permissions so users only see prompts they can actually run.
265
+
266
+ ```python
267
+ from sm_chat.contracts import ChatSuggestedPrompt
268
+
269
+ suggested_prompts = (
270
+ ChatSuggestedPrompt(
271
+ id="inventory.list_recent",
272
+ label="Show recent inventory items",
273
+ prompt="List our most recently updated inventory items and their status.",
274
+ required_permissions=("inventory.view",),
275
+ ),
276
+ ChatSuggestedPrompt(
277
+ id="inventory.draft_item",
278
+ label="Create a draft inventory item",
279
+ prompt="Help me create a draft inventory item.",
280
+ required_permissions=("inventory.view", "inventory.edit"),
281
+ ),
282
+ )
283
+ ```
284
+
285
+ Namespace every `id` as `<provider.id>.<name>` to avoid collisions across
286
+ providers.
287
+
288
+ ---
289
+
290
+ ## 6. Security & privacy checklist
291
+
292
+ Before shipping a new `ChatProvider`, verify every item below:
293
+
294
+ - **Tenant scoping (fail-closed):** Wrap every ORM read/write in your module's
295
+ `tenant_scope(ctx.deps.ai_context.tenant_id)` or filter explicitly on
296
+ `col(Model.tenant_id) == tenant_id`. Refuse execution if `tenant_id` is empty.
297
+ - **Permission & resource policy parity:** Gate every tool in `policies` with
298
+ `ToolPolicy(permissions=(...))` AND apply row-level `ResourcePolicy.filter` /
299
+ ownership / draft visibility checks inside tools and `context_resolver` (e.g.
300
+ hide unpublished drafts from view-only users, enforce collection/calendar
301
+ sharing policies).
302
+ - **Zero PII exposure:** Never return user, subscriber, visitor, uploader, or
303
+ attendee names, email addresses, IP addresses, session tokens, or raw storage
304
+ keys/URLs from tools or `context_resolver`. Return editorial metadata and
305
+ aggregate counts only.
306
+ - **Draft-only writes + HITL:** Any mutating tool must create drafts only and
307
+ set `requires_approval=True` with descriptive `approval_metadata`. Never expose
308
+ publish, send, schedule, or delete tools to the assistant.
309
+ - **Single-session concurrency safety:** Always instantiate
310
+ `FunctionToolset(sequential=True)` when tools use `ctx.deps.ai_context.session`.
311
+ - **Automated coverage:** Write unit tests covering idempotent registration,
312
+ permission gating, HITL `ApprovalRequired` + approved execution, cross-tenant
313
+ isolation, no-PII assertions, and `context_resolver` (matching route,
314
+ non-matching route, unauthorized, and cross-tenant returning `None`).
@@ -0,0 +1,60 @@
1
+ """Wheel build hook: the packaged ``package.json`` points at the packaged layout (#472).
2
+
3
+ ``package.json`` lives at the module root so npm workspaces see it, and its
4
+ entry points say so: ``"./<package>/index.ts"``. The wheel copies it *into* the
5
+ package, next to ``index.ts``, where that path names a folder that does not
6
+ exist; a host that installed the wheel could not import the bare package name.
7
+ This writes the copy with the ``<package>/`` step removed.
8
+
9
+ An editable install serves the source tree, so it keeps the file as written.
10
+ The same file sits in every module that ships an entry point; keep the copies
11
+ identical (``scripts/tests/test_wheel_contents.py``).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import tempfile
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from hatchling.builders.hooks.plugin.interface import BuildHookInterface
22
+
23
+ ENTRY_KEYS = ("exports", "main", "module", "types")
24
+
25
+
26
+ def repoint(value: Any, package: str) -> Any:
27
+ """``./<package>/x`` becomes ``./x`` in a string, at any depth of ``exports``."""
28
+ prefix = f"./{package}/"
29
+ if isinstance(value, str):
30
+ return "./" + value[len(prefix) :] if value.startswith(prefix) else value
31
+ if isinstance(value, dict):
32
+ return {key: repoint(inner, package) for key, inner in value.items()}
33
+ if isinstance(value, list):
34
+ return [repoint(inner, package) for inner in value]
35
+ return value
36
+
37
+
38
+ class PackageJsonHook(BuildHookInterface):
39
+ PLUGIN_NAME = "custom"
40
+
41
+ def initialize(self, version: str, build_data: dict[str, Any]) -> None:
42
+ package = self.config["package"]
43
+ source = Path(self.root) / "package.json"
44
+ target = f"{package}/package.json"
45
+ if version == "editable":
46
+ build_data["force_include"][str(source)] = target
47
+ return
48
+ manifest = json.loads(source.read_text(encoding="utf-8"))
49
+ for key in ENTRY_KEYS:
50
+ if key in manifest:
51
+ manifest[key] = repoint(manifest[key], package)
52
+ self._scratch = tempfile.TemporaryDirectory()
53
+ packaged = Path(self._scratch.name) / "package.json"
54
+ packaged.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
55
+ build_data["force_include"][str(packaged)] = target
56
+
57
+ def finalize(self, version: str, build_data: dict[str, Any], artifact_path: str) -> None:
58
+ scratch = getattr(self, "_scratch", None)
59
+ if scratch is not None:
60
+ scratch.cleanup()
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "@simple-module-py/chat",
3
+ "version": "0.0.20",
4
+ "private": true,
5
+ "main": "./sm_chat/index.ts",
6
+ "exports": {
7
+ ".": "./sm_chat/index.ts"
8
+ },
9
+ "description": "Frontend assets for the Chat module",
10
+ "peerDependencies": {
11
+ "@inertiajs/react": "^3.9.1",
12
+ "@simple-module-py/ai": ">=0.0.18",
13
+ "@simple-module-py/ui": ">=0.0.38",
14
+ "react": "^19.3.1",
15
+ "react-dom": "^19.3.1"
16
+ },
17
+ "devDependencies": {
18
+ "@simple-module-py/tsconfig": "*"
19
+ }
20
+ }