@llmnative/agentico 0.1.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.
Files changed (49) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +78 -0
  3. package/dist/index.js +18 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/index.mjs +1995 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/dist/types/domain/agentDefinition.d.ts +83 -0
  8. package/dist/types/domain/cli/renderManifestCli.d.ts +7 -0
  9. package/dist/types/domain/crossAgentTools.d.ts +13 -0
  10. package/dist/types/domain/defineSubagent.d.ts +5 -0
  11. package/dist/types/domain/destinationRegistry.d.ts +5 -0
  12. package/dist/types/domain/entityChatStore.d.ts +48 -0
  13. package/dist/types/domain/extractErrorMessage.d.ts +1 -0
  14. package/dist/types/domain/extractJsonBlock.d.ts +1 -0
  15. package/dist/types/domain/jsonExportDestination.d.ts +3 -0
  16. package/dist/types/domain/mcpTool.d.ts +9 -0
  17. package/dist/types/domain/microPrompts.d.ts +20 -0
  18. package/dist/types/domain/orchestrator/agenticoOrchestratorAgent.d.ts +34 -0
  19. package/dist/types/domain/orchestrator/prompt.d.ts +17 -0
  20. package/dist/types/domain/prompts.d.ts +29 -0
  21. package/dist/types/domain/resultDestination.d.ts +24 -0
  22. package/dist/types/domain/subagentManifest.d.ts +172 -0
  23. package/dist/types/domain/subagentRegistry.d.ts +11 -0
  24. package/dist/types/domain/subagentUsageCard.d.ts +37 -0
  25. package/dist/types/i18n/de.d.ts +2 -0
  26. package/dist/types/i18n/en.d.ts +2 -0
  27. package/dist/types/i18n/index.d.ts +20 -0
  28. package/dist/types/i18n/it.d.ts +2 -0
  29. package/dist/types/i18n/types.d.ts +55 -0
  30. package/dist/types/index.d.ts +25 -0
  31. package/dist/types/presentation/AgentActivityLog.d.ts +9 -0
  32. package/dist/types/presentation/AgentControls.d.ts +26 -0
  33. package/dist/types/presentation/Agentico.d.ts +23 -0
  34. package/dist/types/presentation/AgenticoContext.d.ts +305 -0
  35. package/dist/types/presentation/AgenticoToggle.d.ts +17 -0
  36. package/dist/types/presentation/ManualEntryRunner.d.ts +22 -0
  37. package/dist/types/presentation/OrchestratorRunner.d.ts +12 -0
  38. package/dist/types/presentation/ResultDestinationPicker.d.ts +29 -0
  39. package/dist/types/presentation/SubagentRunner.d.ts +48 -0
  40. package/dist/types/presentation/deriveHistoryTitle.d.ts +10 -0
  41. package/dist/types/presentation/liveAnchorDestination.d.ts +10 -0
  42. package/dist/types/presentation/reports/GenericResultPreview.d.ts +11 -0
  43. package/dist/types/presentation/reports/subagentReportRegistry.d.ts +58 -0
  44. package/dist/types/presentation/useAIModelCatalog.d.ts +9 -0
  45. package/dist/types/presentation/useAgent.d.ts +140 -0
  46. package/dist/types/presentation/useAgenticoPageContext.d.ts +12 -0
  47. package/dist/types/presentation/useSubagentComponentContext.d.ts +44 -0
  48. package/llms.txt +35 -0
  49. package/package.json +79 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,78 @@
1
+ # @llmnative/agentico
2
+
3
+ Agentic chat orchestrator for [`@llmnative/react`](https://www.npmjs.com/package/@llmnative/react) apps.
4
+
5
+ Agentico is a persistent side panel: the user says what they want, the orchestrator collects the
6
+ parameters in conversation and hands the work to a **subagent** registered by the host app. Every
7
+ subagent also has a deterministic fallback, so the app keeps working without AI.
8
+
9
+ Agentico only orchestrates. The host provides everything concrete: subagents, result
10
+ destinations, reports, cross-agent tools, model-facing prompts, user-facing strings and the
11
+ current scope (tenant, company, workspace…).
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install @llmnative/agentico @llmnative/react zod
17
+ ```
18
+
19
+ Requires Node.js 24 LTS, React 19 and `@llmnative/react` ≥ 1.20.
20
+
21
+ ## Setup (once, at startup)
22
+
23
+ ```tsx
24
+ import { App, locales } from '@llmnative/react';
25
+ import {
26
+ Agentico, AgenticoProvider, AgenticoToggle,
27
+ agenticoPromptsIt, agenticoTranslations, configureAgenticoPrompts,
28
+ registerCrossAgentTools, registerDestinations, registerSubagents,
29
+ } from '@llmnative/agentico';
30
+
31
+ registerSubagents([themeSubagent, importSubagent]); // what the orchestrator can hand off to
32
+ registerDestinations({ [themeLibrary.id]: themeLibrary }); // where results can be saved
33
+ registerCrossAgentTools(({ collected, attachmentsRef, proxyFetch }) => [readSitemapTool(proxyFetch, collected)]);
34
+ configureAgenticoPrompts({ // optional: language and host rules for the model
35
+ ...agenticoPromptsIt,
36
+ responseRules: [...agenticoPromptsIt.responseRules, 'A rule only this app needs.'],
37
+ });
38
+
39
+ <App
40
+ i18n={{ locale: 'it', translations: { it: { ...locales.it, ...agenticoTranslations.it } } }}
41
+ /* … */
42
+ >
43
+ <AgenticoProvider scope={currentCompany && { id: currentCompany.id, dataProvider, storageProvider }}>
44
+ <AgenticoToggle /> {/* in the header */}
45
+ <Agentico /> {/* the panel */}
46
+ </AgenticoProvider>
47
+ </App>
48
+ ```
49
+
50
+ ## Concepts
51
+
52
+ | Concept | API |
53
+ |---|---|
54
+ | **Subagent** — a capability with commands (Zod input), an `AgentDefinition` (prompt, parse, deterministic fallback, tools) and its index route | `defineSubagent`, `registerSubagents`, `SubagentManifest` |
55
+ | **Orchestrator** — reads the CLI catalog of the registered subagents, collects parameters, invokes a `<subagent>_<command>` handoff tool | built in |
56
+ | **Cross-agent tools** — data-collection tools the orchestrator may call (read a sitemap, a CSV…); complete outputs go to a per-conversation `collected` scratchpad, merged into the handoff by `SubagentManifest.withCollected` | `registerCrossAgentTools` |
57
+ | **Result destinations** — where a result can be saved, in the current scope | `registerDestinations`, `ResultDestination` |
58
+ | **Reports** — custom result views per subagent | `registerSubagentReports` |
59
+ | **Scope** — the host's current tenant/company: id + data and storage providers | `<AgenticoProvider scope>` |
60
+ | **Page context** — what the user is looking at, for the orchestrator prompt | `useAgenticoPageContext`, `useSubagentComponentContext` |
61
+ | **Saved chats** — one chat per saved entity, resumable | `configureEntityChatStore`, `getEntityChat`, `listEntityChats` |
62
+ | **Prompts** — model-facing text (en default, it included) | `configureAgenticoPrompts`, `agenticoPromptsEn`, `agenticoPromptsIt` |
63
+ | **Strings** — user-facing text, namespace `agentico` of the framework i18n (en/it/de) | `agenticoTranslations`, `I18nDict.agentico` |
64
+
65
+ ## Development
66
+
67
+ ```bash
68
+ npm run typecheck
69
+ npm test
70
+ npm run build
71
+ ```
72
+
73
+ Changes and releases follow `docs/directives/maintainers/llm-rule-change-release.md` (CR + GitHub
74
+ issue + version + npm), tracked in `.notes/`.
75
+
76
+ ## License
77
+
78
+ Apache-2.0
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("zod-to-json-schema"),l=require("@llmnative/react"),u=require("react");u=s(u);let d=require("react/jsx-runtime");function f(e){return e}var p=[];function m(e){p=e}function h(){return p.length===0&&typeof console<`u`&&console.warn(`[agentico] getSubagentRegistry() letto a registro vuoto — registerSubagents() non è ancora stato chiamato?`),p}function g(e){return p.find(t=>t.id===e)}var _=[];function v(...e){_=e}function y(e){return _.flatMap(t=>t(e))}function b(e){let{$schema:t,...n}=(0,c.zodToJsonSchema)(e,{target:`jsonSchema7`,$refStrategy:`none`});return n}function x(e,t,n,r){return{name:e,description:t,inputSchema:b(n),...r?{outputSchema:b(r)}:{}}}function S(e){let t=b(e.inputSchema),n=t.properties??{},r=new Set(t.required??[]);return Object.entries(n).map(([t,n])=>{let i=typeof n.description==`string`?n.description:``;return{key:t,type:typeof n.type==`string`?n.type:`string`,required:r.has(t),description:i,humanDescription:e.humanFieldHints?.[t]??i}})}var C={orchestratorIntro:`You are Agentico, the orchestrator of this application's tools. Your job is to understand what the user wants to achieve and, once every required parameter is collected, start the right tool among those listed below — do not carry it out yourself "in words", invoke it as a tool.`,responseRules:[`BEFORE asking for any parameter, check the "Page context" below (if present): if a parameter required by the command is already there or can be deduced from it with reasonable certainty, USE it directly — do not ask the user again. Only ask for parameters that cannot be derived from the context.`,`The "<subagent>_<command>" command you close with is the one that does the real work (analysis, matching, generation, extraction — whatever its description says) — NEVER try to produce that result yourself in chat once the raw data is collected.`,`If parameters are really missing (not deducible from the context nor from a data-collection tool) for one of the listed commands, ask in natural language, one question at a time, until you have everything.`,`When you have ALL required parameters of ONE command, actually invoke the tool with that name ("<subagent>_<command>") passing the parameters — do not just describe it, and do not replace the work that command is designed to do.`,`Invoke at most one command per turn.`,`If the user's request is not covered by any of the listed tools, say so clearly instead of inventing one.`,`IMPORTANT: when you invoke a "<subagent>_<command>" command, your comment in THIS turn must only announce the START of the work — NEVER describe its outcome as already obtained, and NEVER say that something "opened" or "is ready to review". The real work starts AFTER this turn, in a session you will never see: any description of the outcome at this point would be invented, even if the tool answered without errors.`,`After invoking a command, do not spontaneously suggest other subagents unrelated to the current request — the user will open a new conversation if they need something else.`],responseRulesHeading:`## How to answer`,toolsHeading:`## Available tools`,pageContextHeading:`## Page context`,pageContextIntro:`The user is interacting from this point of the app — use it to understand what they refer to when the request is not explicit:`,userRequestHeading:`## User request`,noToolsAvailable:`No tools available.`,stopCallingTools:`Stop calling tools. Answer NOW with the final result, in the required format, using everything collected so far.`,handoffQueued:`{label} has been queued for the real execution — the result is not available in this conversation yet.`,closingSummary:[`When you are done answering (with or without tools in this turn),`,`ALWAYS close your text answer with a concise but complete summary of what`,`you did — a few lines, a bullet list when there is more than one action, no`,`needless repetition of the original task. The summary goes AFTER the JSON`,`block requested above, never before it and never instead of it.`].join(` `),multipleCandidates:`Several subagents are candidates on this page — ask the user which one they mean if their message does not make it clear, before going on.`},w={orchestratorIntro:`Sei Agentico, l'orchestratore dei tool di questa applicazione. Il tuo compito è capire cosa vuole ottenere l'utente e, una volta raccolti tutti i parametri necessari, avviare il tool giusto tra quelli elencati sotto — non eseguirlo tu stesso "a parole", invocalo come strumento.`,responseRules:[`PRIMA di chiedere qualunque parametro, controlla il "Contesto pagina" (se presente) qui sotto: se un parametro richiesto dal comando è già lì o si può dedurre da lì con ragionevole certezza (es. l'utente sta guardando lo storico di un tool specifico, o un'esecuzione passata con parametri simili), USALO direttamente — non chiederlo di nuovo all'utente. Chiedi solo i parametri che NON emergono in nessun modo dal contesto.`,`Il comando "<subagent>_<comando>" con cui chiudi è quello che fa il lavoro di analisi vero (matching, generazione, estrazione — qualunque cosa il suo comando descriva) — MAI provare a produrlo tu stesso in chat una volta raccolti i dati grezzi.`,`Se mancano davvero parametri (non deducibili dal contesto né da un tool di raccolta dati) per uno dei comandi elencati, fai domande in linguaggio naturale, una alla volta, finché non hai raccolto tutto.`,`Quando hai TUTTI i parametri richiesti di UN comando (raccolti dall'utente, dedotti dal contesto, o ottenuti da un tool di raccolta dati), invoca davvero lo strumento con quel nome ("<subagent>_<comando>") passandogli i parametri — non limitarti a descriverlo a parole, e non sostituirti al lavoro che quel comando è progettato per fare.`,`Invoca al massimo un comando per turno.`,`Se la richiesta dell'utente non è coperta da nessuno dei tool elencati, dillo chiaramente invece di inventarne uno.`,`IMPORTANTE: quando invochi un comando "<subagent>_<comando>", il tuo commento in QUESTO turno deve annunciare solo l'AVVIO del lavoro (es. "Avvio l'estrazione…", "Sto preparando il mapping…") — MAI descriverne l'esito come già ottenuto (colori, font, loghi, mapping, o qualunque altro dato del risultato) e MAI dire che qualcosa "si è aperto" o "è pronto da rivedere". Il vero lavoro parte DOPO questo turno, in una sessione che tu non vedrai mai: qualunque tua descrizione dell'esito a questo punto sarebbe un'invenzione, anche se il tool ha risposto senza errori.`,`Dopo aver invocato un comando, non proporre spontaneamente altri subagent scollegati dalla richiesta corrente — l'utente aprirà lui una nuova conversazione se gli servirà altro.`],responseRulesHeading:`## Come rispondere`,toolsHeading:`## Tool disponibili`,pageContextHeading:`## Contesto pagina`,pageContextIntro:`L'utente sta interagendo da questo punto dell'app — usalo per capire a cosa si riferisce se non è esplicito nella richiesta:`,userRequestHeading:`## Richiesta dell'utente`,noToolsAvailable:`Nessun tool disponibile.`,stopCallingTools:`Basta chiamare tool. Rispondi ORA con il risultato finale, nel formato richiesto, usando tutte le informazioni raccolte finora.`,handoffQueued:`{label} è stato messo in coda per l'esecuzione reale — il risultato non è ancora disponibile in questa conversazione.`,closingSummary:[`Quando hai finito di rispondere (con o senza aver usato dei tool in questo turno),`,`chiudi SEMPRE la tua risposta testuale con un riepilogo conciso ma esaustivo di cosa`,`hai fatto — poche righe, elenco puntato se le azioni sono più di una, niente`,`ripetizioni superflue del compito originale. Il riepilogo va DOPO il blocco JSON`,`richiesto sopra, mai prima e mai al posto suo.`].join(` `),multipleCandidates:`Più subagent sono candidati su questa pagina — chiedi all'utente quale intende se non è chiaro dal suo messaggio, prima di procedere.`},T=C;function E(e){T={...T,...e}}function D(){return T}function O(){T=C}function k(e,t){return`${e} ${t.map(e=>e.required?`--${e.key} <${e.type}>`:`[--${e.key} <${e.type}>]`).join(` `)}`.trim()}function A(e,t){let n=S(t),r=k(t.name,n),i=n.map(e=>` --${e.key} <${e.type}> (${e.required?`required`:`optional`})${e.description?` — ${e.description}`:``}`);return[`COMMAND: ${e} ${t.name}`,` ${t.summary}`,``,` USAGE`,` ${e} ${r}`,(i.length,``),i.length?` PARAMS`:``,...i,``,` OUTPUT`,j(t.describeOutput(),4),(t.example,``),t.example?` EXAMPLE`:``,t.example?` ${t.example}`:``].filter(e=>e!==``).join(`
2
+ `)}function j(e,t){let n=` `.repeat(t);return e.split(`
3
+ `).map(e=>e&&n+e).join(`
4
+ `)}function M(e){return[`NAME`,` ${e.id} — ${e.label}`,``,`DESCRIPTION`,j(e.description,2),``,...e.commands.map(t=>A(e.id,t))].join(`
5
+ `)}function N(e){return e.length===0?D().noToolsAvailable:e.map(e=>`${e.id} [${e.commands.map(e=>e.name).join(`|`)}] — ${e.label}: ${e.commands.map(e=>e.summary).join(` / `)}`).join(`
6
+ `)}var P={id:`closing-summary`,get text(){return D().closingSummary}},F={[P.id]:P};function I(e,t){if(!t||t.length===0)return e;let n=t.map(e=>F[e]?.text).filter(e=>!!e);return n.length===0?e:`${e}\n\n${n.join(`
7
+ `)}`}function L(e){if(e instanceof Error)return e.message;if(typeof e==`object`&&e){let t=e;if(typeof t.error==`string`)return t.error;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.message==`string`)return e.message}if(typeof t.message==`string`)return t.message;if(typeof t.status==`number`)return`HTTP ${t.status}`;try{return JSON.stringify(e)}catch{}}return String(e)}function R(e){let t=e.match(/```(?:json)?\s*\n?([\s\S]*?)```/i);if(t)return t[1].trim();let n=e.replace(/^```json\s*/i,``).replace(/^```\s*/i,``).replace(/```\s*$/,``).trim();return z(n)??n}function z(e){let t=e.search(/[{[]/);if(t===-1)return null;let n=e[t],r=n===`{`?`}`:`]`,i=0,a=!1,o=!1;for(let s=t;s<e.length;s++){let c=e[s];if(a){o?o=!1:c===`\\`?o=!0:c===`"`&&(a=!1);continue}if(c===`"`){a=!0;continue}if(c===n)i++;else if(c===r&&(i--,i===0))return e.slice(t,s+1)}return null}var B=`json-export`,V={id:B,label:`Export as JSON`,async apply(e){let t=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),n=URL.createObjectURL(t);try{let e=document.createElement(`a`);e.href=n,e.download=`tool-result-${Date.now()}.json`,e.click()}finally{URL.revokeObjectURL(n)}}},H={};function U(e){H=e}function W(){return{[V.id]:V,...H}}var G=`llmnative.agentico.entityChat`;function ee(e){G=e.storageKey}function te(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.entityId!=`string`)return null;let n=t.scopeId??t.tenantId;if(typeof n!=`string`)return null;let{tenantId:r,...i}=t;return{...i,scopeId:n}}function K(){try{let e=localStorage.getItem(G);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(te).filter(e=>e!==null):[]}catch{return[]}}function ne(e){try{localStorage.setItem(G,JSON.stringify(e))}catch{}}var q=(e,t,n)=>`${e}:${t}:${n}`;function re(e,t,n){let r=q(e,t,n);return K().find(e=>q(e.scopeId,e.subagentId,e.entityId)===r)??null}function ie(e){let t=q(e.scopeId,e.subagentId,e.entityId),n=K().filter(e=>q(e.scopeId,e.subagentId,e.entityId)!==t);n.push({...e,savedAt:Date.now()}),ne(n)}function ae(e,t,n){let r=q(e,t,n);ne(K().filter(e=>q(e.scopeId,e.subagentId,e.entityId)!==r))}function J(e){return K().filter(t=>t.scopeId===e).sort((e,t)=>t.savedAt-e.savedAt)}var oe={modelLabel:`Modell`,modelsLoading:`Wird geladen…`,noModelsAvailable:`Keine Modelle verfügbar`,noProviderConnected:`Kein AI-Provider verbunden`,selectModelPlaceholder:`Modell wählen…`,orchestratorStarterHint:`Sag Agentico, was du erreichen willst — es wählt das passende Werkzeug und fragt nach den nötigen Angaben.`,orchestratorStarterPlaceholder:`Beschreibe, was du tun möchtest…`,destinationPickerTitle:`Ergebnis speichern in…`,destinationApplying:`Wird gespeichert…`,destinationNoScope:`Kein Ziel ausgewählt — vor dem Speichern eines auswählen.`,unknownDestination:`Unbekanntes Ziel: {id}`,exportJson:`Als JSON exportieren`,orchestratorUnavailable:`AI nicht verfügbar — öffne das benötigte Werkzeug direkt auf seiner Seite.`,orchestratorContinueWithoutAi:`Weiter ohne AI.`,orchestratorPreparing:`{label} wird vorbereitet…`,orchestratorCollecting:`Parameter für {label} werden gesammelt…`,thinking:`Denke nach…`,stopped:`Vom Benutzer abgebrochen.`,toolRequest:`Werkzeugausführung angefordert`,modelRequestError:`Fehler bei der Anfrage an das Modell`,noProviderResponse:`Keine Antwort vom AI-Provider.`,noActiveSession:`Keine aktive Sitzung — zuerst run() aufrufen.`,requestInProgress:`Eine andere Anfrage läuft bereits.`,invalidResponse:`Ungültige AI-Antwort.`,responseReceived:`Antwort erhalten`,noProviderAvailable:`Kein AI-Provider verfügbar.`,tooManyToolTurns:`Zu viele aufeinanderfolgende Werkzeugaufrufe — das bisher gesammelte deterministische Ergebnis wird verwendet.`,aiDisabledFallback:`AI deaktiviert — das deterministische Ergebnis wird verwendet.`,continueWithoutAiFallback:`Weiter ohne AI — das deterministische Ergebnis wird verwendet.`,newInstance:`Neue Instanz von "{label}"`,chatHistory:`Chatverlauf`,newChat:`Neuer Chat`,searchChats:`Chats durchsuchen…`,messagePlaceholder:`Nachricht schreiben…`,unsavedConversationConfirm:`Diese Unterhaltung wurde nicht gespeichert und geht verloren. Fortfahren?`,noSavedChats:`Noch keine gespeicherten Chats.`,noResults:`Keine Ergebnisse.`,retry:`Erneut versuchen`,retryMessage:`Erneut versuchen.`,continueWithoutAi:`Ohne AI fortfahren`,resumeWithAi:`Mit AI fortsetzen`,openPanel:`Agentenbereich öffnen`,closePanel:`Agentenbereich schließen`},Y={modelLabel:`Model`,modelsLoading:`Loading…`,noModelsAvailable:`No models available`,noProviderConnected:`No AI provider connected`,selectModelPlaceholder:`Choose a model…`,orchestratorStarterHint:`Tell Agentico what you want to do — it will pick the right tool and ask for what it needs.`,orchestratorStarterPlaceholder:`Describe what you want to do…`,destinationPickerTitle:`Save result to…`,destinationApplying:`Saving…`,destinationNoScope:`Nothing selected to save into — select one before saving.`,unknownDestination:`Unknown destination: {id}`,exportJson:`Export as JSON`,orchestratorUnavailable:`AI not available — open the tool you need directly from its page.`,orchestratorContinueWithoutAi:`Continuing without AI.`,orchestratorPreparing:`Preparing {label}…`,orchestratorCollecting:`Collecting the parameters for {label}…`,thinking:`Thinking…`,stopped:`Stopped by the user.`,toolRequest:`Requested to run some tools`,modelRequestError:`Error in the request to the model`,noProviderResponse:`No response from the AI provider.`,noActiveSession:`No active session — call run() first.`,requestInProgress:`Another request is already running.`,invalidResponse:`Invalid AI response.`,responseReceived:`Response received`,noProviderAvailable:`No AI provider available.`,tooManyToolTurns:`Too many consecutive tool-calling turns — using the deterministic result collected so far.`,aiDisabledFallback:`AI disabled — using the deterministic result.`,continueWithoutAiFallback:`Continuing without AI — using the deterministic result.`,newInstance:`New "{label}" instance`,chatHistory:`Chat history`,newChat:`New chat`,searchChats:`Search chats…`,messagePlaceholder:`Write a message…`,unsavedConversationConfirm:`This conversation has not been saved and will be lost. Continue?`,noSavedChats:`No saved chats yet.`,noResults:`No results.`,retry:`Retry`,retryMessage:`Retry.`,continueWithoutAi:`Continue without AI`,resumeWithAi:`Resume with AI`,openPanel:`Open agent panel`,closePanel:`Close agent panel`},se={modelLabel:`Modello`,modelsLoading:`Caricamento…`,noModelsAvailable:`Nessun modello disponibile`,noProviderConnected:`Nessun provider AI connesso`,selectModelPlaceholder:`Scegli un modello…`,orchestratorStarterHint:`Dì ad Agentico cosa vuoi fare — sceglierà lo strumento giusto e ti chiederà cosa serve.`,orchestratorStarterPlaceholder:`Descrivi cosa vuoi fare…`,destinationPickerTitle:`Salva risultato in…`,destinationApplying:`Salvataggio…`,destinationNoScope:`Nessuna destinazione selezionata — selezionane una prima di salvare.`,unknownDestination:`Destinazione sconosciuta: {id}`,exportJson:`Esporta come JSON`,orchestratorUnavailable:`AI non disponibile — apri il tool che ti serve direttamente dalla sua pagina.`,orchestratorContinueWithoutAi:`Continuo senza AI.`,orchestratorPreparing:`Preparo {label}…`,orchestratorCollecting:`Sto raccogliendo i parametri per {label}…`,thinking:`Sto pensando…`,stopped:`Interrotto dall'utente.`,toolRequest:`Richiesta di eseguire dei tool`,modelRequestError:`Errore nella richiesta al modello`,noProviderResponse:`Nessuna risposta dal provider AI.`,noActiveSession:`Nessuna sessione attiva — chiama prima run().`,requestInProgress:`Un'altra richiesta è già in corso.`,invalidResponse:`Risposta AI non valida.`,responseReceived:`Risposta ricevuta`,noProviderAvailable:`Nessun provider AI disponibile.`,tooManyToolTurns:`Troppi turni di tool-calling consecutivi — uso il risultato deterministico raccolto finora.`,aiDisabledFallback:`AI disabilitata — uso il risultato deterministico.`,continueWithoutAiFallback:`Continuo senza AI — uso il risultato deterministico.`,newInstance:`Nuova istanza di "{label}"`,chatHistory:`Storico chat`,newChat:`Nuova chat`,searchChats:`Cerca nelle chat…`,messagePlaceholder:`Scrivi un messaggio…`,unsavedConversationConfirm:`Questa conversazione non è stata salvata e andrà persa. Continuare?`,noSavedChats:`Nessuna chat salvata ancora.`,noResults:`Nessun risultato.`,retry:`Riprova`,retryMessage:`Riprova.`,continueWithoutAi:`Continua senza AI`,resumeWithAi:`Riprendi con AI`,openPanel:`Apri pannello agente`,closePanel:`Chiudi pannello agente`},ce={en:{agentico:Y},it:{agentico:se},de:{agentico:oe}};function X(){let{dict:e}=(0,l.useI18n)(),t=e.agentico;return t?{...Y,...t}:Y}var Z=`agentico-orchestrator`,le=(0,u.createContext)(null);function ue({children:e,scope:t=null}){let[n,r]=(0,u.useState)(null),i=(0,u.useRef)(null);(0,u.useEffect)(()=>{i.current=n},[n]);let[a,o]=(0,u.useState)(!1),s=(0,u.useCallback)(e=>{let t=i.current;t&&t.id!==e.id&&t.onDismiss();let n=t&&t.id===e.id&&t.savedToDisk&&e.savedToDisk===void 0?{...e,savedToDisk:!0}:e;r(n)},[]),c=(0,u.useCallback)(e=>{r(t=>t&&t.id===e?null:t)},[]),l=(0,u.useCallback)(()=>o(e=>!e),[]),f=(0,u.useCallback)(()=>o(!0),[]),[p,m]=(0,u.useState)(null),[h,_]=(0,u.useState)(void 0),[v,y]=(0,u.useState)(void 0),[b,x]=(0,u.useState)(void 0),[S,C]=(0,u.useState)(null),[w,T]=(0,u.useState)(null),[E,O]=(0,u.useState)(void 0),[k,A]=(0,u.useState)([]),j=(0,u.useCallback)((e,t,n=null)=>{A(r=>{let i=r.filter(t=>t.id!==e);return t?[...i,{id:e,text:t,card:n}]:i})},[]),M=k.length>0?k[k.length-1]:null,[N,P]=(0,u.useState)([]),F=(0,u.useCallback)((e,t)=>{P(n=>{let r=n.filter(t=>t.id!==e);return t?[...r,{id:e,...t}]:r})},[]),I=(0,u.useMemo)(()=>N.map(e=>({subagentId:e.subagentId,componentKey:e.componentKey,onResult:e.onResult,pinnedEntityId:e.pinnedEntityId})),[N]),L=(0,u.useMemo)(()=>{let e=new Map;for(let t of N)e.set(t.subagentId,{subagentId:t.subagentId,componentKey:t.componentKey,onResult:t.onResult,contextInfo:t.contextInfo});return[...e.values()]},[N]),R=(0,u.useMemo)(()=>L.map(e=>{let t=g(e.subagentId)?.componentContexts?.[e.componentKey];if(!t)return null;let n=e.contextInfo?`${t.agenticoHint}\n${e.contextInfo}`:t.agenticoHint;return{subagentId:e.subagentId,agenticoHint:n,userMessage:t.userMessage}}).filter(e=>e!==null),[L]),z=(0,u.useMemo)(()=>R.map(e=>e.userMessage),[R]),B=(0,u.useMemo)(()=>{if(R.length===0)return null;if(R.length===1)return R[0].agenticoHint;let e=R.map((e,t)=>`${t+1}. ${e.agenticoHint}`).join(`
8
+ `);return`${D().multipleCandidates}\n\n${e}`},[R])??M?.text??null,V=R.length>0?null:M?.card??null,H=(0,u.useMemo)(()=>[...new Set(I.map(e=>e.subagentId))],[I]),U=H.length===1?H[0]:H.length===0?M?.card?.subagentId??null:null,W=(0,u.useCallback)((e,t)=>{f();let n=i.current;if(n?.id===`agentico-orchestrator`)return;let r=U&&n?.id.startsWith(`subagent-${U}-`)?n:void 0;T(r?{taskId:r.id,activity:[...r.precedingActivity??[],...r.agent.activity]}:null),m(e),_(t?.extraDestinations),y(t?.attachments),x(t?.model),O(t?.scopedSubagentId),C(crypto.randomUUID())},[f,U]),G=(0,u.useCallback)((e,t,n,a,o,s)=>{if(!n||!a)return;let c=i.current;if(!c||c.id!==n)return;let l=c.agent.snapshot();l&&(ie({scopeId:a,subagentId:e,entityId:t,params:o,title:s,history:l.history,activity:[...c.precedingActivity??[],...l.activity]}),r(e=>e&&e.id===n?{...e,savedToDisk:!0}:e))},[]),[ee,te]=(0,u.useState)(null),[K,ne]=(0,u.useState)(null),q=(0,u.useCallback)((e,t,n)=>{f(),te({subagentId:e,entityId:t,snapshot:n}),ne(crypto.randomUUID())},[f]),[re,ae]=(0,u.useState)(null),[J,oe]=(0,u.useState)(null),Y=(0,u.useCallback)((e,t)=>{f(),c(Z),ae({subagentId:e,extraDestinations:t}),oe(crypto.randomUUID())},[f,c]),[se,ce]=(0,u.useState)(null),[X,ue]=(0,u.useState)(null),Q=(0,u.useCallback)((e,t,n)=>{ae(null),ce({subagentId:e,params:t,extraDestinations:n}),ue(crypto.randomUUID())},[]),$=(0,u.useCallback)(()=>{let e=i.current;e&&e.onDismiss()},[]),de=(0,u.useMemo)(()=>({scope:t,task:n,isOpen:a,openTask:s,closeTask:c,toggleOpen:l,pendingGoal:p,startOrchestrator:W,pageContext:B,pageContextCard:V,setPageContext:j,scopedSubagentId:U,pendingScopedSubagentId:E,componentAnchors:I,anchoredUserMessages:z,registerComponentAnchor:F,openPanel:f,pendingExtraDestinations:h,pendingAttachments:v,pendingModel:b,orchestratorRunId:S,pendingCarryOver:w,commitEntityChat:G,resumeEntityChat:q,pendingResume:ee,resumeRunId:K,dismissForeignTask:$,pendingManualEntry:re,manualEntryRunId:J,startManualEntry:Y,pendingResumeWithAI:se,resumeWithAIRunId:X,resumeWithAI:Q}),[t,n,a,s,c,l,p,W,B,V,j,U,E,I,z,F,f,h,v,b,S,w,G,q,ee,K,$,re,J,Y,se,X,Q]);return(0,d.jsx)(le.Provider,{value:de,children:e})}function Q(){let e=(0,u.useContext)(le);if(!e)throw Error(`useAgentico must be used inside AgenticoProvider`);return e}function $(e){let t=e.search(/[{[]/);if(t===-1)return[{type:`text`,content:e}];let n=e[t],r=n===`{`?`}`:`]`,i=0,a=!1,o=!1,s=-1;for(let c=t;c<e.length;c++){let t=e[c];if(a){o?o=!1:t===`\\`?o=!0:t===`"`&&(a=!1);continue}if(t===`"`){a=!0;continue}if(t===n)i++;else if(t===r&&(i--,i===0)){s=c;break}}let c=s===-1?null:e.slice(t,s+1);if(!c||c.length<60)return[{type:`text`,content:e}];try{JSON.parse(c)}catch{return[{type:`text`,content:e}]}let l=[];t>0&&l.push({type:`text`,content:e.slice(0,t)}),l.push({type:`code`,content:c,language:`json`});let u=e.slice(s+1);return u.trim()&&l.push(...$(u)),l}function de(e){let t=[],n=/```(\w+)?\n?([\s\S]*?)```/g,r=0,i;for(;i=n.exec(e);)i.index>r&&t.push(...$(e.slice(r,i.index))),t.push({type:`code`,content:i[2].replace(/\n$/,``),language:i[1]}),r=n.lastIndex;return r<e.length&&t.push(...$(e.slice(r))),t}function fe({content:e,language:t}){let[n,r]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`relative cursor-pointer rounded-md ${n?`max-h-80 overflow-y-auto`:`max-h-28 overflow-hidden`}`,onClick:()=>r(e=>!e),title:n?`Clic per comprimere`:`Clic per espandere`,children:[(0,d.jsx)(l.Code,{language:t,showCopy:n,background:`transparent`,className:`!text-[11px]`,children:e}),!n&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-muted/30 to-transparent`})]})}function pe(e){let t=[],n=/\*\*(.+?)\*\*|`([^`]+)`|\[([^\]]+)\]\(([^)]+)\)/g,r=0,i;for(;i=n.exec(e);)i.index>r&&t.push({type:`text`,content:e.slice(r,i.index)}),i[1]===void 0?i[2]===void 0?i[3]!==void 0&&t.push({type:`link`,content:i[3],href:i[4]}):t.push({type:`code`,content:i[2]}):t.push({type:`bold`,content:i[1]}),r=n.lastIndex;return r<e.length&&t.push({type:`text`,content:e.slice(r)}),t}function me({text:e}){return(0,d.jsx)(d.Fragment,{children:pe(e).map((e,t)=>e.type===`bold`?(0,d.jsx)(`strong`,{className:`font-semibold text-foreground`,children:e.content},t):e.type===`code`?(0,d.jsx)(`code`,{className:`rounded bg-muted px-1 py-0.5 font-mono text-[11px] break-words`,children:e.content},t):e.type===`link`?(0,d.jsx)(`a`,{href:e.href,target:`_blank`,rel:`noreferrer`,className:`text-primary underline underline-offset-2`,children:e.content},t):(0,d.jsx)(u.default.Fragment,{children:e.content},t))})}function he({text:e}){let t=de(e);return(0,d.jsx)(d.Fragment,{children:t.map((e,t)=>e.type===`code`?(0,d.jsx)(fe,{content:e.content,language:e.language},t):e.content.trim()&&(0,d.jsx)(`p`,{className:`whitespace-pre-wrap break-words`,children:(0,d.jsx)(me,{text:e.content})},t))})}function ge({status:e}){return e===`running`?(0,d.jsx)(`span`,{className:`inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-2 border-current border-t-transparent`}):e===`done`?(0,d.jsx)(l.Icon,{name:`check`,size:12,className:`shrink-0 text-green-600`}):e===`stopped`?(0,d.jsx)(l.Icon,{name:`circle-slash`,size:12,className:`shrink-0 text-muted-foreground`}):(0,d.jsx)(l.Icon,{name:`x`,size:12,className:`shrink-0 text-destructive`})}function _e(e,t){return e.status===`running`?t.thinking:e.status===`error`?t.modelRequestError:e.status===`stopped`?t.stopped:e.detail?t.responseReceived:e.toolNames&&e.toolNames.length>0?e.toolNames.join(` · `):t.toolRequest}var ve=96;function ye({entry:e}){let t=(0,u.useRef)(null),[n,r]=(0,u.useState)(!1),[i,a]=(0,u.useState)(!1);(0,u.useLayoutEffect)(()=>{let e=t.current;e&&a(e.scrollHeight>97)},[e.detail,e.attachmentNames]);let o=i&&!n;return(0,d.jsx)(`li`,{className:`sticky top-0 z-10 flex justify-end border-b border-border/40 bg-background py-1.5`,children:(0,d.jsxs)(`div`,{className:`max-w-[85%] rounded-lg bg-primary/10 text-xs text-foreground`,children:[(0,d.jsxs)(`div`,{ref:t,className:`space-y-1 px-2.5 pt-1.5 ${o?`overflow-hidden`:``}`,style:o?{maxHeight:ve}:void 0,children:[e.attachmentNames&&e.attachmentNames.length>0&&(0,d.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.attachmentNames.map((e,t)=>(0,d.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md bg-primary/15 px-1.5 py-0.5 text-[11px] text-foreground`,children:[(0,d.jsx)(l.Icon,{name:`paperclip`,size:10,className:`shrink-0`}),(0,d.jsx)(`span`,{className:`max-w-[160px] truncate`,children:e})]},t))}),(0,d.jsx)(he,{text:e.detail??``})]}),i&&(0,d.jsxs)(`button`,{type:`button`,onClick:()=>r(e=>!e),className:`relative flex w-full items-center justify-center rounded-b-lg py-1 text-muted-foreground hover:bg-primary/15`,title:n?`Comprimi`:`Espandi`,children:[o&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 -top-4 h-4 bg-gradient-to-t from-primary/10 to-transparent`}),(0,d.jsx)(l.Icon,{name:n?`chevron-up`:`chevron-down`,size:12})]})]})})}function be({entry:e}){let t=X();if(e.kind===`user`)return(0,d.jsx)(ye,{entry:e});let n=e.kind===`thinking`&&e.detail?de(e.detail):[],r=n.filter(e=>e.type===`code`),i=n.filter(e=>e.type===`text`&&e.content.trim()),a=e.kind===`thinking`?_e(e,t):e.label;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(ge,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:a})]}),r.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-1`,children:r.map((e,t)=>(0,d.jsx)(fe,{content:e.content,language:e.language},t))}),i.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-2`,children:i.map((e,t)=>(0,d.jsx)(`p`,{className:`whitespace-pre-wrap leading-relaxed text-muted-foreground`,children:(0,d.jsx)(me,{text:e.content.trim()})},t))})]})}function xe({activity:e}){return e.length===0?null:(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:e.map(e=>(0,d.jsx)(be,{entry:e},e.id))})}function Se({className:e=``}){let{isOpen:t,toggleOpen:n,task:r}=Q(),i=X(),a=r?.agent.running??!1;return(0,d.jsx)(l.ActionButton,{icon:`bot`,ariaLabel:t?i.closePanel:i.openPanel,title:t?i.closePanel:i.openPanel,onClick:n,iconClassName:a?`animate-pulse`:void 0,className:`!h-9 !w-9 !p-0 rounded-md ${t?`bg-primary/10 text-primary hover:bg-primary/15`:`bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground`} ${e}`})}var Ce=`llmnative-cms.selectedAIModel`;function we(){try{return localStorage.getItem(Ce)??``}catch{return``}}function Te(e){try{e?localStorage.setItem(Ce,e):localStorage.removeItem(Ce)}catch{}}function Ee(){let e=(0,l.useAIProviderRegistry)()?.registry??{},t=Object.keys(e).length>0,[n,r]=(0,u.useState)({}),[i,a]=(0,u.useState)(!1),[o,s]=(0,u.useState)(we);return(0,u.useEffect)(()=>{if(!t){r({});return}let n=!1;return a(!0),(0,l.getAIModelCatalog)(e).then(e=>{if(n)return;r(e.modelsByProvider);let t=Object.values(e.modelsByProvider).flat();s(e=>t.some(t=>t.id===e)?e:(Te(``),``))}).catch(e=>{console.error(`useAIModelCatalog: getAIModelCatalog failed`,e),n||r({})}).finally(()=>{n||a(!1)}),()=>{n=!0}},[t,JSON.stringify(Object.keys(e).sort())]),{hasProviders:t,modelsByProvider:n,modelsLoading:i,selectedModel:o,setSelectedModel:e=>{Te(e),s(e)}}}var De=20,Oe=26e4;function ke(e){return e.filter(e=>!l.PromptUtils.isTextAttachment(e.mimeType)||e.base64.length<=Oe)}function Ae(e,t={}){let{defaultEnabled:n=!1}=t,[r,i]=(0,u.useState)(n),{hasProviders:a,modelsByProvider:o,modelsLoading:s,selectedModel:c,setSelectedModel:d}=Ee(),[f,p]=(0,u.useState)(!1),[m,h]=(0,u.useState)(null),[g,_]=(0,u.useState)(!1),[v,y]=(0,u.useState)([]),x=X(),S=(0,u.useRef)(x);S.current=x;let C=(0,u.useRef)(null),w=(0,u.useRef)(!1),T=(0,u.useRef)(null),E=()=>{T.current?.abort()},O=(0,l.useAIProviderRegistry)()?.registry??{},k=r&&c?(0,l.parseAIModelRef)(c):null,A=k?O[k.provider]:null,j=async(t,n,r)=>{let i=C.current;if(!i)return h(S.current.noActiveSession),null;let a=r?(0,l.parseAIModelRef)(r):k,o=a?O[a.provider]:null;if(!o||!a)return h(S.current.noProviderAvailable),null;n?.length&&(i.attachmentsRef.current=[...i.attachmentsRef.current??[],...n]);let s=(n??[]).filter(e=>l.PromptUtils.isTextAttachment(e.mimeType)).map(e=>e.base64.length<=Oe?`\n\n[File allegato: ${e.name}]\n${l.PromptUtils.decodeBase64Text(e.base64)}`:`\n\n[File allegato: ${e.name} — troppo grande per essere incollato qui. Usa uno dei tool di lettura file disponibili (es. list_csv_columns/extract_csv_column) per leggerne il contenuto prima di chiedere altro all'utente.]`).join(``),c=ke(n??[]),u=i.tools.map(e=>({name:e.name,description:e.description,inputSchema:b(e.inputSchema)})),d=new Map(i.tools.map(e=>[e.name,e])),f=new AbortController;T.current=f;let p=(e,t,n,r)=>y(i=>i.map(i=>i.id===e?{...i,status:t,...n===void 0?{}:{detail:n},...r===void 0?{}:{toolNames:r}}:i));try{let n=i.history,r=t;for(let t=0;t<De;t++){let l=crypto.randomUUID();y(e=>[...e,{id:l,kind:`thinking`,label:S.current.thinking,status:`running`}]);let m;try{m=await o.complete({prompt:r,model:a.model,history:n,tools:u.length?u:void 0,signal:f.signal,attachments:t===0?c:void 0,logId:i.logId})}catch(t){return i.history=[...n,...r?[{role:`user`,content:r+s}]:[]],f.signal.aborted?(p(l,`stopped`),e.fallback(i.params,i.context)):(p(l,`error`),h(L(t)),null)}if(i.history=[...n,...r?[{role:`user`,content:r+s}]:[]],!m)return f.signal.aborted?(p(l,`stopped`),e.fallback(i.params,i.context)):(p(l,`error`),h(S.current.noProviderResponse),null);if(m.type===`text`)return p(l,`done`,m.text),i.history=[...n,...r?[{role:`user`,content:r+s}]:[],{role:`assistant`,content:m.text}],e.parseResponse(m.text,i.params,i.context)||(console.error(`[useAgent] parseResponse ha restituito null — la risposta del modello non è nel formato atteso da questo subagent. Uso il fallback deterministico.`,{responseLength:m.text.length,responsePreview:m.text.length>2e3?`${m.text.slice(0,1e3)}\n…[troncato qui nel log, ${m.text.length} caratteri totali]…\n${m.text.slice(-1e3)}`:m.text,params:i.params}),h(S.current.invalidResponse),e.fallback(i.params,i.context));let g=m.toolCalls.map(e=>{let t=d.get(e.name);return t?.describeIntent??t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`});p(l,`done`,m.text||void 0,m.text?void 0:g);let _=await Promise.all(m.toolCalls.map(async e=>{let t=d.get(e.name),n=t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`;if(y(t=>[...t,{id:e.id,kind:`tool`,label:n,status:`running`}]),!t)return p(e.id,`error`),{toolCallId:e.id,name:e.name,output:`Tool sconosciuto: ${e.name}`,isError:!0};try{let n=await t.execute(e.input);return p(e.id,`done`),{toolCallId:e.id,name:e.name,output:n}}catch(t){return p(e.id,`error`),{toolCallId:e.id,name:e.name,output:L(t),isError:!0}}}));n=[...n,...r?[{role:`user`,content:r+s}]:[],{role:`assistant`,content:m.text,toolCalls:m.toolCalls},{role:`tool_result`,results:_}],r=``}let l=crypto.randomUUID();y(e=>[...e,{id:l,kind:`thinking`,label:S.current.thinking,status:`running`}]);let m;try{m=await o.complete({prompt:I(D().stopCallingTools,e.microPromptIds),model:a.model,history:n,signal:f.signal,logId:i.logId})}catch{m=null}if(m?.type===`text`){p(l,`done`,m.text),i.history=[...n,{role:`assistant`,content:m.text}];let t=e.parseResponse(m.text,i.params,i.context);if(t)return t}else p(l,f.signal.aborted?`stopped`:`error`),i.history=n;return f.signal.aborted||h(S.current.tooManyToolTurns),e.fallback(i.params,i.context)}finally{T.current=null}};return{enabled:r,setEnabled:i,hasProviders:a,selectedModel:c,setSelectedModel:d,modelsByProvider:o,modelsLoading:s,running:f,error:m,canContinue:g,activity:v,run:async(t,n)=>{if(w.current)return h(S.current.requestInProgress),null;w.current=!0,h(null),y(n?.openingMessage?[{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:n.openingMessage,...n.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]:[]),p(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];C.current={params:t,context:i,tools:o,history:[],logId:crypto.randomUUID(),attachmentsRef:a};let s=n?.model||void 0,c=s?!!O[(0,l.parseAIModelRef)(s)?.provider??``]:!!A;if(!r||!c){_(!1);let n=e.fallback(t,i);return y(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??S.current.aiDisabledFallback}]),n}_(!0);let u=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,d=I(e.buildPrompt(t,i),e.microPromptIds);return await j(d,u,s)}catch(e){return h(L(e)),null}finally{w.current=!1,p(!1)}},resume:async(t,n)=>{if(w.current){h(S.current.requestInProgress);return}w.current=!0,h(null),y(n.activity),p(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];C.current={params:t,context:i,tools:o,history:n.history,logId:crypto.randomUUID(),attachmentsRef:a},_(r&&!!A)}catch(e){h(L(e))}finally{w.current=!1,p(!1)}},sendMessage:async(t,n)=>{if(w.current)return h(S.current.requestInProgress),null;if(h(null),!t.trim())return h(`Messaggio vuoto.`),null;let r=C.current;if(!r)return h(S.current.noActiveSession),null;w.current=!0,p(!0),y(e=>[...e,{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:t,...n?.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]);try{let i=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,a=I(e.buildFollowUpPrompt(t,r.params,r.context),e.microPromptIds);return await j(a,i,n?.model||void 0)}catch(e){return h(L(e)),null}finally{w.current=!1,p(!1)}},stop:E,runFallback:()=>{let t=C.current;if(!t)return null;h(null);let n=e.fallback(t.params,t.context);return y(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??S.current.continueWithoutAiFallback}]),n},snapshot:()=>C.current?{history:C.current.history,activity:v}:null}}function je(){let e=D();return[e.responseRulesHeading,...e.responseRules.map(e=>`- ${e}`)].join(`
9
+ `)}function Me(e,t,n){let r=D(),i=n?`\n${r.pageContextHeading}\n${r.pageContextIntro}\n${n}\n`:``;return`${r.orchestratorIntro}
10
+
11
+ ${r.toolsHeading}
12
+ ${t}
13
+ ${i}
14
+ ${je()}
15
+
16
+ ${r.userRequestHeading}
17
+ ${e}`}function Ne(e,t){return t?{kind:`handoff`,...t}:{kind:`chat`,message:e}}function Pe(e){return{buildContext(){return{cliCatalog:N(h()),handoff:{current:null},collected:{}}},buildPrompt({userGoal:e,pageContext:t},{cliCatalog:n}){return Me(e,n,t)},buildFollowUpPrompt(e,t,{cliCatalog:n}){return`${e}\n\n${je()}\n\n${D().toolsHeading}\n${n}`},parseResponse(e,t,n){let r=n.handoff.current;return n.handoff.current=null,Ne(e,r)},fallback(){return{kind:`chat`,message:e.unavailable}},describeFallback(t){return t.kind===`chat`?t.message:e.continueWithoutAi},getTools(t,n,r){let i=y({attachmentsRef:r,collected:n.collected,proxyFetch:l.proxyFetch}),a=t.scopedSubagentId?g(t.scopedSubagentId):null,o=a?i.filter(e=>(a.crossAgentToolIds??[]).includes(e.name)):i,s=h().flatMap(t=>t.commands.map(r=>({name:`${t.id}_${r.name}`,description:`${t.label}: ${r.summary}`,inputSchema:r.inputSchema,describeInvocation:()=>(0,l.interpolate)(e.preparing,{label:t.label}),describeIntent:(0,l.interpolate)(e.collecting,{label:t.label}),async execute(e){let i=t.withCollected?t.withCollected({...e},n.collected):e;return n.handoff.current={subagentId:t.id,command:r.name,params:i},{status:`queued`,note:(0,l.interpolate)(D().handoffQueued,{label:t.label})}}})));return[...o,...s]}}}function Fe(e,t){return e.deriveHistoryTitle?.(t)??e.label}function Ie({manifest:e,result:t,meta:n,taskId:r,initiallyApplied:i,onApplied:a,extraDestinations:o}){let s=X(),c=Q(),f=c.scope,p=(0,l.useProxy)(),[m,h]=(0,u.useState)(null),[g,_]=(0,u.useState)(new Set(i??[])),[v,y]=(0,u.useState)(null),b=W(),x=new Map;e.destinationIds.forEach(e=>{let t=b[e];t&&x.set(e,t)}),(o??[]).forEach(e=>x.set(e.id,e)),x.set(V.id,V);let S=Array.from(x.values()),C=async i=>{h(i),y(null);try{let o=x.get(i);if(!o)throw Error((0,l.interpolate)(s.unknownDestination,{id:i}));if(i!==`json-export`&&!f)throw Error(s.destinationNoScope);let u=await o.apply(t,{scopeId:f?.id??``,dataProvider:f?.dataProvider,storageProvider:f?.storageProvider??null,proxyFetch:p},n);_(e=>new Set(e).add(i)),a?.(i),u?.id&&c.commitEntityChat(e.id,u.id,r,f?.id,n,Fe(e,n))}catch(e){y(e instanceof Error?e.message:String(e))}finally{h(null)}};return(0,d.jsxs)(`div`,{className:`space-y-2`,children:[(0,d.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:s.destinationPickerTitle}),(0,d.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:S.map(e=>(0,d.jsx)(`button`,{type:`button`,disabled:m!==null,onClick:()=>void C(e.id),className:`cursor-pointer rounded-md border border-input bg-background px-2.5 py-1.5 text-xs font-medium transition-colors hover:bg-accent hover:text-accent-foreground disabled:cursor-not-allowed disabled:opacity-60`,children:m===e.id?s.destinationApplying:`${g.has(e.id)?`✓ `:``}${e.id===`json-export`?s.exportJson:e.label}`},e.id))}),v&&(0,d.jsx)(`p`,{className:`text-xs text-destructive`,children:v})]})}var Le={};function Re(e){Object.assign(Le,e)}function ze(e){return Le[e]}function Be({result:e}){let[t,n]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`relative cursor-pointer rounded-md border border-border/60 ${t?`max-h-80 overflow-y-auto`:`max-h-28 overflow-hidden`}`,onClick:()=>n(e=>!e),title:t?`Clic per comprimere`:`Clic per espandere`,children:[(0,d.jsx)(l.Code,{language:`json`,showCopy:t,background:`transparent`,className:`!text-[11px]`,children:JSON.stringify(e,null,2)}),!t&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-muted/30 to-transparent`})]})}function Ve(e,t,n){return e.length===0?null:{id:`live-component`,label:`Applica al componente aperto`,async apply(r){e.forEach(e=>e.onResult?.(r,t,n))}}}function He({manifest:e,params:t,extraDestinations:n,precedingActivity:r,taskId:i,resumeSeed:a,model:o}){let s=Ae(e.definition,{defaultEnabled:!0}),c=Q(),f=c.scope,p=(0,l.useProxy)(),m=(0,u.useRef)(i??`subagent-${e.id}-${crypto.randomUUID()}`).current,[h,g]=(0,u.useState)(null),[_,v]=(0,u.useState)([]),[y,b]=(0,u.useState)(null),x=ze(e.id),S=x?.kind===`selection`?x:null,[C,w]=(0,u.useState)(null),T=(0,u.useRef)(!1),E=(0,u.useRef)(0),D=(0,u.useRef)(null);h&&h!==D.current&&(D.current=h,E.current=(r?.length??0)+s.activity.length);let O=(0,u.useRef)(!1),k=!s.hasProviders||s.selectedModel!==``;(0,u.useEffect)(()=>{!T.current&&k&&(T.current=!0,a?s.resume(e.toParams(t),a):(o&&s.setSelectedModel(o),s.run(e.toParams(t),{model:o}).then(e=>{e&&g(e)})))},[k]),(0,u.useEffect)(()=>{if(!h||!f)return;let n=e.autoApplyDestinationIds??[],r=c.componentAnchors.find(t=>t.subagentId===e.id&&t.pinnedEntityId)?.pinnedEntityId,i=W();n.forEach(n=>{let a=i[n];a&&(b(null),a.apply(h,{scopeId:f.id,dataProvider:f.dataProvider,storageProvider:f.storageProvider,proxyFetch:p},{...t,pinnedEntityId:r}).then(n=>{n?.id&&c.commitEntityChat(e.id,n.id,m,f.id,t,Fe(e,t))}).catch(e=>b(e instanceof Error?e.message:String(e))))})},[h,s.activity,f]),(0,u.useEffect)(()=>{h&&S&&w(S.defaultSelection(h))},[h,S]);let A=(e,t)=>{w(n=>n&&{...n,[e]:t})},j=e=>g(e),M=(0,u.useMemo)(()=>h&&S&&C?S.applySelection(h,C):h,[h,S,C]),N=(0,u.useMemo)(()=>c.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[c.componentAnchors,e.id]),P=(0,u.useMemo)(()=>Ve(N,t,m),[N,t,m]),F=(0,u.useMemo)(()=>P?[P,...n??[]]:n,[P,n]),I=e=>{v(t=>t.includes(e)?t:[...t,e])};return(0,u.useEffect)(()=>{O.current||c.openTask({id:m,title:Fe(e,t),icon:e.icon,agent:s,onApplied:e=>g(e),precedingActivity:r,panelExtraAnchorIndex:E.current,onDismiss:()=>{O.current=!0,s.running&&s.stop(),c.closeTask(m)},panelExtra:h?(0,d.jsxs)(d.Fragment,{children:[S&&C?(0,d.jsx)(S.Report,{result:h,selection:C,onChange:A}):x?.kind===`editable`?(0,d.jsx)(x.Report,{result:h,onResultChange:j}):(0,d.jsx)(Be,{result:M}),y&&(0,d.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Salvataggio automatico non riuscito: `,y]}),(0,d.jsx)(Ie,{manifest:e,result:M,meta:t,taskId:m,initiallyApplied:_,onApplied:I,extraDestinations:F})]}):void 0})},[s.activity,s.running,s.error,s.canContinue,s.selectedModel,s.modelsByProvider,s.hasProviders,c.openTask,c.componentAnchors,m,e,t,h,M,C,_,n,r,y]),(0,u.useEffect)(()=>()=>{c.closeTask(m)},[c.closeTask,m]),null}function Ue({userGoal:e}){let t=X(),n=Ae((0,u.useMemo)(()=>Pe({unavailable:t.orchestratorUnavailable,continueWithoutAi:t.orchestratorContinueWithoutAi,preparing:t.orchestratorPreparing,collecting:t.orchestratorCollecting}),[]),{defaultEnabled:!0}),r=Q(),[i,a]=(0,u.useState)(null),o=(0,u.useRef)(!1),s=!n.hasProviders||n.selectedModel!==``,c=(0,u.useRef)(r.pendingExtraDestinations),l=(0,u.useRef)(r.pendingAttachments),f=(0,u.useRef)(r.pendingModel),p=(0,u.useRef)(r.pendingScopedSubagentId??r.scopedSubagentId??void 0),m=(0,u.useRef)(r.pendingCarryOver),h=(0,u.useRef)(!1),_=e=>{e&&typeof e==`object`&&e.kind===`handoff`&&(a(e),r.closeTask(Z))};(0,u.useEffect)(()=>{!o.current&&s&&(o.current=!0,f.current&&n.setSelectedModel(f.current),n.run({userGoal:e,pageContext:r.pageContext,scopedSubagentId:p.current??null},{attachments:l.current,model:f.current,openingMessage:e}).then(e=>{e&&_(e)}))},[s]),(0,u.useEffect)(()=>{h.current||r.openTask({id:Z,title:`Agentico`,icon:`bot`,agent:n,onApplied:_,scopedSubagentId:p.current,precedingActivity:m.current?.activity,onDismiss:()=>{h.current=!0,n.running&&n.stop(),r.closeTask(Z)}})},[n.activity,n.running,n.error,n.canContinue,n.selectedModel,n.modelsByProvider,n.hasProviders,r.openTask]),(0,u.useEffect)(()=>()=>{r.closeTask(Z)},[r.closeTask]);let v=(0,u.useMemo)(()=>[...m.current?.activity??[],...n.activity],[n.activity]);if(!i)return null;let y=g(i.subagentId);return y?(0,d.jsx)(He,{manifest:y,params:i.params,extraDestinations:c.current,model:f.current||void 0,taskId:m.current?.taskId,precedingActivity:v}):null}function We({manifest:e,extraDestinations:t}){let n=Ae(e.definition,{defaultEnabled:!1}),r=X(),i=Q(),a=(0,u.useRef)(`manual-${e.id}-${crypto.randomUUID()}`).current,[o,s]=(0,u.useState)(null),[c,f]=(0,u.useState)([]),p=ze(e.id),m=p?.kind===`selection`?p:null,[h,g]=(0,u.useState)(null),[_,v]=(0,u.useState)(null),y=(0,u.useRef)(!1),b=t=>{if(!e.manualEntry)return;let r;try{r=e.manualEntry.fromRawText(t)}catch(e){console.error(`[ManualEntryRunner] manualEntry.fromRawText ha rifiutato il testo:`,e);return}v(r),f([]),n.run(r,{openingMessage:t}).then(e=>{e&&s(e)})};(0,u.useEffect)(()=>{o&&m&&g(m.defaultSelection(o))},[o,m]);let x=(e,t)=>{g(n=>n&&{...n,[e]:t})},S=e=>s(e),C=(0,u.useMemo)(()=>o&&m&&h?m.applySelection(o,h):o,[o,m,h]),w=e=>{f(t=>t.includes(e)?t:[...t,e])},T=(0,u.useMemo)(()=>i.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[i.componentAnchors,e.id]),E=(0,u.useMemo)(()=>_?Ve(T,_,a):null,[T,_,a]),D=(0,u.useMemo)(()=>E?[E,...t??[]]:t,[E,t]);return(0,u.useEffect)(()=>{y.current||i.openTask({id:a,title:e.label,icon:e.icon,agent:n,onApplied:e=>s(e),manualEntry:e.manualEntry?{prompt:e.manualEntry.prompt,onSubmit:b}:void 0,onDismiss:()=>{y.current=!0,n.running&&n.stop(),i.closeTask(a)},panelExtra:o?(0,d.jsxs)(`div`,{className:`space-y-2`,children:[m&&h?(0,d.jsx)(m.Report,{result:o,selection:h,onChange:x}):p?.kind===`editable`?(0,d.jsx)(p.Report,{result:o,onResultChange:S}):(0,d.jsx)(Be,{result:C}),(0,d.jsx)(Ie,{manifest:e,result:C,meta:_??{},taskId:a,initiallyApplied:c,onApplied:w,extraDestinations:D}),n.hasProviders&&(0,d.jsx)(l.ActionButton,{label:r.resumeWithAi,variant:`outline-secondary`,className:`text-xs`,onClick:()=>{_&&i.resumeWithAI(e.id,_,t)}})]}):void 0})},[n.activity,n.running,n.error,n.hasProviders,i.componentAnchors,o,C,h,c,_]),(0,u.useEffect)(()=>()=>{i.closeTask(a)},[]),null}var Ge=420;function Ke(e){return Object.values(e).flat().map(e=>({label:e.model,value:e.id,pricing:e.pricing??null,group:e.providerLabel??e.provider}))}function qe({task:e}){let t=X(),[n,r]=(0,u.useState)(``),{agent:i,onApplied:a,manualEntry:o}=e,s=i.running,c=e=>{if(r(``),o){o.onSubmit(e.text);return}i.sendMessage(e.text,{attachments:e.files,model:e.model}).then(e=>{e&&a(e)})},f=!o&&i.hasProviders&&!i.selectedModel;return(0,d.jsx)(l.Chatbot,{value:n,onChange:r,placeholder:o?.prompt??t.messagePlaceholder,running:s,onStop:i.stop,disabled:!n.trim()||f,onSubmit:c,attachments:!o,models:o?[]:Ke(i.modelsByProvider),selectedModel:o?``:i.selectedModel,onModelChange:i.setSelectedModel,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function Je(){let{startOrchestrator:e}=Q(),t=X(),[n,r]=(0,u.useState)(``),{hasProviders:i,modelsByProvider:a,selectedModel:o,setSelectedModel:s}=Ee(),c=t=>{t.text.trim()&&(e(t.text.trim(),{attachments:t.files.length>0?t.files:void 0,model:t.model||void 0}),r(``))},f=i&&!o;return(0,d.jsx)(l.Chatbot,{value:n,onChange:r,placeholder:t.orchestratorStarterPlaceholder,disabled:!n.trim()||f,onSubmit:c,attachments:!0,models:Ke(a),selectedModel:o,onModelChange:s,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function Ye({card:e}){let t=X();return e.humanSummaryOnly?(0,d.jsxs)(`div`,{className:`space-y-2 rounded-lg border border-border/60 p-3`,children:[(0,d.jsxs)(`p`,{className:`text-xs font-medium text-foreground`,children:[`"`,e.label,`"`]}),(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.humanSummary})]}):(0,d.jsxs)(`div`,{className:`space-y-2 rounded-lg border border-border/60 p-3`,children:[(0,d.jsx)(`p`,{className:`text-xs font-medium text-foreground`,children:(0,l.interpolate)(t.newInstance,{label:e.label})}),(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.humanSummary}),e.fields.length>0&&(0,d.jsx)(`ul`,{className:`space-y-1`,children:e.fields.map(e=>(0,d.jsxs)(`li`,{className:`flex items-start gap-1.5 text-xs`,children:[(0,d.jsx)(l.Badge,{variant:e.required?`primary`:`secondary`,className:`mt-px shrink-0`,children:e.required?`richiesto`:`opzionale`}),(0,d.jsxs)(`span`,{className:`min-w-0`,children:[(0,d.jsx)(`span`,{className:`font-mono text-foreground`,children:e.key}),e.humanDescription?(0,d.jsxs)(`span`,{className:`text-muted-foreground`,children:[` — `,e.humanDescription]}):null]})]},e.key))}),e.example&&(0,d.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Esempio: `,(0,d.jsx)(`span`,{className:`font-mono`,children:e.example})]})]})}function Xe({messages:e}){return(0,d.jsx)(`div`,{className:`space-y-2 rounded-lg border border-border/60 p-3`,children:e.map((e,t)=>(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e},t))})}function Ze({scopeId:e,open:t,onOpenChange:n,onSelect:r,onNewChat:i}){let a=X(),[o,s]=(0,u.useState)(``),c=(0,u.useMemo)(()=>t?J(e):[],[e,t]),f=(0,u.useMemo)(()=>{let e=o.trim().toLowerCase();return e?c.filter(t=>{let n=g(t.subagentId)?.label??t.subagentId;return t.title.toLowerCase().includes(e)||n.toLowerCase().includes(e)}):c},[c,o]);return(0,d.jsx)(l.Dropdown,{trigger:{icon:`history`,title:a.chatHistory},triggerClassName:`!h-9 !w-9 !p-0 rounded-md bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground`,open:t,onOpenChange:n,position:`end`,strategy:`absolute`,menuClassName:`w-[380px] max-h-[70vh] overflow-y-auto`,header:(0,d.jsxs)(`div`,{className:`flex items-center gap-2 px-1 pb-1.5`,children:[(0,d.jsx)(l.Icon,{name:`search`,size:14,className:`shrink-0 text-muted-foreground`}),(0,d.jsx)(`input`,{autoFocus:!0,value:o,onChange:e=>s(e.target.value),placeholder:a.searchChats,className:`min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),(0,d.jsx)(l.ActionButton,{icon:`square-pen`,ariaLabel:a.newChat,title:a.newChat,variant:`link`,className:`shrink-0`,onClick:i})]}),children:f.length===0?(0,d.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground`,children:c.length===0?a.noSavedChats:a.noResults}):f.map(e=>{let t=g(e.subagentId);return(0,d.jsx)(l.DropdownItem,{icon:t?.icon??`bot`,onClick:()=>r(e.subagentId,e.entityId,e),children:(0,d.jsxs)(`span`,{className:`flex min-w-0 flex-1 items-center justify-between gap-2`,children:[(0,d.jsxs)(`span`,{className:`min-w-0 truncate`,children:[(0,d.jsx)(`span`,{className:`text-muted-foreground`,children:t?.label??e.subagentId}),` · `,e.title||e.entityId]}),(0,d.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,children:new Date(e.savedAt).toLocaleString()})]})},`${e.subagentId}:${e.entityId}`)})})}function Qe(){let{task:e,isOpen:t,pendingGoal:n,orchestratorRunId:r,pageContext:i,pageContextCard:a,anchoredUserMessages:o,pendingResume:s,resumeRunId:c,dismissForeignTask:f,resumeEntityChat:p,pendingManualEntry:m,manualEntryRunId:h,startManualEntry:_,pendingExtraDestinations:v,pendingResumeWithAI:y,resumeWithAIRunId:b,scope:x}=Q(),S=X(),C=(0,u.useRef)(null),[w,T]=(0,u.useState)(!1),E=()=>{(!e||e.agent.running||e.savedToDisk||window.confirm(S.unsavedConversationConfirm))&&(f(),T(!1))},D=e?[...e.precedingActivity??[],...e.agent.activity]:[],O=D.length,k=Math.max(0,Math.min(e?.panelExtraAnchorIndex??O,O)),A=D.slice(0,k),j=D.slice(k),M=!!(e&&!e.agent.running&&e.agent.error),N=e?.id===`agentico-orchestrator`&&e.scopedSubagentId?g(e.scopedSubagentId):void 0,P=N?.manualEntry?N:null,F=(0,u.useRef)(!0);(0,u.useEffect)(()=>{let e=C.current;if(!e)return;let t=()=>{F.current=e.scrollHeight-e.scrollTop-e.clientHeight<80};return e.addEventListener(`scroll`,t),()=>e.removeEventListener(`scroll`,t)},[e?.id]),(0,u.useEffect)(()=>{let e=C.current;e&&(F.current=!0,e.scrollTop=e.scrollHeight)},[e?.id]),(0,u.useEffect)(()=>{let e=C.current;e&&F.current&&(e.scrollTop=e.scrollHeight)},[O,M]);let I=n?(0,d.jsx)(Ue,{userGoal:n},r):null,L=s?g(s.subagentId):void 0,R=s&&L?(0,d.jsx)(He,{manifest:L,params:s.snapshot.params,taskId:`entitychat-${s.subagentId}-${s.entityId}`,resumeSeed:{history:s.snapshot.history,activity:s.snapshot.activity}},c):null,z=m?g(m.subagentId):void 0,B=m&&z?(0,d.jsx)(We,{manifest:z,extraDestinations:m.extraDestinations},h):null,V=y?g(y.subagentId):void 0,H=y&&V?(0,d.jsx)(He,{manifest:V,params:y.params,extraDestinations:y.extraDestinations},b):null;return t?(0,d.jsxs)(d.Fragment,{children:[I,R,B,H,(0,d.jsxs)(`div`,{style:{width:420},className:`relative flex h-full shrink-0 flex-col border-l border-border bg-background`,children:[(0,d.jsxs)(`div`,{className:`flex min-h-[60px] items-center gap-1 border-b border-border/60 px-4 py-3`,children:[(0,d.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-lg font-semibold leading-tight`,children:e?e.title:`Agentico`}),x&&(0,d.jsx)(Ze,{scopeId:x.id,open:w,onOpenChange:T,onNewChat:E,onSelect:(e,t,n)=>p(e,t,n)}),(0,d.jsx)(Se,{})]}),(0,d.jsx)(`div`,{ref:C,className:`flex-1 overflow-y-auto px-3 pb-2`,children:(0,d.jsx)(`div`,{className:`pt-2`,children:e?(0,d.jsxs)(d.Fragment,{children:[e.manualEntry&&D.length===0&&(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.manualEntry.prompt}),(0,d.jsx)(xe,{activity:A}),e.panelExtra&&(0,d.jsx)(`div`,{className:`mt-3`,children:e.panelExtra}),j.length>0&&(0,d.jsx)(xe,{activity:j}),!e.agent.running&&e.agent.error&&(0,d.jsxs)(`div`,{className:`mt-2 flex items-center gap-2`,children:[(0,d.jsx)(`p`,{className:`flex-1 text-xs text-destructive`,children:e.agent.error}),(0,d.jsx)(l.ActionButton,{label:S.retry,variant:`secondary`,className:`shrink-0`,onClick:()=>{e.agent.sendMessage(S.retryMessage).then(t=>{t&&e.onApplied(t)})}}),(0,d.jsx)(l.ActionButton,{label:S.continueWithoutAi,variant:`secondary`,className:`shrink-0`,onClick:()=>{if(P){_(P.id,v);return}let t=e.agent.runFallback();t&&e.onApplied(t)}})]})]}):o.length>0?(0,d.jsx)(Xe,{messages:o}):a?(0,d.jsx)(Ye,{card:a}):(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i??S.orchestratorStarterHint})})}),(0,d.jsx)(`div`,{className:`border-t border-border/60 px-4 py-3`,children:e?(0,d.jsx)(qe,{task:e},e.id):(0,d.jsx)(Je,{})})]})]}):(0,d.jsxs)(d.Fragment,{children:[I,R,B,H]})}function $e(e,t){let{setPageContext:n}=Q(),r=(0,u.useRef)(crypto.randomUUID()).current;(0,u.useEffect)(()=>(n(r,e,t??null),()=>n(r,null)),[e,t])}function et(e,t,n,r,i=!0,a){let{registerComponentAnchor:o}=Q(),s=(0,u.useRef)(crypto.randomUUID()).current,c=(0,u.useRef)(n);c.current=n,(0,u.useEffect)(()=>{if(i)return o(s,{subagentId:e,componentKey:t,contextInfo:r,pinnedEntityId:a,onResult:(e,t,n)=>c.current?.(e,t,n)}),()=>o(s,null)},[e,t,r,i,a])}exports.AGENTICO_WIDTH=Ge,exports.Agentico=Qe,exports.AgenticoProvider=ue,exports.AgenticoToggle=Se,exports.JSON_EXPORT_DESTINATION_ID=B,exports.MICRO_PROMPT_REGISTRY=F,exports.ORCHESTRATOR_TASK_ID=Z,exports.SUMMARY_MICRO_PROMPT=P,exports.agenticoDe=oe,exports.agenticoEn=Y,exports.agenticoIt=se,exports.agenticoPromptsEn=C,exports.agenticoPromptsIt=w,exports.agenticoTranslations=ce,exports.applyMicroPrompts=I,exports.configureAgenticoPrompts=E,exports.configureEntityChatStore=ee,exports.createCrossAgentTools=y,exports.defineSubagent=f,exports.extractErrorMessage=L,exports.extractJsonBlock=R,exports.findSubagentManifest=g,exports.getAgenticoPrompts=D,exports.getDestinationRegistry=W,exports.getEntityChat=re,exports.getSubagentRegistry=h,exports.getSubagentReport=ze,exports.jsonExportDestination=V,exports.listEntityChats=J,exports.registerCrossAgentTools=v,exports.registerDestinations=U,exports.registerSubagentReports=Re,exports.registerSubagents=m,exports.removeEntityChat=ae,exports.renderRegistryCli=N,exports.renderSubagentCli=M,exports.resetAgenticoPrompts=O,exports.saveEntityChat=ie,exports.toJsonSchema=b,exports.toMcpTool=x,exports.useAgent=Ae,exports.useAgentico=Q,exports.useAgenticoI18n=X,exports.useAgenticoPageContext=$e,exports.useSubagentComponentContext=et;
18
+ //# sourceMappingURL=index.js.map