@agentrica/mcp 0.2.0 → 0.3.0

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/README.en.md CHANGED
@@ -12,7 +12,7 @@ The agent files are in Italian. The agent answers in the language you write in.
12
12
 
13
13
  - The server runs only locally: the client starts it on your computer and the two talk over stdio. The server has no remote part.
14
14
  - The only content it reads is the `agents/` files included in the package, once, at startup. The text that reaches the model is the text of those files: you can read it before using it.
15
- - It writes no files, opens no network connections, logs nothing, collects and sends no data, and has no telemetry.
15
+ - It writes no files, opens no network connections, logs nothing, collects and sends no data, and has no telemetry. With `--panel` it opens a page on your computer only: see [Local panel](#local-panel).
16
16
  - It runs nothing in your project. It only gives instructions to the model: what the model does in the project depends on the client and on the permissions you grant it.
17
17
  - **Where the data goes.** The agent's text, the task and the files the model reads in your project go to the model provider through your client, under that provider's terms. Agentrica does not receive them. Leave personal data, secrets and customer data out of the task unless they are needed.
18
18
  - The agents are AI: their conclusions are proposals to check. The privacy and security agents do not replace a DPO, a lawyer or a security officer, and their findings are not a compliance certification.
@@ -24,7 +24,7 @@ You need Node 22 or later, with npm.
24
24
  **Claude Code**, from your project folder:
25
25
 
26
26
  ```sh
27
- claude mcp add agentrica -- npx -y @agentrica/mcp@0.2.0
27
+ claude mcp add agentrica -- npx -y @agentrica/mcp@0.3.0
28
28
  ```
29
29
 
30
30
  On first start npx downloads the package from npm. The version stays the one you set until you change it: role updates do not arrive unless you choose them.
@@ -36,7 +36,7 @@ On first start npx downloads the package from npm. The version stays the one you
36
36
  "mcpServers": {
37
37
  "agentrica": {
38
38
  "command": "npx",
39
- "args": ["-y", "@agentrica/mcp@0.2.0"]
39
+ "args": ["-y", "@agentrica/mcp@0.3.0"]
40
40
  }
41
41
  }
42
42
  }
@@ -45,7 +45,7 @@ On first start npx downloads the package from npm. The version stays the one you
45
45
  **Least privilege (recommended).** Install the package in its own folder and start it with Node's permission model: the server can only read that folder, and Node blocks file writes, network connections and child processes. The server needs none of them, so it works the same; the permissions limit the damage of any future defect.
46
46
 
47
47
  ```sh
48
- npm install -g --ignore-scripts @agentrica/mcp@0.2.0
48
+ npm install -g --ignore-scripts @agentrica/mcp@0.3.0
49
49
  npm root -g
50
50
  ```
51
51
 
@@ -72,7 +72,7 @@ Put the task in quotes: Claude Code splits arguments on spaces.
72
72
  **Squad.** With `--agents` the server loads only the agents you list: agent ids and department codes, comma-separated, case-insensitive. For example the whole software department plus the accessibility agent:
73
73
 
74
74
  ```sh
75
- claude mcp add agentrica -- npx -y @agentrica/mcp@0.2.0 --agents aisa,aiwda-08
75
+ claude mcp add agentrica -- npx -y @agentrica/mcp@0.3.0 --agents aisa,aiwda-08
76
76
  ```
77
77
 
78
78
  The command menu shows only the squad's prompts, and `elenca_agenti` and `agente` see only those agents too. Without `--agents` all 56 agents are available. An unknown id or code stops the server with a message naming it, in the client's logs. In Claude Code prompts do not enter the model's context (we checked with `/context`): a squad makes the menu shorter, it does not save tokens.
@@ -88,12 +88,58 @@ For example: "Use elenca_agenti, pick the right Agentrica agent and check the ac
88
88
 
89
89
  Number 01 in each department is the director: it coordinates the specialists and consolidates their findings.
90
90
 
91
+ ## Local panel
92
+
93
+ With `--panel` the server also opens a page on your computer where you follow the project and make the choices the agent asks you for, instead of answering in the terminal:
94
+
95
+ ```sh
96
+ claude mcp add agentrica -- npx -y @agentrica/mcp@0.3.0 --panel
97
+ ```
98
+
99
+ Then ask the agent to open the panel (`open_panel` tool): the page opens in your browser. It shows:
100
+
101
+ - **Da decidere** (to decide): pending choices, with options and reasons; your answer, with an optional note, goes back to the agent;
102
+ - **Agenti in uso** (agents in use): the Agentrica agents called in this session, with the start of the task;
103
+ - **Fasi** (phases): the project phases, the open phase with backlog and acceptance criteria;
104
+ - **Rilievi** (findings): open findings from phases and audits, by priority and department.
105
+
106
+ With the panel the model has two more tools:
107
+
108
+ | Tool | Input | What it does |
109
+ |---|---|---|
110
+ | `open_panel` | none | opens the page in the browser and returns its URL |
111
+ | `ask_user` | `question`, 2–4 `options` (`label`, `description`), optional `header` and `multiple` | shows the choice in the page and returns the answer |
112
+
113
+ If the page is not open, `ask_user` opens it. The client waits for the answer as long as the server sends progress notifications (up to 4 hours; 25 minutes with a client that does not request them), then the agent asks in the terminal. The client's own questions, such as tool permissions, stay in the client.
114
+
115
+ **What changes with `--panel`.** The server opens a random port on `127.0.0.1` only, reads `plan/`, `audit/` and the git status (`git status`) of the project folder, and keeps the last 20 agent calls in memory. It writes no files and sends no data off your computer. The page opens only with the random token in the URL, valid for that session; requests from other sites or with another `Host` are refused. The Node permission model recommended above does not apply with `--panel`, which needs the local network and `git`.
116
+
117
+ **Format of `plan/` and `audit/`.** The panel reads the agentic-starter plan format, in Italian, the same as Agentrica's own [`plan/`](https://github.com/flgisimone/agentrica/tree/main/plan) and [`audit/`](https://github.com/flgisimone/agentrica/tree/main/audit); if something is missing, the page says what.
118
+
119
+ - `plan/README.md` with a `## Fasi` section and a `| Fase | File | Contenuto | Stato |` table, the file as a link (`[14-pannello.md](14-pannello.md)`). The open phase is the first one whose status is neither `completata` nor `sospesa`.
120
+ - In the phase file: `# Title`, a `**Obiettivo**: …` line, `## Backlog` with the `| # | Task | Priorità |` table, `## Criteri di accettazione` and `## Fatto` as lists; a task is done when its id appears in bold under «Fatto» (`- **F14-01** …`). `## Rilievi aperti` is a list, with the priority (`P0`–`P3`) in the text.
121
+ - `audit/<folder>/<file>.json` with `agente` (e.g. `"AICA-02 · …"`, which gives the department) and a `rilievi` list of objects with `id`, `titolo`, `priorita` and optional `stato`.
122
+
123
+ ## Put to the test
124
+
125
+ Three agents tested on 2026-11-15 against three small projects with planted, documented defects, using `@agentrica/mcp@0.2.0 --agents <id>`, Claude Code for VS Code and Opus 5.5 (medium reasoning). One run per case, counted by hand.
126
+
127
+ | Agent | Project | Defects found | False findings | Other valid findings |
128
+ |---|---|---|---|---|
129
+ | AISA-09 · REGULUS, Application Security | Node REST API | 6 of 6 | 0 | 2 |
130
+ | AIWDA-08 · GACRUX, Accessibility | sign-up form | 8 of 8 | 0 | 2 |
131
+ | AIPCA-02 · ALIOTH, GDPR | gym booking service | 7 of 7 | 0 | 3 |
132
+
133
+ Limits: the defects are few, known and fairly obvious; one model and one run per case; a result like this says nothing about how an agent does on a large project. Projects, expected defects, counting rules and the agents' full reports (in Italian) are in [`examples/`](https://github.com/flgisimone/agentrica/tree/main/examples): you can repeat the tests.
134
+
91
135
  ## Updates
92
136
 
93
137
  The agents' text comes from the `agents/` files of the installed version. To update, change the version in the command (or reinstall with `npm install -g`) and restart the client. Ids and code names do not change.
94
138
 
95
139
  ## Versions
96
140
 
141
+ - **0.3.0**: local panel with `--panel`: phases, backlog, findings, agents in use and choices made from the page (`open_panel` and `ask_user` tools). Without `--panel` nothing changes.
142
+ - **0.2.1**: name `io.github.flgisimone/agentrica` for the official MCP registry; agents and behaviour unchanged.
97
143
  - **0.2.0**: `--agents` argument to load only a squad of agents or departments; in an empty project, or when what the role must examine is missing, the agent says so and proposes first steps to confirm, without inventing findings.
98
144
  - **0.1.0**: first published version. 56 agents in five departments, one prompt per agent and the `elenca_agenti` and `agente` tools.
99
145
 
package/README.md CHANGED
@@ -10,7 +10,7 @@ Ogni agente è un ruolo con un metodo e dei limiti dichiarati, per esempio `AISA
10
10
 
11
11
  - Il server gira solo in locale: lo avvia il client sul tuo computer e i due comunicano con stdio. Il server non ha una parte remota.
12
12
  - Come contenuto legge solo i file di `agents/` inclusi nel pacchetto, una volta all'avvio. Il testo che arriva al modello è quello di quei file: puoi leggerlo prima di usarlo.
13
- - Non scrive file, non apre connessioni di rete, non registra, non raccoglie e non invia dati, non ha telemetria.
13
+ - Non scrive file, non apre connessioni di rete, non registra, non raccoglie e non invia dati, non ha telemetria. Con `--panel` apre una pagina solo sul tuo computer: vedi [Pannello locale](#pannello-locale).
14
14
  - Non esegue niente nel tuo progetto. Dà soltanto istruzioni al modello: quello che il modello fa nel progetto dipende dal client e dai permessi che gli concedi.
15
15
  - **Dove vanno i dati.** Il testo dell'agente, il compito e i file che il modello legge nel tuo progetto vanno al fornitore del modello attraverso il tuo client, secondo le condizioni di quel fornitore. Agentrica non li riceve. Nel compito non inserire dati personali, segreti o dati di clienti che non servono.
16
16
  - Gli agenti sono IA: le loro conclusioni sono proposte da verificare. Gli agenti di privacy e sicurezza non sostituiscono un DPO, un avvocato o un responsabile della sicurezza, e i loro rilievi non sono una certificazione di conformità.
@@ -22,7 +22,7 @@ Serve Node 22 o successivo, con npm.
22
22
  **Claude Code**, dalla cartella del tuo progetto:
23
23
 
24
24
  ```sh
25
- claude mcp add agentrica -- npx -y @agentrica/mcp@0.2.0
25
+ claude mcp add agentrica -- npx -y @agentrica/mcp@0.3.0
26
26
  ```
27
27
 
28
28
  Al primo avvio npx scarica il pacchetto da npm. La versione resta quella indicata finché non la cambi tu: un aggiornamento dei ruoli non arriva senza che tu lo scelga.
@@ -34,7 +34,7 @@ Al primo avvio npx scarica il pacchetto da npm. La versione resta quella indicat
34
34
  "mcpServers": {
35
35
  "agentrica": {
36
36
  "command": "npx",
37
- "args": ["-y", "@agentrica/mcp@0.2.0"]
37
+ "args": ["-y", "@agentrica/mcp@0.3.0"]
38
38
  }
39
39
  }
40
40
  }
@@ -43,7 +43,7 @@ Al primo avvio npx scarica il pacchetto da npm. La versione resta quella indicat
43
43
  **Permessi minimi (consigliato).** Installa il pacchetto in una cartella sua e avvialo con il permission model di Node: il server può solo leggere quella cartella, e Node blocca scritture su file, connessioni di rete e processi figli. Il server non ne ha bisogno, quindi funziona uguale; i permessi limitano i danni di un eventuale difetto futuro.
44
44
 
45
45
  ```sh
46
- npm install -g --ignore-scripts @agentrica/mcp@0.2.0
46
+ npm install -g --ignore-scripts @agentrica/mcp@0.3.0
47
47
  npm root -g
48
48
  ```
49
49
 
@@ -70,7 +70,7 @@ Metti il compito fra virgolette: Claude Code separa gli argomenti con gli spazi.
70
70
  **Squadra.** Con `--agents` il server carica solo gli agenti che indichi: id di agenti e sigle di reparti, separati da virgole, senza distinguere maiuscole. Per esempio tutto il reparto software più l'agente dell'accessibilità:
71
71
 
72
72
  ```sh
73
- claude mcp add agentrica -- npx -y @agentrica/mcp@0.2.0 --agents aisa,aiwda-08
73
+ claude mcp add agentrica -- npx -y @agentrica/mcp@0.3.0 --agents aisa,aiwda-08
74
74
  ```
75
75
 
76
76
  Nel menu dei comandi restano solo i prompt della squadra, e anche `elenca_agenti` e `agente` vedono solo quelli. Senza `--agents` ci sono tutti i 56 agenti. Un id o una sigla sconosciuti fermano il server con un messaggio che li nomina, nei log del client. In Claude Code i prompt non entrano nel contesto del modello (lo abbiamo verificato con `/context`): la squadra rende il menu più corto, ma non fa risparmiare token.
@@ -88,12 +88,58 @@ Il numero 01 di ogni reparto è il direttore: coordina gli specialisti e consoli
88
88
 
89
89
  I file degli agenti sono in italiano; l'agente risponde nella lingua in cui gli scrivi.
90
90
 
91
+ ## Pannello locale
92
+
93
+ Con `--panel` il server apre anche una pagina sul tuo computer da cui segui il progetto e prendi le scelte che l'agente ti chiede, invece di rispondere nel terminale:
94
+
95
+ ```sh
96
+ claude mcp add agentrica -- npx -y @agentrica/mcp@0.3.0 --panel
97
+ ```
98
+
99
+ Poi chiedi all'agente di aprire il pannello (tool `open_panel`): la pagina si apre nel browser. Mostra:
100
+
101
+ - **Da decidere**: le scelte in attesa, con le opzioni e le motivazioni; la risposta, con una nota facoltativa, torna all'agente;
102
+ - **Agenti in uso**: gli agenti di Agentrica chiamati in questa sessione, con l'inizio del compito;
103
+ - **Fasi**: le fasi del progetto, la fase aperta con backlog e criteri di accettazione;
104
+ - **Rilievi**: i rilievi aperti delle fasi e quelli degli audit, per priorità e reparto.
105
+
106
+ Con il pannello il modello ha due tool in più:
107
+
108
+ | Tool | Input | Cosa fa |
109
+ |---|---|---|
110
+ | `open_panel` | nessuno | apre la pagina nel browser e ne restituisce l'URL |
111
+ | `ask_user` | `question`, 2–4 `options` (`label`, `description`), `header` e `multiple` facoltativi | mostra la scelta nella pagina e restituisce la risposta |
112
+
113
+ Se la pagina non è aperta, `ask_user` la apre. Il client aspetta la risposta finché il server manda notifiche di avanzamento (fino a 4 ore; 25 minuti con un client che non le chiede), poi l'agente chiede nel terminale. Le domande del client, come i permessi dei tool, restano nel client.
114
+
115
+ **Cosa cambia con `--panel`.** Il server apre una porta casuale solo su `127.0.0.1`, legge `plan/`, `audit/` e lo stato di git (`git status`) della cartella del progetto e tiene in memoria le ultime 20 chiamate agli agenti. Non scrive file e non manda dati fuori dal computer. La pagina si apre solo con il token casuale contenuto nell'URL, che vale per quella sessione; le richieste da altri siti o con un altro `Host` sono rifiutate. Il permission model di Node consigliato sopra non si usa con `--panel`, che ha bisogno della rete locale e di `git`.
116
+
117
+ **Formato di `plan/` e `audit/`.** Il pannello legge il formato dei piani di agentic-starter, lo stesso del [`plan/`](https://github.com/flgisimone/agentrica/tree/main/plan) e dell'[`audit/`](https://github.com/flgisimone/agentrica/tree/main/audit) di Agentrica; se qualcosa manca, la pagina dice cosa.
118
+
119
+ - `plan/README.md` con una sezione `## Fasi` e una tabella `| Fase | File | Contenuto | Stato |`, il file come link (`[14-pannello.md](14-pannello.md)`). La fase aperta è la prima con uno stato diverso da `completata` e `sospesa`.
120
+ - Nel file della fase: `# Titolo`, una riga `**Obiettivo**: …`, `## Backlog` con la tabella `| # | Task | Priorità |`, `## Criteri di accettazione` e `## Fatto` come elenchi; un task è fatto quando il suo id compare in grassetto in «Fatto» (`- **F14-01** …`). `## Rilievi aperti` è un elenco, con la priorità (`P0`–`P3`) nel testo.
121
+ - `audit/<cartella>/<file>.json` con `agente` (es. `"AICA-02 · …"`, da cui il reparto) e un elenco `rilievi` di oggetti con `id`, `titolo`, `priorita` e `stato` facoltativo.
122
+
123
+ ## Messi alla prova
124
+
125
+ Tre agenti provati il 2026-11-15 su tre piccoli progetti con difetti piantati e documentati, con `@agentrica/mcp@0.2.0 --agents <id>`, Claude Code per VS Code e Opus 5.5 (ragionamento medio). Un'esecuzione per caso, contata a mano.
126
+
127
+ | Agente | Progetto | Difetti trovati | Rilievi falsi | Altri rilievi validi |
128
+ |---|---|---|---|---|
129
+ | AISA-09 · REGULUS, Application Security | API REST in Node | 6 su 6 | 0 | 2 |
130
+ | AIWDA-08 · GACRUX, Accessibility | form di iscrizione | 8 su 8 | 0 | 2 |
131
+ | AIPCA-02 · ALIOTH, GDPR | prenotazioni di una palestra | 7 su 7 | 0 | 3 |
132
+
133
+ Limiti: i difetti sono pochi, noti e abbastanza evidenti; un solo modello e una sola esecuzione per caso; un risultato del genere non dice come va un agente su un progetto grande. Progetti, difetti attesi, regole di conteggio e rapporti completi degli agenti sono in [`examples/`](https://github.com/flgisimone/agentrica/tree/main/examples): puoi ripetere le prove.
134
+
91
135
  ## Aggiornamenti
92
136
 
93
137
  Il testo degli agenti viene dai file di `agents/` della versione installata. Per aggiornare cambia la versione nel comando (o reinstalla con `npm install -g`) e riavvia il client. Gli id e i nomi in codice non cambiano.
94
138
 
95
139
  ## Versioni
96
140
 
141
+ - **0.3.0**: pannello locale con `--panel`: fasi, backlog, rilievi, agenti in uso e scelte da prendere dalla pagina (tool `open_panel` e `ask_user`). Senza `--panel` nulla cambia.
142
+ - **0.2.1**: nome `io.github.flgisimone/agentrica` per il registro MCP ufficiale; agenti e comportamento invariati.
97
143
  - **0.2.0**: argomento `--agents` per caricare solo una squadra di agenti o reparti; con un progetto vuoto, o senza ciò che il ruolo deve esaminare, l'agente lo dice e propone i primi passi da confermare, senza inventare rilievi.
98
144
  - **0.1.0**: prima versione pubblicata. 56 agenti in cinque reparti, un prompt per agente e i tool `elenca_agenti` e `agente`.
99
145
 
@@ -0,0 +1,282 @@
1
+ // Pagina del pannello: legge /api/state, si aggiorna con /api/events e manda le risposte a /api/answer.
2
+ // I dati del progetto entrano nel DOM solo come testo (textContent), mai come HTML.
3
+ "use strict";
4
+
5
+ const DEPARTMENTS = ["AIBPD", "AICA", "AIPCA", "AISA", "AIWDA"];
6
+ const PRIORITIES = ["P0", "P1", "P2", "P3", ""];
7
+ const REFRESH_MS = 10_000;
8
+ const TITLE = "Agentrica · pannello";
9
+
10
+ let state = null;
11
+ let filter = "";
12
+ const $ = (id) => document.getElementById(id);
13
+
14
+ /** Crea un elemento con attributi e figli (stringhe o nodi). */
15
+ function el(tag, attrs = {}, ...children) {
16
+ const node = document.createElement(tag);
17
+ for (const [key, value] of Object.entries(attrs)) {
18
+ if (value === false || value == null) continue;
19
+ if (key === "class") node.className = value;
20
+ else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);
21
+ else node.setAttribute(key, value === true ? "" : value);
22
+ }
23
+ node.append(...children.flat().filter((c) => c != null && c !== false));
24
+ return node;
25
+ }
26
+
27
+ /** Testo dei file Markdown: `codice` diventa <code>, link e grassetti restano solo testo. */
28
+ function inline(text) {
29
+ const plain = text.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/\*\*([^*]+)\*\*/g, "$1");
30
+ return plain.split("`").map((part, i) => (i % 2 ? el("code", {}, part) : part));
31
+ }
32
+
33
+ const time = (iso) => new Date(iso).toLocaleTimeString("it-IT", { hour: "2-digit", minute: "2-digit" });
34
+ const empty = (text) => el("p", { class: "empty" }, text);
35
+
36
+ function renderHeader({ project }) {
37
+ const git = project.git
38
+ ? ` · branch ${project.git.branch} · ${project.git.changed === 1 ? "1 file modificato" : `${project.git.changed} file modificati`}`
39
+ : " · non è un repository git";
40
+ $("project").textContent = project.name + git;
41
+ const problems = $("problems");
42
+ problems.hidden = project.problems.length === 0;
43
+ problems.textContent = project.problems.join("\n");
44
+ }
45
+
46
+ // Le domande non si ridisegnano a ogni aggiornamento: una scelta a metà resterebbe persa.
47
+ function renderQuestions({ questions }) {
48
+ const box = $("questions");
49
+ const ids = new Set(questions.map((q) => q.id));
50
+ for (const node of [...box.querySelectorAll("[data-question]")]) {
51
+ if (!ids.has(node.dataset.question) && !node.dataset.sent) node.remove();
52
+ }
53
+ for (const question of questions) {
54
+ if (!box.querySelector(`[data-question="${CSS.escape(question.id)}"]`)) box.append(questionCard(question));
55
+ }
56
+ const waiting = questions.length;
57
+ box.querySelector(".empty")?.remove();
58
+ if (!box.querySelector("[data-question]")) {
59
+ box.append(empty("Nessuna scelta in attesa. Quando un agente ha bisogno di te, la domanda compare qui."));
60
+ }
61
+ document.title = waiting ? `(${waiting}) ${TITLE}` : TITLE;
62
+ }
63
+
64
+ function questionCard(question) {
65
+ const name = `q-${question.id}`;
66
+ const type = question.multiple ? "checkbox" : "radio";
67
+ const error = el("p", { class: "error", role: "alert", hidden: true });
68
+ const note = el("textarea", { name: "note", maxlength: "2000" });
69
+ const options = question.options.map((option) => {
70
+ const recommended = /\s*\((Recommended|Consigliata)\)\s*$/i;
71
+ return el(
72
+ "label",
73
+ { class: "option" },
74
+ el("input", { type, name, value: option.label }),
75
+ el(
76
+ "span",
77
+ {},
78
+ el("strong", {}, option.label.replace(recommended, ""), recommended.test(option.label) && el("span", { class: "recommended" }, "Consigliata")),
79
+ option.description,
80
+ ),
81
+ );
82
+ });
83
+ const form = el(
84
+ "form",
85
+ { class: "question", "data-question": question.id, onsubmit: (event) => submit(event, question, form, error) },
86
+ question.header && el("span", { class: "tag" }, question.header),
87
+ el("fieldset", {}, el("legend", {}, question.question), options),
88
+ el("label", { class: "note" }, "Nota (facoltativa)", note),
89
+ el("button", { type: "submit", class: "send" }, "Invia risposta"),
90
+ error,
91
+ );
92
+ $("announce").textContent = `Nuova scelta da prendere: ${question.question}`;
93
+ return form;
94
+ }
95
+
96
+ async function submit(event, question, form, error) {
97
+ event.preventDefault();
98
+ const choices = [...form.querySelectorAll("input:checked")].map((input) => input.value);
99
+ const note = form.elements.note.value;
100
+ if (choices.length === 0 && note.trim() === "") {
101
+ error.textContent = "Scegli un'opzione o scrivi una nota.";
102
+ error.hidden = false;
103
+ return;
104
+ }
105
+ const response = await fetch("/api/answer", {
106
+ method: "POST",
107
+ headers: { "Content-Type": "application/json" },
108
+ body: JSON.stringify({ id: question.id, choices, note }),
109
+ }).catch(() => null);
110
+ if (!response || !response.ok) {
111
+ error.textContent = response ? await response.text() : "Il pannello non risponde: la sessione è ancora aperta?";
112
+ error.hidden = false;
113
+ return;
114
+ }
115
+ form.dataset.sent = "true";
116
+ form.replaceChildren(el("p", { class: "sent", role: "status" }, `Risposta inviata: ${[...choices, note.trim()].filter(Boolean).join(", ")}`));
117
+ setTimeout(() => {
118
+ form.remove();
119
+ if (state) renderQuestions(state);
120
+ }, 5000);
121
+ }
122
+
123
+ function renderActivity({ activity }) {
124
+ $("activity").replaceChildren(
125
+ activity.length === 0
126
+ ? empty("Nessun agente usato in questa sessione.")
127
+ : el(
128
+ "ol",
129
+ { class: "activity" },
130
+ activity.map((a) =>
131
+ el(
132
+ "li",
133
+ { "data-dept": a.department },
134
+ el("time", { datetime: a.time, class: "mono" }, time(a.time)),
135
+ el("span", { class: "dot" }, el("strong", {}, a.codeName), ` — ${a.role}`),
136
+ a.task && el("span", { class: "task" }, a.task),
137
+ ),
138
+ ),
139
+ ),
140
+ );
141
+ }
142
+
143
+ function table(head, rows) {
144
+ return el(
145
+ "div",
146
+ { class: "scroll" },
147
+ el("table", {}, el("thead", {}, el("tr", {}, head.map((h) => el("th", { scope: "col" }, h)))), el("tbody", {}, rows)),
148
+ );
149
+ }
150
+
151
+ function renderPhases({ project }) {
152
+ const open = project.openPhase;
153
+ $("open-phase").replaceChildren(
154
+ ...(open
155
+ ? [
156
+ el("h3", {}, inline(open.title), ` — ${open.status}`),
157
+ open.goal && el("p", { class: "goal" }, inline(open.goal)),
158
+ open.tasks.length
159
+ ? table(
160
+ ["Task", "Descrizione", "Priorità", "Stato"],
161
+ open.tasks.map((t) =>
162
+ el(
163
+ "tr",
164
+ {},
165
+ el("th", { scope: "row", class: "mono" }, t.id),
166
+ el("td", {}, inline(t.task)),
167
+ el("td", {}, t.priority),
168
+ el("td", { class: t.done ? "status-done" : "" }, t.done ? "Fatto" : "Da fare"),
169
+ ),
170
+ ),
171
+ )
172
+ : empty("Backlog non ancora scritto."),
173
+ open.criteria.length > 0 && el("h3", {}, "Criteri di accettazione"),
174
+ open.criteria.length > 0 && el("ul", { class: "criteria" }, open.criteria.map((c) => el("li", {}, inline(c)))),
175
+ ]
176
+ : []),
177
+ );
178
+ // Aperto solo senza una fase in corso: altrimenti la tabella completa spinge giù i rilievi.
179
+ const all = $("phases").querySelector("details");
180
+ const wasOpen = all ? all.open : !open;
181
+ $("phases").replaceChildren(
182
+ project.phases.length === 0
183
+ ? empty("Nessuna fase trovata in plan/README.md.")
184
+ : el("details", { open: wasOpen }, el("summary", {}, `Tutte le fasi (${project.phases.length})`), table(
185
+ ["Fase", "Contenuto", "Stato"],
186
+ project.phases.map((p) =>
187
+ el(
188
+ "tr",
189
+ { class: open && p.id === open.id ? "current" : "" },
190
+ el("th", { scope: "row" }, p.id),
191
+ el("td", {}, inline(p.summary)),
192
+ el("td", {}, p.status),
193
+ ),
194
+ ),
195
+ )),
196
+ );
197
+ }
198
+
199
+ // I pulsanti si creano una volta sola: ricrearli a ogni aggiornamento toglierebbe il focus da tastiera.
200
+ function renderFilters() {
201
+ const box = $("filters");
202
+ if (!box.firstChild) {
203
+ box.append(
204
+ ...["", ...DEPARTMENTS].map((code) =>
205
+ el("button", { type: "button", "data-code": code, onclick: () => ((filter = code), render()) }, code || "Tutti"),
206
+ ),
207
+ );
208
+ }
209
+ for (const button of box.children) button.setAttribute("aria-pressed", String(button.dataset.code === filter));
210
+ }
211
+
212
+ const LABELS = { P0: "P0 · critica", P1: "P1 · alta", P2: "P2 · media", P3: "P3 · bassa", "": "Senza priorità" };
213
+
214
+ function findingItem(f) {
215
+ return el(
216
+ "li",
217
+ {},
218
+ f.id && el("strong", { class: "mono" }, `${f.id} `),
219
+ inline(f.title),
220
+ el("span", { class: "finding-meta" }, [f.department, f.source, f.status].filter(Boolean).join(" · ")),
221
+ );
222
+ }
223
+
224
+ // Un gruppo per priorità, richiudibile: P0 e P1 aperti, gli altri chiusi; si ricorda la scelta dell'utente.
225
+ const opened = { P0: true, P1: true };
226
+
227
+ function renderFindings({ project }) {
228
+ const shown = project.findings.filter((f) => !filter || f.department === filter);
229
+ const fromPhases = (f) => !f.source.endsWith(".json");
230
+ const groups = PRIORITIES.map((priority) => {
231
+ const items = shown.filter((f) => f.priority === priority).sort((a, b) => fromPhases(b) - fromPhases(a));
232
+ if (items.length === 0) return null;
233
+ const details = el(
234
+ "details",
235
+ { open: Boolean(opened[priority]), ontoggle: () => (opened[priority] = details.open) },
236
+ el("summary", {}, el("span", { class: `prio prio-${priority}` }, LABELS[priority]), ` (${items.length})`),
237
+ el("ul", { class: "findings" }, items.map(findingItem)),
238
+ );
239
+ return details;
240
+ });
241
+ $("findings").replaceChildren(
242
+ ...(shown.length ? groups.filter(Boolean) : [empty(filter ? `Nessun rilievo di ${filter}.` : "Nessun rilievo.")]),
243
+ el("p", { class: "hint" }, "In ogni gruppo prima i «Rilievi aperti» dei file di fase, poi i rilievi degli audit con il loro stato."),
244
+ );
245
+ }
246
+
247
+ function render() {
248
+ if (!state) return;
249
+ renderHeader(state);
250
+ renderQuestions(state);
251
+ renderActivity(state);
252
+ renderPhases(state);
253
+ renderFilters();
254
+ renderFindings(state);
255
+ }
256
+
257
+ async function refresh() {
258
+ const response = await fetch("/api/state").catch(() => null);
259
+ if (!response || !response.ok) return;
260
+ state = await response.json();
261
+ render();
262
+ }
263
+
264
+ function connect() {
265
+ const link = $("link");
266
+ const events = new EventSource("/api/events");
267
+ events.onopen = () => {
268
+ link.dataset.state = "ok";
269
+ link.textContent = "Sessione collegata";
270
+ refresh();
271
+ };
272
+ events.addEventListener("change", refresh);
273
+ events.onerror = () => {
274
+ link.dataset.state = "off";
275
+ link.textContent = "Collegamento con la sessione interrotto. Riavvia la sessione di Claude Code per riaprire il pannello.";
276
+ };
277
+ }
278
+
279
+ connect();
280
+ refresh();
281
+ setInterval(() => document.visibilityState === "visible" && refresh(), REFRESH_MS);
282
+ document.addEventListener("visibilitychange", () => document.visibilityState === "visible" && refresh());
@@ -0,0 +1,44 @@
1
+ <!doctype html>
2
+ <html lang="it">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <meta name="color-scheme" content="dark" />
7
+ <title>Agentrica · pannello</title>
8
+ <link rel="stylesheet" href="/style.css" />
9
+ <script src="/app.js" defer></script>
10
+ </head>
11
+ <body>
12
+ <header class="top">
13
+ <div class="wrap top-row">
14
+ <h1 class="brand">Agentrica <span aria-hidden="true">·</span> pannello</h1>
15
+ <p class="meta" id="project">Caricamento…</p>
16
+ <p class="link" id="link" role="status">Collegamento in corso…</p>
17
+ </div>
18
+ </header>
19
+ <main class="wrap">
20
+ <p class="problems" id="problems" hidden></p>
21
+ <div class="live">
22
+ <section aria-labelledby="h-decide" class="card">
23
+ <h2 id="h-decide">Da decidere</h2>
24
+ <div id="announce" class="sr-only" aria-live="polite"></div>
25
+ <div id="questions"></div>
26
+ </section>
27
+ <section aria-labelledby="h-agents" class="card">
28
+ <h2 id="h-agents">Agenti in uso</h2>
29
+ <div id="activity"></div>
30
+ </section>
31
+ </div>
32
+ <section aria-labelledby="h-phases" class="card">
33
+ <h2 id="h-phases">Fasi</h2>
34
+ <div id="open-phase"></div>
35
+ <div id="phases"></div>
36
+ </section>
37
+ <section aria-labelledby="h-findings" class="card">
38
+ <h2 id="h-findings">Rilievi</h2>
39
+ <div id="filters" class="filters" role="group" aria-label="Filtra per reparto"></div>
40
+ <div id="findings"></div>
41
+ </section>
42
+ </main>
43
+ </body>
44
+ </html>
@@ -0,0 +1,110 @@
1
+ /* Palette del sito (apps/site/src/app/globals.css), tema scuro; contrasti AA misurati lì sugli stessi fondi. */
2
+ :root {
3
+ --background: #0b1020;
4
+ --foreground: #e8ebf4;
5
+ --card: #121a2e;
6
+ --secondary: #18223b;
7
+ --muted-foreground: #a8b1c7;
8
+ --destructive: #ff7a6b;
9
+ --border: #26324f;
10
+ --ring: #ffffff;
11
+ --aibpd: #f5b544;
12
+ --aica: #ff7a6b;
13
+ --aipca: #b49cff;
14
+ --aisa: #38d6f0;
15
+ --aiwda: #4fe0a8;
16
+ --dept: var(--muted-foreground);
17
+ --radius: 12px;
18
+ color-scheme: dark;
19
+ }
20
+
21
+ [data-dept="AIBPD"] { --dept: var(--aibpd); }
22
+ [data-dept="AICA"] { --dept: var(--aica); }
23
+ [data-dept="AIPCA"] { --dept: var(--aipca); }
24
+ [data-dept="AISA"] { --dept: var(--aisa); }
25
+ [data-dept="AIWDA"] { --dept: var(--aiwda); }
26
+
27
+ * { box-sizing: border-box; }
28
+
29
+ body {
30
+ margin: 0;
31
+ background: var(--background);
32
+ color: var(--foreground);
33
+ font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
34
+ }
35
+
36
+ code, .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 0.92em; }
37
+ code { background: var(--secondary); border-radius: 4px; padding: 0 0.25em; }
38
+
39
+ :focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
40
+
41
+ .wrap { max-width: 1200px; margin: 0 auto; padding: 0 16px; }
42
+
43
+ .top { border-bottom: 1px solid var(--border); background: var(--card); }
44
+ .top-row { display: flex; flex-wrap: wrap; gap: 4px 24px; align-items: baseline; padding-block: 12px; }
45
+ .top p { margin: 0; }
46
+ .brand { font-size: 1rem; font-weight: 700; margin: 0; }
47
+ .meta, .link { color: var(--muted-foreground); }
48
+ .link { margin-left: auto; }
49
+ .link[data-state="ok"]::before { content: "● "; color: var(--aiwda); }
50
+ .link[data-state="off"] { color: var(--destructive); }
51
+
52
+ main { display: grid; gap: 16px; padding-block: 16px 48px; }
53
+ .live { display: grid; gap: 16px; }
54
+ @media (min-width: 960px) { .live { grid-template-columns: 3fr 2fr; align-items: start; } }
55
+
56
+ .card { background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px 20px; min-width: 0; }
57
+ h2 { font-size: 1.15rem; margin: 0 0 12px; }
58
+ h3 { font-size: 1rem; margin: 16px 0 8px; }
59
+ .empty, .hint { color: var(--muted-foreground); margin: 0; }
60
+ .problems { margin: 0; padding: 12px 16px; border: 1px solid var(--destructive); border-radius: var(--radius); white-space: pre-line; }
61
+
62
+ .question { border: 1px solid var(--border); border-radius: var(--radius); padding: 12px 16px; background: var(--secondary); }
63
+ .question + .question { margin-top: 12px; }
64
+ .question fieldset { border: 0; margin: 0; padding: 0; }
65
+ .question legend { font-weight: 600; padding: 0; margin-bottom: 8px; }
66
+ .tag { display: inline-block; font-size: 0.8rem; color: var(--muted-foreground); border: 1px solid var(--border); border-radius: 999px; padding: 0 8px; margin-bottom: 6px; }
67
+ .option { display: grid; grid-template-columns: auto 1fr; gap: 0 10px; padding: 8px; border-radius: 8px; cursor: pointer; }
68
+ .option:hover { background: var(--card); }
69
+ .option input { margin-top: 0.3em; accent-color: var(--aisa); width: 1.05rem; height: 1.05rem; }
70
+ .option strong { display: block; }
71
+ .option span { color: var(--muted-foreground); }
72
+ .recommended { color: var(--aiwda); font-size: 0.85rem; font-weight: 600; margin-left: 6px; }
73
+ label.note { display: block; margin-top: 8px; }
74
+ textarea { display: block; width: 100%; margin-top: 4px; min-height: 3.5em; resize: vertical; background: var(--background); color: var(--foreground); border: 1px solid var(--border); border-radius: 8px; padding: 8px; font: inherit; }
75
+ button { font: inherit; cursor: pointer; border-radius: 8px; }
76
+ .send { margin-top: 12px; background: var(--foreground); color: var(--background); border: 0; padding: 8px 16px; font-weight: 600; }
77
+ .error { color: var(--destructive); margin: 8px 0 0; }
78
+ .sent { margin: 0; }
79
+
80
+ ol.activity { list-style: none; margin: 0; padding: 0; }
81
+ ol.activity li { display: grid; grid-template-columns: 3.5em 1fr; gap: 0 8px; padding: 6px 0; border-top: 1px solid var(--border); }
82
+ ol.activity li:first-child { border-top: 0; }
83
+ .dot::before { content: "●"; color: var(--dept); margin-right: 6px; }
84
+ .task { grid-column: 2; color: var(--muted-foreground); overflow-wrap: anywhere; }
85
+
86
+ .scroll { overflow-x: auto; }
87
+ table { border-collapse: collapse; width: 100%; }
88
+ th, td { text-align: left; padding: 6px 10px 6px 0; border-top: 1px solid var(--border); vertical-align: top; }
89
+ thead th { border-top: 0; color: var(--muted-foreground); font-weight: 600; font-size: 0.9rem; }
90
+ tr.current td { color: var(--foreground); font-weight: 600; }
91
+ .status-done { color: var(--aiwda); }
92
+ .goal { margin: 0 0 8px; }
93
+ ul.criteria { margin: 0; padding-left: 1.2em; }
94
+
95
+ .filters { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 8px; }
96
+ .filters button { background: transparent; color: var(--foreground); border: 1px solid var(--border); padding: 4px 12px; }
97
+ .filters button[aria-pressed="true"] { background: var(--foreground); color: var(--background); border-color: var(--foreground); }
98
+ ul.findings { list-style: none; margin: 0; padding: 0; }
99
+ ul.findings li { padding: 8px 0; border-top: 1px solid var(--border); }
100
+ ul.findings li:first-child { border-top: 0; }
101
+ .finding-meta { display: block; color: var(--muted-foreground); font-size: 0.9rem; }
102
+ .prio { font-weight: 700; }
103
+ summary { cursor: pointer; padding: 6px 0; font-weight: 600; }
104
+ details + details { border-top: 1px solid var(--border); }
105
+ .hint { margin-top: 12px; font-size: 0.9rem; }
106
+ .prio-P0 { color: var(--destructive); }
107
+
108
+ .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
109
+
110
+ @media (prefers-reduced-motion: no-preference) { .option, .filters button { transition: background-color 120ms; } }
@@ -0,0 +1,220 @@
1
+ // Pannello locale: server HTTP nello stesso processo del server MCP, attivo solo con --panel.
2
+ // Chi raggiunge la pagina risponde alle domande dell'agente, quindi le difese sono strette: ascolto solo su 127.0.0.1
3
+ // con porta casuale; token casuale nell'URL aperto dal tool, scambiato con un cookie HttpOnly e SameSite=Strict;
4
+ // Host fisso contro il DNS rebinding; Origin fisso e JSON obbligatorio per le POST; CSP 'self' e nessuna risorsa
5
+ // esterna. Le rotte sono un elenco chiuso: nessun percorso dell'URL diventa un percorso di file.
6
+ import { spawn } from "node:child_process";
7
+ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
8
+ import { readFileSync } from "node:fs";
9
+ import { createServer } from "node:http";
10
+ import { join } from "node:path";
11
+ import { readProject } from "./project.js";
12
+ const MAX_BODY_BYTES = 16_000;
13
+ const MAX_NOTE = 2000;
14
+ const MAX_ACTIVITY = 20;
15
+ const KEEPALIVE_MS = 25_000;
16
+ const SECURITY_HEADERS = {
17
+ "Content-Security-Policy": "default-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
18
+ "X-Content-Type-Options": "nosniff",
19
+ "X-Frame-Options": "DENY",
20
+ "Referrer-Policy": "no-referrer",
21
+ "Cache-Control": "no-store",
22
+ "Cross-Origin-Resource-Policy": "same-origin",
23
+ };
24
+ const PAGE_FILES = {
25
+ "/": ["index.html", "text/html; charset=utf-8"],
26
+ "/app.js": ["app.js", "text/javascript; charset=utf-8"],
27
+ "/style.css": ["style.css", "text/css; charset=utf-8"],
28
+ };
29
+ function sameSecret(given, token) {
30
+ if (!given)
31
+ return false;
32
+ const a = Buffer.from(given);
33
+ const b = Buffer.from(token);
34
+ return a.length === b.length && timingSafeEqual(a, b);
35
+ }
36
+ function cookie(req, name) {
37
+ for (const part of (req.headers.cookie ?? "").split(";")) {
38
+ const [key, ...value] = part.trim().split("=");
39
+ if (key === name)
40
+ return value.join("=");
41
+ }
42
+ return undefined;
43
+ }
44
+ function send(res, status, body = "", type = "text/plain; charset=utf-8") {
45
+ res.writeHead(status, { ...SECURITY_HEADERS, "Content-Type": type });
46
+ res.end(body);
47
+ }
48
+ function readBody(req) {
49
+ return new Promise((resolve, reject) => {
50
+ let size = 0;
51
+ const chunks = [];
52
+ req.on("data", (chunk) => {
53
+ size += chunk.length;
54
+ if (size > MAX_BODY_BYTES) {
55
+ reject(new Error("corpo troppo grande"));
56
+ req.destroy();
57
+ }
58
+ else
59
+ chunks.push(chunk);
60
+ });
61
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
62
+ req.on("error", reject);
63
+ });
64
+ }
65
+ /** Controlla una risposta della pagina contro la domanda: etichette esistenti, una sola se la scelta è singola. */
66
+ export function parseAnswer(question, body) {
67
+ if (typeof body !== "object" || body === null)
68
+ return null;
69
+ const { choices, note = "" } = body;
70
+ if (!Array.isArray(choices) || typeof note !== "string" || note.length > MAX_NOTE)
71
+ return null;
72
+ const labels = new Set(question.options.map((o) => o.label));
73
+ const picked = [...new Set(choices)];
74
+ if (!picked.every((c) => typeof c === "string" && labels.has(c)))
75
+ return null;
76
+ if (picked.length === 0 && note.trim() === "")
77
+ return null;
78
+ if (!question.multiple && picked.length > 1)
79
+ return null;
80
+ return { choices: picked, note: note.trim() };
81
+ }
82
+ /** Apre l'URL nel browser predefinito; se non riesce (es. sessione remota) l'URL resta nella risposta del tool. */
83
+ export function openBrowser(url) {
84
+ const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
85
+ try {
86
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
87
+ child.on("error", () => { });
88
+ child.unref();
89
+ }
90
+ catch {
91
+ // Nessun browser: l'utente apre l'URL a mano.
92
+ }
93
+ }
94
+ export async function startPanel(root, pageDir = join(import.meta.dirname, "page")) {
95
+ const token = randomBytes(32).toString("hex");
96
+ const pages = Object.fromEntries(Object.entries(PAGE_FILES).map(([route, [file, type]]) => [route, { body: readFileSync(join(pageDir, file)), type }]));
97
+ const pending = new Map();
98
+ const activity = [];
99
+ const viewers = new Set();
100
+ const changed = () => {
101
+ for (const viewer of viewers)
102
+ viewer.write("event: change\ndata: {}\n\n");
103
+ };
104
+ const server = createServer((req, res) => {
105
+ // Un errore in una richiesta non deve fermare il processo, che è anche il server MCP della sessione.
106
+ handle(req, res).catch(() => {
107
+ if (!res.headersSent)
108
+ send(res, 500, "Errore del pannello.");
109
+ else
110
+ res.end();
111
+ });
112
+ });
113
+ async function handle(req, res) {
114
+ const port = server.address().port;
115
+ const origin = `http://127.0.0.1:${port}`;
116
+ if (req.headers.host !== `127.0.0.1:${port}`)
117
+ return send(res, 421, "Host non valido.");
118
+ const url = new URL(req.url ?? "/", origin);
119
+ const cookieName = `agentrica_panel_${port}`;
120
+ if (req.method === "GET" && url.pathname === "/" && url.searchParams.has("t")) {
121
+ if (!sameSecret(url.searchParams.get("t") ?? undefined, token))
122
+ return send(res, 403, "Token non valido.");
123
+ // Il token esce dalla barra degli indirizzi e dalla cronologia: da qui vale il cookie.
124
+ res.writeHead(303, { ...SECURITY_HEADERS, Location: "/", "Set-Cookie": `${cookieName}=${token}; HttpOnly; SameSite=Strict; Path=/` });
125
+ res.end();
126
+ return;
127
+ }
128
+ if (!sameSecret(cookie(req, cookieName), token)) {
129
+ return send(res, 403, "Apri il pannello dall'URL che dà il tool open_panel dell'agente.");
130
+ }
131
+ if (req.method === "GET" && url.pathname in pages) {
132
+ const page = pages[url.pathname];
133
+ return send(res, 200, page.body.toString("utf8"), page.type);
134
+ }
135
+ if (req.method === "GET" && url.pathname === "/api/state") {
136
+ const project = await readProject(root);
137
+ const questions = [...pending.values()].map((p) => p.question);
138
+ return send(res, 200, JSON.stringify({ project, questions, activity }), "application/json; charset=utf-8");
139
+ }
140
+ if (req.method === "GET" && url.pathname === "/api/events") {
141
+ res.writeHead(200, { ...SECURITY_HEADERS, "Content-Type": "text/event-stream; charset=utf-8", Connection: "keep-alive" });
142
+ res.write("retry: 3000\n\n");
143
+ viewers.add(res);
144
+ req.on("close", () => viewers.delete(res));
145
+ return;
146
+ }
147
+ if (req.method === "POST" && url.pathname === "/api/answer") {
148
+ if (req.headers.origin !== origin)
149
+ return send(res, 403, "Origine non valida.");
150
+ if (!req.headers["content-type"]?.startsWith("application/json"))
151
+ return send(res, 415, "Serve JSON.");
152
+ let body;
153
+ try {
154
+ body = JSON.parse(await readBody(req));
155
+ }
156
+ catch {
157
+ return send(res, 400, "Richiesta non valida.");
158
+ }
159
+ const entry = typeof body?.id === "string" ? pending.get(body.id) : undefined;
160
+ if (!entry)
161
+ return send(res, 404, "La domanda non è più in attesa.");
162
+ const answer = parseAnswer(entry.question, body);
163
+ if (!answer)
164
+ return send(res, 400, "Risposta non valida.");
165
+ entry.resolve(answer);
166
+ res.writeHead(204, SECURITY_HEADERS);
167
+ res.end();
168
+ return;
169
+ }
170
+ return send(res, 404, "Non trovato.");
171
+ }
172
+ await new Promise((resolve, reject) => {
173
+ server.once("error", reject);
174
+ server.listen(0, "127.0.0.1", resolve);
175
+ });
176
+ const port = server.address().port;
177
+ const keepalive = setInterval(() => viewers.forEach((viewer) => viewer.write(": ping\n\n")), KEEPALIVE_MS);
178
+ keepalive.unref();
179
+ server.unref();
180
+ return {
181
+ url: `http://127.0.0.1:${port}/?t=${token}`,
182
+ ask(input, signal) {
183
+ return new Promise((resolve, reject) => {
184
+ const id = randomUUID();
185
+ const done = () => {
186
+ pending.delete(id);
187
+ signal.removeEventListener("abort", abort);
188
+ changed();
189
+ };
190
+ const abort = () => {
191
+ done();
192
+ reject(signal.reason);
193
+ };
194
+ if (signal.aborted)
195
+ return reject(signal.reason);
196
+ signal.addEventListener("abort", abort);
197
+ pending.set(id, {
198
+ question: { ...input, id, askedAt: new Date().toISOString() },
199
+ resolve: (answer) => {
200
+ done();
201
+ resolve(answer);
202
+ },
203
+ });
204
+ changed();
205
+ });
206
+ },
207
+ record(entry) {
208
+ activity.unshift({ ...entry, time: new Date().toISOString() });
209
+ activity.length = Math.min(activity.length, MAX_ACTIVITY);
210
+ changed();
211
+ },
212
+ hasViewers: () => viewers.size > 0,
213
+ close() {
214
+ clearInterval(keepalive);
215
+ for (const viewer of viewers)
216
+ viewer.end();
217
+ return new Promise((resolve) => server.close(() => resolve()));
218
+ },
219
+ };
220
+ }
@@ -0,0 +1,184 @@
1
+ // Lettura del progetto dell'utente per il pannello: fasi e backlog da plan/, rilievi da plan/ e audit/, stato di git.
2
+ // Il formato è quello di agentic-starter, descritto nel README del pacchetto. Si legge solo dentro plan/ e audit/
3
+ // della cartella del progetto: i link simbolici che escono sono rifiutati e ogni file ha un limite di dimensione.
4
+ // Un file mancante o fuori formato diventa un problema in `problems`, mai un errore che ferma il pannello.
5
+ import { execFile } from "node:child_process";
6
+ import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
7
+ import { basename, join, sep } from "node:path";
8
+ import { promisify } from "node:util";
9
+ const MAX_FILE_BYTES = 1_000_000;
10
+ const DEPARTMENT = /\b(AIBPD|AICA|AIPCA|AISA|AIWDA)\b/;
11
+ const PRIORITY = /\bP[0-3]\b/;
12
+ const CLOSED = new Set(["completata", "sospesa"]);
13
+ /** Legge un file di testo sotto `root`, rifiutando link simbolici che escono e file troppo grandi. */
14
+ function readInside(root, path) {
15
+ const real = realpathSync(path);
16
+ if (!real.startsWith(root + sep))
17
+ throw new Error("fuori dalla cartella del progetto");
18
+ if (statSync(real).size > MAX_FILE_BYTES)
19
+ throw new Error("file troppo grande");
20
+ return readFileSync(real, "utf8");
21
+ }
22
+ /** Le righe di una sezione «## Titolo», fino alla sezione successiva dello stesso livello. */
23
+ export function section(markdown, heading) {
24
+ const lines = markdown.split("\n");
25
+ const start = lines.findIndex((line) => line.trim() === `## ${heading}`);
26
+ if (start === -1)
27
+ return null;
28
+ const end = lines.findIndex((line, i) => i > start && line.startsWith("## "));
29
+ return lines.slice(start + 1, end === -1 ? undefined : end);
30
+ }
31
+ /** Le righe di dati della prima tabella Markdown fra `lines`, senza intestazione e separatore. */
32
+ export function tableRows(lines) {
33
+ const rows = lines.filter((line) => line.trim().startsWith("|"));
34
+ return rows.slice(2).map((row) => row.trim().replace(/^\||\|$/g, "").split("|").map((cell) => cell.trim()));
35
+ }
36
+ /** Gli elementi di primo livello di un elenco puntato. */
37
+ export function bullets(lines) {
38
+ return lines.filter((line) => line.startsWith("- ")).map((line) => line.slice(2).trim());
39
+ }
40
+ const linkTarget = (cell) => /\]\(([^)]+)\)/.exec(cell)?.[1] ?? null;
41
+ const priorityOf = (text) => PRIORITY.exec(text)?.[0] ?? "";
42
+ function readPhases(root, plan, problems) {
43
+ let readme;
44
+ try {
45
+ readme = readInside(root, join(plan, "README.md"));
46
+ }
47
+ catch {
48
+ problems.push("Non trovo plan/README.md: il pannello legge il formato di agentic-starter (vedi il README del pacchetto).");
49
+ return [];
50
+ }
51
+ const fasi = section(readme, "Fasi");
52
+ const rows = fasi ? tableRows(fasi) : [];
53
+ if (rows.length === 0) {
54
+ problems.push("In plan/README.md manca la tabella «## Fasi» (Fase | File | Contenuto | Stato).");
55
+ return [];
56
+ }
57
+ return rows.map(([id = "", file = "", summary = "", status = ""]) => {
58
+ const target = linkTarget(file);
59
+ // Solo un nome di file dentro plan/: niente cartelle né percorsi che risalgono.
60
+ const safe = target && /^[\w.-]+\.md$/.test(target) && target !== "README.md" ? target : null;
61
+ return { id, file: safe, summary, status };
62
+ });
63
+ }
64
+ function readOpenPhase(root, plan, phase, problems) {
65
+ if (!phase.file)
66
+ return null;
67
+ let text;
68
+ try {
69
+ text = readInside(root, join(plan, phase.file));
70
+ }
71
+ catch {
72
+ problems.push(`Non trovo plan/${phase.file}, il file della fase ${phase.id}.`);
73
+ return null;
74
+ }
75
+ const title = /^# (.+)$/m.exec(text)?.[1] ?? phase.id;
76
+ const goal = /^\*\*Obiettivo\*\*:\s*(.+)$/m.exec(text)?.[1] ?? "";
77
+ const done = (section(text, "Fatto") ?? []).join("\n");
78
+ const backlog = section(text, "Backlog");
79
+ if (!backlog)
80
+ problems.push(`In plan/${phase.file} manca la sezione «## Backlog».`);
81
+ const tasks = tableRows(backlog ?? []).map(([id = "", task = "", priority = ""]) => ({
82
+ id,
83
+ task,
84
+ priority,
85
+ done: id !== "" && done.includes(`**${id}**`),
86
+ }));
87
+ return { id: phase.id, title, goal, status: phase.status, tasks, criteria: bullets(section(text, "Criteri di accettazione") ?? []) };
88
+ }
89
+ /** I «Rilievi aperti» dei file di fase, che sono l'elenco curato dei rilievi ancora da chiudere. */
90
+ function readPhaseFindings(root, plan, phases) {
91
+ return phases.flatMap((phase) => {
92
+ if (!phase.file)
93
+ return [];
94
+ let text;
95
+ try {
96
+ text = readInside(root, join(plan, phase.file));
97
+ }
98
+ catch {
99
+ return [];
100
+ }
101
+ return bullets(section(text, "Rilievi aperti") ?? [])
102
+ .filter((item) => !/^nessuno\b/i.test(item))
103
+ .map((item) => ({
104
+ id: "",
105
+ title: item,
106
+ priority: priorityOf(item),
107
+ department: DEPARTMENT.exec(item)?.[1] ?? null,
108
+ source: phase.id,
109
+ status: null,
110
+ }));
111
+ });
112
+ }
113
+ const asText = (value) => (typeof value === "string" ? value : "");
114
+ function readAuditFindings(root, problems) {
115
+ const audit = join(root, "audit");
116
+ let folders;
117
+ try {
118
+ folders = readdirSync(audit, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
119
+ }
120
+ catch {
121
+ return [];
122
+ }
123
+ return folders.flatMap((folder) => {
124
+ const files = readdirSync(join(audit, folder)).filter((name) => name.endsWith(".json")).sort();
125
+ return files.flatMap((file) => {
126
+ const source = `${folder}/${file}`;
127
+ let data;
128
+ try {
129
+ data = JSON.parse(readInside(root, join(audit, folder, file)));
130
+ }
131
+ catch {
132
+ problems.push(`audit/${source} non è un JSON leggibile: saltato.`);
133
+ return [];
134
+ }
135
+ const record = data;
136
+ if (!Array.isArray(record.rilievi)) {
137
+ problems.push(`audit/${source} non ha l'elenco «rilievi»: saltato.`);
138
+ return [];
139
+ }
140
+ const department = DEPARTMENT.exec(asText(record.agente))?.[1] ?? null;
141
+ const items = record.rilievi.filter((item) => typeof item === "object" && item !== null);
142
+ return items.map((item) => ({
143
+ id: asText(item.id),
144
+ title: asText(item.titolo),
145
+ priority: priorityOf(asText(item.priorita)),
146
+ department,
147
+ source,
148
+ status: asText(item.stato) || null,
149
+ }));
150
+ });
151
+ });
152
+ }
153
+ const run = promisify(execFile);
154
+ /** Branch e numero di file modificati; null se la cartella non è un repository git o git non c'è. */
155
+ export async function readGit(root) {
156
+ try {
157
+ // Niente fsmonitor (un comando scelto dalla config del repository) e niente lock: il pannello legge e basta.
158
+ const args = ["--no-optional-locks", "-c", "core.fsmonitor=false", "status", "--porcelain=v1", "--branch"];
159
+ const { stdout } = await run("git", args, { cwd: root, timeout: 2000 });
160
+ const [head = "", ...rest] = stdout.split("\n").filter(Boolean);
161
+ const branch = head.replace(/^## /, "").replace(/^No commits yet on /, "").split("...")[0] ?? "";
162
+ return { branch, changed: rest.length };
163
+ }
164
+ catch {
165
+ return null;
166
+ }
167
+ }
168
+ /** Legge plan/ e audit/ di `root` (la cartella del progetto, già risolta con realpath). */
169
+ export function readPlan(root) {
170
+ const problems = [];
171
+ const plan = join(root, "plan");
172
+ const phases = readPhases(root, plan, problems);
173
+ const open = phases.find((phase) => !CLOSED.has(phase.status.toLowerCase()));
174
+ return {
175
+ name: basename(root),
176
+ phases,
177
+ openPhase: open ? readOpenPhase(root, plan, open, problems) : null,
178
+ findings: [...readPhaseFindings(root, plan, phases), ...readAuditFindings(root, problems)],
179
+ problems,
180
+ };
181
+ }
182
+ export async function readProject(root) {
183
+ return { ...readPlan(root), git: await readGit(root) };
184
+ }
@@ -1,5 +1,5 @@
1
1
  /** Versione del server, uguale a quella di package.json (lo controlla prompt.test.ts). */
2
- export const VERSION = "0.2.0";
2
+ export const VERSION = "0.3.0";
3
3
  /** Cerca un agente per id, senza distinguere maiuscole e minuscole («aisa-02» o «AISA-02»). */
4
4
  export function findAgent(catalog, id) {
5
5
  const wanted = id.toUpperCase();
@@ -2,12 +2,16 @@
2
2
  // Server MCP di Agentrica su stdio: un prompt per agente e due tool (elenca_agenti, agente).
3
3
  // Con --agents (es. --agents aisa,aiwda-08) prompt e tool vedono solo la squadra; senza, tutti gli agenti.
4
4
  // Legge solo i file di agents/ all'avvio; non scrive file, non apre connessioni e non registra dati.
5
+ // Con --panel (F14) apre anche il pannello locale su 127.0.0.1 (panel.ts), che legge plan/, audit/ e lo stato di git
6
+ // della cartella corrente e aggiunge i tool open_panel e ask_user; le chiamate agli agenti restano solo in memoria.
7
+ import { realpathSync } from "node:fs";
5
8
  import { join } from "node:path";
6
9
  import { parseArgs } from "node:util";
7
10
  import { loadCatalog } from "../../catalog/src/index.js";
8
11
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
9
12
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
10
13
  import { z } from "zod";
14
+ import { openBrowser, startPanel } from "./panel.js";
11
15
  import { agentSummary, agentText, codeName, findAgent, selectSquad, VERSION } from "./prompt.js";
12
16
  // agents/ è in un punto fisso rispetto a questo file, senza risalire le cartelle: la cartella corrente è il progetto
13
17
  // dell'utente e non deve poter fornire un'altra agents/. Tre livelli sopra c'è agents/ sia da un clone
@@ -24,8 +28,11 @@ function fail(message) {
24
28
  }
25
29
  const reason = (error) => (error instanceof Error ? error.message : String(error));
26
30
  let spec;
31
+ let withPanel = false;
27
32
  try {
28
- spec = parseArgs({ options: { agents: { type: "string" } } }).values.agents;
33
+ const { values } = parseArgs({ options: { agents: { type: "string" }, panel: { type: "boolean" } } });
34
+ spec = values.agents;
35
+ withPanel = values.panel ?? false;
29
36
  }
30
37
  catch (error) {
31
38
  fail(reason(error));
@@ -48,19 +55,45 @@ catch (error) {
48
55
  const all = catalog.flatMap((department) => department.agents.map((agent) => ({ department, agent })));
49
56
  const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
50
57
  const codes = catalog.map((d) => d.code);
58
+ let panel;
59
+ if (withPanel) {
60
+ try {
61
+ panel = await startPanel(realpathSync(process.cwd()));
62
+ }
63
+ catch (error) {
64
+ fail(`pannello non avviato: ${reason(error)}`);
65
+ }
66
+ }
67
+ /** Registra nel pannello che un agente è stato usato: id, nome in codice, ruolo e l'inizio del compito. */
68
+ function used({ department, agent }, task) {
69
+ const line = (task ?? "").replace(/\s+/g, " ").trim();
70
+ panel?.record({
71
+ id: agent.id,
72
+ codeName: codeName(agent),
73
+ role: agent.role,
74
+ department: department.code,
75
+ task: line.length > 120 ? `${line.slice(0, 119)}…` : line,
76
+ });
77
+ }
51
78
  const server = new McpServer({ name: "agentrica", version: VERSION }, {
52
79
  instructions: `Agentrica: ${count(all.length, "agente IA", "agenti IA")} in ${count(catalog.length, "reparto", "reparti")} (${codes.join(", ")}). ` +
53
80
  "Per scegliere un agente usa elenca_agenti; per lavorare come quell'agente carica le sue istruzioni con agente. " +
54
- `I prompt hanno il nome dell'id dell'agente, es. ${all[0].agent.id.toLowerCase()}.`,
81
+ `I prompt hanno il nome dell'id dell'agente, es. ${all[0].agent.id.toLowerCase()}.` +
82
+ (panel
83
+ ? " Il pannello locale è attivo: per le scelte che spettano all'utente usa ask_user, che mostra la domanda nella pagina; open_panel dà l'URL della pagina."
84
+ : ""),
55
85
  });
56
86
  const TASK = z.string().max(20_000).optional().describe("Il compito da affidare all'agente nel progetto corrente.");
57
87
  const READ_ONLY = { readOnlyHint: true, openWorldHint: false };
58
88
  for (const found of all) {
59
89
  const title = `${codeName(found.agent)} — ${found.agent.role}`;
60
- server.registerPrompt(found.agent.id.toLowerCase(), { title, description: agentSummary(found), argsSchema: { compito: TASK } }, ({ compito }) => ({
61
- description: title,
62
- messages: [{ role: "user", content: { type: "text", text: agentText(found, compito) } }],
63
- }));
90
+ server.registerPrompt(found.agent.id.toLowerCase(), { title, description: agentSummary(found), argsSchema: { compito: TASK } }, ({ compito }) => {
91
+ used(found, compito);
92
+ return {
93
+ description: title,
94
+ messages: [{ role: "user", content: { type: "text", text: agentText(found, compito) } }],
95
+ };
96
+ });
64
97
  }
65
98
  server.registerTool("elenca_agenti", {
66
99
  title: "Elenca gli agenti di Agentrica",
@@ -94,6 +127,77 @@ server.registerTool("agente", {
94
127
  content: [{ type: "text", text: "Agente non trovato: usa elenca_agenti per vedere gli id." }],
95
128
  };
96
129
  }
130
+ used(found, compito);
97
131
  return { content: [{ type: "text", text: agentText(found, compito) }] };
98
132
  });
133
+ if (panel)
134
+ registerPanelTools(panel);
135
+ function registerPanelTools(panel) {
136
+ const PROGRESS_MS = 30_000;
137
+ // Claude Code interrompe un tool stdio dopo 30 minuti senza risposta né avanzamento (plan/14-pannello.md, F14-01).
138
+ const WAIT_WITH_PROGRESS_MS = 4 * 60 * 60_000;
139
+ const WAIT_WITHOUT_PROGRESS_MS = 25 * 60_000;
140
+ server.registerTool("open_panel", {
141
+ title: "Apri il pannello di Agentrica",
142
+ description: "Apre nel browser il pannello locale del progetto (fasi, backlog, rilievi, agenti in uso, scelte in attesa) e ne restituisce l'URL.",
143
+ annotations: { readOnlyHint: true, openWorldHint: false },
144
+ }, () => {
145
+ openBrowser(panel.url);
146
+ return {
147
+ content: [{ type: "text", text: `Pannello aperto nel browser. Se non si è aperto, l'utente può aprire questo URL, valido solo su questo computer: ${panel.url}` }],
148
+ };
149
+ });
150
+ const option = z.object({
151
+ label: z.string().min(1).max(80).describe("Etichetta breve dell'opzione."),
152
+ description: z.string().max(500).describe("Cosa comporta l'opzione, con la motivazione."),
153
+ });
154
+ server.registerTool("ask_user", {
155
+ title: "Chiedi una scelta all'utente nel pannello",
156
+ description: "Mostra all'utente, nel pannello locale, una scelta con 2–4 opzioni e aspetta la risposta (le etichette scelte e una nota facoltativa). " +
157
+ "Metti per prima l'opzione consigliata, con « (Consigliata)» alla fine dell'etichetta. Se l'utente non risponde, chiedi nel terminale.",
158
+ inputSchema: {
159
+ question: z.string().min(1).max(2000).describe("La domanda completa, comprensibile da sola."),
160
+ header: z.string().max(40).optional().describe("Titolo breve, es. «Strada»."),
161
+ options: z.array(option).min(2).max(4).describe("Le opzioni, la consigliata per prima."),
162
+ multiple: z.boolean().optional().describe("true se si può scegliere più di un'opzione."),
163
+ },
164
+ annotations: { readOnlyHint: true, openWorldHint: false },
165
+ }, async ({ question, header, options, multiple }, extra) => {
166
+ const labels = options.map((o) => o.label);
167
+ if (new Set(labels).size !== labels.length) {
168
+ return { isError: true, content: [{ type: "text", text: "Le etichette delle opzioni devono essere diverse." }] };
169
+ }
170
+ const progressToken = extra._meta?.progressToken;
171
+ const wait = progressToken === undefined ? WAIT_WITHOUT_PROGRESS_MS : WAIT_WITH_PROGRESS_MS;
172
+ let progress = 0;
173
+ const ticker = progressToken === undefined
174
+ ? undefined
175
+ : setInterval(() => {
176
+ extra
177
+ .sendNotification({
178
+ method: "notifications/progress",
179
+ params: { progressToken, progress: ++progress, message: "In attesa della risposta nel pannello" },
180
+ })
181
+ .catch(() => { });
182
+ }, PROGRESS_MS);
183
+ if (!panel.hasViewers())
184
+ openBrowser(panel.url);
185
+ try {
186
+ const answer = await panel.ask({ question, header: header ?? "", options, multiple: multiple ?? false }, AbortSignal.any([extra.signal, AbortSignal.timeout(wait)]));
187
+ const chosen = answer.choices.length ? `L'utente ha scelto: ${answer.choices.join("; ")}.` : "L'utente non ha scelto un'opzione.";
188
+ return { content: [{ type: "text", text: answer.note ? `${chosen}\nNota dell'utente: ${answer.note}` : chosen }] };
189
+ }
190
+ catch {
191
+ return {
192
+ content: [{ type: "text", text: `Nessuna risposta dal pannello entro ${Math.round(wait / 60_000)} minuti: chiedi all'utente nel terminale.` }],
193
+ };
194
+ }
195
+ finally {
196
+ clearInterval(ticker);
197
+ }
198
+ });
199
+ }
99
200
  await server.connect(new StdioServerTransport());
201
+ // Con il pannello, una pagina aperta tiene vivo il processo: quando il client chiude stdio, il server esce.
202
+ if (panel)
203
+ process.stdin.on("close", () => process.exit(0));
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@agentrica/mcp",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
+ "mcpName": "io.github.flgisimone/agentrica",
4
5
  "description": "I 56 agenti IA di Agentrica come server MCP locale (stdio): un prompt per agente e due tool in sola lettura.",
5
6
  "license": "MIT",
6
7
  "author": "Giulio Simone Floresta",
@@ -23,7 +24,7 @@
23
24
  "node": ">=22"
24
25
  },
25
26
  "scripts": {
26
- "prepack": "rm -rf dist agents LICENSE && tsc -p tsconfig.build.json && cp -R ../../agents agents && cp ../../LICENSE LICENSE"
27
+ "prepack": "rm -rf dist agents LICENSE && tsc -p tsconfig.build.json && cp -R src/page dist/mcp/src/page && cp -R ../../agents agents && cp ../../LICENSE LICENSE"
27
28
  },
28
29
  "dependencies": {
29
30
  "@modelcontextprotocol/sdk": "1.32.2",