mnemo-client 1.2.0__tar.gz → 2.0.0__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 (43) hide show
  1. {mnemo_client-1.2.0/src/mnemo_client.egg-info → mnemo_client-2.0.0}/PKG-INFO +13 -39
  2. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/README.md +12 -38
  3. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/__init__.py +3 -7
  4. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/_chat_impl.py +0 -7
  5. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/chat.py +1 -3
  6. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/embed/mnemo-chat.js +5 -5
  7. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/model.py +50 -27
  8. {mnemo_client-1.2.0 → mnemo_client-2.0.0/src/mnemo_client.egg-info}/PKG-INFO +13 -39
  9. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client.egg-info/SOURCES.txt +1 -7
  10. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/tests/test_chat.py +24 -8
  11. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/tests/test_client_credentials.py +7 -7
  12. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/tests/test_operation_validation.py +1 -23
  13. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/tests/test_rag.py +14 -0
  14. mnemo_client-1.2.0/src/mnemo_client/_network_impl.py +0 -162
  15. mnemo_client-1.2.0/src/mnemo_client/_settings_impl.py +0 -72
  16. mnemo_client-1.2.0/src/mnemo_client/network.py +0 -145
  17. mnemo_client-1.2.0/src/mnemo_client/settings.py +0 -115
  18. mnemo_client-1.2.0/tests/test_network.py +0 -114
  19. mnemo_client-1.2.0/tests/test_settings.py +0 -70
  20. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/LICENSE +0 -0
  21. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/MANIFEST.in +0 -0
  22. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/pyproject.toml +0 -0
  23. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/setup.cfg +0 -0
  24. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/_abstract.py +0 -0
  25. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/_embed_impl.py +0 -0
  26. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/_rag_impl.py +0 -0
  27. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/client.py +0 -0
  28. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/embed.py +0 -0
  29. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/embed_helpers.py +0 -0
  30. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/exception.py +0 -0
  31. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/factory.py +0 -0
  32. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/py.typed +0 -0
  33. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client/rag.py +0 -0
  34. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client.egg-info/dependency_links.txt +0 -0
  35. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/src/mnemo_client.egg-info/top_level.txt +0 -0
  36. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/tests/fake_server.py +0 -0
  37. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/tests/test_chat_stream.py +0 -0
  38. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/tests/test_embed.py +0 -0
  39. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/tests/test_embed_asset.py +0 -0
  40. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/tests/test_embed_examples.py +0 -0
  41. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/tests/test_embed_snippet.py +0 -0
  42. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/tests/test_embed_token_auth.py +0 -0
  43. {mnemo_client-1.2.0 → mnemo_client-2.0.0}/tests/test_embed_token_endpoint.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mnemo-client
3
- Version: 1.2.0
3
+ Version: 2.0.0
4
4
  Summary: Python client for the MNEMO API, the multi-tenant AI memory service from Panaxon AI
5
5
  Author: PANAXON.AI, LLC
6
6
  License-Expression: Apache-2.0
@@ -29,8 +29,9 @@ Dynamic: license-file
29
29
  # mnemo-client (Python)
30
30
 
31
31
  Python client for the [MNEMO](https://panaxon.ai) API, the multi-tenant AI memory service from Panaxon AI. It lets
32
- a Python application chat with MNEMO, query MnemoRAG, manage memory subjects and sessions, change account settings
33
- and use memory sharing, without writing any HTTP code.
32
+ a Python application chat with MNEMO, query MnemoRAG, and manage memory subjects and sessions without writing
33
+ any HTTP code. Configuration and governance (knowledge sharing, account settings, RAG configuration) are managed in
34
+ Dorothy, not through this client.
34
35
 
35
36
  - Python 3.9+
36
37
  - No runtime dependencies (HTTP through the standard library's `urllib`)
@@ -51,7 +52,7 @@ uv add mnemo-client
51
52
  poetry add mnemo-client
52
53
  ```
53
54
 
54
- To pin a version, put `mnemo-client==1.2.0` in `requirements.txt` (or `mnemo-client>=1.2,<2` to take compatible
55
+ To pin a version, put `mnemo-client==2.0.0` in `requirements.txt` (or `mnemo-client>=2,<3` to take compatible
55
56
  updates). The package has no dependencies outside the standard library.
56
57
 
57
58
  The package you install is `mnemo-client`, with a dash; the module you import is `mnemo_client`, with an underscore:
@@ -134,15 +135,13 @@ deployment, override it with `.base_url(...)`. The timeout is 120 seconds by def
134
135
  |---|---|---|
135
136
  | `MnemoChatClient` | Chat, sessions, history, subjects, plan, health | `ChatMessageResponse`, or `dict` / `list` |
136
137
  | `MnemoRAGClient` | Ask a question against a MnemoRAG configuration (Pro / Enterprise) | `RagQueryResponse` |
137
- | `MnemoSettingsClient` | Read and update account settings | `SettingsResponse` |
138
- | `MnemoNetworkClient` | Private grants, public publishing and subscriptions, affiliations | parsed JSON (`dict` / `list`) |
139
138
 
140
- Every client takes an `operation(...)` from its own `Operation` enum. The defaults are `CHAT` for chat, `QUERY`
141
- for RAG and `GET_SETTINGS` for settings. Network has no default, so you must set one. The docstring of each
139
+ Every client takes an `operation(...)` from its own `Operation` enum. The defaults are `CHAT` for chat and `QUERY`
140
+ for RAG. The docstring of each
142
141
  `Operation` member lists the builder parameters it needs and the type it returns. A missing required parameter
143
142
  fails before any request is made.
144
143
 
145
- The typed models (`ChatMessageResponse`, `RagQueryResponse`, `SettingsResponse`, ...) are frozen dataclasses. Their
144
+ The typed models (`ChatMessageResponse`, `RagQueryResponse`, ...) are frozen dataclasses. Their
146
145
  attributes are the snake_case form of the JSON fields (`total_ms`, `last_updated`), and their timestamps are
147
146
  `datetime` objects. Calls without a typed model return the parsed JSON, whose keys stay camelCase as the service
148
147
  sends them.
@@ -178,31 +177,6 @@ if answer.found:
178
177
 
179
178
  The tenant comes from your API key, so the master key cannot be used here.
180
179
 
181
- ### Settings
182
-
183
- ```python
184
- updated = (MnemoSettingsClient.Builder()
185
- .api_key(key).account_id("acct-123")
186
- .operation(MnemoSettingsClient.Operation.UPDATE_SETTINGS)
187
- .lookback_days(30)
188
- .build().execute())
189
- ```
190
-
191
- Only the settings you set are changed. `provider_api_key(...)` is your own LLM provider key. It is not the same as
192
- `api_key(...)`, which authenticates you to MNEMO.
193
-
194
- ### Network
195
-
196
- ```python
197
- (MnemoNetworkClient.Builder()
198
- .api_key(key).tenant_id("acme")
199
- .operation(MnemoNetworkClient.Operation.SUBSCRIBE)
200
- .counterpart_tenant_id("globex").subject("Roadmap")
201
- .build().execute())
202
- ```
203
-
204
- `tenant_id` is always the tenant making the call; `counterpart_tenant_id` is the other party.
205
-
206
180
  ## Embed a chat in your web app
207
181
 
208
182
  `<mnemo-chat>` puts a MNEMO chat in your own page with one script tag and one element. The page never holds an API key: your server uses this library to mint a **short-lived embed token** (15 minutes, one allowed origin, chat only) and hands it to the component.
@@ -297,7 +271,7 @@ Answers are untrusted text: the component renders a small, safe subset of Markdo
297
271
  - *"This token cannot be used from this origin" (403)*: same cause. A server-side call that sends no `Origin` header is refused too.
298
272
  - *Token endpoint 401/403*: your own sign-in check failed, or the API key behind `EmbedTokenEndpoint` is not an ADMIN key of that tenant.
299
273
  - *The chat box never appears*: the browser blocked the script (CSP), or the element was written self-closing; custom elements need `<mnemo-chat></mnemo-chat>`.
300
- - *Needs client 1.2.0 and a MNEMO backend with embed tokens (live since 2026-11-14).*
274
+ - *Needs client 1.2.0 or later and a MNEMO backend with embed tokens (live since 2026-11-14).*
301
275
 
302
276
  ## Error handling
303
277
 
@@ -337,10 +311,10 @@ This client does not cover:
337
311
  - Token-by-token streaming chat (`chat/stream`). `INIT_SESSION` does use the init event stream, but reads it to the
338
312
  end and returns the result.
339
313
  - File ingest and OCR uploads.
340
- - The administrative endpoints: account and user management, API token management, billing, and RAG configuration
341
- CRUD.
342
-
343
- The same network calls as in the Java client are not covered yet.
314
+ - Configuration and governance, which are managed in Dorothy: account and user management, API token management,
315
+ billing, account settings, knowledge sharing (the memory network) and MnemoRAG configuration. Version 2.0.0
316
+ removed `MnemoSettingsClient`, `MnemoNetworkClient` and the `RENAME_SESSION` operation for that reason (see the
317
+ changelog).
344
318
 
345
319
  ## Building and testing
346
320
 
@@ -1,8 +1,9 @@
1
1
  # mnemo-client (Python)
2
2
 
3
3
  Python client for the [MNEMO](https://panaxon.ai) API, the multi-tenant AI memory service from Panaxon AI. It lets
4
- a Python application chat with MNEMO, query MnemoRAG, manage memory subjects and sessions, change account settings
5
- and use memory sharing, without writing any HTTP code.
4
+ a Python application chat with MNEMO, query MnemoRAG, and manage memory subjects and sessions without writing
5
+ any HTTP code. Configuration and governance (knowledge sharing, account settings, RAG configuration) are managed in
6
+ Dorothy, not through this client.
6
7
 
7
8
  - Python 3.9+
8
9
  - No runtime dependencies (HTTP through the standard library's `urllib`)
@@ -23,7 +24,7 @@ uv add mnemo-client
23
24
  poetry add mnemo-client
24
25
  ```
25
26
 
26
- To pin a version, put `mnemo-client==1.2.0` in `requirements.txt` (or `mnemo-client>=1.2,<2` to take compatible
27
+ To pin a version, put `mnemo-client==2.0.0` in `requirements.txt` (or `mnemo-client>=2,<3` to take compatible
27
28
  updates). The package has no dependencies outside the standard library.
28
29
 
29
30
  The package you install is `mnemo-client`, with a dash; the module you import is `mnemo_client`, with an underscore:
@@ -106,15 +107,13 @@ deployment, override it with `.base_url(...)`. The timeout is 120 seconds by def
106
107
  |---|---|---|
107
108
  | `MnemoChatClient` | Chat, sessions, history, subjects, plan, health | `ChatMessageResponse`, or `dict` / `list` |
108
109
  | `MnemoRAGClient` | Ask a question against a MnemoRAG configuration (Pro / Enterprise) | `RagQueryResponse` |
109
- | `MnemoSettingsClient` | Read and update account settings | `SettingsResponse` |
110
- | `MnemoNetworkClient` | Private grants, public publishing and subscriptions, affiliations | parsed JSON (`dict` / `list`) |
111
110
 
112
- Every client takes an `operation(...)` from its own `Operation` enum. The defaults are `CHAT` for chat, `QUERY`
113
- for RAG and `GET_SETTINGS` for settings. Network has no default, so you must set one. The docstring of each
111
+ Every client takes an `operation(...)` from its own `Operation` enum. The defaults are `CHAT` for chat and `QUERY`
112
+ for RAG. The docstring of each
114
113
  `Operation` member lists the builder parameters it needs and the type it returns. A missing required parameter
115
114
  fails before any request is made.
116
115
 
117
- The typed models (`ChatMessageResponse`, `RagQueryResponse`, `SettingsResponse`, ...) are frozen dataclasses. Their
116
+ The typed models (`ChatMessageResponse`, `RagQueryResponse`, ...) are frozen dataclasses. Their
118
117
  attributes are the snake_case form of the JSON fields (`total_ms`, `last_updated`), and their timestamps are
119
118
  `datetime` objects. Calls without a typed model return the parsed JSON, whose keys stay camelCase as the service
120
119
  sends them.
@@ -150,31 +149,6 @@ if answer.found:
150
149
 
151
150
  The tenant comes from your API key, so the master key cannot be used here.
152
151
 
153
- ### Settings
154
-
155
- ```python
156
- updated = (MnemoSettingsClient.Builder()
157
- .api_key(key).account_id("acct-123")
158
- .operation(MnemoSettingsClient.Operation.UPDATE_SETTINGS)
159
- .lookback_days(30)
160
- .build().execute())
161
- ```
162
-
163
- Only the settings you set are changed. `provider_api_key(...)` is your own LLM provider key. It is not the same as
164
- `api_key(...)`, which authenticates you to MNEMO.
165
-
166
- ### Network
167
-
168
- ```python
169
- (MnemoNetworkClient.Builder()
170
- .api_key(key).tenant_id("acme")
171
- .operation(MnemoNetworkClient.Operation.SUBSCRIBE)
172
- .counterpart_tenant_id("globex").subject("Roadmap")
173
- .build().execute())
174
- ```
175
-
176
- `tenant_id` is always the tenant making the call; `counterpart_tenant_id` is the other party.
177
-
178
152
  ## Embed a chat in your web app
179
153
 
180
154
  `<mnemo-chat>` puts a MNEMO chat in your own page with one script tag and one element. The page never holds an API key: your server uses this library to mint a **short-lived embed token** (15 minutes, one allowed origin, chat only) and hands it to the component.
@@ -269,7 +243,7 @@ Answers are untrusted text: the component renders a small, safe subset of Markdo
269
243
  - *"This token cannot be used from this origin" (403)*: same cause. A server-side call that sends no `Origin` header is refused too.
270
244
  - *Token endpoint 401/403*: your own sign-in check failed, or the API key behind `EmbedTokenEndpoint` is not an ADMIN key of that tenant.
271
245
  - *The chat box never appears*: the browser blocked the script (CSP), or the element was written self-closing; custom elements need `<mnemo-chat></mnemo-chat>`.
272
- - *Needs client 1.2.0 and a MNEMO backend with embed tokens (live since 2026-11-14).*
246
+ - *Needs client 1.2.0 or later and a MNEMO backend with embed tokens (live since 2026-11-14).*
273
247
 
274
248
  ## Error handling
275
249
 
@@ -309,10 +283,10 @@ This client does not cover:
309
283
  - Token-by-token streaming chat (`chat/stream`). `INIT_SESSION` does use the init event stream, but reads it to the
310
284
  end and returns the result.
311
285
  - File ingest and OCR uploads.
312
- - The administrative endpoints: account and user management, API token management, billing, and RAG configuration
313
- CRUD.
314
-
315
- The same network calls as in the Java client are not covered yet.
286
+ - Configuration and governance, which are managed in Dorothy: account and user management, API token management,
287
+ billing, account settings, knowledge sharing (the memory network) and MnemoRAG configuration. Version 2.0.0
288
+ removed `MnemoSettingsClient`, `MnemoNetworkClient` and the `RENAME_SESSION` operation for that reason (see the
289
+ changelog).
316
290
 
317
291
  ## Building and testing
318
292
 
@@ -37,17 +37,15 @@ from .model import (
37
37
  Attachment,
38
38
  ChatMessageResponse,
39
39
  EmbedToken,
40
+ Groundedness,
40
41
  RagQueryResponse,
41
42
  ResponseTiming,
42
- SettingsResponse,
43
43
  StreamEvent,
44
44
  TokenUsage,
45
45
  )
46
- from .network import MnemoNetworkClient
47
46
  from .rag import MnemoRAGClient
48
- from .settings import MnemoSettingsClient
49
47
 
50
- __version__ = "1.2.0"
48
+ __version__ = "2.0.0"
51
49
 
52
50
  __all__ = [
53
51
  "Attachment",
@@ -55,6 +53,7 @@ __all__ = [
55
53
  "EmbedSnippet",
56
54
  "EmbedToken",
57
55
  "EmbedTokenEndpoint",
56
+ "Groundedness",
58
57
  "MnemoChatClient",
59
58
  "MnemoClient",
60
59
  "MnemoClientBuilder",
@@ -62,12 +61,9 @@ __all__ = [
62
61
  "MnemoClientFactory",
63
62
  "MnemoEmbedClient",
64
63
  "MnemoError",
65
- "MnemoNetworkClient",
66
64
  "MnemoRAGClient",
67
- "MnemoSettingsClient",
68
65
  "RagQueryResponse",
69
66
  "ResponseTiming",
70
- "SettingsResponse",
71
67
  "StreamEvent",
72
68
  "TokenUsage",
73
69
  ]
@@ -53,7 +53,6 @@ class MnemoChatClientImpl(AbstractMnemoClient, MnemoChatClient):
53
53
  Op.CHAT: self._chat,
54
54
  Op.LIST_SESSIONS: self._list_sessions,
55
55
  Op.GET_HISTORY: self._get_history,
56
- Op.RENAME_SESSION: self._rename_session,
57
56
  Op.CLOSE_SESSION: self._close_session,
58
57
  Op.LIST_SUBJECTS: self._list_subjects,
59
58
  Op.DELETE_SUBJECT: self._delete_subject,
@@ -120,12 +119,6 @@ class MnemoChatClientImpl(AbstractMnemoClient, MnemoChatClient):
120
119
  tenantId=_require(self._tenant_id(), "tenant_id"), before=b._before,
121
120
  size=b._size))
122
121
 
123
- def _rename_session(self, base: str) -> Dict[str, Any]:
124
- b = self._builder
125
- return self._send("PATCH", _path(base, "mnemo/sessions/{id}/name", id=_require(b._session_id, "session_id")),
126
- _body(tenantId=_require(self._tenant_id(), "tenant_id"),
127
- sessionName=_require(b._session_name, "session_name")))
128
-
129
122
  def _close_session(self, base: str) -> None:
130
123
  b = self._builder
131
124
  return self._send("DELETE", _query(_path(base, "mnemo/sessions/{id}", id=_require(b._session_id, "session_id")),
@@ -82,8 +82,6 @@ class MnemoChatClient(MnemoClient):
82
82
  GET_HISTORY = "GET_HISTORY"
83
83
  """One page of a session's history, newest first; needs tenant_id, session_id, optional before/size.
84
84
  Returns ``dict``."""
85
- RENAME_SESSION = "RENAME_SESSION"
86
- """Renames a session; needs tenant_id, session_id, session_name. Returns ``dict``."""
87
85
  CLOSE_SESSION = "CLOSE_SESSION"
88
86
  """Closes a session, or deletes it when ``permanent``; needs tenant_id, session_id. Returns ``None``."""
89
87
  LIST_SUBJECTS = "LIST_SUBJECTS"
@@ -132,7 +130,7 @@ class MnemoChatClient(MnemoClient):
132
130
  return self
133
131
 
134
132
  def session_name(self, session_name: str) -> MnemoChatClient.Builder:
135
- """The name for ``INIT_SESSION`` (optional), or the new name for ``RENAME_SESSION``."""
133
+ """The name for ``INIT_SESSION`` (optional)."""
136
134
  self._session_name = session_name
137
135
  return self
138
136
 
@@ -1,9 +1,9 @@
1
1
  /*! @panaxon/mnemo-client <mnemo-chat> - Apache-2.0 - (c) PANAXON.AI, LLC */
2
- "use strict";(()=>{var Q=Object.defineProperty;var X=(i,t,e)=>t in i?Q(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var a=(i,t,e)=>X(i,typeof t!="symbol"?t+"":t,e);var h=class extends Error{constructor(e,s=0,n){super(e.message,n);a(this,"error");a(this,"httpStatus");this.name="MnemoClientException",this.error=e,this.httpStatus=s}};var l=class i{constructor(t,e){a(this,"code");a(this,"message");this.code=t,this.message=e??i.defaultMessage(t)}};(s=>{let i;(c=>(c.UNDEFINED_ERROR="MNERR-0000",c.INVALID_REQUEST="MNERR-0001",c.MISSING_API_KEY="MNERR-0002",c.UNAUTHORIZED="MNERR-0401",c.FORBIDDEN="MNERR-0403",c.NOT_FOUND="MNERR-0404",c.RATE_LIMITED="MNERR-0429",c.SERVER_ERROR="MNERR-0500",c.IO_ERROR="MNERR-0600",c.SERIALIZATION_ERROR="MNERR-0601",c.INIT_FAILED="MNERR-0700"))(i=s.Code||(s.Code={}));let t={"MNERR-0000":"Undefined error","MNERR-0001":"Invalid request","MNERR-0002":"API key is required","MNERR-0401":"Missing or invalid API key","MNERR-0403":"Access denied or plan does not include this feature","MNERR-0404":"Resource not found","MNERR-0429":"Rate limit or quota exceeded","MNERR-0500":"MNEMO server error","MNERR-0600":"Unable to reach the MNEMO service","MNERR-0601":"Unable to read the MNEMO response","MNERR-0700":"Session initialization failed"};function e(n){return t[n]}s.defaultMessage=e})(l||(l={}));function ee(){return typeof window<"u"||typeof globalThis.document<"u"}var A=class A{constructor(){a(this,"_apiKey");a(this,"_clientId");a(this,"_clientSecret");a(this,"_embedToken");a(this,"_allowApiKeyInBrowser",!1);a(this,"_oauth",{});a(this,"_baseUrl",A.DEFAULT_BASE_URL);a(this,"_tenantId");a(this,"_timeoutMs",12e4)}apiKey(t){return this.refuseInBrowser("apiKey"),this._apiKey=t,this}clientCredentials(t,e){return this.refuseInBrowser("clientCredentials"),this._clientId=t,this._clientSecret=e,this}embedToken(t){return this._embedToken=t,this}allowApiKeyInBrowser(t){return this._allowApiKeyInBrowser=t,this}baseUrl(t){return this._baseUrl=t,this}tenantId(t){return this._tenantId=t,this}timeout(t){return this._timeoutMs=t,this}refuseInBrowser(t){if(!this._allowApiKeyInBrowser&&ee())throw new h(new l(l.Code.INVALID_REQUEST,`${t} would be visible to every visitor of the page; use embedToken in a browser (or call allowApiKeyInBrowser(true) first if this is deliberate)`))}};a(A,"DEFAULT_BASE_URL","https://mnemo-api.panaxon.ai/api");var y=A;var te="X-Mnemo-Api-Token",ne=6e4,C=class{constructor(t){a(this,"settings");this.settings=t}async withTarget(t){let e=!(E(this.settings._clientId)&&E(this.settings._clientSecret)),s=!E(this.settings._embedToken);if(e&&!E(this.settings._apiKey))throw S("set either apiKey or clientCredentials, not both");if(s&&!E(this.settings._apiKey))throw S("set either apiKey or embedToken, not both");if(s&&e)throw S("set either clientCredentials or embedToken, not both");if(e&&(E(this.settings._clientId)||E(this.settings._clientSecret)))throw S("clientCredentials needs both a client id and a client secret");if(!e&&!s&&E(this.settings._apiKey))throw new h(new l(l.Code.MISSING_API_KEY));if(E(this.settings._baseUrl))throw S("baseUrl is required");ae(this.settings._baseUrl);let n=this.settings._timeoutMs;if(typeof n!="number"||!Number.isFinite(n)||n<0)throw S("timeout must be zero or positive");return t(this.settings._baseUrl.replace(/\/+$/,""))}async send(t,e,s,n=!0){let r=await this.request(t,e,"application/json",s);return!n||r.length===0?null:T(r)}async sendEventStream(t,e,s){return se(await this.request(t,e,"text/event-stream",s))}async streamEvents(t,e,s){let n=await this.withAuth(r=>this.open(t,e,"text/event-stream",s,r));return re(n)}async request(t,e,s,n){return this.withAuth(async r=>{let o=await this.open(t,e,s,n,r);return this.text(o)})}async withAuth(t){if(E(this.settings._clientId)){let e=E(this.settings._embedToken)?this.settings._apiKey:this.settings._embedToken;return t({[te]:e})}try{return await t(await this.bearer(!1))}catch(e){if(!(e instanceof h)||e.httpStatus!==401)throw e}return t(await this.bearer(!0))}async bearer(t){return{Authorization:"Bearer "+await this.accessToken(t)}}async accessToken(t){let s=this.settings._oauth;return!t&&s.token!==void 0&&s.token.expiresAt-Date.now()>ne?s.token.value:(s.fetch===void 0&&(s.fetch=this.fetchToken().finally(()=>{s.fetch=void 0})),s.fetch)}async fetchToken(){let t=this.settings,e=`${encodeURIComponent(t._clientId)}:${encodeURIComponent(t._clientSecret)}`,s=await this.perform("POST",t._baseUrl.replace(/\/+$/,"")+"/oauth/token","application/json",new URLSearchParams({grant_type:"client_credentials"}),{Authorization:"Basic "+btoa(e)}),n=T(s),r=Number(n?.expires_in);if(typeof n?.access_token!="string"||!Number.isFinite(r))throw new h(new l(l.Code.SERIALIZATION_ERROR));return t._oauth.token={value:n.access_token,expiresAt:Date.now()+r*1e3},n.access_token}async perform(t,e,s,n,r){return this.text(await this.open(t,e,s,n,r))}async text(t){try{let e=await t.text();return t.status===204?"":e}catch(e){throw new h(new l(l.Code.IO_ERROR),0,{cause:e})}}async open(t,e,s,n,r){let o={Accept:s,...r},d;n instanceof URLSearchParams?d=n:n!==void 0&&(o["Content-Type"]="application/json",d=JSON.stringify(n));let g=this.settings._timeoutMs,p=0;try{let m=await fetch(e,{method:t.toUpperCase(),headers:o,body:d,redirect:"manual",signal:g>0?AbortSignal.timeout(g):void 0});if(p=m.status,p>=300&&p<400)throw new h(new l(l.Code.INVALID_REQUEST,`the service answered with a redirect (HTTP ${p}), which is not followed so the credentials are never sent to another location; check the baseUrl`),p);if(p>=400)throw ie(p,await m.text());return m}catch(m){throw m instanceof h?m:new h(new l(l.Code.IO_ERROR),0,{cause:m})}}tenantId(){return this.settings._tenantId}};function se(i){let t=new N;return[...t.push(i),...t.end()]}async function*re(i){let t=i.body;if(t==null)return;let e=t.getReader(),s=new TextDecoder,n=new N;try{for(;;){let r;try{r=await e.read()}catch(o){throw new h(new l(l.Code.IO_ERROR),0,{cause:o})}if(r.done)break;for(let o of n.push(s.decode(r.value,{stream:!0})))yield{event:o.name,data:o.data}}for(let r of[...n.push(s.decode()),...n.end()])yield{event:r.name,data:r.data}}finally{await e.cancel().catch(()=>{})}}var N=class{constructor(){a(this,"buffer","");a(this,"name",null);a(this,"data",[]);a(this,"open",!1)}push(t){this.buffer+=t;let e=this.buffer.endsWith("\r")?"\r":"",s=(e?this.buffer.slice(0,-1):this.buffer).split(/\r\n|\r|\n/);this.buffer=s.pop()+e;let n=[];for(let r of s)this.line(r,n);return n}end(){let t=[];return this.buffer.length>0&&(this.line(this.buffer.replace(/\r$/,""),t),this.buffer=""),this.dispatch(t),t}line(t,e){if(t.length===0)this.dispatch(e);else if(!t.startsWith(":")){let s=t.indexOf(":"),n=s<0?t:t.substring(0,s),r=s<0?"":t.substring(s+1);r.startsWith(" ")&&(r=r.substring(1)),n==="event"?(this.name=r,this.open=!0):n==="data"&&(this.data.push(r),this.open=!0)}}dispatch(t){this.open&&t.push({name:this.name??"message",data:this.data.join(`
3
- `)}),this.name=null,this.data=[],this.open=!1}};function T(i){try{return JSON.parse(i)}catch(t){throw new h(new l(l.Code.SERIALIZATION_ERROR),0,{cause:t})}}function ie(i,t){let e;i===401?e=l.Code.UNAUTHORIZED:i===403?e=l.Code.FORBIDDEN:i===404?e=l.Code.NOT_FOUND:i===429?e=l.Code.RATE_LIMITED:i>=500?e=l.Code.SERVER_ERROR:e=l.Code.INVALID_REQUEST;let s=null;try{let n=JSON.parse(t)?.error;s=n==null?null:String(n)}catch{}return new h(new l(e,s),i)}var oe=new Set(["localhost","127.0.0.1","[::1]"]);function ae(i){let t;try{t=new URL(i.trim())}catch{throw S("baseUrl is not a valid URL")}if(!(t.protocol==="https:"||t.protocol==="http:"&&oe.has(t.hostname)))throw S("baseUrl must use https (http is allowed only for localhost, 127.0.0.1 and ::1)")}function E(i){return i==null||i.trim().length===0}function u(i,t){if(E(i))throw S(`${t} is required`);return i}function S(i){return new h(new l(l.Code.INVALID_REQUEST,i))}function R(i){let t={};for(let[e,s]of Object.entries(i))s!=null&&(t[e]=s);return t}function w(i,t){let e=[];for(let[s,n]of Object.entries(t))n!=null&&e.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(n))}`);return e.length===0?i:`${i}?${e.join("&")}`}function f(i,t,e={}){return`${i}/${t.replace(/\{(\w+)}/g,(s,n)=>encodeURIComponent(e[n]))}`}var M=class extends C{constructor(e){super(e);a(this,"builder");this.builder=e}async execute(){let e=this.builder._operation;if(e==null)throw S("operation is required");let s=I.Operation;return this.withTarget(async n=>{switch(e){case s.INIT_SESSION:return this.initSession(n);case s.CHAT:return this.chat(n);case s.CHAT_STREAM:return this.chatStream(n);case s.LIST_SESSIONS:return this.listSessions(n);case s.GET_HISTORY:return this.getHistory(n);case s.RENAME_SESSION:return this.renameSession(n);case s.CLOSE_SESSION:return this.closeSession(n);case s.LIST_SUBJECTS:return this.listSubjects(n);case s.DELETE_SUBJECT:return this.deleteSubject(n);case s.UPDATE_SUBJECT_DESCRIPTION:return this.updateSubjectDescription(n);case s.GET_PLAN:return this.getPlan(n);case s.HEALTH:return this.health(n);default:throw S(`unknown operation ${String(e)}`)}})}async initSession(e){let s=await this.sendEventStream("POST",f(e,"mnemo/init/stream"),R({tenantId:u(this.tenantId(),"tenantId"),sessionId:u(this.builder._sessionId,"sessionId"),sessionName:this.builder._sessionName})),n=[],r=null;for(let o of s)if(o.name==="init-stage")n.push(T(o.data));else if(o.name==="complete")r=T(o.data);else if(o.name==="error"){let d=T(o.data)?.error;throw new h(new l(l.Code.INIT_FAILED,d==null?o.data:String(d)))}if(r==null)throw new h(new l(l.Code.INIT_FAILED,"The service ended the stream before initialization completed"));return{...r,ready:!0,stages:n}}chat(e){return this.send("POST",f(e,"mnemo/chat"),R({tenantId:u(this.tenantId(),"tenantId"),sessionId:u(this.builder._sessionId,"sessionId"),message:u(this.builder._message,"message")}))}chatStream(e){return this.streamEvents("POST",f(e,"mnemo/chat/stream"),R({tenantId:u(this.tenantId(),"tenantId"),sessionId:u(this.builder._sessionId,"sessionId"),message:u(this.builder._message,"message")}))}listSessions(e){return this.send("GET",w(f(e,"mnemo/sessions"),{tenantId:u(this.tenantId(),"tenantId"),q:this.builder._query,page:this.builder._page,size:this.builder._size}))}getHistory(e){return this.send("GET",w(f(e,"mnemo/sessions/{id}/history",{id:u(this.builder._sessionId,"sessionId")}),{tenantId:u(this.tenantId(),"tenantId"),before:this.builder._before,size:this.builder._size}))}renameSession(e){return this.send("PATCH",f(e,"mnemo/sessions/{id}/name",{id:u(this.builder._sessionId,"sessionId")}),R({tenantId:u(this.tenantId(),"tenantId"),sessionName:u(this.builder._sessionName,"sessionName")}))}closeSession(e){return this.send("DELETE",w(f(e,"mnemo/sessions/{id}",{id:u(this.builder._sessionId,"sessionId")}),{tenantId:u(this.tenantId(),"tenantId"),permanent:this.builder._permanent}),void 0,!1)}listSubjects(e){return this.send("GET",w(f(e,"mnemo/subjects"),{tenantId:u(this.tenantId(),"tenantId")}))}deleteSubject(e){return this.send("DELETE",w(f(e,"mnemo/subject/{name}",{name:u(this.builder._subjectName,"subjectName")}),{tenantId:u(this.tenantId(),"tenantId")}),void 0,!1)}updateSubjectDescription(e){return this.send("PATCH",f(e,"mnemo/subject/{name}/description",{name:u(this.builder._subjectName,"subjectName")}),R({tenantId:u(this.tenantId(),"tenantId"),description:this.builder._description}))}getPlan(e){return this.send("GET",w(f(e,"mnemo/plan"),{tenantId:u(this.tenantId(),"tenantId")}))}health(e){return this.send("GET",f(e,"mnemo/health"))}};var I;(e=>{let i;(c=>(c.INIT_SESSION="INIT_SESSION",c.CHAT="CHAT",c.CHAT_STREAM="CHAT_STREAM",c.LIST_SESSIONS="LIST_SESSIONS",c.GET_HISTORY="GET_HISTORY",c.RENAME_SESSION="RENAME_SESSION",c.CLOSE_SESSION="CLOSE_SESSION",c.LIST_SUBJECTS="LIST_SUBJECTS",c.DELETE_SUBJECT="DELETE_SUBJECT",c.UPDATE_SUBJECT_DESCRIPTION="UPDATE_SUBJECT_DESCRIPTION",c.GET_PLAN="GET_PLAN",c.HEALTH="HEALTH"))(i=e.Operation||(e.Operation={}));class t extends y{constructor(){super(...arguments);a(this,"_operation","CHAT");a(this,"_sessionId");a(this,"_message");a(this,"_sessionName");a(this,"_subjectName");a(this,"_description");a(this,"_query");a(this,"_page");a(this,"_size");a(this,"_before");a(this,"_permanent",!1)}operation(r){return this._operation=r,this}sessionId(r){return this._sessionId=r,this}message(r){return this._message=r,this}sessionName(r){return this._sessionName=r,this}subjectName(r){return this._subjectName=r,this}description(r){return this._description=r,this}query(r){return this._query=r,this}page(r){return this._page=r,this}size(r){return this._size=r,this}before(r){return this._before=r,this}permanent(r){return this._permanent=r,this}build(){return new M(this)}}e.Builder=t})(I||(I={}));var le=new Set(["http:","https:","mailto:"]);function H(i){let t=i.trim();if(t.length===0||/[\u0000-\u001f\u007f\s]/.test(t))return null;let e;try{e=new URL(t)}catch{return null}return le.has(e.protocol)?e.href:null}function D(i,t){let e=t.createDocumentFragment();if(i.length>1e5){for(let s of i.split(/\n{2,}/)){let n=t.createElement("p");n.textContent=s,e.appendChild(n)}return e}return $(i.replace(/\r\n?/g,`
2
+ "use strict";(()=>{var Q=Object.defineProperty;var X=(i,t,e)=>t in i?Q(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var a=(i,t,e)=>X(i,typeof t!="symbol"?t+"":t,e);var c=class extends Error{constructor(e,s=0,n){super(e.message,n);a(this,"error");a(this,"httpStatus");this.name="MnemoClientException",this.error=e,this.httpStatus=s}};var l=class i{constructor(t,e){a(this,"code");a(this,"message");this.code=t,this.message=e??i.defaultMessage(t)}};(s=>{let i;(S=>(S.UNDEFINED_ERROR="MNERR-0000",S.INVALID_REQUEST="MNERR-0001",S.MISSING_API_KEY="MNERR-0002",S.UNAUTHORIZED="MNERR-0401",S.FORBIDDEN="MNERR-0403",S.NOT_FOUND="MNERR-0404",S.RATE_LIMITED="MNERR-0429",S.SERVER_ERROR="MNERR-0500",S.IO_ERROR="MNERR-0600",S.SERIALIZATION_ERROR="MNERR-0601",S.INIT_FAILED="MNERR-0700"))(i=s.Code||(s.Code={}));let t={"MNERR-0000":"Undefined error","MNERR-0001":"Invalid request","MNERR-0002":"API key is required","MNERR-0401":"Missing or invalid API key","MNERR-0403":"Access denied or plan does not include this feature","MNERR-0404":"Resource not found","MNERR-0429":"Rate limit or quota exceeded","MNERR-0500":"MNEMO server error","MNERR-0600":"Unable to reach the MNEMO service","MNERR-0601":"Unable to read the MNEMO response","MNERR-0700":"Session initialization failed"};function e(n){return t[n]}s.defaultMessage=e})(l||(l={}));function ee(){return typeof window<"u"||typeof globalThis.document<"u"}var C=class C{constructor(){a(this,"_apiKey");a(this,"_clientId");a(this,"_clientSecret");a(this,"_embedToken");a(this,"_allowApiKeyInBrowser",!1);a(this,"_oauth",{});a(this,"_baseUrl",C.DEFAULT_BASE_URL);a(this,"_tenantId");a(this,"_timeoutMs",12e4)}apiKey(t){return this.refuseInBrowser("apiKey"),this._apiKey=t,this}clientCredentials(t,e){return this.refuseInBrowser("clientCredentials"),this._clientId=t,this._clientSecret=e,this}embedToken(t){return this._embedToken=t,this}allowApiKeyInBrowser(t){return this._allowApiKeyInBrowser=t,this}baseUrl(t){return this._baseUrl=t,this}tenantId(t){return this._tenantId=t,this}timeout(t){return this._timeoutMs=t,this}refuseInBrowser(t){if(!this._allowApiKeyInBrowser&&ee())throw new c(new l(l.Code.INVALID_REQUEST,`${t} would be visible to every visitor of the page; use embedToken in a browser (or call allowApiKeyInBrowser(true) first if this is deliberate)`))}};a(C,"DEFAULT_BASE_URL","https://mnemo-api.panaxon.ai/api");var T=C;var te="X-Mnemo-Api-Token",ne=6e4,N=class{constructor(t){a(this,"settings");this.settings=t}async withTarget(t){let e=!(b(this.settings._clientId)&&b(this.settings._clientSecret)),s=!b(this.settings._embedToken);if(e&&!b(this.settings._apiKey))throw E("set either apiKey or clientCredentials, not both");if(s&&!b(this.settings._apiKey))throw E("set either apiKey or embedToken, not both");if(s&&e)throw E("set either clientCredentials or embedToken, not both");if(e&&(b(this.settings._clientId)||b(this.settings._clientSecret)))throw E("clientCredentials needs both a client id and a client secret");if(!e&&!s&&b(this.settings._apiKey))throw new c(new l(l.Code.MISSING_API_KEY));if(b(this.settings._baseUrl))throw E("baseUrl is required");ae(this.settings._baseUrl);let n=this.settings._timeoutMs;if(typeof n!="number"||!Number.isFinite(n)||n<0)throw E("timeout must be zero or positive");return t(this.settings._baseUrl.replace(/\/+$/,""))}async send(t,e,s,n=!0){let r=await this.request(t,e,"application/json",s);return!n||r.length===0?null:R(r)}async sendEventStream(t,e,s){return se(await this.request(t,e,"text/event-stream",s))}async streamEvents(t,e,s){let n=await this.withAuth(r=>this.open(t,e,"text/event-stream",s,r));return re(n)}async request(t,e,s,n){return this.withAuth(async r=>{let o=await this.open(t,e,s,n,r);return this.text(o)})}async withAuth(t){if(b(this.settings._clientId)){let e=b(this.settings._embedToken)?this.settings._apiKey:this.settings._embedToken;return t({[te]:e})}try{return await t(await this.bearer(!1))}catch(e){if(!(e instanceof c)||e.httpStatus!==401)throw e}return t(await this.bearer(!0))}async bearer(t){return{Authorization:"Bearer "+await this.accessToken(t)}}async accessToken(t){let s=this.settings._oauth;return!t&&s.token!==void 0&&s.token.expiresAt-Date.now()>ne?s.token.value:(s.fetch===void 0&&(s.fetch=this.fetchToken().finally(()=>{s.fetch=void 0})),s.fetch)}async fetchToken(){let t=this.settings,e=`${encodeURIComponent(t._clientId)}:${encodeURIComponent(t._clientSecret)}`,s=await this.perform("POST",t._baseUrl.replace(/\/+$/,"")+"/oauth/token","application/json",new URLSearchParams({grant_type:"client_credentials"}),{Authorization:"Basic "+btoa(e)}),n=R(s),r=Number(n?.expires_in);if(typeof n?.access_token!="string"||!Number.isFinite(r))throw new c(new l(l.Code.SERIALIZATION_ERROR));return t._oauth.token={value:n.access_token,expiresAt:Date.now()+r*1e3},n.access_token}async perform(t,e,s,n,r){return this.text(await this.open(t,e,s,n,r))}async text(t){try{let e=await t.text();return t.status===204?"":e}catch(e){throw new c(new l(l.Code.IO_ERROR),0,{cause:e})}}async open(t,e,s,n,r){let o={Accept:s,...r},d;n instanceof URLSearchParams?d=n:n!==void 0&&(o["Content-Type"]="application/json",d=JSON.stringify(n));let m=this.settings._timeoutMs,p=0;try{let h=await fetch(e,{method:t.toUpperCase(),headers:o,body:d,redirect:"manual",signal:m>0?AbortSignal.timeout(m):void 0});if(p=h.status,p>=300&&p<400)throw new c(new l(l.Code.INVALID_REQUEST,`the service answered with a redirect (HTTP ${p}), which is not followed so the credentials are never sent to another location; check the baseUrl`),p);if(p>=400)throw ie(p,await h.text());return h}catch(h){throw h instanceof c?h:new c(new l(l.Code.IO_ERROR),0,{cause:h})}}tenantId(){return this.settings._tenantId}};function se(i){let t=new M;return[...t.push(i),...t.end()]}async function*re(i){let t=i.body;if(t==null)return;let e=t.getReader(),s=new TextDecoder,n=new M;try{for(;;){let r;try{r=await e.read()}catch(o){throw new c(new l(l.Code.IO_ERROR),0,{cause:o})}if(r.done)break;for(let o of n.push(s.decode(r.value,{stream:!0})))yield{event:o.name,data:o.data}}for(let r of[...n.push(s.decode()),...n.end()])yield{event:r.name,data:r.data}}finally{await e.cancel().catch(()=>{})}}var M=class{constructor(){a(this,"buffer","");a(this,"name",null);a(this,"data",[]);a(this,"open",!1)}push(t){this.buffer+=t;let e=this.buffer.endsWith("\r")?"\r":"",s=(e?this.buffer.slice(0,-1):this.buffer).split(/\r\n|\r|\n/);this.buffer=s.pop()+e;let n=[];for(let r of s)this.line(r,n);return n}end(){let t=[];return this.buffer.length>0&&(this.line(this.buffer.replace(/\r$/,""),t),this.buffer=""),this.dispatch(t),t}line(t,e){if(t.length===0)this.dispatch(e);else if(!t.startsWith(":")){let s=t.indexOf(":"),n=s<0?t:t.substring(0,s),r=s<0?"":t.substring(s+1);r.startsWith(" ")&&(r=r.substring(1)),n==="event"?(this.name=r,this.open=!0):n==="data"&&(this.data.push(r),this.open=!0)}}dispatch(t){this.open&&t.push({name:this.name??"message",data:this.data.join(`
3
+ `)}),this.name=null,this.data=[],this.open=!1}};function R(i){try{return JSON.parse(i)}catch(t){throw new c(new l(l.Code.SERIALIZATION_ERROR),0,{cause:t})}}function ie(i,t){let e;i===401?e=l.Code.UNAUTHORIZED:i===403?e=l.Code.FORBIDDEN:i===404?e=l.Code.NOT_FOUND:i===429?e=l.Code.RATE_LIMITED:i>=500?e=l.Code.SERVER_ERROR:e=l.Code.INVALID_REQUEST;let s=null;try{let n=JSON.parse(t)?.error;s=n==null?null:String(n)}catch{}return new c(new l(e,s),i)}var oe=new Set(["localhost","127.0.0.1","[::1]"]);function ae(i){let t;try{t=new URL(i.trim())}catch{throw E("baseUrl is not a valid URL")}if(!(t.protocol==="https:"||t.protocol==="http:"&&oe.has(t.hostname)))throw E("baseUrl must use https (http is allowed only for localhost, 127.0.0.1 and ::1)")}function b(i){return i==null||i.trim().length===0}function u(i,t){if(b(i))throw E(`${t} is required`);return i}function E(i){return new c(new l(l.Code.INVALID_REQUEST,i))}function k(i){let t={};for(let[e,s]of Object.entries(i))s!=null&&(t[e]=s);return t}function y(i,t){let e=[];for(let[s,n]of Object.entries(t))n!=null&&e.push(`${encodeURIComponent(s)}=${encodeURIComponent(String(n))}`);return e.length===0?i:`${i}?${e.join("&")}`}function v(i,t,e={}){return`${i}/${t.replace(/\{(\w+)}/g,(s,n)=>encodeURIComponent(e[n]))}`}var L=class extends N{constructor(e){super(e);a(this,"builder");this.builder=e}async execute(){let e=this.builder._operation;if(e==null)throw E("operation is required");let s=w.Operation;return this.withTarget(async n=>{switch(e){case s.INIT_SESSION:return this.initSession(n);case s.CHAT:return this.chat(n);case s.CHAT_STREAM:return this.chatStream(n);case s.LIST_SESSIONS:return this.listSessions(n);case s.GET_HISTORY:return this.getHistory(n);case s.CLOSE_SESSION:return this.closeSession(n);case s.LIST_SUBJECTS:return this.listSubjects(n);case s.DELETE_SUBJECT:return this.deleteSubject(n);case s.UPDATE_SUBJECT_DESCRIPTION:return this.updateSubjectDescription(n);case s.GET_PLAN:return this.getPlan(n);case s.HEALTH:return this.health(n);default:throw E(`unknown operation ${String(e)}`)}})}async initSession(e){let s=await this.sendEventStream("POST",v(e,"mnemo/init/stream"),k({tenantId:u(this.tenantId(),"tenantId"),sessionId:u(this.builder._sessionId,"sessionId"),sessionName:this.builder._sessionName})),n=[],r=null;for(let o of s)if(o.name==="init-stage")n.push(R(o.data));else if(o.name==="complete")r=R(o.data);else if(o.name==="error"){let d=R(o.data)?.error;throw new c(new l(l.Code.INIT_FAILED,d==null?o.data:String(d)))}if(r==null)throw new c(new l(l.Code.INIT_FAILED,"The service ended the stream before initialization completed"));return{...r,ready:!0,stages:n}}chat(e){return this.send("POST",v(e,"mnemo/chat"),k({tenantId:u(this.tenantId(),"tenantId"),sessionId:u(this.builder._sessionId,"sessionId"),message:u(this.builder._message,"message")}))}chatStream(e){return this.streamEvents("POST",v(e,"mnemo/chat/stream"),k({tenantId:u(this.tenantId(),"tenantId"),sessionId:u(this.builder._sessionId,"sessionId"),message:u(this.builder._message,"message")}))}listSessions(e){return this.send("GET",y(v(e,"mnemo/sessions"),{tenantId:u(this.tenantId(),"tenantId"),q:this.builder._query,page:this.builder._page,size:this.builder._size}))}getHistory(e){return this.send("GET",y(v(e,"mnemo/sessions/{id}/history",{id:u(this.builder._sessionId,"sessionId")}),{tenantId:u(this.tenantId(),"tenantId"),before:this.builder._before,size:this.builder._size}))}closeSession(e){return this.send("DELETE",y(v(e,"mnemo/sessions/{id}",{id:u(this.builder._sessionId,"sessionId")}),{tenantId:u(this.tenantId(),"tenantId"),permanent:this.builder._permanent}),void 0,!1)}listSubjects(e){return this.send("GET",y(v(e,"mnemo/subjects"),{tenantId:u(this.tenantId(),"tenantId")}))}deleteSubject(e){return this.send("DELETE",y(v(e,"mnemo/subject/{name}",{name:u(this.builder._subjectName,"subjectName")}),{tenantId:u(this.tenantId(),"tenantId")}),void 0,!1)}updateSubjectDescription(e){return this.send("PATCH",v(e,"mnemo/subject/{name}/description",{name:u(this.builder._subjectName,"subjectName")}),k({tenantId:u(this.tenantId(),"tenantId"),description:this.builder._description}))}getPlan(e){return this.send("GET",y(v(e,"mnemo/plan"),{tenantId:u(this.tenantId(),"tenantId")}))}health(e){return this.send("GET",v(e,"mnemo/health"))}};var w;(e=>{let i;(g=>(g.INIT_SESSION="INIT_SESSION",g.CHAT="CHAT",g.CHAT_STREAM="CHAT_STREAM",g.LIST_SESSIONS="LIST_SESSIONS",g.GET_HISTORY="GET_HISTORY",g.CLOSE_SESSION="CLOSE_SESSION",g.LIST_SUBJECTS="LIST_SUBJECTS",g.DELETE_SUBJECT="DELETE_SUBJECT",g.UPDATE_SUBJECT_DESCRIPTION="UPDATE_SUBJECT_DESCRIPTION",g.GET_PLAN="GET_PLAN",g.HEALTH="HEALTH"))(i=e.Operation||(e.Operation={}));class t extends T{constructor(){super(...arguments);a(this,"_operation","CHAT");a(this,"_sessionId");a(this,"_message");a(this,"_sessionName");a(this,"_subjectName");a(this,"_description");a(this,"_query");a(this,"_page");a(this,"_size");a(this,"_before");a(this,"_permanent",!1)}operation(r){return this._operation=r,this}sessionId(r){return this._sessionId=r,this}message(r){return this._message=r,this}sessionName(r){return this._sessionName=r,this}subjectName(r){return this._subjectName=r,this}description(r){return this._description=r,this}query(r){return this._query=r,this}page(r){return this._page=r,this}size(r){return this._size=r,this}before(r){return this._before=r,this}permanent(r){return this._permanent=r,this}build(){return new L(this)}}e.Builder=t})(w||(w={}));var le=new Set(["http:","https:","mailto:"]);function H(i){let t=i.trim();if(t.length===0||/[\u0000-\u001f\u007f\s]/.test(t))return null;let e;try{e=new URL(t)}catch{return null}return le.has(e.protocol)?e.href:null}function U(i,t){let e=t.createDocumentFragment();if(i.length>1e5){for(let s of i.split(/\n{2,}/)){let n=t.createElement("p");n.textContent=s,e.appendChild(n)}return e}return $(i.replace(/\r\n?/g,`
4
4
  `).split(`
5
- `),t,e),e}var z=/^\s{0,3}(`{3,}|~{3,})/,F=/^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/,q=/^\s{0,3}([-*_])(\s*\1){2,}\s*$/,L=/^\s{0,3}[-*+]\s+(.*)$/,P=/^\s{0,3}\d{1,9}[.)]\s+(.*)$/,O=/^\s{0,3}>\s?(.*)$/;function $(i,t,e,s=0){let n=0;for(;n<i.length;){let r=i[n];if(r.trim().length===0){n++;continue}let o=z.exec(r);if(o){let b=o[1],_=[];for(n++;n<i.length&&!i[n].trim().startsWith(b);)_.push(i[n]),n++;n++;let B=t.createElement("pre"),j=t.createElement("code");j.textContent=_.join(`
6
- `),B.appendChild(j),e.appendChild(B);continue}let d=F.exec(r);if(d){let b=t.createElement("h"+Math.min(d[1].length+2,6));x(d[2],t,b,0),e.appendChild(b),n++;continue}if(q.test(r)){e.appendChild(t.createElement("hr")),n++;continue}if(O.test(r)&&s<4){let b=[];for(;n<i.length&&O.test(i[n]);)b.push(O.exec(i[n])[1]),n++;let _=t.createElement("blockquote");$(b,t,_,s+1),e.appendChild(_);continue}let g=L.test(r)?L:P.test(r)?P:null;if(g){let b=t.createElement(g===L?"ul":"ol");for(;n<i.length&&g.test(i[n]);){let _=t.createElement("li");x(g.exec(i[n])[1],t,_,0),b.appendChild(_),n++}e.appendChild(b);continue}let p=[];for(;n<i.length&&i[n].trim().length>0&&(p.length===0||!de(i[n]));)p.push(i[n]),n++;let m=t.createElement("p");p.forEach((b,_)=>{_>0&&m.appendChild(t.createElement("br")),x(b.trim(),t,m,0)}),e.appendChild(m)}}function de(i){return z.test(i)||F.test(i)||q.test(i)||O.test(i)||L.test(i)||P.test(i)}var ce=/(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)|\[([^\]\n]*)\]\(([^()\s]*(?:\([^()\s]*\)[^()\s]*)*)(?:\s+"[^"\n]*")?\)|\*\*([^\n]+?)\*\*|\*([^*\s](?:[^*\n]*[^*\s])?)\*/g;function x(i,t,e,s){if(s>=4){e.appendChild(t.createTextNode(i));return}let n=new RegExp(ce.source,"g"),r=0;for(let o=n.exec(i);o!==null;o=n.exec(i))if(o.index>r&&e.appendChild(t.createTextNode(i.substring(r,o.index))),r=o.index+o[0].length,o[2]!==void 0){let d=t.createElement("code");d.textContent=o[2].trim(),e.appendChild(d)}else if(o[3]!==void 0){let d=H(o[4]);if(d===null)x(o[3],t,e,s+1);else{let g=t.createElement("a");g.setAttribute("href",d),g.setAttribute("rel","noopener noreferrer"),g.setAttribute("target","_blank"),x(o[3],t,g,s+1),e.appendChild(g)}}else{let d=t.createElement(o[5]!==void 0?"strong":"em");x(o[5]??o[6],t,d,s+1),e.appendChild(d)}r<i.length&&e.appendChild(t.createTextNode(i.substring(r)))}var J=`
5
+ `),t,e),e}var z=/^\s{0,3}(`{3,}|~{3,})/,F=/^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/,q=/^\s{0,3}([-*_])(\s*\1){2,}\s*$/,O=/^\s{0,3}[-*+]\s+(.*)$/,D=/^\s{0,3}\d{1,9}[.)]\s+(.*)$/,P=/^\s{0,3}>\s?(.*)$/;function $(i,t,e,s=0){let n=0;for(;n<i.length;){let r=i[n];if(r.trim().length===0){n++;continue}let o=z.exec(r);if(o){let f=o[1],I=[];for(n++;n<i.length&&!i[n].trim().startsWith(f);)I.push(i[n]),n++;n++;let j=t.createElement("pre"),g=t.createElement("code");g.textContent=I.join(`
6
+ `),j.appendChild(g),e.appendChild(j);continue}let d=F.exec(r);if(d){let f=t.createElement("h"+Math.min(d[1].length+2,6));x(d[2],t,f,0),e.appendChild(f),n++;continue}if(q.test(r)){e.appendChild(t.createElement("hr")),n++;continue}if(P.test(r)&&s<4){let f=[];for(;n<i.length&&P.test(i[n]);)f.push(P.exec(i[n])[1]),n++;let I=t.createElement("blockquote");$(f,t,I,s+1),e.appendChild(I);continue}let m=O.test(r)?O:D.test(r)?D:null;if(m){let f=t.createElement(m===O?"ul":"ol");for(;n<i.length&&m.test(i[n]);){let I=t.createElement("li");x(m.exec(i[n])[1],t,I,0),f.appendChild(I),n++}e.appendChild(f);continue}let p=[];for(;n<i.length&&i[n].trim().length>0&&(p.length===0||!de(i[n]));)p.push(i[n]),n++;let h=t.createElement("p");p.forEach((f,I)=>{I>0&&h.appendChild(t.createElement("br")),x(f.trim(),t,h,0)}),e.appendChild(h)}}function de(i){return z.test(i)||F.test(i)||q.test(i)||P.test(i)||O.test(i)||D.test(i)}var ce=/(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)|\[([^\]\n]*)\]\(([^()\s]*(?:\([^()\s]*\)[^()\s]*)*)(?:\s+"[^"\n]*")?\)|\*\*([^\n]+?)\*\*|\*([^*\s](?:[^*\n]*[^*\s])?)\*/g;function x(i,t,e,s){if(s>=4){e.appendChild(t.createTextNode(i));return}let n=new RegExp(ce.source,"g"),r=0;for(let o=n.exec(i);o!==null;o=n.exec(i))if(o.index>r&&e.appendChild(t.createTextNode(i.substring(r,o.index))),r=o.index+o[0].length,o[2]!==void 0){let d=t.createElement("code");d.textContent=o[2].trim(),e.appendChild(d)}else if(o[3]!==void 0){let d=H(o[4]);if(d===null)x(o[3],t,e,s+1);else{let m=t.createElement("a");m.setAttribute("href",d),m.setAttribute("rel","noopener noreferrer"),m.setAttribute("target","_blank"),x(o[3],t,m,s+1),e.appendChild(m)}}else{let d=t.createElement(o[5]!==void 0?"strong":"em");x(o[5]??o[6],t,d,s+1),e.appendChild(d)}r<i.length&&e.appendChild(t.createTextNode(i.substring(r)))}var J=`
7
7
  :host { display: block; width: 100%; height: 480px; min-height: 240px; box-sizing: border-box; contain: content; }
8
8
  *, *::before, *::after { box-sizing: border-box; }
9
9
  .root {
@@ -62,4 +62,4 @@ button {
62
62
  }
63
63
  button:disabled { opacity: .5; cursor: default; }
64
64
  .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
65
- `;var G={chat:"Chat",conversation:"Conversation",message:"Your message",placeholder:"Ask a question…",send:"Send",thinking:"Thinking…",connecting:"Connecting…",you:"You",assistant:"Assistant",errorStart:"The chat could not start. Please try again later.",errorSession:"The chat session has expired. Please reload the page.",errorBusy:"Too many messages. Please wait a moment and try again.",errorSend:"The message could not be sent. Please try again.",errorNoTenant:"The chat is not configured: no tenant was provided."},he={chat:"Chat",conversation:"Conversación",message:"Tu mensaje",placeholder:"Haz una pregunta…",send:"Enviar",thinking:"Pensando…",connecting:"Conectando…",you:"Tú",assistant:"Asistente",errorStart:"No se pudo iniciar el chat. Inténtalo de nuevo más tarde.",errorSession:"La sesión del chat ha caducado. Recarga la página.",errorBusy:"Demasiados mensajes. Espera un momento e inténtalo de nuevo.",errorSend:"No se pudo enviar el mensaje. Inténtalo de nuevo.",errorNoTenant:"El chat no está configurado: falta el inquilino."},ue={chat:"Discussion",conversation:"Conversation",message:"Votre message",placeholder:"Posez une question…",send:"Envoyer",thinking:"Réflexion…",connecting:"Connexion…",you:"Vous",assistant:"Assistant",errorStart:"Le chat n'a pas pu démarrer. Réessayez plus tard.",errorSession:"La session de chat a expiré. Rechargez la page.",errorBusy:"Trop de messages. Patientez un instant et réessayez.",errorSend:"Le message n'a pas pu être envoyé. Réessayez.",errorNoTenant:"Le chat n'est pas configuré : aucun locataire fourni."},me={chat:"Chat",conversation:"Unterhaltung",message:"Ihre Nachricht",placeholder:"Stellen Sie eine Frage…",send:"Senden",thinking:"Denke nach…",connecting:"Verbinde…",you:"Sie",assistant:"Assistent",errorStart:"Der Chat konnte nicht gestartet werden. Bitte versuchen Sie es später erneut.",errorSession:"Die Chat-Sitzung ist abgelaufen. Bitte laden Sie die Seite neu.",errorBusy:"Zu viele Nachrichten. Bitte warten Sie einen Moment und versuchen Sie es erneut.",errorSend:"Die Nachricht konnte nicht gesendet werden. Bitte versuchen Sie es erneut.",errorNoTenant:"Der Chat ist nicht konfiguriert: Es wurde kein Mandant angegeben."},ge={en:G,es:he,fr:ue,de:me};function U(i){let t=(i??"").trim().toLowerCase().split(/[-_]/)[0]??"";return ge[t]??G}var pe=6e4,fe=50,be=new Set(["light","dark","auto"]),Ee=/^(?:\d+(?:\.\d+)?|\.\d+)(?:px|%|em|rem|ex|ch|vh|vw|vmin|vmax|svh|svw|lvh|lvw|dvh|dvw|cm|mm|in|pt|pc)$/i,Se=/^calc\([0-9a-z%+\-*/(). ]{1,100}\)$/i,ve=/^(?:auto|fit-content|min-content|max-content)$/i;function Y(i){let t=(i??"").trim();return/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(t)?t+"px":Ee.test(t)||ve.test(t)||Se.test(t)&&_e(t)?t:null}function _e(i){let t=0;for(let e of i)if(t+=e==="("?1:e===")"?-1:0,t<0)return!1;return t===0}var v=class extends Error{constructor(e,s,n,r=0){super(s);a(this,"code",e);a(this,"userMessage",n);a(this,"status",r)}},Ie=globalThis.HTMLElement??class{},k=class extends Ie{constructor(){super();a(this,"root");a(this,"log");a(this,"statusLine");a(this,"errorLine");a(this,"input");a(this,"sendButton");a(this,"strings",U(null));a(this,"generation",0);a(this,"started",!1);a(this,"streaming",!1);a(this,"tokenInfo");a(this,"tokenFetch");a(this,"sessionId");a(this,"tenant");a(this,"initDone",!1);a(this,"initRun");a(this,"freshSession",!1);let e=this.ownerDocument,s=this.attachShadow({mode:"open"}),n=e.createElement("style");n.textContent=J,this.root=e.createElement("div"),this.root.className="root",this.root.setAttribute("part","root"),this.root.setAttribute("role","region"),this.log=e.createElement("div"),this.log.className="log",this.log.setAttribute("role","log"),this.log.setAttribute("aria-live","polite"),this.log.setAttribute("tabindex","0"),this.statusLine=e.createElement("p"),this.statusLine.className="status",this.statusLine.setAttribute("role","status"),this.errorLine=e.createElement("p"),this.errorLine.className="error",this.errorLine.setAttribute("role","alert");let r=e.createElement("form");this.input=e.createElement("textarea"),this.input.rows=1,this.input.setAttribute("autocomplete","off"),this.sendButton=e.createElement("button"),this.sendButton.type="submit",r.append(this.input,this.sendButton),this.root.append(this.log,this.statusLine,this.errorLine,r),s.append(n,this.root),r.addEventListener("submit",o=>{o.preventDefault(),this.submit()}),this.input.addEventListener("keydown",o=>{o.key==="Enter"&&!o.shiftKey&&!o.isComposing?(o.preventDefault(),this.submit()):o.key==="Escape"&&this.streaming&&(o.preventDefault(),this.stop())}),this.applyAttributes()}static get observedAttributes(){return["token-url","base-url","width","height","theme","placeholder","session-id","locale","tenant-id"]}connectedCallback(){this.applyAttributes(),this.started||(this.started=!0,this.begin())}disconnectedCallback(){this.started=!1,this.discardConversation()}attributeChangedCallback(e,s,n){s!==n&&(this.applyAttributes(),this.started&&(e==="token-url"||e==="base-url"||e==="session-id"||e==="tenant-id")&&(this.tokenInfo=void 0,this.tokenFetch=void 0,this.discardConversation(),this.begin()))}open(){this.input.focus(),this.ensureReady(),this.scrollIntoView?.({block:"nearest"})}reset(){this.discardConversation(),this.freshSession=!0,this.begin(),this.input.focus()}applyAttributes(){let e=this.getAttribute("theme")?.trim().toLowerCase()??"";this.root.setAttribute("data-theme",be.has(e)?e:"auto");let s=this.getAttribute("locale")?.trim()??"";/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(s)?this.root.setAttribute("lang",s):this.root.removeAttribute("lang"),this.strings=U(s),this.root.setAttribute("aria-label",this.strings.chat),this.log.setAttribute("aria-label",this.strings.conversation),this.input.setAttribute("aria-label",this.strings.message),this.input.placeholder=this.getAttribute("placeholder")??this.strings.placeholder,this.sendButton.textContent=this.strings.send;for(let n of["width","height"]){let r=Y(this.getAttribute(n));r===null?this.style.removeProperty(n):this.style.setProperty(n,r)}}begin(){this.initDone=!1,this.initRun=void 0,this.ensureReady()}ensureReady(){if(this.initDone)return Promise.resolve(!0);if(this.initRun===void 0){let e=this.initialize(this.generation).finally(()=>{this.initRun===e&&(this.initRun=void 0)});this.initRun=e}return this.initRun}async initialize(e){this.setStatus(this.strings.connecting);try{let s=await this.currentToken(!1),n=s.tenantId??this.getAttribute("tenant-id")?.trim();if(!n)throw new v("config-error","no tenant: the token endpoint returned no tenantId and there is no tenant-id attribute","errorNoTenant");this.tenant=n,this.sessionId??(this.sessionId=this.chooseSessionId(s.sessionPrefix));let r=this.sessionId,o=!1;if(!this.freshSession){let d=await this.loadHistory(r);if(e!==this.generation)return!1;o=d>0}return o||await this.withToken(d=>this.client(d,I.Operation.INIT_SESSION,r).build().execute()),e!==this.generation?!1:(this.freshSession=!1,this.initDone=!0,this.setStatus(""),this.emit("mnemo-ready",{sessionId:r}),!0)}catch(s){return e===this.generation&&(this.setStatus(""),this.fail(s,"errorStart")),!1}}async loadHistory(e){let s;try{s=await this.withToken(r=>this.client(r,I.Operation.GET_HISTORY,e).size(fe).build().execute())}catch(r){if(r instanceof h&&r.httpStatus===404)return 0;throw r}let n=Array.isArray(s.entries)?s.entries:[];for(let r of[...n].reverse()){let o=r;typeof o?.request?.message=="string"&&this.addMessage("user",o.request.message),typeof o?.response?.message=="string"&&this.addMessage("assistant",o.response.message)}return n.length}chooseSessionId(e){let s=(this.getAttribute("session-id")??"").trim().replace(/[^A-Za-z0-9._-]/g,"_").slice(0,64),n=`mnemo-chat:${this.getAttribute("token-url")??""}|${s}`,r=this.storage(),o=null;if(!this.freshSession)try{o=r?.getItem(n)??null}catch{}if(o===null)if(s&&!this.freshSession)o=s;else{o=(s?s+"-":"")+we();try{r?.setItem(n,o)}catch{}}return o.startsWith(e)?o:e+o}storage(){try{return this.ownerDocument.defaultView?.sessionStorage??null}catch{return null}}currentToken(e){let s=this.tokenInfo;if(!e&&s!==void 0&&s.expiresAtMs-Date.now()>pe)return Promise.resolve(s);if(this.tokenFetch===void 0){let n=this.fetchToken().then(r=>(this.tokenFetch===n&&(this.tokenInfo=r),r)).finally(()=>{this.tokenFetch===n&&(this.tokenFetch=void 0)});this.tokenFetch=n}return this.tokenFetch}async fetchToken(){let e=this.getAttribute("token-url")?.trim();if(!e)throw new v("config-error","the token-url attribute is required","errorStart");let s;try{s=await fetch(e,{headers:{Accept:"application/json"},credentials:"same-origin",cache:"no-store"})}catch(o){throw new v("token-error",`the token endpoint could not be reached: ${K(o)}`,"errorStart")}if(!s.ok)throw new v("token-error",`the token endpoint answered HTTP ${s.status}`,"errorStart",s.status);let n;try{n=await s.json()}catch{throw new v("token-error","the token endpoint did not answer with JSON","errorStart")}let r=Z(n?.expiresAt);if(typeof n?.token!="string"||n.token.length===0||r===null)throw new v("token-error","the token endpoint's answer lacks token or expiresAt","errorStart");return{token:n.token,expiresAtMs:r,sessionPrefix:typeof n.sessionPrefix=="string"?n.sessionPrefix:"",tenantId:typeof n.tenantId=="string"&&n.tenantId.length>0?n.tenantId:null}}async withToken(e){let s=await this.currentToken(!1);try{return await e(s.token)}catch(n){if(!(n instanceof h)||n.httpStatus!==401)throw n}return e((await this.currentToken(!0)).token)}client(e,s,n){let r=new I.Builder().embedToken(e).tenantId(this.tenant).sessionId(n).operation(s),o=this.getAttribute("base-url")?.trim();return o?r.baseUrl(o):r.baseUrl(y.DEFAULT_BASE_URL)}submit(){let e=this.input.value.trim();e.length===0||this.streaming||(this.input.value="",this.send(e))}async send(e){let s=this.generation;this.setStreaming(!0),this.setError(""),this.addMessage("user",e),this.emit("mnemo-message",{role:"user",text:e});let n=this.addMessage("assistant","");n.classList.add("pending");let r="",o=null;try{let d=await this.ensureReady();if(s!==this.generation)return;if(!d){n.remove(),this.setStreaming(!1);return}let g=this.sessionId,p=await this.withToken(m=>this.client(m,I.Operation.CHAT_STREAM,g).message(e).build().execute());for await(let m of p){if(s!==this.generation)return;if(m.event==="message")r+=m.data,n.classList.remove("pending"),this.fillMessage(n,"assistant",r),this.keepAtBottom();else if(m.event==="quota-warning")this.setStatus(V(m.data,"message")??"");else if(m.event==="error"){o=new v("chat-error",V(m.data,"error")??"the service reported an error","errorSend");break}else if(m.event==="done")break}}catch(d){o=d}s===this.generation&&(n.classList.remove("pending"),r.length===0&&n.remove(),this.setStreaming(!1),r.length>0&&this.emit("mnemo-message",{role:"assistant",text:r}),o!==null?this.fail(o,"errorSend"):r.length===0&&this.fail(new v("chat-error","the answer was empty","errorSend"),"errorSend"),this.input.focus())}stop(){let e=this.streaming;this.generation++,this.setStreaming(!1);for(let s of Array.from(this.log.querySelectorAll(".pending")))s.remove();e&&this.setStatus("")}discardConversation(){this.generation++,this.initDone=!1,this.initRun=void 0,this.sessionId=void 0,this.streaming=!1,this.sendButton.disabled=!1,this.log.removeAttribute("aria-busy"),this.log.replaceChildren(),this.setStatus(""),this.setError("")}addMessage(e,s){let n=this.ownerDocument.createElement("div");return n.className=`msg ${e}`,this.fillMessage(n,e,s),this.log.appendChild(n),this.keepAtBottom(),n}fillMessage(e,s,n){let r=this.ownerDocument,o=r.createElement("span");o.className="sr-only",o.textContent=(s==="user"?this.strings.you:this.strings.assistant)+": ",s==="user"?e.replaceChildren(o,r.createTextNode(n)):e.replaceChildren(o,D(n,r))}keepAtBottom(){this.log.scrollTop=this.log.scrollHeight}setStreaming(e){this.streaming=e,this.sendButton.disabled=e,e?(this.log.setAttribute("aria-busy","true"),this.setStatus(this.strings.thinking)):(this.log.removeAttribute("aria-busy"),this.setStatus(""))}setStatus(e){this.statusLine.textContent=e}setError(e){this.errorLine.textContent=e}fail(e,s){let n="client-error",r=K(e),o=0,d=s;e instanceof v?(n=e.code,o=e.status,d=e.userMessage):e instanceof h&&(n=e.error.code,o=e.httpStatus,r=e.message,o===401||o===403?d="errorSession":o===429&&(d="errorBusy")),this.setError(this.strings[d]),this.setStreaming(!1),this.emit("mnemo-error",{code:n,message:r,status:o})}emit(e,s){this.dispatchEvent(new CustomEvent(e,{detail:s,bubbles:!0,composed:!0}))}};function K(i){return i instanceof Error?i.message:String(i)}function V(i,t){try{let e=JSON.parse(i)?.[t];return typeof e=="string"?e:null}catch{return null}}function Z(i){let t;if(typeof i=="number")t=i<1e11?i*1e3:i;else if(typeof i=="string"&&i.trim().length>0)t=/^\d+(\.\d+)?$/.test(i.trim())?Z(Number(i))??NaN:Date.parse(i);else return null;return Number.isFinite(t)?t:null}function we(){let i=new Uint8Array(8);return globalThis.crypto.getRandomValues(i),Array.from(i,t=>t.toString(16).padStart(2,"0")).join("")}function W(i="mnemo-chat"){typeof customElements<"u"&&customElements.get(i)===void 0&&customElements.define(i,k)}W();})();
65
+ `;var G={chat:"Chat",conversation:"Conversation",message:"Your message",placeholder:"Ask a question…",send:"Send",thinking:"Thinking…",connecting:"Connecting…",you:"You",assistant:"Assistant",errorStart:"The chat could not start. Please try again later.",errorSession:"The chat session has expired. Please reload the page.",errorBusy:"Too many messages. Please wait a moment and try again.",errorSend:"The message could not be sent. Please try again.",errorNoTenant:"The chat is not configured: no tenant was provided."},he={chat:"Chat",conversation:"Conversación",message:"Tu mensaje",placeholder:"Haz una pregunta…",send:"Enviar",thinking:"Pensando…",connecting:"Conectando…",you:"Tú",assistant:"Asistente",errorStart:"No se pudo iniciar el chat. Inténtalo de nuevo más tarde.",errorSession:"La sesión del chat ha caducado. Recarga la página.",errorBusy:"Demasiados mensajes. Espera un momento e inténtalo de nuevo.",errorSend:"No se pudo enviar el mensaje. Inténtalo de nuevo.",errorNoTenant:"El chat no está configurado: falta el inquilino."},ue={chat:"Discussion",conversation:"Conversation",message:"Votre message",placeholder:"Posez une question…",send:"Envoyer",thinking:"Réflexion…",connecting:"Connexion…",you:"Vous",assistant:"Assistant",errorStart:"Le chat n'a pas pu démarrer. Réessayez plus tard.",errorSession:"La session de chat a expiré. Rechargez la page.",errorBusy:"Trop de messages. Patientez un instant et réessayez.",errorSend:"Le message n'a pas pu être envoyé. Réessayez.",errorNoTenant:"Le chat n'est pas configuré : aucun locataire fourni."},me={chat:"Chat",conversation:"Unterhaltung",message:"Ihre Nachricht",placeholder:"Stellen Sie eine Frage…",send:"Senden",thinking:"Denke nach…",connecting:"Verbinde…",you:"Sie",assistant:"Assistent",errorStart:"Der Chat konnte nicht gestartet werden. Bitte versuchen Sie es später erneut.",errorSession:"Die Chat-Sitzung ist abgelaufen. Bitte laden Sie die Seite neu.",errorBusy:"Zu viele Nachrichten. Bitte warten Sie einen Moment und versuchen Sie es erneut.",errorSend:"Die Nachricht konnte nicht gesendet werden. Bitte versuchen Sie es erneut.",errorNoTenant:"Der Chat ist nicht konfiguriert: Es wurde kein Mandant angegeben."},ge={en:G,es:he,fr:ue,de:me};function B(i){let t=(i??"").trim().toLowerCase().split(/[-_]/)[0]??"";return ge[t]??G}var pe=6e4,fe=50,be=new Set(["light","dark","auto"]),Ee=/^(?:\d+(?:\.\d+)?|\.\d+)(?:px|%|em|rem|ex|ch|vh|vw|vmin|vmax|svh|svw|lvh|lvw|dvh|dvw|cm|mm|in|pt|pc)$/i,ve=/^calc\([0-9a-z%+\-*/(). ]{1,100}\)$/i,Se=/^(?:auto|fit-content|min-content|max-content)$/i;function Y(i){let t=(i??"").trim();return/^(?:\d+(?:\.\d+)?|\.\d+)$/.test(t)?t+"px":Ee.test(t)||Se.test(t)||ve.test(t)&&_e(t)?t:null}function _e(i){let t=0;for(let e of i)if(t+=e==="("?1:e===")"?-1:0,t<0)return!1;return t===0}var _=class extends Error{constructor(e,s,n,r=0){super(s);a(this,"code",e);a(this,"userMessage",n);a(this,"status",r)}},Ie=globalThis.HTMLElement??class{},A=class extends Ie{constructor(){super();a(this,"root");a(this,"log");a(this,"statusLine");a(this,"errorLine");a(this,"input");a(this,"sendButton");a(this,"strings",B(null));a(this,"generation",0);a(this,"started",!1);a(this,"streaming",!1);a(this,"tokenInfo");a(this,"tokenFetch");a(this,"sessionId");a(this,"tenant");a(this,"initDone",!1);a(this,"initRun");a(this,"freshSession",!1);let e=this.ownerDocument,s=this.attachShadow({mode:"open"}),n=e.createElement("style");n.textContent=J,this.root=e.createElement("div"),this.root.className="root",this.root.setAttribute("part","root"),this.root.setAttribute("role","region"),this.log=e.createElement("div"),this.log.className="log",this.log.setAttribute("role","log"),this.log.setAttribute("aria-live","polite"),this.log.setAttribute("tabindex","0"),this.statusLine=e.createElement("p"),this.statusLine.className="status",this.statusLine.setAttribute("role","status"),this.errorLine=e.createElement("p"),this.errorLine.className="error",this.errorLine.setAttribute("role","alert");let r=e.createElement("form");this.input=e.createElement("textarea"),this.input.rows=1,this.input.setAttribute("autocomplete","off"),this.sendButton=e.createElement("button"),this.sendButton.type="submit",r.append(this.input,this.sendButton),this.root.append(this.log,this.statusLine,this.errorLine,r),s.append(n,this.root),r.addEventListener("submit",o=>{o.preventDefault(),this.submit()}),this.input.addEventListener("keydown",o=>{o.key==="Enter"&&!o.shiftKey&&!o.isComposing?(o.preventDefault(),this.submit()):o.key==="Escape"&&this.streaming&&(o.preventDefault(),this.stop())}),this.applyAttributes()}static get observedAttributes(){return["token-url","base-url","width","height","theme","placeholder","session-id","locale","tenant-id"]}connectedCallback(){this.applyAttributes(),this.started||(this.started=!0,this.begin())}disconnectedCallback(){this.started=!1,this.discardConversation()}attributeChangedCallback(e,s,n){s!==n&&(this.applyAttributes(),this.started&&(e==="token-url"||e==="base-url"||e==="session-id"||e==="tenant-id")&&(this.tokenInfo=void 0,this.tokenFetch=void 0,this.discardConversation(),this.begin()))}open(){this.input.focus(),this.ensureReady(),this.scrollIntoView?.({block:"nearest"})}reset(){this.discardConversation(),this.freshSession=!0,this.begin(),this.input.focus()}applyAttributes(){let e=this.getAttribute("theme")?.trim().toLowerCase()??"";this.root.setAttribute("data-theme",be.has(e)?e:"auto");let s=this.getAttribute("locale")?.trim()??"";/^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(s)?this.root.setAttribute("lang",s):this.root.removeAttribute("lang"),this.strings=B(s),this.root.setAttribute("aria-label",this.strings.chat),this.log.setAttribute("aria-label",this.strings.conversation),this.input.setAttribute("aria-label",this.strings.message),this.input.placeholder=this.getAttribute("placeholder")??this.strings.placeholder,this.sendButton.textContent=this.strings.send;for(let n of["width","height"]){let r=Y(this.getAttribute(n));r===null?this.style.removeProperty(n):this.style.setProperty(n,r)}}begin(){this.initDone=!1,this.initRun=void 0,this.ensureReady()}ensureReady(){if(this.initDone)return Promise.resolve(!0);if(this.initRun===void 0){let e=this.initialize(this.generation).finally(()=>{this.initRun===e&&(this.initRun=void 0)});this.initRun=e}return this.initRun}async initialize(e){this.setStatus(this.strings.connecting);try{let s=await this.currentToken(!1),n=s.tenantId??this.getAttribute("tenant-id")?.trim();if(!n)throw new _("config-error","no tenant: the token endpoint returned no tenantId and there is no tenant-id attribute","errorNoTenant");this.tenant=n,this.sessionId??(this.sessionId=this.chooseSessionId(s.sessionPrefix));let r=this.sessionId,o=!1;if(!this.freshSession){let d=await this.loadHistory(r);if(e!==this.generation)return!1;o=d>0}return o||await this.withToken(d=>this.client(d,w.Operation.INIT_SESSION,r).build().execute()),e!==this.generation?!1:(this.freshSession=!1,this.initDone=!0,this.setStatus(""),this.emit("mnemo-ready",{sessionId:r}),!0)}catch(s){return e===this.generation&&(this.setStatus(""),this.fail(s,"errorStart")),!1}}async loadHistory(e){let s;try{s=await this.withToken(r=>this.client(r,w.Operation.GET_HISTORY,e).size(fe).build().execute())}catch(r){if(r instanceof c&&r.httpStatus===404)return 0;throw r}let n=Array.isArray(s.entries)?s.entries:[];for(let r of[...n].reverse()){let o=r;typeof o?.request?.message=="string"&&this.addMessage("user",o.request.message),typeof o?.response?.message=="string"&&this.addMessage("assistant",o.response.message)}return n.length}chooseSessionId(e){let s=(this.getAttribute("session-id")??"").trim().replace(/[^A-Za-z0-9._-]/g,"_").slice(0,64),n=`mnemo-chat:${this.getAttribute("token-url")??""}|${s}`,r=this.storage(),o=null;if(!this.freshSession)try{o=r?.getItem(n)??null}catch{}if(o===null)if(s&&!this.freshSession)o=s;else{o=(s?s+"-":"")+we();try{r?.setItem(n,o)}catch{}}return o.startsWith(e)?o:e+o}storage(){try{return this.ownerDocument.defaultView?.sessionStorage??null}catch{return null}}currentToken(e){let s=this.tokenInfo;if(!e&&s!==void 0&&s.expiresAtMs-Date.now()>pe)return Promise.resolve(s);if(this.tokenFetch===void 0){let n=this.fetchToken().then(r=>(this.tokenFetch===n&&(this.tokenInfo=r),r)).finally(()=>{this.tokenFetch===n&&(this.tokenFetch=void 0)});this.tokenFetch=n}return this.tokenFetch}async fetchToken(){let e=this.getAttribute("token-url")?.trim();if(!e)throw new _("config-error","the token-url attribute is required","errorStart");let s;try{s=await fetch(e,{headers:{Accept:"application/json"},credentials:"same-origin",cache:"no-store"})}catch(o){throw new _("token-error",`the token endpoint could not be reached: ${K(o)}`,"errorStart")}if(!s.ok)throw new _("token-error",`the token endpoint answered HTTP ${s.status}`,"errorStart",s.status);let n;try{n=await s.json()}catch{throw new _("token-error","the token endpoint did not answer with JSON","errorStart")}let r=Z(n?.expiresAt);if(typeof n?.token!="string"||n.token.length===0||r===null)throw new _("token-error","the token endpoint's answer lacks token or expiresAt","errorStart");return{token:n.token,expiresAtMs:r,sessionPrefix:typeof n.sessionPrefix=="string"?n.sessionPrefix:"",tenantId:typeof n.tenantId=="string"&&n.tenantId.length>0?n.tenantId:null}}async withToken(e){let s=await this.currentToken(!1);try{return await e(s.token)}catch(n){if(!(n instanceof c)||n.httpStatus!==401)throw n}return e((await this.currentToken(!0)).token)}client(e,s,n){let r=new w.Builder().embedToken(e).tenantId(this.tenant).sessionId(n).operation(s),o=this.getAttribute("base-url")?.trim();return o?r.baseUrl(o):r.baseUrl(T.DEFAULT_BASE_URL)}submit(){let e=this.input.value.trim();e.length===0||this.streaming||(this.input.value="",this.send(e))}async send(e){let s=this.generation;this.setStreaming(!0),this.setError(""),this.addMessage("user",e),this.emit("mnemo-message",{role:"user",text:e});let n=this.addMessage("assistant","");n.classList.add("pending");let r="",o=null;try{let d=await this.ensureReady();if(s!==this.generation)return;if(!d){n.remove(),this.setStreaming(!1);return}let m=this.sessionId,p=await this.withToken(h=>this.client(h,w.Operation.CHAT_STREAM,m).message(e).build().execute());for await(let h of p){if(s!==this.generation)return;if(h.event==="message")r+=h.data,n.classList.remove("pending"),this.fillMessage(n,"assistant",r),this.keepAtBottom();else if(h.event==="quota-warning")this.setStatus(V(h.data,"message")??"");else if(h.event==="error"){o=new _("chat-error",V(h.data,"error")??"the service reported an error","errorSend");break}else if(h.event==="done")break}}catch(d){o=d}s===this.generation&&(n.classList.remove("pending"),r.length===0&&n.remove(),this.setStreaming(!1),r.length>0&&this.emit("mnemo-message",{role:"assistant",text:r}),o!==null?this.fail(o,"errorSend"):r.length===0&&this.fail(new _("chat-error","the answer was empty","errorSend"),"errorSend"),this.input.focus())}stop(){let e=this.streaming;this.generation++,this.setStreaming(!1);for(let s of Array.from(this.log.querySelectorAll(".pending")))s.remove();e&&this.setStatus("")}discardConversation(){this.generation++,this.initDone=!1,this.initRun=void 0,this.sessionId=void 0,this.streaming=!1,this.sendButton.disabled=!1,this.log.removeAttribute("aria-busy"),this.log.replaceChildren(),this.setStatus(""),this.setError("")}addMessage(e,s){let n=this.ownerDocument.createElement("div");return n.className=`msg ${e}`,this.fillMessage(n,e,s),this.log.appendChild(n),this.keepAtBottom(),n}fillMessage(e,s,n){let r=this.ownerDocument,o=r.createElement("span");o.className="sr-only",o.textContent=(s==="user"?this.strings.you:this.strings.assistant)+": ",s==="user"?e.replaceChildren(o,r.createTextNode(n)):e.replaceChildren(o,U(n,r))}keepAtBottom(){this.log.scrollTop=this.log.scrollHeight}setStreaming(e){this.streaming=e,this.sendButton.disabled=e,e?(this.log.setAttribute("aria-busy","true"),this.setStatus(this.strings.thinking)):(this.log.removeAttribute("aria-busy"),this.setStatus(""))}setStatus(e){this.statusLine.textContent=e}setError(e){this.errorLine.textContent=e}fail(e,s){let n="client-error",r=K(e),o=0,d=s;e instanceof _?(n=e.code,o=e.status,d=e.userMessage):e instanceof c&&(n=e.error.code,o=e.httpStatus,r=e.message,o===401||o===403?d="errorSession":o===429&&(d="errorBusy")),this.setError(this.strings[d]),this.setStreaming(!1),this.emit("mnemo-error",{code:n,message:r,status:o})}emit(e,s){this.dispatchEvent(new CustomEvent(e,{detail:s,bubbles:!0,composed:!0}))}};function K(i){return i instanceof Error?i.message:String(i)}function V(i,t){try{let e=JSON.parse(i)?.[t];return typeof e=="string"?e:null}catch{return null}}function Z(i){let t;if(typeof i=="number")t=i<1e11?i*1e3:i;else if(typeof i=="string"&&i.trim().length>0)t=/^\d+(\.\d+)?$/.test(i.trim())?Z(Number(i))??NaN:Date.parse(i);else return null;return Number.isFinite(t)?t:null}function we(){let i=new Uint8Array(8);return globalThis.crypto.getRandomValues(i),Array.from(i,t=>t.toString(16).padStart(2,"0")).join("")}function W(i="mnemo-chat"){typeof customElements<"u"&&customElements.get(i)===void 0&&customElements.define(i,A)}W();})();
@@ -21,7 +21,7 @@
21
21
  # Author: edward.suryadi
22
22
  # Since: Oct-2026
23
23
 
24
- """Typed responses for the core calls (chat, RAG, settings).
24
+ """Typed responses for the core calls (chat, RAG).
25
25
 
26
26
  Attribute names are the snake_case form of the service's JSON fields. Fields this client does not know about are
27
27
  ignored and missing ones take their default, so a newer service never breaks an older client.
@@ -93,6 +93,35 @@ class Attachment:
93
93
  mime_type=data.get("mimeType"), file_name=data.get("fileName"))
94
94
 
95
95
 
96
+ @dataclass(frozen=True)
97
+ class Groundedness:
98
+ """The opt-in groundedness check's result for one answer: whether the stored text supports it (not that the answer or the data is true).
99
+
100
+ ``verdict`` is GROUNDED, PARTIAL or UNVERIFIED; ``notice`` is the sentence to show for the last two; ``follow_up`` and
101
+ ``follow_up_text`` are only ever on a streamed chat result, never on a MnemoRAG one. Today the server sends the chat result only on
102
+ the stream Dorothy's web client asks for, not on ``POST mnemo/chat``, so ``ChatMessageResponse.groundedness`` is not populated for
103
+ this client; the MnemoRAG one is. Strings, so a value added later does not break an older client.
104
+ """
105
+
106
+ score: float = 0.0
107
+ verdict: Optional[str] = None
108
+ reason: Optional[str] = None
109
+ unsupported_claims: List[str] = field(default_factory=list)
110
+ notice: Optional[str] = None
111
+ follow_up: Optional[str] = None
112
+ follow_up_text: Optional[str] = None
113
+ truncated: bool = False
114
+
115
+ @classmethod
116
+ def from_dict(cls, data: Optional[Dict[str, Any]]) -> Optional[Groundedness]:
117
+ if data is None:
118
+ return None
119
+ return cls(score=float(data.get("score") or 0.0), verdict=data.get("verdict"), reason=data.get("reason"),
120
+ unsupported_claims=list(data.get("unsupportedClaims") or []), notice=data.get("notice"),
121
+ follow_up=data.get("followUp"), follow_up_text=data.get("followUpText"),
122
+ truncated=bool(data.get("truncated")))
123
+
124
+
96
125
  @dataclass(frozen=True)
97
126
  class ChatMessageResponse:
98
127
  """The assistant reply to a chat message (result of ``MnemoChatClient.Operation.CHAT``)."""
@@ -108,6 +137,14 @@ class ChatMessageResponse:
108
137
  reasoning_trace: Optional[str] = None
109
138
  quota_warning: Optional[str] = None
110
139
  token_usage: Optional[TokenUsage] = None
140
+ # Additive, None when the server did not send them. reason/explanation: why a plain not-found is one. source/authority/confidence
141
+ # (high, medium or low): where an answer built from stored data came from. groundedness: the opt-in check's result.
142
+ reason: Optional[str] = None
143
+ source: Optional[str] = None
144
+ authority: Optional[str] = None
145
+ confidence: Optional[str] = None
146
+ explanation: Optional[str] = None
147
+ groundedness: Optional[Groundedness] = None
111
148
 
112
149
  @classmethod
113
150
  def from_dict(cls, data: Dict[str, Any]) -> ChatMessageResponse:
@@ -117,7 +154,10 @@ class ChatMessageResponse:
117
154
  attachments=None if attachments is None else [Attachment.from_dict(a) for a in attachments],
118
155
  timestamp=data.get("timestamp") or 0, timing=ResponseTiming.from_dict(data.get("timing")),
119
156
  session_name=data.get("sessionName"), reasoning_trace=data.get("reasoningTrace"),
120
- quota_warning=data.get("quotaWarning"), token_usage=TokenUsage.from_dict(data.get("tokenUsage")))
157
+ quota_warning=data.get("quotaWarning"), token_usage=TokenUsage.from_dict(data.get("tokenUsage")),
158
+ reason=data.get("reason"), source=data.get("source"), authority=data.get("authority"),
159
+ confidence=data.get("confidence"), explanation=data.get("explanation"),
160
+ groundedness=Groundedness.from_dict(data.get("groundedness")))
121
161
 
122
162
 
123
163
  @dataclass(frozen=True)
@@ -134,8 +174,13 @@ class RagQueryResponse:
134
174
  subjects_used: List[str] = field(default_factory=list)
135
175
  token_usage: Optional[TokenUsage] = None
136
176
  # Only on a not-found, when the server knows why: OUT_OF_SCOPE, NOT_IN_MEMORY, AMBIGUOUS_ENTITY, PARTIAL_MATCH,
137
- # INDEX_NOT_READY, UNVERIFIED_ANSWER (STALE is reserved and never sent). A string, so a later code does not break an older client.
177
+ # INDEX_NOT_READY, UNVERIFIED_ANSWER, INCOMPLETE_DATA (STALE is reserved and never sent). A string, so a later code does not break an older client.
138
178
  reason: Optional[str] = None
179
+ # The one plain sentence for ``reason``; present exactly when ``reason`` is.
180
+ explanation: Optional[str] = None
181
+ # Only for a configuration created with checkGroundedness on, a found answer the check ran on, and when it finished in time.
182
+ # Such a configuration adds up to about 4 seconds to every response.
183
+ groundedness: Optional[Groundedness] = None
139
184
 
140
185
  @classmethod
141
186
  def from_dict(cls, data: Dict[str, Any]) -> RagQueryResponse:
@@ -143,30 +188,8 @@ class RagQueryResponse:
143
188
  authority=data.get("authority"), confidence=data.get("confidence"),
144
189
  last_updated=_instant(data.get("lastUpdated")), retrieval_tier=data.get("retrievalTier"),
145
190
  subjects_used=list(data.get("subjectsUsed") or []),
146
- token_usage=TokenUsage.from_dict(data.get("tokenUsage")), reason=data.get("reason"))
147
-
148
-
149
- @dataclass(frozen=True)
150
- class SettingsResponse:
151
- """An account's MNEMO settings. The provider API key is never returned, only whether one is stored."""
152
-
153
- account_id: Optional[str] = None
154
- provider: Optional[str] = None
155
- model: Optional[str] = None
156
- ingest_model: Optional[str] = None
157
- has_api_key: bool = False
158
- lookback_days: int = 0
159
- encrypt_data: bool = False
160
- shared_memory_ttl_hours: int = 0
161
- updated_at: Optional[datetime] = None
162
-
163
- @classmethod
164
- def from_dict(cls, data: Dict[str, Any]) -> SettingsResponse:
165
- return cls(account_id=data.get("accountId"), provider=data.get("provider"), model=data.get("model"),
166
- ingest_model=data.get("ingestModel"), has_api_key=bool(data.get("hasApiKey")),
167
- lookback_days=data.get("lookbackDays") or 0, encrypt_data=bool(data.get("encryptData")),
168
- shared_memory_ttl_hours=data.get("sharedMemoryTtlHours") or 0,
169
- updated_at=_instant(data.get("updatedAt")))
191
+ token_usage=TokenUsage.from_dict(data.get("tokenUsage")), reason=data.get("reason"),
192
+ explanation=data.get("explanation"), groundedness=Groundedness.from_dict(data.get("groundedness")))
170
193
 
171
194
 
172
195
  @dataclass(frozen=True)