Metadata-Version: 2.4
Name: imio.omnia.assistant
Version: 2.0.0
Summary: AI chat assistant widget integrating iMio's Omnia API for Plone
Author-email: Antoine Duchêne <antoine.duchene@imio.be>
License-Expression: GPL-2.0-only
Project-URL: PyPI, https://pypi.org/project/imio.omnia.assistant
Project-URL: Source, https://github.com/IMIO/imio.omnia.assistant
Project-URL: Issues, https://github.com/IMIO/imio.omnia.assistant/issues
Project-URL: Changelog, https://github.com/IMIO/imio.omnia.assistant/blob/master/CHANGES.rst
Keywords: Python,Plone,CMS,AI,Omnia,Assistant,Chat
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Framework :: Plone
Classifier: Framework :: Plone :: 6.1
Classifier: Framework :: Plone :: 6.2
Classifier: Framework :: Plone :: Addon
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.12
Description-Content-Type: text/x-rst
License-File: LICENSE.GPL
License-File: LICENSE.rst
Requires-Dist: httpx2
Requires-Dist: imio.omnia.core>=2.0
Requires-Dist: plone.api
Requires-Dist: plone.app.layout
Requires-Dist: plone.app.registry
Requires-Dist: plone.base
Requires-Dist: plone.protect
Requires-Dist: plone.registry
Requires-Dist: plone.z3cform
Requires-Dist: Products.CMFCore
Requires-Dist: Products.GenericSetup
Requires-Dist: z3c.form
Requires-Dist: z3c.jbot
Requires-Dist: Zope
Requires-Dist: zope.component
Requires-Dist: zope.globalrequest
Requires-Dist: zope.i18nmessageid
Requires-Dist: zope.interface
Requires-Dist: zope.publisher
Requires-Dist: zope.schema
Provides-Extra: test
Requires-Dist: imio.omnia.core[test]; extra == "test"
Requires-Dist: plone.app.testing; extra == "test"
Requires-Dist: plone.browserlayer; extra == "test"
Requires-Dist: plone.classicui; extra == "test"
Dynamic: license-file

====================
imio.omnia.assistant
====================

A floating AI chat assistant for Plone 6, part of the
`Omnia <https://gitlab.imio.be/imio/imio.omnia>`_ suite by iMio.

This package adds a chat widget (a floating panel or a right sidebar) to
every page of the Plone site. The assistant streams responses from an
OpenAI-compatible API through a secure server-side proxy, and can read the
current page when a question needs it. It relies on ``imio.omnia.core`` for
API connectivity, authentication, and the shared Omnia control panel.


Features
========

- **Floating panel or sidebar** — a panel opening from a round button in the
  bottom-right corner, or docked on the right and pushing the page. The
  visitor can switch between both from the panel header.
- **Real-time streaming** — SSE-based chat completions streamed token by token.
- **Page reading** — the model calls a ``read_page`` tool, run in the browser,
  that returns the page content (HTML or plain text, selected by a CSS
  selector).
- **Large-context handling** — when the page content exceeds the configured
  limit, the model asks the visitor to quote the relevant passage: selecting
  text shows a « Demander à Omnia » button under it.
- **Keyboard shortcut** — ``Alt+I`` toggles the panel open/closed.
- **Secure by design** — API credentials never reach the browser; all
  requests go through ``@@omnia-assistant-api``, guarded by a Plone
  permission, an Origin check and Plone's CSRF token.
- **Configurable** — system prompt, disclaimer, model, MCP servers, display dimensions,
  conversation length, and context extraction are all adjustable from the
  control panel.


Installation
============

Requires Plone 6.1 (Python 3.12 or 3.13) or Plone 6.2 (Python 3.12 to 3.14).

Add ``imio.omnia.assistant`` to the dependencies of your project (``pip``,
``uv`` or buildout ``eggs``) and restart Plone.

The package is auto-included in Plone via ``plone.autoinclude``, so no
ZCML slug is needed.

``imio.omnia.core`` must be installed first. Its GenericSetup profile is
declared as a dependency in ``profiles/default/metadata.xml``, so installing
``imio.omnia.assistant`` via the Plone add-on control panel is sufficient.


Configuration
=============

All settings are editable from the **Assistant** tab of the Omnia control
panel (Site Setup > Omnia > ``@@omnia-assistant-settings``).

Registry settings
-----------------

Stored under the prefix
``imio.omnia.assistant.browser.controlpanel.IOmniaAssistantSettings``:

=============================  =================================================
Field                          Purpose
=============================  =================================================
``enabled``                    Enable or disable the assistant globally
                               (default: ``False``: installing the add-on
                               does not show the assistant)
``visible_to``                 ``everyone`` (default) or ``authenticated``:
                               only users logged in to the site see and can
                               call the assistant
``model``                      Model name for the OpenAI-compatible API
                               (vocabulary fetched from the API at form load)
``base_prompt``                System prompt prepended server-side to every
                               conversation
``tracing``                    Trace each reply in Langfuse through the Omnia
                               gateway (default: ``True``)
``include_page_content``       Include the current page as context
                               (default: ``True``)
``page_content_selector``      CSS selector(s) to extract page content
                               (default: ``#content``)
``page_content_clean``         Use ``innerText`` instead of ``innerHTML``
                               for cleaner extraction (default: ``False``)
``max_context_chars``          Maximum characters of page content
                               ``read_page`` returns (default: ``20000``)
``max_messages_per_session``   Maximum number of user messages allowed in a
                               single conversation (default: ``0``, unlimited)
``layout``                     ``floating`` (round button + popover) or
                               ``sidebar`` (docked right, default:
                               ``floating``)
``initial_width``              Initial panel width in pixels (default: ``380``)
``initial_height``             Initial panel height in pixels (default: ``520``)
``disclaimer``                 Disclaimer text shown at the bottom of the panel
``mcp_url``                    Base URL of the MCP servers, e.g.
                               ``https://mcp.app.imio.be``: each server answers
                               at ``{mcp_url}/{name}/mcp``. Filled from
                               ``OMNIA_MCP_URL`` on install and on every Zope
                               startup (imio.omnia.core)
``mcp_servers``                MCP servers whose tools the assistant may use,
                               picked from the servers the package offers
                               (``MCP_SERVERS``: ``omnia``)
=============================  =================================================


How it works
============

Widget loading
--------------

The default GenericSetup profile registers one Plone resource bundle,
``omnia-assistant``: the self-contained UMD build of
`@imiobe/omnia-assistant-ui <https://gitlab.imio.be/ia/omnia-assistant-ui>`_
(React and styles bundled inside, rendered in a shadow root).

An ``OmniaAssistantConfigViewlet`` registered in ``plone.htmlhead`` sets
``window.omnia_assistant_settings`` from the Plone registry (model, selectors,
layout, dimensions, etc.). The bundle reads it and mounts itself into a
``<div id="omnia-assistant-root">`` it appends to the page body.

The widget is not rendered when the ``enabled`` setting is ``False``, nor for
anonymous visitors when ``visible_to`` is ``authenticated``; the proxy then
answers ``404`` as well.
More generally, page-level availability and server-side prompt composition are
exposed through the ``IOmniaAssistantAdapter`` multi-adapter. The default
implementation reads ``enabled``, ``visible_to`` and ``base_prompt`` from the
registry.

Langfuse traces
---------------

When ``tracing`` is on, the widget posts an OTLP/JSON trace of each reply
(model calls, tool calls, token usage) to
``<portal_url>/@@omnia-assistant-api/traces``. The proxy relays it as it is,
without the system prompt, to ``{openai_api_url}/traces``: the Omnia gateway
(``/v1/traces``) forwards it to Langfuse. It answers ``404`` when ``tracing``
is off.

The gateway only accepts traces under an sso-apps token (``openai_auth_type``
set to ``oauth2``), drops the identity attributes the browser writes and
stamps its own: the pouvoir local of the token (a ``pl_<name>`` group, or the
``x-imio-municipality`` header for the applications its ``access.yaml`` lists
under ``pouvoir_local_declarers``), else the client id.

Streaming chat
--------------

Chat messages are sent as POST requests to
``<portal_url>/@@omnia-assistant-api/chat/completions`` with ``stream: true``.
The assistant proxy inherits from the shared
``imio.omnia.core.browser.proxy.OmniaOpenAIProxyView`` implementation, keeps
the shared auth/streaming behavior, and forwards the request to the
configured OpenAI-compatible gateway in real time.

The widget sends no ``Authorization`` header. The caller must have the
``imio.omnia.core: Access Omnia OpenAI proxy`` permission, which
``imio.omnia.core`` grants to ``Authenticated`` users: the same-origin
``fetch()`` carries the session cookie. Requests whose ``Origin`` host differs
from the portal's are rejected.

Every request must also carry plone.protect's CSRF token in an
``X-CSRF-TOKEN`` header, otherwise the proxy answers ``403``. The viewlet
puts it in ``request_headers`` of ``window.omnia_assistant_settings``, for
anonymous visitors too, and the widget (2.9.0 or later) adds those headers to
its chat and MCP requests.

Projects that need anonymous access can override that permission mapping in
their own GenericSetup ``rolemap.xml``.

The request payload follows the OpenAI Chat Completions format::

    {
      "model": "<configured model>",
      "messages": [
        { "role": "user", "content": "<user message>" }
      ],
      "tools": [{ "type": "function", "function": { "name": "read_page" } }],
      "stream": true
    }

When the model calls ``read_page``, the widget runs it and calls the model
again with the result as a ``tool`` message.

If ``base_prompt`` is configured, the assistant proxy prepends it server-side
as the first ``system`` message before dispatching upstream. The prompt is no
longer exposed in ``window.omnia_assistant_settings``.
Projects can override that behavior with a more specific
``IOmniaAssistantAdapter`` that changes availability rules or returns a custom
system prompt for the current context/request.

MCP tools
---------

Omnia has no endpoint listing its MCP servers yet: the package offers a fixed
list, ``MCP_SERVERS`` in ``browser/controlpanel.py`` (``omnia`` for
now). The servers checked in ``mcp_servers`` reach the widget as
``mcp_servers`` (names only). The widget lists their tools on the first
message and offers them to the model, which must support tool calling.

The widget sends its MCP JSON-RPC requests (``tools/list``, ``tools/call``)
to ``<portal_url>/@@omnia-assistant-api/{name}/mcp``. The assistant proxy
applies the same gates as for the chat (Origin, CSRF token, assistant
enabled), answers ``404`` for a server that is not checked, and relays the
request to ``{mcp_url}/{name}/mcp`` without adding the system prompt. The
upstream reply (JSON or a single SSE event) and the ``Mcp-Session-Id`` header
are passed back as they are.

The Omnia credentials (``x-imio-*`` headers and the SSO-Apps token, when
``openai_auth_type`` is ``oauth2``) are only sent when ``mcp_url`` is an
``imio.be`` host. The MCP server must accept the token of the configured
SSO-Apps realm: a staging MCP host rejects a production token.

Conversation length limit
-------------------------

When ``max_messages_per_session`` is greater than ``0``, the assistant proxy
rejects (HTTP 400) any request whose payload contains more user messages than
the configured limit; the widget shows the error in the reply. Assistant
replies and tool results do not consume the limit. Starting a new conversation
from the panel header ("Nouveau") resets the counter.

Page reading
------------

When ``include_page_content`` is ``True``, the widget offers the model a
``read_page`` tool. It returns the DOM content matched by
``page_content_selector``, as ``innerHTML`` or ``innerText`` (controlled by
``page_content_clean``). The page is never sent up front, so:

- the configured model must support tool calling (``mistral-*`` and
  ``zai-glm-5-2`` on the Omnia gateway do);
- ``base_prompt`` should tell the model to call ``read_page`` before
  answering a question about the page, otherwise it answers without reading
  it.

If the content exceeds ``max_context_chars`` characters, ``read_page`` tells
the model to ask the visitor to quote the relevant passage.

Uninstall
---------

The uninstall profile removes the assistant settings and the
``omnia-assistant`` bundle from the registry.


Frontend development
====================

The widget is developed in its own repository and published to npm as
``@imiobe/omnia-assistant-ui``. ``browser/resources/package.json`` pins the
version; the built file is committed to ``browser/static/`` and served via
``++plone++imio.omnia.assistant/``.

After bumping the version::

    make build-js          # npm ci + copy the UMD bundle to static/
    make clean-js          # remove the built artifact

Tests covering the registry export and proxy enforcement live in
``src/imio/omnia/assistant/tests/`` and should be kept in sync with any
setting or frontend behavior changes.

The frontend stack uses **Vite** (library mode), **React**,
**@assistant-ui/react** (chat runtime), **Mousetrap** (keyboard shortcuts),
and **Tailwind CSS v4**.


Development
===========

You only need `uv <https://docs.astral.sh/uv/>`_ ::

    make install         # .venv (Python 3.12, Plone 6.2.3) and instance configuration
    make create-site     # create a "Plone" site with imio.omnia.assistant installed
    make start           # http://localhost:8080/Plone (admin / admin)
    make console         # debug console on the instance
    make i18n            # update the translation files
    make remove-data     # remove all content (and the .venv)

``make clean && PLONE_VERSION=6.1-latest make install`` builds against another
Plone release, and ``DELETE_EXISTING=1 make create-site`` recreates the site.

``mx.ini`` checks out the ``plone62`` branch of ``imio.helpers`` in
``sources/``: its releases still use old-style namespaces. Drop it from
``mx.ini`` and ``.meta.toml`` (``test_deps_additional``) once it is released.

Tests and code quality are managed by `plone.meta <https://github.com/plone/meta>`_
and `tox <https://tox.wiki>`_ ::

    make test            # tests with Plone 6.2.3
    make lint            # pre-commit hooks (black, isort, flake8, zpretty, codespell...)
    make format          # reformat code
    make test-all        # lint, every supported Python / Plone version, dependency checks

Any tox environment can be run directly, e.g.
``uvx --with tox-uv tox -e py313-plone61``. Do not edit the files generated by
plone.meta: change ``.meta.toml`` and run
``uvx --from plone.meta config-package --branch current .`` instead.


Translations
============

This product has been translated into:

- English
- French


Authors
=======

- `iMio, SCRL <https://imio.be>`_
- Antoine Duchene


License
=======

The project is licensed under the GPLv2.

Contributors
============

- Antoine Duchêne, antoine.duchene@imio.be

Changelog
=========


2.0.0 (2026-12-01)
------------------

- Fill the MCP servers URL (``mcp_url``) from the ``OMNIA_MCP_URL``
  environment variable when the profile is installed, with imio.omnia.core's
  ``apply_env_to_registry``, which also fills it on every Zope startup.
  [thomlamb]

- Breaking: migrate to PEP 420 native namespaces (setuptools 81 / Plone 6.2).
  Support Plone 6.1 on Python 3.12 and 3.13, and Plone 6.2 on Python 3.12 to
  3.14. Requires imio.omnia.core 2.0, which has native namespaces too.
  [thomlamb]

- Move the package metadata from ``setup.py`` to ``pyproject.toml``, configure
  the package with plone.meta (tox, GitHub Actions, pre-commit) and replace the
  buildout development environment by a uv one on Plone 6.2.3. The
  ``z3c.autoinclude`` entry point becomes a ``plone.autoinclude`` one. Remove
  the buildout files and the Selenium robot test, which can't run on
  plone.app.robotframework 3.
  [thomlamb]

- Import ``INonInstallable``, ``IPloneSiteRoot``, ``IBundleRegistry`` and
  ``get_installer`` from ``plone.base``, and declare the dependencies the code
  imports (``httpx2``, used by the proxy, among them).
  [thomlamb]

- Fix ``update_locale``, which looked for the locales one folder too high:
  replace it by the script of pas.plugins.kimug (``make i18n``).
  [thomlamb]

- Turn the assistant off by default (``enabled``): installing the add-on no
  longer shows the widget to every visitor, each site turns it on in the
  control panel. Sites where it is already installed keep their setting.
  [thomlamb]

- Add MCP server settings to the assistant control panel: the MCP servers URL
  (``mcp_url``) and a checkbox list to pick, among the servers the package
  offers (``omnia`` for now), those whose tools the assistant may use.
  The proxy relays the widget's ``{name}/mcp`` requests to
  ``{mcp_url}/{name}/mcp``. Upgrade step 1004.
  [thomlamb]

- Add a "Visible to" setting (``visible_to``): ``everyone`` by default, or
  ``authenticated`` to hide the assistant from anonymous visitors and refuse
  their proxy requests. Upgrade step 1005.
  [thomlamb]

- Bump @imiobe/omnia-assistant-ui from 2.9.0 to 2.10.0. Its new ``tracing``
  option (Langfuse traces posted to ``{apiServiceUrl}/traces``) stays off:
  the proxy does not relay that path.
  [thomlamb]

- Add a "Trace replies in Langfuse" setting (``tracing``, on by default):
  the widget posts a trace of each reply to ``@@omnia-assistant-api/traces``,
  which the proxy relays as it is to the Omnia gateway's ``/v1/traces``.
  Upgrade step 1006.
  [thomlamb]


1.1 (2026-10-09)
----------------

- Bump @imiobe/omnia-assistant-ui from 0.3.2 to 2.9.0 and replace the HMAC
  token by Plone's CSRF token (``X-CSRF-TOKEN`` header).
  [chris-adam]

- Replace the ``mode`` setting by ``layout`` (``floating`` / ``sidebar``),
  migrated by upgrade step 1003.
  [chris-adam]

- Require imio.omnia.core 1.3: its proxy checks the CSRF token the widget
  sends.
  [duchenean]


1.0 (2026-08-03)
----------------

- OIA-241: Follow imio.omnia.core's httpx -> httpx2 migration in test mocks;
  drop unused httpx dependency.
  [duchenean]

- OIA-241: Bundle the UI from the published npm package
  @imiobe/omnia-assistant-ui (0.3.2) instead of a git submodule.
  [duchenean]


1.0a4 (2026-04-03)
------------------

- Load imio.omnia.core ZCML.
  [aduchene]


1.0a3 (2026-04-03)
------------------

- Re-release because ZCML files were lacking (2).
  [aduchene]


1.0a2 (2026-04-03)
------------------

- Re-release because ZCML files were lacking.
  [aduchene]


1.0a1 (2026-04-03)
------------------

- Initial release.
  [duchenean]
- Added floating/fixed AI chat assistant widget built with Vite + Preact
  and ``@assistant-ui/react``.
  [duchenean]
- Added real-time SSE streaming of chat completions from the
  OpenAI-compatible Omnia gateway.
  [duchenean]
- Added server-side API proxy (``@@omnia-assistant-api``) so upstream
  credentials are never exposed to the browser.
  [duchenean]
- Added HMAC-signed bearer token authentication (2-hour expiration) for
  proxy requests, signed with the Plone site keyring.
  [duchenean]
- Added automatic page content injection as conversation context, with
  configurable CSS selectors, HTML or plain-text mode, and character limit.
  [duchenean]
- Added server-side system prompt (``base_prompt``) injection — no longer
  exposed to the frontend.
  [duchenean]
- Added control panel tab (``@@omnia-assistant-settings``) in the shared
  Omnia settings UI: enable/disable, model selection, display mode
  (floating/fixed), dimensions, disclaimer, and conversation limits.
  [duchenean]
- Added ``IOmniaAssistantAdapter`` extension point for context-specific
  availability, system prompt composition, and frontend config overrides.
  [duchenean]
- Added dynamic model vocabulary fetched from the ``IOmniaOpenAIService``.
  [duchenean]
- Added ``max_messages_per_session`` enforced both client and server-side.
  [duchenean]
- Added keyboard shortcut (Alt+I) to toggle the assistant panel.
  [duchenean]
- Added i18n support (en, fr).
  [duchenean]
