@llmnative/agentico 0.2.0 → 0.4.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.md CHANGED
@@ -16,7 +16,7 @@ current scope (tenant, company, workspace…).
16
16
  npm install @llmnative/agentico @llmnative/react zod
17
17
  ```
18
18
 
19
- Requires Node.js 24 LTS, React 19 and `@llmnative/react` ≥ 1.20.
19
+ Requires Node.js 24 LTS, React 19 and `@llmnative/react` ≥ 1.34.
20
20
 
21
21
  ## Setup (once, at startup)
22
22
 
@@ -60,6 +60,8 @@ configureAgenticoPrompts({ // optional: langu
60
60
  | **Page context** — what the user is looking at, for the orchestrator prompt | `useAgenticoPageContext`, `useSubagentComponentContext` |
61
61
  | **Saved chats** — one chat per saved entity, resumable | `configureEntityChatStore`, `getEntityChat`, `listEntityChats` |
62
62
  | **Remote subagents** — turns answered by the host (a remote agent with its own memory, e.g. an opencode session), streamed with its steps; its own models in the composer, no fallback | `AgentDefinition.executor` (`AgentExecutor`, `models`, `defaultModel`) |
63
+ | **Message parts** — a remote reply in parts, as in the Vercel AI SDK / AG-UI: Markdown text (tables, lists, code; repaired while it streams), the reasoning of the model (closed, "Reasoned for 12 s"), the steps grouped and collapsible, questions answered with a click. Answers go back structured: to the waiting turn (`onQuestions` resolves) or as a new turn with `answers`. Parts are saved with the chat; chats saved with text only still load | `AgentExecutorTurn.onText(text, { id?, done? })`, `onReasoning(text, { id?, done?, duration? })`, `onStep`, `onQuestions(questions, { id? })`, `AgentExecutorTurn.answers`, `AgentMessagePart`, `useAgent().answerQuestions` |
64
+ | **Panel** — a column beside the page, resizable by dragging its inner edge (or with the arrow keys on it; double click resets), the width kept per browser (`localStorage`, key `agentico:panel-width`). Questions waiting in the latest message of the agent are docked at the bottom in place of the composer, until answered or stopped | `<Agentico defaultWidth minWidth maxWidth onWidthChange>`, `AGENTICO_WIDTH`, `AGENTICO_MIN_WIDTH`, `AGENTICO_MAX_WIDTH` |
63
65
  | **Direct start** — a page starts a subagent without the orchestrator; with `chatEntityId` its chat is saved at every turn under that entity and resumed from the history; `onlyWhenAnchored` keeps it off the other pages | `useAgentico().startSubagent`, `entityChatTaskId`, `SubagentManifest.chatEntityId`, `SubagentManifest.onlyWhenAnchored` |
64
66
  | **Controls** — the actions of the prompt of a subagent (e.g. "Finish") and what the host shows above it, from a hook of the host | `registerSubagentControls` |
65
67
  | **History** — chats per entity, the open one marked, archived on hover (with the host deciding what archiving does) | `SubagentManifest.onArchive`, `confirmArchive` |
package/dist/index.js CHANGED
@@ -1,18 +1,21 @@
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(`
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");var f=`text`,p=`reasoning`;function m(e,t,n){let r=e.findIndex(e=>e.type===t.type&&e.id===t.id);if(r>=0)return e.map((e,n)=>n===r?t:e);let i=t.type===`reasoning`||!n?e:e.map(e=>e.type===`reasoning`&&e.streaming?n(e):e),a=i.findIndex(e=>e.type===`text`&&e.id===`text`);return(t.type===`tool`||t.type===`reasoning`)&&a>=0?[...i.slice(0,a),t,...i.slice(a)]:[...i,t]}function h(e){return e.filter(e=>e.type===`text`).map(e=>e.text).filter(Boolean).join(`
2
+
3
+ `)}function g(e,t){return t.map((t,n)=>`${t.header??e[n]?.header??e[n]?.question??t.id??`${n+1}`}: ${t.values.join(`, `)}`).join(`
4
+ `)}function _(e){return e}var v=[];function y(e){v=e}function b(){return v.length===0&&typeof console<`u`&&console.warn(`[agentico] getSubagentRegistry() letto a registro vuoto — registerSubagents() non è ancora stato chiamato?`),v}function x(e){return v.find(t=>t.id===e)}var S=[];function C(...e){S=e}function w(e){return S.flatMap(t=>t(e))}function T(e){let{$schema:t,...n}=(0,c.zodToJsonSchema)(e,{target:`jsonSchema7`,$refStrategy:`none`});return n}function E(e,t,n,r){return{name:e,description:t,inputSchema:T(n),...r?{outputSchema:T(r)}:{}}}function D(e){let t=T(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 O={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.`},k={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.`},A=O;function j(e){A={...A,...e}}function M(){return A}function N(){A=O}function P(e,t){return`${e} ${t.map(e=>e.required?`--${e.key} <${e.type}>`:`[--${e.key} <${e.type}>]`).join(` `)}`.trim()}function F(e,t){let n=D(t),r=P(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`,I(t.describeOutput(),4),(t.example,``),t.example?` EXAMPLE`:``,t.example?` ${t.example}`:``].filter(e=>e!==``).join(`
5
+ `)}function I(e,t){let n=` `.repeat(t);return e.split(`
3
6
  `).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 K(e){G=e.storageKey}function ee(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 q(){try{let e=localStorage.getItem(G);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(ee).filter(e=>e!==null):[]}catch{return[]}}function te(e){try{localStorage.setItem(G,JSON.stringify(e))}catch{}}var J=(e,t,n)=>`${e}:${t}:${n}`;function ne(e,t,n){let r=J(e,t,n);return q().find(e=>J(e.scopeId,e.subagentId,e.entityId)===r)??null}function re(e){let t=J(e.scopeId,e.subagentId,e.entityId),n=q().filter(e=>J(e.scopeId,e.subagentId,e.entityId)!==t);n.push({...e,savedAt:Date.now()}),te(n)}function ie(e,t,n){let r=J(e,t,n);te(q().filter(e=>J(e.scopeId,e.subagentId,e.entityId)!==r))}function ae(e){return q().filter(t=>t.scopeId===e).sort((e,t)=>t.savedAt-e.savedAt)}var Y=(e,t)=>`entitychat-${e}-${t}`,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.`,archiveChat:`Archivieren`,noResults:`Keine Ergebnisse.`,retry:`Erneut versuchen`,retryMessage:`Erneut versuchen.`,continueWithoutAi:`Ohne AI fortfahren`,resumeWithAi:`Mit AI fortsetzen`,openPanel:`Agentenbereich öffnen`,closePanel:`Agentenbereich schließen`},X={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.`,archiveChat:`Archive`,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.`,archiveChat:`Archivia`,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:X},it:{agentico:se},de:{agentico:oe}};function Z(){let{dict:e}=(0,l.useI18n)(),t=e.agentico;return t?{...X,...t}:X}var Q=`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&&(re({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))},[]),[K,ee]=(0,u.useState)(null),[q,te]=(0,u.useState)(null),J=(0,u.useCallback)((e,t,n)=>{f(),ee({subagentId:e,entityId:t,snapshot:n}),te(crypto.randomUUID())},[f]),[ne,ie]=(0,u.useState)(null),[ae,Y]=(0,u.useState)(null),oe=(0,u.useCallback)((e,t)=>{f(),c(Q),ie({subagentId:e,extraDestinations:t}),Y(crypto.randomUUID())},[f,c]),[X,se]=(0,u.useState)(null),[ce,Z]=(0,u.useState)(null),ue=(0,u.useCallback)((e,t,n)=>{ie(null),se({subagentId:e,params:t,extraDestinations:n}),Z(crypto.randomUUID())},[]),[$,de]=(0,u.useState)(null),[fe,pe]=(0,u.useState)(null),me=(0,u.useCallback)((e,t,n)=>{f(),de({subagentId:e,params:t,...n}),pe(crypto.randomUUID())},[f]),he=(0,u.useCallback)(()=>{let e=i.current;e&&e.onDismiss()},[]),ge=(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:J,pendingResume:K,resumeRunId:q,dismissForeignTask:he,pendingManualEntry:ne,manualEntryRunId:ae,startManualEntry:oe,pendingResumeWithAI:X,resumeWithAIRunId:ce,resumeWithAI:ue,startSubagent:me,pendingStart:$,startRunId:fe}),[t,n,a,s,c,l,p,W,B,V,j,U,E,I,z,F,f,h,v,b,S,w,G,J,K,q,he,ne,ae,oe,X,ce,ue,me,$,fe]);return(0,d.jsx)(le.Provider,{value:ge,children:e})}function $(){let e=(0,u.useContext)(le);if(!e)throw Error(`useAgentico must be used inside AgenticoProvider`);return e}function de(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(...de(u)),l}function fe(e){let t=[],n=/```(\w+)?\n?([\s\S]*?)```/g,r=0,i;for(;i=n.exec(e);)i.index>r&&t.push(...de(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(...de(e.slice(r))),t}function pe({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 me(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 he({text:e}){return(0,d.jsx)(d.Fragment,{children:me(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 ge({text:e}){let t=fe(e);return(0,d.jsx)(d.Fragment,{children:t.map((e,t)=>e.type===`code`?(0,d.jsx)(pe,{content:e.content,language:e.language},t):e.content.trim()&&(0,d.jsx)(`p`,{className:`whitespace-pre-wrap break-words`,children:(0,d.jsx)(he,{text:e.content})},t))})}function _e({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 ve(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 ye=96;function be({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:ye}: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)(ge,{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 xe({entry:e}){let t=Z();if(e.kind===`user`)return(0,d.jsx)(be,{entry:e});let n=e.kind===`thinking`&&e.detail?fe(e.detail):[],r=n.filter(e=>e.type===`code`),i=n.filter(e=>e.type===`text`&&e.content.trim()),a=e.kind===`thinking`?ve(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)(_e,{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)(pe,{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)(he,{text:e.content.trim()})},t))})]})}function Se({activity:e}){return e.length===0?null:(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:e.map(e=>(0,d.jsx)(xe,{entry:e},e.id))})}function Ce({className:e=``}){let{isOpen:t,toggleOpen:n,task:r}=$(),i=Z(),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 we=`llmnative-cms.selectedAIModel`;function Te(){try{return localStorage.getItem(we)??``}catch{return``}}function Ee(e){try{e?localStorage.setItem(we,e):localStorage.removeItem(we)}catch{}}function De(){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)(Te);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:(Ee(``),``))}).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=>{Ee(e),s(e)}}}var Oe=20,ke=26e4;function Ae(e){return e.filter(e=>!l.PromptUtils.isTextAttachment(e.mimeType)||e.base64.length<=ke)}function je(e,t={}){let{defaultEnabled:n=!1}=t,[r,i]=(0,u.useState)(n),{hasProviders:a,modelsByProvider:o,modelsLoading:s,selectedModel:c,setSelectedModel:d}=De(),[f,p]=(0,u.useState)(!1),[m,h]=(0,u.useState)(null),[g,_]=(0,u.useState)(!1),[v,y]=(0,u.useState)([]),x=Z(),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=e.executor,M=!!j,[N,P]=(0,u.useState)([]),[F,R]=(0,u.useState)(``),z=(0,u.useRef)(``),B=e=>{z.current=e,R(e)},V=e=>{P(j?.models?.(e)??[]),B(j?.defaultModel?.(e)??``)},H=async(e,t,n)=>{let r=C.current;if(!r||!j)return h(S.current.noActiveSession),null;let i=new AbortController;T.current=i;let a=crypto.randomUUID();y(e=>[...e,{id:a,kind:`thinking`,label:S.current.thinking,status:`running`}]);let o=(e,t)=>y(n=>n.map(n=>n.id===a?{...n,status:e,...t===void 0?{}:{detail:t}}:n)),s=e=>{let t=`step-${a}-${e.id}`;y(n=>{if(n.some(e=>e.id===t))return n.map(n=>n.id===t?{...n,label:e.label,status:e.status}:n);let r=n.findIndex(e=>e.id===a),i={id:t,kind:`tool`,label:e.label,status:e.status};return r<0?[...n,i]:[...n.slice(0,r),i,...n.slice(r)]})};try{let a=await j.turn({params:r.params,context:r.context,text:e,first:t,signal:i.signal,...n||z.current?{model:n||z.current}:{},onText:e=>o(`running`,e),onStep:s});return o(`done`,a.text),r.history=[...r.history,...e?[{role:`user`,content:e}]:[],{role:`assistant`,content:a.text}],a.result??null}catch(t){return r.history=[...r.history,...e?[{role:`user`,content:e}]:[]],i.signal.aborted?(o(`stopped`),null):(o(`error`),h(L(t)),null)}finally{T.current=null}},U=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<=ke?`\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=Ae(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<Oe;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:M?F:c,setSelectedModel:M?B:d,modelsByProvider:o,modelsLoading:s,running:f,error:m,canContinue:g,remote:M,remoteModels:N,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)??[];if(C.current={params:t,context:i,tools:o,history:[],logId:crypto.randomUUID(),attachmentsRef:a},M)return _(!0),V(t),await H(n?.openingMessage??``,!0);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 U(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},M&&V(t),_(M||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{if(M)return await H(t,!1,n?.model||void 0);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 U(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 Me(){let e=D();return[e.responseRulesHeading,...e.responseRules.map(e=>`- ${e}`)].join(`
9
- `)}function Ne(e,t,n){let r=D(),i=n?`\n${r.pageContextHeading}\n${r.pageContextIntro}\n${n}\n`:``;return`${r.orchestratorIntro}
7
+ `)}function L(e){return[`NAME`,` ${e.id} — ${e.label}`,``,`DESCRIPTION`,I(e.description,2),``,...e.commands.map(t=>F(e.id,t))].join(`
8
+ `)}function R(e){return e.length===0?M().noToolsAvailable:e.map(e=>`${e.id} [${e.commands.map(e=>e.name).join(`|`)}] — ${e.label}: ${e.commands.map(e=>e.summary).join(` / `)}`).join(`
9
+ `)}var z={id:`closing-summary`,get text(){return M().closingSummary}},ee={[z.id]:z};function B(e,t){if(!t||t.length===0)return e;let n=t.map(e=>ee[e]?.text).filter(e=>!!e);return n.length===0?e:`${e}\n\n${n.join(`
10
+ `)}`}function V(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 H(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 te(n)??n}function te(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 U=`json-export`,W={id:U,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)}}},G={};function K(e){G=e}function q(){return{[W.id]:W,...G}}var J=`llmnative.agentico.entityChat`;function Y(e){J=e.storageKey}function ne(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 X(){try{let e=localStorage.getItem(J);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(ne).filter(e=>e!==null):[]}catch{return[]}}function re(e){try{localStorage.setItem(J,JSON.stringify(e))}catch{}}var Z=(e,t,n)=>`${e}:${t}:${n}`;function ie(e,t,n){let r=Z(e,t,n);return X().find(e=>Z(e.scopeId,e.subagentId,e.entityId)===r)??null}function ae(e){let t=Z(e.scopeId,e.subagentId,e.entityId),n=X().filter(e=>Z(e.scopeId,e.subagentId,e.entityId)!==t);n.push({...e,savedAt:Date.now()}),re(n)}function oe(e,t,n){let r=Z(e,t,n);re(X().filter(e=>Z(e.scopeId,e.subagentId,e.entityId)!==r))}function se(e){return X().filter(t=>t.scopeId===e).sort((e,t)=>t.savedAt-e.savedAt)}var ce=(e,t)=>`entitychat-${e}-${t}`,le={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.`,oneStep:`1 Schritt`,steps:`{count} Schritte`,stepsLabel:`Schritte des Agenten`,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.`,archiveChat:`Archivieren`,noResults:`Keine Ergebnisse.`,retry:`Erneut versuchen`,retryMessage:`Erneut versuchen.`,continueWithoutAi:`Ohne AI fortfahren`,resumeWithAi:`Mit AI fortsetzen`,openPanel:`Agentenbereich öffnen`,closePanel:`Agentenbereich schließen`,resizePanel:`Agent-Bereich in der Größe ändern`,resizePanelHint:`Ziehen zum Ändern der Größe, Doppelklick zum Zurücksetzen`,pendingQuestions:`Fragen des Agenten`,stop:`Stoppen`},ue={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.`,oneStep:`1 step`,steps:`{count} steps`,stepsLabel:`Steps of the agent`,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.`,archiveChat:`Archive`,noResults:`No results.`,retry:`Retry`,retryMessage:`Retry.`,continueWithoutAi:`Continue without AI`,resumeWithAi:`Resume with AI`,openPanel:`Open agent panel`,closePanel:`Close agent panel`,resizePanel:`Resize the agent panel`,resizePanelHint:`Drag to resize, double-click to reset`,pendingQuestions:`Questions of the agent`,stop:`Stop`},de={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.`,oneStep:`1 passo`,steps:`{count} passi`,stepsLabel:`Passi dell'agente`,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.`,archiveChat:`Archivia`,noResults:`Nessun risultato.`,retry:`Riprova`,retryMessage:`Riprova.`,continueWithoutAi:`Continua senza AI`,resumeWithAi:`Riprendi con AI`,openPanel:`Apri pannello agente`,closePanel:`Chiudi pannello agente`,resizePanel:`Ridimensiona il pannello dell'agente`,resizePanelHint:`Trascina per ridimensionare, doppio clic per ripristinare`,pendingQuestions:`Domande dell'agente`,stop:`Ferma`},fe={en:{agentico:ue},it:{agentico:de},de:{agentico:le}};function Q(){let{dict:e}=(0,l.useI18n)(),t=e.agentico;return t?{...ue,...t}:ue}var pe=`agentico-orchestrator`,me=(0,u.createContext)(null);function he({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,g]=(0,u.useState)(void 0),[_,v]=(0,u.useState)(void 0),[y,b]=(0,u.useState)(void 0),[S,C]=(0,u.useState)(null),[w,T]=(0,u.useState)(null),[E,D]=(0,u.useState)(void 0),[O,k]=(0,u.useState)([]),A=(0,u.useCallback)((e,t,n=null)=>{k(r=>{let i=r.filter(t=>t.id!==e);return t?[...i,{id:e,text:t,card:n}]:i})},[]),j=O.length>0?O[O.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=x(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]),ee=(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(`
11
+ `);return`${M().multipleCandidates}\n\n${e}`},[R])??j?.text??null,B=R.length>0?null:j?.card??null,V=(0,u.useMemo)(()=>[...new Set(I.map(e=>e.subagentId))],[I]),H=V.length===1?V[0]:V.length===0?j?.card?.subagentId??null:null,te=(0,u.useCallback)((e,t)=>{f();let n=i.current;if(n?.id===`agentico-orchestrator`)return;let r=H&&n?.id.startsWith(`subagent-${H}-`)?n:void 0;T(r?{taskId:r.id,activity:[...r.precedingActivity??[],...r.agent.activity]}:null),m(e),g(t?.extraDestinations),v(t?.attachments),b(t?.model),D(t?.scopedSubagentId),C(crypto.randomUUID())},[f,H]),U=(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&&(ae({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))},[]),[W,G]=(0,u.useState)(null),[K,q]=(0,u.useState)(null),J=(0,u.useCallback)((e,t,n)=>{f(),G({subagentId:e,entityId:t,snapshot:n}),q(crypto.randomUUID())},[f]),[Y,ne]=(0,u.useState)(null),[X,re]=(0,u.useState)(null),Z=(0,u.useCallback)((e,t)=>{f(),c(pe),ne({subagentId:e,extraDestinations:t}),re(crypto.randomUUID())},[f,c]),[ie,oe]=(0,u.useState)(null),[se,ce]=(0,u.useState)(null),le=(0,u.useCallback)((e,t,n)=>{ne(null),oe({subagentId:e,params:t,extraDestinations:n}),ce(crypto.randomUUID())},[]),[ue,de]=(0,u.useState)(null),[fe,Q]=(0,u.useState)(null),he=(0,u.useCallback)((e,t,n)=>{f(),de({subagentId:e,params:t,...n}),Q(crypto.randomUUID())},[f]),$=(0,u.useCallback)(()=>{let e=i.current;e&&e.onDismiss()},[]),ge=(0,u.useMemo)(()=>({scope:t,task:n,isOpen:a,openTask:s,closeTask:c,toggleOpen:l,pendingGoal:p,startOrchestrator:te,pageContext:ee,pageContextCard:B,setPageContext:A,scopedSubagentId:H,pendingScopedSubagentId:E,componentAnchors:I,anchoredUserMessages:z,registerComponentAnchor:F,openPanel:f,pendingExtraDestinations:h,pendingAttachments:_,pendingModel:y,orchestratorRunId:S,pendingCarryOver:w,commitEntityChat:U,resumeEntityChat:J,pendingResume:W,resumeRunId:K,dismissForeignTask:$,pendingManualEntry:Y,manualEntryRunId:X,startManualEntry:Z,pendingResumeWithAI:ie,resumeWithAIRunId:se,resumeWithAI:le,startSubagent:he,pendingStart:ue,startRunId:fe}),[t,n,a,s,c,l,p,te,ee,B,A,H,E,I,z,F,f,h,_,y,S,w,U,J,W,K,$,Y,X,Z,ie,se,le,he,ue,fe]);return(0,d.jsx)(me.Provider,{value:ge,children:e})}function $(){let e=(0,u.useContext)(me);if(!e)throw Error(`useAgentico must be used inside AgenticoProvider`);return e}function ge(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(...ge(u)),l}function _e(e){let t=[],n=/```(\w+)?\n?([\s\S]*?)```/g,r=0,i;for(;i=n.exec(e);)i.index>r&&t.push(...ge(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(...ge(e.slice(r))),t}function ve({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 ye({text:e,tone:t}){let n=_e(e);return(0,d.jsx)(d.Fragment,{children:n.map((e,n)=>e.type===`code`?(0,d.jsx)(ve,{content:e.content,language:e.language},n):e.content.trim()&&(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:t,className:`break-words text-xs leading-relaxed`},n))})}function be({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 xe(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 Se=96;function Ce({entry:e,pinned:t=!0}){let n=(0,u.useRef)(null),[r,i]=(0,u.useState)(!1),[a,o]=(0,u.useState)(!1);(0,u.useLayoutEffect)(()=>{let e=n.current;e&&o(e.scrollHeight>97)},[e.detail,e.attachmentNames]);let s=a&&!r;return(0,d.jsx)(`div`,{className:`${t?`sticky top-0 z-20 border-b border-border/40`:``} flex justify-end 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:n,className:`space-y-1 px-2.5 pt-1.5 ${s?`overflow-hidden`:``}`,style:s?{maxHeight:Se}: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)(ye,{text:e.detail??``})]}),a&&(0,d.jsxs)(`button`,{type:`button`,onClick:()=>i(e=>!e),className:`relative flex w-full items-center justify-center rounded-b-lg py-1 text-muted-foreground hover:bg-primary/15`,title:r?`Comprimi`:`Espandi`,children:[s&&(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:r?`chevron-up`:`chevron-down`,size:12})]})]})})}var we={running:`loader-circle`,done:`check`,error:`x`,stopped:`circle-slash`};function Te({steps:e}){let t=Q(),n=e.filter(e=>e.status===`running`).at(-1),r=e.some(e=>e.status===`error`),i=n?.label??(e.length===1?t.oneStep:(0,l.interpolate)(t.steps,{count:e.length}));return(0,d.jsx)(l.Tree,{ariaLabel:t.stepsLabel,selectedId:null,itemClassName:`py-0.5 text-xs text-muted-foreground`,nodes:[{id:`steps-${e[0]?.id??``}`,label:i,icon:n?`loader-circle`:r?`circle-alert`:`list-checks`,children:e.map(e=>({id:e.id,label:(0,d.jsx)(`span`,{className:e.status===`error`?`text-destructive`:void 0,children:e.label}),icon:we[e.status]}))}]})}function Ee(e,t){let n=e.at(-1);if(!n||n.kind!==`thinking`||!n.parts||n.status===`stopped`||n.status===`error`)return null;let r=[...n.parts].reverse().find(e=>e.type===`questions`);return!r||r.answers||!t(n.id)?null:{entry:n,part:r}}function De({entry:e,part:t,questions:n,autoFocus:r,className:i}){let a=!!n?.canAnswer(e.id);return(0,d.jsx)(l.ChatQuestions,{questions:t.questions,...t.answers?{answers:t.answers}:{},disabled:!t.answers&&!a,onSubmit:n&&a?r=>n.onAnswer(e.id,t.id,r):void 0,autoFocus:r,className:i??`text-xs`})}function Oe({entry:e,questions:t,hiddenPartId:n}){let r=(e.parts??[]).filter(e=>e.type!==`questions`||e.id!==n),i=[];for(let e of r){let t=i.at(-1);e.type===`tool`?t&&`steps`in t?t.steps.push(e):i.push({key:`tool-${e.id}`,steps:[e]}):i.push({key:`${e.type}-${e.id}`,part:e})}return(0,d.jsx)(`div`,{className:`space-y-2`,children:i.map(n=>{if(`steps`in n)return(0,d.jsx)(Te,{steps:n.steps},n.key);let{part:r}=n;return r.type===`text`?r.text.trim()?(0,d.jsx)(l.ChatMarkdown,{content:r.text,streaming:r.streaming,className:`break-words text-xs leading-relaxed text-foreground`},n.key):null:r.type===`reasoning`?(0,d.jsx)(l.ChatReasoning,{content:r.text,streaming:r.streaming,duration:r.duration,className:`my-0`},n.key):(0,d.jsx)(De,{entry:e,part:r,questions:t},n.key)})})}function ke({entry:e,questions:t,hiddenPartId:n}){let r=Q();if(e.kind===`thinking`&&e.parts){let i=e.status===`error`||e.status===`stopped`||e.status===`running`&&e.parts.length===0;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[e.parts.length>0&&(0,d.jsx)(Oe,{entry:e,questions:t,hiddenPartId:n}),i&&(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5 ${e.parts.length>0?`mt-1`:``}`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(be,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:xe(e,r)})]})]})}let i=e.kind===`thinking`&&e.detail?_e(e.detail):[],a=i.filter(e=>e.type===`code`),o=i.filter(e=>e.type===`text`&&e.content.trim()),s=e.kind===`thinking`?xe(e,r):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)(be,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:s})]}),a.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-1`,children:a.map((e,t)=>(0,d.jsx)(ve,{content:e.content,language:e.language},t))}),o.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-2`,children:o.map((e,t)=>(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:`muted`,className:`break-words text-xs leading-relaxed`},t))})]})}function Ae({activity:e,questions:t,docked:n,pinUserMessages:r=!0}){if(e.length===0)return null;let i=[];for(let t of e)t.kind===`user`||i.length===0?i.push(t.kind===`user`?{user:t,entries:[]}:{entries:[t]}):i[i.length-1].entries.push(t);return(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:i.map(e=>(0,d.jsxs)(`li`,{children:[e.user&&(0,d.jsx)(Ce,{entry:e.user,pinned:r}),e.entries.length>0&&(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:e.entries.map(e=>(0,d.jsx)(ke,{entry:e,questions:t,hiddenPartId:n?.entry.id===e.id?n.part.id:void 0},e.id))})]},e.user?.id??e.entries[0]?.id))})}var je=420,Me=320,Ne=`60vw`,Pe=`agentico:panel-width`;function Fe(e,t){if(typeof e==`number`)return e;let n=Number.parseFloat(e);return Number.isFinite(n)?Math.round(n/100*t):1/0}function Ie(e,t,n){return Math.round(Math.min(Math.max(e,t),Math.max(t,n)))}function Le(){try{let e=window.localStorage.getItem(Pe),t=e===null?NaN:Number(e);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function Re(e){try{e===null?window.localStorage.removeItem(Pe):window.localStorage.setItem(Pe,String(e))}catch{}}function ze(){return typeof window>`u`?1/0:window.innerWidth}function Be({defaultWidth:e=420,minWidth:t=320,maxWidth:n=Ne,onWidthChange:r}){let[i,a]=(0,u.useState)(ze),[o,s]=(0,u.useState)(()=>Le()??e);(0,u.useEffect)(()=>{if(typeof window>`u`)return;let e=()=>a(window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let c=t,l=Math.max(c,Fe(n,i)),d=Ie(o,c,l);return(0,u.useEffect)(()=>{r?.(d)},[d]),{width:d,min:c,max:l,set:(0,u.useCallback)(e=>s(Ie(e,c,l)),[c,l]),commit:(0,u.useCallback)(e=>Re(Ie(e,c,l)),[c,l]),reset:(0,u.useCallback)(()=>{s(e),Re(null)},[e])}}function Ve({width:e,min:t,max:n,onResize:r,onCommit:i,onReset:a}){let o=Q(),s=(0,u.useRef)(null),[c,l]=(0,u.useState)(!1),f=e=>Math.round(Math.min(Math.max(e,t),Math.max(t,n))),p=e=>{let t=s.current;if(t&&t.pointerId===e.pointerId){s.current=null,l(!1),document.body.style.removeProperty(`cursor`),document.body.style.removeProperty(`user-select`);try{e.currentTarget.releasePointerCapture(e.pointerId)}catch{}i(t.last)}};return(0,d.jsx)(`div`,{role:`separator`,"aria-orientation":`vertical`,"aria-label":o.resizePanel,"aria-valuenow":e,"aria-valuemin":t,"aria-valuemax":n,tabIndex:0,title:o.resizePanelHint,"data-dragging":c||void 0,className:`group absolute inset-y-0 -left-1 z-30 flex w-2 cursor-col-resize touch-none select-none justify-center outline-none`,onPointerDown:t=>{if(t.button===0){t.preventDefault(),s.current={pointerId:t.pointerId,startX:t.clientX,startWidth:e,last:e},l(!0),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`;try{t.currentTarget.setPointerCapture(t.pointerId)}catch{}}},onPointerMove:e=>{let t=s.current;t&&t.pointerId===e.pointerId&&(t.last=f(t.startWidth+(t.startX-e.clientX)),r(t.last))},onPointerUp:p,onPointerCancel:p,onLostPointerCapture:p,onDoubleClick:a,onKeyDown:a=>{let o=a.shiftKey?64:16,s=null;if(a.key===`ArrowLeft`?s=e+o:a.key===`ArrowRight`?s=e-o:a.key===`Home`?s=t:a.key===`End`&&(s=n),s===null)return;a.preventDefault();let c=f(s);r(c),i(c)},children:(0,d.jsx)(`span`,{"aria-hidden":!0,className:`h-full w-0.5 transition-colors ${c?`bg-primary`:`bg-transparent group-hover:bg-primary/50 group-focus-visible:bg-primary`}`})})}function He({className:e=``}){let{isOpen:t,toggleOpen:n,task:r}=$(),i=Q(),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 Ue=`llmnative-cms.selectedAIModel`;function We(){try{return localStorage.getItem(Ue)??``}catch{return``}}function Ge(e){try{e?localStorage.setItem(Ue,e):localStorage.removeItem(Ue)}catch{}}function Ke(){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:(Ge(``),``))}).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=>{Ge(e),s(e)}}}var qe=20,Je=26e4;function Ye(e){return e.filter(e=>!l.PromptUtils.isTextAttachment(e.mimeType)||e.base64.length<=Je)}function Xe(e,t={}){let{defaultEnabled:n=!1}=t,[r,i]=(0,u.useState)(n),{hasProviders:a,modelsByProvider:o,modelsLoading:s,selectedModel:c,setSelectedModel:d}=Ke(),[p,_]=(0,u.useState)(!1),[v,y]=(0,u.useState)(null),[b,x]=(0,u.useState)(!1),[S,C]=(0,u.useState)([]),w=(0,u.useRef)([]),E=e=>{C(t=>{let n=typeof e==`function`?e(t):e;return w.current=n,n})},D=(0,u.useRef)(new Map),O=Q(),k=(0,u.useRef)(O);k.current=O;let A=(0,u.useRef)(null),j=(0,u.useRef)(!1),N=(0,u.useRef)(null),P=()=>{N.current?.abort()},F=(0,l.useAIProviderRegistry)()?.registry??{},I=r&&c?(0,l.parseAIModelRef)(c):null,L=I?F[I.provider]:null,R=e.executor,z=!!R,[ee,H]=(0,u.useState)([]),[te,U]=(0,u.useState)(``),W=(0,u.useRef)(``),G=e=>{W.current=e,U(e)},K=e=>{H(R?.models?.(e)??[]),G(R?.defaultModel?.(e)??``)},q=async(e,t,n,r)=>{let i=A.current;if(!i||!R)return y(k.current.noActiveSession),null;let a=new AbortController;N.current=a;let o=crypto.randomUUID();E(e=>[...e,{id:o,kind:`thinking`,label:k.current.thinking,status:`running`,parts:[]}]);let s=new Map,c=e=>Math.max(1,Math.round((Date.now()-(s.get(e)??Date.now()))/1e3)),l=e=>({...e,streaming:!1,duration:e.duration??c(e.id)}),u=(e,t)=>E(n=>n.map(n=>{if(n.id!==o)return n;let r=e(n.parts??[]),i=h(r);return{...n,parts:r,...t?{status:t}:{},...i?{detail:i}:{}}})),d=e=>u(t=>m(t,e,l)),p=!1,g=(e,t)=>{t?.id&&t.id!==`text`&&(p=!0),d({type:`text`,id:t?.id??`text`,text:e,streaming:!t?.done})},_=(e,t)=>{let n=t?.id??`reasoning`;s.has(n)||s.set(n,Date.now()),d({type:`reasoning`,id:n,text:e,streaming:!t?.done,...t?.duration===void 0?t?.done?{duration:c(n)}:{}:{duration:t.duration}})},v=e=>d({type:`tool`,id:e.id,label:e.label,status:e.status}),b=new Set,x=0,S=()=>{for(let e of b){let t=D.current.get(e);D.current.delete(e),t?.reject(new DOMException(`The turn was stopped.`,`AbortError`))}b.clear()};a.signal.addEventListener(`abort`,S);let C=(e,t)=>{x+=1;let n=t?.id??`questions-${x}`;d({type:`questions`,id:n,questions:e});let r=`${o}:${n}`;return a.signal.aborted?Promise.reject(new DOMException(`The turn was stopped.`,`AbortError`)):(b.add(r),new Promise((e,t)=>{D.current.set(r,{resolve:e,reject:t})}))},w=(e,t)=>{u(n=>(t&&!p?m(n,{type:`text`,id:f,text:t,streaming:!1},l):n).map(t=>t.type===`reasoning`&&t.streaming?l(t):t.type===`text`&&t.streaming?{...t,streaming:!1}:t.type===`tool`&&t.status===`running`&&e!==`done`?{...t,status:`stopped`}:t),e),a.signal.removeEventListener(`abort`,S);for(let e of b)D.current.delete(e);b.clear()},T=e||r?.historyText||``;try{let o=await R.turn({params:i.params,context:i.context,text:e,first:t,signal:a.signal,...n||W.current?{model:n||W.current}:{},...r?{answers:{id:r.id,answers:r.answers}}:{},onText:g,onReasoning:_,onStep:v,onQuestions:C});return w(`done`,o.text),i.history=[...i.history,...T?[{role:`user`,content:T}]:[],{role:`assistant`,content:o.text}],o.result??null}catch(e){return i.history=[...i.history,...T?[{role:`user`,content:T}]:[]],a.signal.aborted?(w(`stopped`),null):(w(`error`),y(V(e)),null)}finally{N.current=null}},J=async(e,t,n)=>{let r=w.current.find(t=>t.id===e)?.parts?.find(e=>e.type===`questions`&&e.id===t);if(!r||r.type!==`questions`)throw y(k.current.noActiveSession),Error(k.current.noActiveSession);let i=()=>E(r=>r.map(r=>r.id===e?{...r,parts:r.parts?.map(e=>e.type===`questions`&&e.id===t?{...e,answers:n}:e)}:r)),a=`${e}:${t}`,o=D.current.get(a);if(o)return D.current.delete(a),i(),o.resolve(n),null;if(j.current)throw y(k.current.requestInProgress),Error(k.current.requestInProgress);if(!z||!A.current)throw y(k.current.noActiveSession),Error(k.current.noActiveSession);j.current=!0,_(!0),y(null),i();try{return await q(``,!1,void 0,{id:t,answers:n,historyText:g(r.questions,n)})}finally{j.current=!1,_(!1)}},Y=async(t,n,r)=>{let i=A.current;if(!i)return y(k.current.noActiveSession),null;let a=r?(0,l.parseAIModelRef)(r):I,o=a?F[a.provider]:null;if(!o||!a)return y(k.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<=Je?`\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=Ye(n??[]),u=i.tools.map(e=>({name:e.name,description:e.description,inputSchema:T(e.inputSchema)})),d=new Map(i.tools.map(e=>[e.name,e])),f=new AbortController;N.current=f;let p=(e,t,n,r)=>E(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<qe;t++){let l=crypto.randomUUID();E(e=>[...e,{id:l,kind:`thinking`,label:k.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`),y(V(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`),y(k.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}),y(k.current.invalidResponse),e.fallback(i.params,i.context));let h=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:h);let g=await Promise.all(m.toolCalls.map(async e=>{let t=d.get(e.name),n=t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`;if(E(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:V(t),isError:!0}}}));n=[...n,...r?[{role:`user`,content:r+s}]:[],{role:`assistant`,content:m.text,toolCalls:m.toolCalls},{role:`tool_result`,results:g}],r=``}let l=crypto.randomUUID();E(e=>[...e,{id:l,kind:`thinking`,label:k.current.thinking,status:`running`}]);let m;try{m=await o.complete({prompt:B(M().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||y(k.current.tooManyToolTurns),e.fallback(i.params,i.context)}finally{N.current=null}};return{enabled:r,setEnabled:i,hasProviders:a,selectedModel:z?te:c,setSelectedModel:z?G:d,modelsByProvider:o,modelsLoading:s,running:p,error:v,canContinue:b,remote:z,remoteModels:ee,activity:S,run:async(t,n)=>{if(j.current)return y(k.current.requestInProgress),null;j.current=!0,y(null),E(n?.openingMessage?[{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:n.openingMessage,...n.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]:[]),_(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];if(A.current={params:t,context:i,tools:o,history:[],logId:crypto.randomUUID(),attachmentsRef:a},z)return x(!0),K(t),await q(n?.openingMessage??``,!0);let s=n?.model||void 0,c=s?!!F[(0,l.parseAIModelRef)(s)?.provider??``]:!!L;if(!r||!c){x(!1);let n=e.fallback(t,i);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.aiDisabledFallback}]),n}x(!0);let u=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,d=B(e.buildPrompt(t,i),e.microPromptIds);return await Y(d,u,s)}catch(e){return y(V(e)),null}finally{j.current=!1,_(!1)}},resume:async(t,n)=>{if(j.current){y(k.current.requestInProgress);return}j.current=!0,y(null),E(n.activity),_(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];A.current={params:t,context:i,tools:o,history:n.history,logId:crypto.randomUUID(),attachmentsRef:a},z&&K(t),x(z||r&&!!L)}catch(e){y(V(e))}finally{j.current=!1,_(!1)}},sendMessage:async(t,n)=>{if(j.current)return y(k.current.requestInProgress),null;if(y(null),!t.trim())return y(`Messaggio vuoto.`),null;let r=A.current;if(!r)return y(k.current.noActiveSession),null;j.current=!0,_(!0),E(e=>[...e,{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:t,...n?.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]);try{if(z)return await q(t,!1,n?.model||void 0);let i=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,a=B(e.buildFollowUpPrompt(t,r.params,r.context),e.microPromptIds);return await Y(a,i,n?.model||void 0)}catch(e){return y(V(e)),null}finally{j.current=!1,_(!1)}},stop:P,runFallback:()=>{let t=A.current;if(!t)return null;y(null);let n=e.fallback(t.params,t.context);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.continueWithoutAiFallback}]),n},snapshot:()=>A.current?{history:A.current.history,activity:S}:null,answerQuestions:J}}function Ze(){let e=M();return[e.responseRulesHeading,...e.responseRules.map(e=>`- ${e}`)].join(`
12
+ `)}function Qe(e,t,n){let r=M(),i=n?`\n${r.pageContextHeading}\n${r.pageContextIntro}\n${n}\n`:``;return`${r.orchestratorIntro}
10
13
 
11
14
  ${r.toolsHeading}
12
15
  ${t}
13
16
  ${i}
14
- ${Me()}
17
+ ${Ze()}
15
18
 
16
19
  ${r.userRequestHeading}
17
- ${e}`}function Pe(e,t){return t?{kind:`handoff`,...t}:{kind:`chat`,message:e}}function Fe(e){return h().filter(t=>!t.onlyWhenAnchored||e===t.id)}function Ie(e){return{buildContext(e){return{cliCatalog:N(Fe(e.scopedSubagentId)),handoff:{current:null},collected:{}}},buildPrompt({userGoal:e,pageContext:t},{cliCatalog:n}){return Ne(e,n,t)},buildFollowUpPrompt(e,t,{cliCatalog:n}){return`${e}\n\n${Me()}\n\n${D().toolsHeading}\n${n}`},parseResponse(e,t,n){let r=n.handoff.current;return n.handoff.current=null,Pe(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=Fe(t.scopedSubagentId).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 Le(e,t){return e.deriveHistoryTitle?.(t)??e.label}function Re({manifest:e,result:t,meta:n,taskId:r,initiallyApplied:i,onApplied:a,extraDestinations:o}){let s=Z(),c=$(),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,Le(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 ze={};function Be(e){Object.assign(ze,e)}function Ve(e){return ze[e]}function He({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 Ue(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))}}}var We={};function Ge(e){Object.assign(We,e)}function Ke(e){return We[e]}var qe=()=>({});function Je({manifest:e,params:t,extraDestinations:n,precedingActivity:r,taskId:i,resumeSeed:a,model:o,openingMessage:s}){let c=je(e.definition,{defaultEnabled:!0}),f=$(),p=f.scope,m=(0,l.useProxy)(),h=(0,u.useRef)(i??`subagent-${e.id}-${crypto.randomUUID()}`).current,[g,_]=(0,u.useState)(null),[v,y]=(0,u.useState)([]),[b,x]=(0,u.useState)(null),S=Ve(e.id),C=S?.kind===`selection`?S:null,[w,T]=(0,u.useState)(null),E=(0,u.useRef)(!1),D=(0,u.useRef)(0),O=(0,u.useRef)(null);g&&g!==O.current&&(O.current=g,D.current=(r?.length??0)+c.activity.length);let k=(0,u.useRef)(!1),A=c.remote||!c.hasProviders||c.selectedModel!==``;(0,u.useEffect)(()=>{!E.current&&A&&(E.current=!0,a?c.resume(e.toParams(t),a):(o&&c.setSelectedModel(o),c.run(e.toParams(t),{model:o,openingMessage:s}).then(e=>{e&&_(e)})))},[A]),(0,u.useEffect)(()=>{if(!g||!p)return;let n=e.autoApplyDestinationIds??[],r=f.componentAnchors.find(t=>t.subagentId===e.id&&t.pinnedEntityId)?.pinnedEntityId,i=W();n.forEach(n=>{let a=i[n];a&&(x(null),a.apply(g,{scopeId:p.id,dataProvider:p.dataProvider,storageProvider:p.storageProvider,proxyFetch:m},{...t,pinnedEntityId:r}).then(n=>{n?.id&&f.commitEntityChat(e.id,n.id,h,p.id,t,Le(e,t))}).catch(e=>x(e instanceof Error?e.message:String(e))))})},[g,c.activity,p]),(0,u.useEffect)(()=>{g&&C&&T(C.defaultSelection(g))},[g,C]);let j=(e,t)=>{T(n=>n&&{...n,[e]:t})},M=e=>_(e),N=(0,u.useMemo)(()=>g&&C&&w?C.applySelection(g,w):g,[g,C,w]),P=(0,u.useMemo)(()=>f.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[f.componentAnchors,e.id]),F=(0,u.useMemo)(()=>Ue(P,t,h),[P,t,h]),I=(0,u.useMemo)(()=>F?[F,...n??[]]:n,[F,n]),L=e.chatEntityId?.(t),R=(0,u.useRef)(!1);(0,u.useEffect)(()=>{let n=R.current&&!c.running;if(R.current=c.running,!n||!L||!p)return;let i=c.snapshot();i&&re({scopeId:p.id,subagentId:e.id,entityId:L,params:t,title:Le(e,t),history:i.history,activity:[...r??[],...i.activity]})},[c.running]);let z=()=>{k.current=!0,c.running&&c.stop(),f.closeTask(h)},B=(0,u.useRef)(Ke(e.id)??qe).current,V=B({params:t,taskId:h,running:c.running,close:z}),H=e=>{y(t=>t.includes(e)?t:[...t,e])};return(0,u.useEffect)(()=>{k.current||f.openTask({id:h,title:Le(e,t),icon:e.icon,agent:c,onApplied:e=>_(e),precedingActivity:r,panelExtraAnchorIndex:D.current,onDismiss:z,...L?{savedToDisk:!0}:{},panelActions:V.content,composerActions:V.actions,panelExtra:g?(0,d.jsxs)(d.Fragment,{children:[C&&w?(0,d.jsx)(C.Report,{result:g,selection:w,onChange:j}):S?.kind===`editable`?(0,d.jsx)(S.Report,{result:g,onResultChange:M}):(0,d.jsx)(He,{result:N}),b&&(0,d.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Salvataggio automatico non riuscito: `,b]}),(0,d.jsx)(Re,{manifest:e,result:N,meta:t,taskId:h,initiallyApplied:v,onApplied:H,extraDestinations:I})]}):void 0})},[c.activity,c.running,c.error,c.canContinue,c.selectedModel,c.modelsByProvider,c.hasProviders,c.remoteModels,f.openTask,f.componentAnchors,h,e,t,g,N,w,v,n,r,b,V.content,V.actions]),(0,u.useEffect)(()=>()=>{f.closeTask(h)},[f.closeTask,h]),null}function Ye({userGoal:e}){let t=Z(),n=je((0,u.useMemo)(()=>Ie({unavailable:t.orchestratorUnavailable,continueWithoutAi:t.orchestratorContinueWithoutAi,preparing:t.orchestratorPreparing,collecting:t.orchestratorCollecting}),[]),{defaultEnabled:!0}),r=$(),[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(Q))};(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:Q,title:`Agentico`,icon:`bot`,agent:n,onApplied:_,scopedSubagentId:p.current,precedingActivity:m.current?.activity,onDismiss:()=>{h.current=!0,n.running&&n.stop(),r.closeTask(Q)}})},[n.activity,n.running,n.error,n.canContinue,n.selectedModel,n.modelsByProvider,n.hasProviders,r.openTask]),(0,u.useEffect)(()=>()=>{r.closeTask(Q)},[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)(Je,{manifest:y,params:i.params,extraDestinations:c.current,model:f.current||void 0,taskId:m.current?.taskId,precedingActivity:v}):null}function Xe({manifest:e,extraDestinations:t}){let n=je(e.definition,{defaultEnabled:!1}),r=Z(),i=$(),a=(0,u.useRef)(`manual-${e.id}-${crypto.randomUUID()}`).current,[o,s]=(0,u.useState)(null),[c,f]=(0,u.useState)([]),p=Ve(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)(()=>_?Ue(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)(He,{result:C}),(0,d.jsx)(Re,{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 Ze=420;function Qe(e){return Object.values(e).flat().map(e=>({label:e.model,value:e.id,pricing:e.pricing??null,group:e.providerLabel??e.provider}))}function $e({task:e}){let t=Z(),[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.remote&&i.remoteModels.length===0,p=!f&&!i.remote&&i.hasProviders&&!i.selectedModel,m=f?[]:i.remote?i.remoteModels:Qe(i.modelsByProvider);return(0,d.jsx)(l.Chatbot,{value:n,onChange:r,placeholder:o?.prompt??t.messagePlaceholder,running:s,onStop:i.stop,disabled:!n.trim()||p,onSubmit:c,attachments:!o&&!i.remote,models:m,selectedModel:f?``:i.selectedModel,actions:e.composerActions,onModelChange:i.setSelectedModel,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function et(){let{startOrchestrator:e}=$(),t=Z(),[n,r]=(0,u.useState)(``),{hasProviders:i,modelsByProvider:a,selectedModel:o,setSelectedModel:s}=De(),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:Qe(a),selectedModel:o,onModelChange:s,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function tt(e,t,n=Date.now()){let r=Math.round((e-n)/1e3),i=new Intl.RelativeTimeFormat(t,{numeric:`auto`,style:`short`});for(let[e,t]of[[`day`,86400],[`hour`,3600],[`minute`,60]])if(Math.abs(r)>=t)return i.format(Math.round(r/t),e);return i.format(0,`minute`)}function nt({card:e}){let t=Z();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 rt({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 it({scopeId:e,currentTaskId:t,open:n,onOpenChange:r,onSelect:i,onNewChat:a,onArchivedCurrent:o}){let s=Z(),{locale:c}=(0,l.useI18n)(),[f,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(0),_=(0,u.useMemo)(()=>n?ae(e):[],[e,n,m]),v=async n=>{let r=g(n.subagentId),i=await r?.confirmArchive?.(n.entityId,n.params);if(!i||window.confirm(i)){try{await r?.onArchive?.(n.entityId,n.params)}catch{return}ie(e,n.subagentId,n.entityId),t===Y(n.subagentId,n.entityId)&&o(),h(e=>e+1)}},y=(0,u.useMemo)(()=>{let e=f.trim().toLowerCase();return e?_.filter(t=>{let n=g(t.subagentId)?.label??t.subagentId;return t.title.toLowerCase().includes(e)||n.toLowerCase().includes(e)}):_},[_,f]);return(0,d.jsx)(l.Dropdown,{trigger:{icon:`history`,title:s.chatHistory},triggerClassName:`!h-9 !w-9 !p-0 rounded-md bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground`,open:n,onOpenChange:r,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:f,onChange:e=>p(e.target.value),placeholder:s.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:s.newChat,title:s.newChat,variant:`link`,className:`shrink-0`,onClick:a})]}),children:y.length===0?(0,d.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground`,children:_.length===0?s.noSavedChats:s.noResults}):y.map(e=>{let n=g(e.subagentId),r=t===Y(e.subagentId,e.entityId);return(0,d.jsx)(l.DropdownItem,{icon:r?`check`:n?.icon??`bot`,className:r?`bg-accent font-medium`:void 0,actions:[{icon:`archive`,label:s.archiveChat,onClick:()=>void v(e)}],onClick:()=>i(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:n?.label??e.subagentId}),` · `,e.title||e.entityId]}),(0,d.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,title:new Date(e.savedAt).toLocaleString(c),children:tt(e.savedAt,c)})]})},`${e.subagentId}:${e.entityId}`)})})}function at(){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,pendingStart:x,startRunId:S,scope:C}=$(),w=Z(),T=(0,u.useRef)(null),[E,D]=(0,u.useState)(!1),O=()=>{(!e||e.agent.running||e.savedToDisk||window.confirm(w.unsavedConversationConfirm))&&(f(),D(!1))},k=e?[...e.precedingActivity??[],...e.agent.activity]:[],A=k.length,j=Math.max(0,Math.min(e?.panelExtraAnchorIndex??A,A)),M=k.slice(0,j),N=k.slice(j),P=!!(e&&!e.agent.running&&e.agent.error),F=e?.id===`agentico-orchestrator`&&e.scopedSubagentId?g(e.scopedSubagentId):void 0,I=F?.manualEntry?F:null,L=(0,u.useRef)(!0);(0,u.useEffect)(()=>{let e=T.current;if(!e)return;let t=()=>{L.current=e.scrollHeight-e.scrollTop-e.clientHeight<80};return e.addEventListener(`scroll`,t),()=>e.removeEventListener(`scroll`,t)},[e?.id]),(0,u.useEffect)(()=>{let e=T.current;e&&(L.current=!0,e.scrollTop=e.scrollHeight)},[e?.id]);let R=k.at(-1)?.detail?.length??0;(0,u.useEffect)(()=>{let e=T.current;e&&L.current&&(e.scrollTop=e.scrollHeight)},[A,P,R]);let z=(0,u.useRef)(null);(0,u.useEffect)(()=>{let e=T.current,t=z.current;if(!e||!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>{L.current&&(e.scrollTop=e.scrollHeight)});return n.observe(t),()=>n.disconnect()},[e?.id,t]);let B=n?(0,d.jsx)(Ye,{userGoal:n},r):null,V=s?g(s.subagentId):void 0,H=s&&V?(0,d.jsx)(Je,{manifest:V,params:s.snapshot.params,taskId:Y(s.subagentId,s.entityId),resumeSeed:{history:s.snapshot.history,activity:s.snapshot.activity}},c):null,U=m?g(m.subagentId):void 0,W=m&&U?(0,d.jsx)(Xe,{manifest:U,extraDestinations:m.extraDestinations},h):null,G=y?g(y.subagentId):void 0,K=y&&G?(0,d.jsx)(Je,{manifest:G,params:y.params,extraDestinations:y.extraDestinations},b):null,ee=x?g(x.subagentId):void 0,q=x&&ee?(0,d.jsx)(Je,{manifest:ee,params:x.params,taskId:x.taskId,openingMessage:x.openingMessage},S):null;return t?(0,d.jsxs)(d.Fragment,{children:[B,H,W,K,q,(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`}),C&&(0,d.jsx)(it,{scopeId:C.id,currentTaskId:e?.id??null,open:E,onOpenChange:D,onNewChat:O,onSelect:(e,t,n)=>p(e,t,n),onArchivedCurrent:f}),(0,d.jsx)(Ce,{})]}),(0,d.jsx)(`div`,{ref:T,className:`flex-1 overflow-y-auto px-3 pb-2`,children:(0,d.jsx)(`div`,{ref:z,className:`pt-2`,children:e?(0,d.jsxs)(d.Fragment,{children:[e.manualEntry&&k.length===0&&(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.manualEntry.prompt}),(0,d.jsx)(Se,{activity:M}),e.panelExtra&&(0,d.jsx)(`div`,{className:`mt-3`,children:e.panelExtra}),N.length>0&&(0,d.jsx)(Se,{activity:N}),!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:w.retry,variant:`secondary`,className:`shrink-0`,onClick:()=>{e.agent.sendMessage(w.retryMessage).then(t=>{t&&e.onApplied(t)})}}),!e.agent.remote&&(0,d.jsx)(l.ActionButton,{label:w.continueWithoutAi,variant:`secondary`,className:`shrink-0`,onClick:()=>{if(I){_(I.id,v);return}let t=e.agent.runFallback();t&&e.onApplied(t)}})]})]}):o.length>0?(0,d.jsx)(rt,{messages:o}):a?(0,d.jsx)(nt,{card:a}):(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i??w.orchestratorStarterHint})})}),(0,d.jsxs)(`div`,{className:`border-t border-border/60 px-4 py-3`,children:[e?.panelActions&&(0,d.jsx)(`div`,{className:`mb-2`,children:e.panelActions}),e?(0,d.jsx)($e,{task:e},e.id):(0,d.jsx)(et,{})]})]})]}):(0,d.jsxs)(d.Fragment,{children:[B,H,W,K,q]})}function ot(e,t){let{setPageContext:n}=$(),r=(0,u.useRef)(crypto.randomUUID()).current;(0,u.useEffect)(()=>(n(r,e,t??null),()=>n(r,null)),[e,t])}function st(e,t,n,r,i=!0,a){let{registerComponentAnchor:o}=$(),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=Ze,exports.Agentico=at,exports.AgenticoProvider=ue,exports.AgenticoToggle=Ce,exports.JSON_EXPORT_DESTINATION_ID=B,exports.MICRO_PROMPT_REGISTRY=F,exports.ORCHESTRATOR_TASK_ID=Q,exports.SUMMARY_MICRO_PROMPT=P,exports.agenticoDe=oe,exports.agenticoEn=X,exports.agenticoIt=se,exports.agenticoPromptsEn=C,exports.agenticoPromptsIt=w,exports.agenticoTranslations=ce,exports.applyMicroPrompts=I,exports.configureAgenticoPrompts=E,exports.configureEntityChatStore=K,exports.createCrossAgentTools=y,exports.defineSubagent=f,exports.entityChatTaskId=Y,exports.extractErrorMessage=L,exports.extractJsonBlock=R,exports.findSubagentManifest=g,exports.getAgenticoPrompts=D,exports.getDestinationRegistry=W,exports.getEntityChat=ne,exports.getSubagentControls=Ke,exports.getSubagentRegistry=h,exports.getSubagentReport=Ve,exports.jsonExportDestination=V,exports.listEntityChats=ae,exports.registerCrossAgentTools=v,exports.registerDestinations=U,exports.registerSubagentControls=Ge,exports.registerSubagentReports=Be,exports.registerSubagents=m,exports.removeEntityChat=ie,exports.renderRegistryCli=N,exports.renderSubagentCli=M,exports.resetAgenticoPrompts=O,exports.saveEntityChat=re,exports.toJsonSchema=b,exports.toMcpTool=x,exports.useAgent=je,exports.useAgentico=$,exports.useAgenticoI18n=Z,exports.useAgenticoPageContext=ot,exports.useSubagentComponentContext=st;
20
+ ${e}`}function $e(e,t){return t?{kind:`handoff`,...t}:{kind:`chat`,message:e}}function et(e){return b().filter(t=>!t.onlyWhenAnchored||e===t.id)}function tt(e){return{buildContext(e){return{cliCatalog:R(et(e.scopedSubagentId)),handoff:{current:null},collected:{}}},buildPrompt({userGoal:e,pageContext:t},{cliCatalog:n}){return Qe(e,n,t)},buildFollowUpPrompt(e,t,{cliCatalog:n}){return`${e}\n\n${Ze()}\n\n${M().toolsHeading}\n${n}`},parseResponse(e,t,n){let r=n.handoff.current;return n.handoff.current=null,$e(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=w({attachmentsRef:r,collected:n.collected,proxyFetch:l.proxyFetch}),a=t.scopedSubagentId?x(t.scopedSubagentId):null,o=a?i.filter(e=>(a.crossAgentToolIds??[]).includes(e.name)):i,s=et(t.scopedSubagentId).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)(M().handoffQueued,{label:t.label})}}})));return[...o,...s]}}}function nt(e,t){return e.deriveHistoryTitle?.(t)??e.label}function rt({manifest:e,result:t,meta:n,taskId:r,initiallyApplied:i,onApplied:a,extraDestinations:o}){let s=Q(),c=$(),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=q(),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(W.id,W);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,nt(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 it={};function at(e){Object.assign(it,e)}function ot(e){return it[e]}function st({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 ct(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))}}}var lt={};function ut(e){Object.assign(lt,e)}function dt(e){return lt[e]}var ft=()=>({});function pt({manifest:e,params:t,extraDestinations:n,precedingActivity:r,taskId:i,resumeSeed:a,model:o,openingMessage:s}){let c=Xe(e.definition,{defaultEnabled:!0}),f=$(),p=f.scope,m=(0,l.useProxy)(),h=(0,u.useRef)(i??`subagent-${e.id}-${crypto.randomUUID()}`).current,[g,_]=(0,u.useState)(null),[v,y]=(0,u.useState)([]),[b,x]=(0,u.useState)(null),S=ot(e.id),C=S?.kind===`selection`?S:null,[w,T]=(0,u.useState)(null),E=(0,u.useRef)(!1),D=(0,u.useRef)(0),O=(0,u.useRef)(null);g&&g!==O.current&&(O.current=g,D.current=(r?.length??0)+c.activity.length);let k=(0,u.useRef)(!1),A=c.remote||!c.hasProviders||c.selectedModel!==``;(0,u.useEffect)(()=>{!E.current&&A&&(E.current=!0,a?c.resume(e.toParams(t),a):(o&&c.setSelectedModel(o),c.run(e.toParams(t),{model:o,openingMessage:s}).then(e=>{e&&_(e)})))},[A]),(0,u.useEffect)(()=>{if(!g||!p)return;let n=e.autoApplyDestinationIds??[],r=f.componentAnchors.find(t=>t.subagentId===e.id&&t.pinnedEntityId)?.pinnedEntityId,i=q();n.forEach(n=>{let a=i[n];a&&(x(null),a.apply(g,{scopeId:p.id,dataProvider:p.dataProvider,storageProvider:p.storageProvider,proxyFetch:m},{...t,pinnedEntityId:r}).then(n=>{n?.id&&f.commitEntityChat(e.id,n.id,h,p.id,t,nt(e,t))}).catch(e=>x(e instanceof Error?e.message:String(e))))})},[g,c.activity,p]),(0,u.useEffect)(()=>{g&&C&&T(C.defaultSelection(g))},[g,C]);let j=(e,t)=>{T(n=>n&&{...n,[e]:t})},M=e=>_(e),N=(0,u.useMemo)(()=>g&&C&&w?C.applySelection(g,w):g,[g,C,w]),P=(0,u.useMemo)(()=>f.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[f.componentAnchors,e.id]),F=(0,u.useMemo)(()=>ct(P,t,h),[P,t,h]),I=(0,u.useMemo)(()=>F?[F,...n??[]]:n,[F,n]),L=e.chatEntityId?.(t),R=(0,u.useRef)(!1);(0,u.useEffect)(()=>{let n=R.current&&!c.running;if(R.current=c.running,!n||!L||!p)return;let i=c.snapshot();i&&ae({scopeId:p.id,subagentId:e.id,entityId:L,params:t,title:nt(e,t),history:i.history,activity:[...r??[],...i.activity]})},[c.running]);let z=()=>{k.current=!0,c.running&&c.stop(),f.closeTask(h)},ee=(0,u.useRef)(dt(e.id)??ft).current,B=ee({params:t,taskId:h,running:c.running,close:z}),V=e=>{y(t=>t.includes(e)?t:[...t,e])};return(0,u.useEffect)(()=>{k.current||f.openTask({id:h,title:nt(e,t),icon:e.icon,agent:c,onApplied:e=>_(e),precedingActivity:r,panelExtraAnchorIndex:D.current,onDismiss:z,...L?{savedToDisk:!0}:{},panelActions:B.content,composerActions:B.actions,panelExtra:g?(0,d.jsxs)(d.Fragment,{children:[C&&w?(0,d.jsx)(C.Report,{result:g,selection:w,onChange:j}):S?.kind===`editable`?(0,d.jsx)(S.Report,{result:g,onResultChange:M}):(0,d.jsx)(st,{result:N}),b&&(0,d.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Salvataggio automatico non riuscito: `,b]}),(0,d.jsx)(rt,{manifest:e,result:N,meta:t,taskId:h,initiallyApplied:v,onApplied:V,extraDestinations:I})]}):void 0})},[c.activity,c.running,c.error,c.canContinue,c.selectedModel,c.modelsByProvider,c.hasProviders,c.remoteModels,f.openTask,f.componentAnchors,h,e,t,g,N,w,v,n,r,b,B.content,B.actions]),(0,u.useEffect)(()=>()=>{f.closeTask(h)},[f.closeTask,h]),null}function mt({userGoal:e}){let t=Q(),n=Xe((0,u.useMemo)(()=>tt({unavailable:t.orchestratorUnavailable,continueWithoutAi:t.orchestratorContinueWithoutAi,preparing:t.orchestratorPreparing,collecting:t.orchestratorCollecting}),[]),{defaultEnabled:!0}),r=$(),[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),g=e=>{e&&typeof e==`object`&&e.kind===`handoff`&&(a(e),r.closeTask(pe))};(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&&g(e)}))},[s]),(0,u.useEffect)(()=>{h.current||r.openTask({id:pe,title:`Agentico`,icon:`bot`,agent:n,onApplied:g,scopedSubagentId:p.current,precedingActivity:m.current?.activity,onDismiss:()=>{h.current=!0,n.running&&n.stop(),r.closeTask(pe)}})},[n.activity,n.running,n.error,n.canContinue,n.selectedModel,n.modelsByProvider,n.hasProviders,r.openTask]),(0,u.useEffect)(()=>()=>{r.closeTask(pe)},[r.closeTask]);let _=(0,u.useMemo)(()=>[...m.current?.activity??[],...n.activity],[n.activity]);if(!i)return null;let v=x(i.subagentId);return v?(0,d.jsx)(pt,{manifest:v,params:i.params,extraDestinations:c.current,model:f.current||void 0,taskId:m.current?.taskId,precedingActivity:_}):null}function ht({manifest:e,extraDestinations:t}){let n=Xe(e.definition,{defaultEnabled:!1}),r=Q(),i=$(),a=(0,u.useRef)(`manual-${e.id}-${crypto.randomUUID()}`).current,[o,s]=(0,u.useState)(null),[c,f]=(0,u.useState)([]),p=ot(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)(()=>_?ct(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)(st,{result:C}),(0,d.jsx)(rt,{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}function gt(e){return Object.values(e).flat().map(e=>({label:e.model,value:e.id,pricing:e.pricing??null,group:e.providerLabel??e.provider}))}function _t({task:e}){let t=Q(),[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.remote&&i.remoteModels.length===0,p=!f&&!i.remote&&i.hasProviders&&!i.selectedModel,m=f?[]:i.remote?i.remoteModels:gt(i.modelsByProvider);return(0,d.jsx)(l.Chatbot,{value:n,onChange:r,placeholder:o?.prompt??t.messagePlaceholder,running:s,onStop:i.stop,disabled:!n.trim()||p,onSubmit:c,attachments:!o&&!i.remote,models:m,selectedModel:f?``:i.selectedModel,actions:e.composerActions,onModelChange:i.setSelectedModel,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function vt(){let{startOrchestrator:e}=$(),t=Q(),[n,r]=(0,u.useState)(``),{hasProviders:i,modelsByProvider:a,selectedModel:o,setSelectedModel:s}=Ke(),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:gt(a),selectedModel:o,onModelChange:s,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function yt(e,t,n=Date.now()){let r=Math.round((e-n)/1e3),i=new Intl.RelativeTimeFormat(t,{numeric:`auto`,style:`short`});for(let[e,t]of[[`day`,86400],[`hour`,3600],[`minute`,60]])if(Math.abs(r)>=t)return i.format(Math.round(r/t),e);return i.format(0,`minute`)}function bt({card:e}){let t=Q();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 xt({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 St({scopeId:e,currentTaskId:t,open:n,onOpenChange:r,onSelect:i,onNewChat:a,onArchivedCurrent:o}){let s=Q(),{locale:c}=(0,l.useI18n)(),[f,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(0),g=(0,u.useMemo)(()=>n?se(e):[],[e,n,m]),_=async n=>{let r=x(n.subagentId),i=await r?.confirmArchive?.(n.entityId,n.params);if(!i||window.confirm(i)){try{await r?.onArchive?.(n.entityId,n.params)}catch{return}oe(e,n.subagentId,n.entityId),t===ce(n.subagentId,n.entityId)&&o(),h(e=>e+1)}},v=(0,u.useMemo)(()=>{let e=f.trim().toLowerCase();return e?g.filter(t=>{let n=x(t.subagentId)?.label??t.subagentId;return t.title.toLowerCase().includes(e)||n.toLowerCase().includes(e)}):g},[g,f]);return(0,d.jsx)(l.Dropdown,{trigger:{icon:`history`,title:s.chatHistory},triggerClassName:`!h-9 !w-9 !p-0 rounded-md bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground`,open:n,onOpenChange:r,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:f,onChange:e=>p(e.target.value),placeholder:s.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:s.newChat,title:s.newChat,variant:`link`,className:`shrink-0`,onClick:a})]}),children:v.length===0?(0,d.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground`,children:g.length===0?s.noSavedChats:s.noResults}):v.map(e=>{let n=x(e.subagentId),r=t===ce(e.subagentId,e.entityId);return(0,d.jsx)(l.DropdownItem,{icon:r?`check`:n?.icon??`bot`,className:r?`bg-accent font-medium`:void 0,actions:[{icon:`archive`,label:s.archiveChat,onClick:()=>void _(e)}],onClick:()=>i(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:n?.label??e.subagentId}),` · `,e.title||e.entityId]}),(0,d.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,title:new Date(e.savedAt).toLocaleString(c),children:yt(e.savedAt,c)})]})},`${e.subagentId}:${e.entityId}`)})})}function Ct({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}={}){let{task:i,isOpen:a,pendingGoal:o,orchestratorRunId:s,pageContext:c,pageContextCard:f,anchoredUserMessages:p,pendingResume:m,resumeRunId:h,dismissForeignTask:g,resumeEntityChat:_,pendingManualEntry:v,manualEntryRunId:y,startManualEntry:b,pendingExtraDestinations:S,pendingResumeWithAI:C,resumeWithAIRunId:w,pendingStart:T,startRunId:E,scope:D}=$(),O=Q(),k=(0,u.useRef)(null),[A,j]=(0,u.useState)(!1),M=Be({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}),N=()=>{(!i||i.agent.running||i.savedToDisk||window.confirm(O.unsavedConversationConfirm))&&(g(),j(!1))},P=i?[...i.precedingActivity??[],...i.agent.activity]:[],F=P.length,I=Math.max(0,Math.min(i?.panelExtraAnchorIndex??F,F)),L=P.slice(0,I),R=P.slice(I),z=!!(i&&!i.agent.running&&i.agent.error),ee=new Set(i?.agent.activity.map(e=>e.id)??[]),B=i?{canAnswer:e=>ee.has(e),onAnswer:(e,t,n)=>i.agent.answerQuestions(e,t,n).then(e=>{e&&i.onApplied(e)})}:void 0,V=B?Ee(P,B.canAnswer):null,H=i?.id===`agentico-orchestrator`&&i.scopedSubagentId?x(i.scopedSubagentId):void 0,te=H?.manualEntry?H:null,U=(0,u.useRef)(!0);(0,u.useEffect)(()=>{let e=k.current;if(!e)return;let t=()=>{U.current=e.scrollHeight-e.scrollTop-e.clientHeight<80};return e.addEventListener(`scroll`,t),()=>e.removeEventListener(`scroll`,t)},[i?.id]),(0,u.useEffect)(()=>{let e=k.current;e&&(U.current=!0,e.scrollTop=e.scrollHeight)},[i?.id]);let W=P.at(-1)?.detail?.length??0;(0,u.useEffect)(()=>{let e=k.current;e&&U.current&&(e.scrollTop=e.scrollHeight)},[F,z,W]);let G=(0,u.useRef)(null);(0,u.useEffect)(()=>{let e=k.current,t=G.current;if(!e||!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>{U.current&&(e.scrollTop=e.scrollHeight)});return n.observe(t),()=>n.disconnect()},[i?.id,a]);let K=o?(0,d.jsx)(mt,{userGoal:o},s):null,q=m?x(m.subagentId):void 0,J=m&&q?(0,d.jsx)(pt,{manifest:q,params:m.snapshot.params,taskId:ce(m.subagentId,m.entityId),resumeSeed:{history:m.snapshot.history,activity:m.snapshot.activity}},h):null,Y=v?x(v.subagentId):void 0,ne=v&&Y?(0,d.jsx)(ht,{manifest:Y,extraDestinations:v.extraDestinations},y):null,X=C?x(C.subagentId):void 0,re=C&&X?(0,d.jsx)(pt,{manifest:X,params:C.params,extraDestinations:C.extraDestinations},w):null,Z=T?x(T.subagentId):void 0,ie=T&&Z?(0,d.jsx)(pt,{manifest:Z,params:T.params,taskId:T.taskId,openingMessage:T.openingMessage},E):null;return a?(0,d.jsxs)(d.Fragment,{children:[K,J,ne,re,ie,(0,d.jsxs)(`div`,{style:{width:M.width},className:`relative flex h-full shrink-0 flex-col border-l border-border bg-background`,children:[(0,d.jsx)(Ve,{width:M.width,min:M.min,max:M.max,onResize:M.set,onCommit:M.commit,onReset:M.reset}),(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:i?i.title:`Agentico`}),D&&(0,d.jsx)(St,{scopeId:D.id,currentTaskId:i?.id??null,open:A,onOpenChange:j,onNewChat:N,onSelect:(e,t,n)=>_(e,t,n),onArchivedCurrent:g}),(0,d.jsx)(He,{})]}),(0,d.jsx)(`div`,{ref:k,className:`flex-1 overflow-y-auto px-3 pb-2 ${V?`min-h-24`:`min-h-0`}`,children:(0,d.jsx)(`div`,{ref:G,className:`pt-2`,children:i?(0,d.jsxs)(d.Fragment,{children:[i.manualEntry&&P.length===0&&(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i.manualEntry.prompt}),(0,d.jsx)(Ae,{activity:L,questions:B,docked:V,pinUserMessages:!V}),i.panelExtra&&(0,d.jsx)(`div`,{className:`mt-3`,children:i.panelExtra}),R.length>0&&(0,d.jsx)(Ae,{activity:R,questions:B,docked:V,pinUserMessages:!V}),!i.agent.running&&i.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:i.agent.error}),(0,d.jsx)(l.ActionButton,{label:O.retry,variant:`secondary`,className:`shrink-0`,onClick:()=>{i.agent.sendMessage(O.retryMessage).then(e=>{e&&i.onApplied(e)})}}),!i.agent.remote&&(0,d.jsx)(l.ActionButton,{label:O.continueWithoutAi,variant:`secondary`,className:`shrink-0`,onClick:()=>{if(te){b(te.id,S);return}let e=i.agent.runFallback();e&&i.onApplied(e)}})]})]}):p.length>0?(0,d.jsx)(xt,{messages:p}):f?(0,d.jsx)(bt,{card:f}):(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c??O.orchestratorStarterHint})})}),i&&V?(0,d.jsxs)(`section`,{"aria-label":O.pendingQuestions,className:`flex min-h-0 shrink flex-col border-t border-border/60`,children:[i.panelActions&&(0,d.jsx)(`div`,{className:`shrink-0 px-4 pt-3`,children:i.panelActions}),(0,d.jsx)(`div`,{className:`min-h-0 overflow-y-auto px-4 py-3`,children:(0,d.jsx)(De,{entry:V.entry,part:V.part,questions:B,autoFocus:!0},`${V.entry.id}:${V.part.id}`)}),i.agent.running&&(0,d.jsx)(`div`,{className:`flex shrink-0 justify-end px-4 pb-3`,children:(0,d.jsx)(l.ActionButton,{icon:`square`,label:O.stop,variant:`secondary`,onClick:i.agent.stop})})]}):(0,d.jsxs)(`div`,{className:`border-t border-border/60 px-4 py-3`,children:[i?.panelActions&&(0,d.jsx)(`div`,{className:`mb-2`,children:i.panelActions}),i?(0,d.jsx)(_t,{task:i},i.id):(0,d.jsx)(vt,{})]})]})]}):(0,d.jsxs)(d.Fragment,{children:[K,J,ne,re,ie]})}function wt(e,t){let{setPageContext:n}=$(),r=(0,u.useRef)(crypto.randomUUID()).current;(0,u.useEffect)(()=>(n(r,e,t??null),()=>n(r,null)),[e,t])}function Tt(e,t,n,r,i=!0,a){let{registerComponentAnchor:o}=$(),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_MAX_WIDTH=Ne,exports.AGENTICO_MIN_WIDTH=Me,exports.AGENTICO_WIDTH=je,exports.AGENTICO_WIDTH_STORAGE_KEY=Pe,exports.Agentico=Ct,exports.AgenticoProvider=he,exports.AgenticoToggle=He,exports.DEFAULT_REASONING_PART_ID=p,exports.DEFAULT_TEXT_PART_ID=f,exports.JSON_EXPORT_DESTINATION_ID=U,exports.MICRO_PROMPT_REGISTRY=ee,exports.ORCHESTRATOR_TASK_ID=pe,exports.SUMMARY_MICRO_PROMPT=z,exports.agenticoDe=le,exports.agenticoEn=ue,exports.agenticoIt=de,exports.agenticoPromptsEn=O,exports.agenticoPromptsIt=k,exports.agenticoTranslations=fe,exports.applyMicroPrompts=B,exports.configureAgenticoPrompts=j,exports.configureEntityChatStore=Y,exports.createCrossAgentTools=w,exports.defineSubagent=_,exports.entityChatTaskId=ce,exports.extractErrorMessage=V,exports.extractJsonBlock=H,exports.findSubagentManifest=x,exports.formatQuestionAnswers=g,exports.getAgenticoPrompts=M,exports.getDestinationRegistry=q,exports.getEntityChat=ie,exports.getSubagentControls=dt,exports.getSubagentRegistry=b,exports.getSubagentReport=ot,exports.jsonExportDestination=W,exports.listEntityChats=se,exports.messagePartsText=h,exports.registerCrossAgentTools=C,exports.registerDestinations=K,exports.registerSubagentControls=ut,exports.registerSubagentReports=at,exports.registerSubagents=y,exports.removeEntityChat=oe,exports.renderRegistryCli=R,exports.renderSubagentCli=L,exports.resetAgenticoPrompts=N,exports.saveEntityChat=ae,exports.toJsonSchema=T,exports.toMcpTool=E,exports.upsertMessagePart=m,exports.useAgent=Xe,exports.useAgentico=$,exports.useAgenticoI18n=Q,exports.useAgenticoPageContext=wt,exports.useSubagentComponentContext=Tt;
18
21
  //# sourceMappingURL=index.js.map