@maggioli-rd/aicore-agent-chat 0.0.0-stage → 1.0.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Maggioli S.p.A.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,190 @@
1
- # Temporary Holding Version
1
+ # @maggioli-rd/aicore-agent-chat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `<aicore-agent-chat>`: la chat con un agente AI-CORE, da incorporare in qualunque pagina web (React, Angular, Vue, HTML semplice). Il browser chiama direttamente le API pubbliche di AI-CORE (`/api/v1`) con il **JWT dell'utente** che l'applicazione ospite ha già (la «corsia token» di AI-CORE): niente proxy, niente chiave API.
4
+
5
+ ```
6
+ browser (applicazione ospite)
7
+ ├─ getToken({ retry }) → JWT dell'utente (es. ID token Firebase)
8
+ └─ <aicore-agent-chat> ── fetch ───────────► https://<aicore>/api/v1/…
9
+ Authorization: Bearer <JWT>
10
+ X-Tenant: <spazio di lavoro aperto>
11
+ ```
12
+
13
+ Conversazioni dell'utente, risposta in streaming con le fonti, allegati, interruzione, valutazione delle risposte, pannello per sviluppatori. Risponde sempre la **versione pubblicata** dell'agente.
14
+
15
+ ## Prerequisiti in AI-CORE
16
+
17
+ Il sistema AI-CORE deve fidarsi del provider di identità dell'app: in console, _Integrazione_ → _Login dei tuoi utenti_ → **Collega un provider** (issuer, chiavi, audience, tenant dai claim). Dalla console, **Prova un token** verifica un token prima di provarlo dal browser.
18
+
19
+ ## Installazione
20
+
21
+ ```bash
22
+ npm install @maggioli-rd/aicore-agent-chat
23
+ ```
24
+
25
+ Oppure, senza bundler, il bundle unico (dipendenze incluse) da una CDN:
26
+
27
+ ```html
28
+ <script
29
+ type="module"
30
+ src="https://cdn.jsdelivr.net/npm/@maggioli-rd/aicore-agent-chat@1/dist/aicore-agent-chat.js"
31
+ ></script>
32
+ ```
33
+
34
+ `@1` segue l'ultima 1.x. In produzione fissa la versione esatta (`@1.2.3`) e aggiungi `integrity="sha384-…" crossorigin="anonymous"` (Subresource Integrity; jsDelivr mostra l'hash di ogni file): così una CDN compromessa non può cambiare lo script.
35
+
36
+ | Import | Cosa |
37
+ | --------------------------------------- | ----------------------------------------------------------------------------------------------------- |
38
+ | `@maggioli-rd/aicore-agent-chat` | `AicoreAgentChat`, `defineAicoreAgentChat()` e tutto `/core`. Non registra l'elemento |
39
+ | `@maggioli-rd/aicore-agent-chat/define` | come sopra, e registra `<aicore-agent-chat>` all'import |
40
+ | `@maggioli-rd/aicore-agent-chat/core` | il client senza interfaccia: `AicoreChatClient`, `AicoreChatSession`, errori, tipi, `decodeJwtClaims` |
41
+ | `@maggioli-rd/aicore-agent-chat/jsx` | i tipi JSX di `<aicore-agent-chat>` per React 19 |
42
+ | `@maggioli-rd/aicore-agent-chat/bundle` | il bundle unico (`dist/aicore-agent-chat.js`), che registra l'elemento |
43
+
44
+ ## Uso
45
+
46
+ ```html
47
+ <aicore-agent-chat
48
+ base-url="https://aicore-test.maggioliresearch.net"
49
+ agent="<id agente>"
50
+ tenant="<spazio di lavoro>"
51
+ lang="it"
52
+ style="display: block; height: 640px"
53
+ ></aicore-agent-chat>
54
+
55
+ <script type="module">
56
+ import "@maggioli-rd/aicore-agent-chat/define";
57
+
58
+ const chat = document.querySelector("aicore-agent-chat");
59
+ // Firebase: getIdToken(true) chiede un token nuovo, non quello in cache.
60
+ chat.getToken = async ({ retry }) =>
61
+ (await auth.currentUser?.getIdToken(retry)) ?? null;
62
+ chat.addEventListener("aicore-conversation", (e) => {
63
+ // e.detail.idConv: da salvare per riaprire la conversazione (attributo `conversation`)
64
+ });
65
+ chat.addEventListener("aicore-auth-required", () => {
66
+ // l'utente deve rifare il login
67
+ });
68
+ </script>
69
+ ```
70
+
71
+ La chat riempie il box che le dai. Sotto una certa larghezza l'elenco delle conversazioni si apre dal pulsante ☰.
72
+
73
+ ### React 19 (Next.js, Vite…)
74
+
75
+ L'elemento estende `HTMLElement`: va caricato solo nel browser (in Next.js dentro un `useEffect`, oppure con `dynamic(…, { ssr: false })`).
76
+
77
+ ```tsx
78
+ import type {} from "@maggioli-rd/aicore-agent-chat/jsx";
79
+ import type { AicoreAgentChat } from "@maggioli-rd/aicore-agent-chat";
80
+
81
+ function Chat({ agentId, tenant }: { agentId: string; tenant: string }) {
82
+ const ref = useRef<AicoreAgentChat>(null);
83
+ useEffect(() => {
84
+ void import("@maggioli-rd/aicore-agent-chat").then(
85
+ ({ defineAicoreAgentChat }) => {
86
+ defineAicoreAgentChat();
87
+ if (ref.current)
88
+ ref.current.getToken = ({ retry }) => getIdToken(retry);
89
+ },
90
+ );
91
+ }, []);
92
+ return (
93
+ <aicore-agent-chat
94
+ ref={ref}
95
+ base-url={AICORE_URL}
96
+ agent={agentId}
97
+ tenant={tenant}
98
+ lang="it"
99
+ />
100
+ );
101
+ }
102
+ ```
103
+
104
+ ### Senza interfaccia
105
+
106
+ ```ts
107
+ import { AicoreChatClient } from "@maggioli-rd/aicore-agent-chat/core";
108
+
109
+ const client = new AicoreChatClient({ baseUrl, tenant, getToken });
110
+ const { items } = await client.listAgents();
111
+ ```
112
+
113
+ ## Interfaccia di `<aicore-agent-chat>`
114
+
115
+ | Attributo (e proprietà) | Cosa |
116
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
117
+ | `base-url` (`baseUrl`) | origin di AI-CORE, senza `/api/v1` |
118
+ | `agent` | id dell'agente |
119
+ | `tenant` | inviato come `X-Tenant`. Obbligatorio se il token ammette più tenant: solo la pagina sa quale è aperto |
120
+ | `conversation` | conversazione da aprire |
121
+ | `lang` | `it` o `en`. Se manca, la lingua dell'antenato più vicino con `lang` (fino a `<html>`): italiano per `it…` o nessuna lingua, inglese per ogni altra |
122
+ | `developer` | mostra il pannello per sviluppatori: API, tenant, versione pubblicata, ultimo errore con `X-Request-Id`, eventi del turno, richieste. Spento se assente |
123
+
124
+ Proprietà:
125
+
126
+ - `getToken({ retry })`: vedi sotto.
127
+ - `strings`: testi al posto di quelli predefiniti, anche solo alcuni (tipo `StringsOverride`). Per esempio un'altra avvertenza, oppure un'altra lingua:
128
+ ```js
129
+ chat.strings = {
130
+ disclaimer: "Risposte generate da IA: verifica sempre.",
131
+ errors: { network: "Servizio non disponibile, riprova più tardi." },
132
+ };
133
+ ```
134
+ - `state` (sola lettura): lo stato della chat (`ChatState`).
135
+
136
+ Eventi (`bubbles`, `composed`):
137
+
138
+ | Evento | `detail` |
139
+ | ----------------------- | --------------------------------------------------------------------------------------------- |
140
+ | `aicore-conversation` | `{ idConv, idAgent }`. `idConv` null: conversazione vuota, AI-CORE la apre al primo messaggio |
141
+ | `aicore-turn` | `{ idConv, idQuery, turn }`, a fine risposta |
142
+ | `aicore-error` | `AicoreError` (`status`, `kind`, `errorCode`, `requestId`, …) |
143
+ | `aicore-auth-required` | `AicoreError`: nessun token valido, anche dopo un nuovo tentativo |
144
+ | `aicore-tenant-refused` | `AicoreError`: il tenant non è tra quelli del token (`403`) |
145
+
146
+ ### Il token
147
+
148
+ - `getToken({ retry })` restituisce il JWT dell'utente (direttamente o in una `Promise`), oppure `null` se non c'è.
149
+ - Il componente lo tiene in memoria fino a 30 s prima di `exp`.
150
+ - Su `401` con `error="invalid_token"` chiede un token con `retry: true`: l'ospite **non** deve restituire quello in cache. Riprova una sola volta, poi emette `aicore-auth-required`.
151
+ - AI-CORE blocca l'indirizzo IP dopo 30 risposte `401` in un minuto: non restituire mai un token scaduto.
152
+ - **Cambio di utente** (logout, login con un altro account): assegna di nuovo `getToken`, anche con la stessa funzione riscritta. Il componente dimentica il token in memoria e ne chiede subito uno: se è di un altro utente (`sub` diverso) chiude la conversazione e ricarica l'elenco. Lo stesso avviene da solo alla scadenza del token.
153
+
154
+ ### Tema
155
+
156
+ Variabili CSS sull'elemento, altrimenti i token Magma della pagina (`--magma-*`), altrimenti valori neutri: `--aicore-chat-surface`, `--aicore-chat-surface-muted`, `--aicore-chat-text`, `--aicore-chat-text-muted`, `--aicore-chat-border`, `--aicore-chat-accent`, `--aicore-chat-accent-hover`, `--aicore-chat-on-accent`, `--aicore-chat-accent-soft`, `--aicore-chat-accent-text`, `--aicore-chat-danger`, `--aicore-chat-danger-soft`, `--aicore-chat-radius`, `--aicore-chat-radius-small`, `--aicore-chat-font-family`, `--aicore-chat-font-mono`, `--aicore-chat-font-size` (predefinita `15px`; le altre dimensioni del testo la seguono).
157
+
158
+ `::part()`: `rail`, `header`, `error`, `transcript`, `message`, `message-user`, `message-assistant`, `sources`, `composer`, `input`, `send`, `stop`, `developer`.
159
+
160
+ ### Content Security Policy
161
+
162
+ - `connect-src` deve ammettere l'origin di AI-CORE.
163
+ - `script-src` deve ammettere la CDN, se carichi il bundle da lì.
164
+ - Stili: nessun requisito. Il componente usa un foglio di stile costruito (`adoptedStyleSheets`), che `style-src` non blocca; solo nei browser senza questa funzione ripiega su un `<style>`, che richiede `'unsafe-inline'`.
165
+ - Trusted Types (`require-trusted-types-for 'script'`): ammetti il criterio `aicore-agent-chat` (`trusted-types aicore-agent-chat`). Il componente lo usa solo per l'HTML delle risposte, già ripulito da DOMPurify.
166
+
167
+ Funziona anche su pagine servite in HTTP semplice (intranet); senza HTTPS il browser non dà accesso agli appunti e il pulsante «Copia» non compare.
168
+
169
+ ### Sicurezza del markdown
170
+
171
+ Le risposte vengono da un modello, che un prompt injection può guidare. L'HTML grezzo nel markdown è mostrato come testo; le immagini diventano link (un'immagine si carica da sola e il suo URL può portare fuori la conversazione); l'HTML passa comunque da DOMPurify; i link si aprono in una nuova scheda senza `opener` né `referrer`.
172
+
173
+ ## Sviluppo
174
+
175
+ ```bash
176
+ npm install
177
+ npm run dev # pagina demo (demo/): base-url, agente, tenant e un JWT incollato
178
+ npm test
179
+ npm run check # typecheck, lint, formato, test, build
180
+ ```
181
+
182
+ Per la demo, `.env` (vedi `.env.example`) dà i valori iniziali del modulo. Il token incollato non viene salvato.
183
+
184
+ ## Rilascio
185
+
186
+ Commit [Conventional Commits](https://www.conventionalcommits.org). Il merge su `main` (o su `beta`, come prerelease) rilascia con semantic-release: versione, `CHANGELOG.md`, tag e release su GitLab, poi `npm publish` (tag npm `latest`, oppure `beta`). Serve la variabile CI `NPM_TOKEN` (mascherata e protetta), con permesso di pubblicazione su `@maggioli-rd`.
187
+
188
+ ## Licenza
189
+
190
+ [MIT](LICENSE)