@llmnative/agentico 0.18.0 → 0.19.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
@@ -71,6 +71,7 @@ configureAgenticoPrompts({ // optional: langu
71
71
  | **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` |
72
72
  | **Sessions of one chat and who speaks** (CR-018) — the saved chats with the same `thread` key are sessions of one chat: the earlier ones above the open one, read-only, loaded as the person scrolls up, each with its own context; the messages of the person carry their name and picture, each turn of the agent starts with its own | `SubagentManifest.thread`, `SubagentManifest.speaker`, `<AgenticoProvider person>`, `chatThreadOf`, `earlierSessions`, `ChatAuthor` |
73
73
  | **What happened around a chat** (CR-019) — the events of the host (the work of other agents…) among the messages of a chat with a `thread`, by time, each a compact card with who did it; a filter in the header (Conversation only); the model never reads them. Each entry of a chat keeps when it was born (`at`) | `<AgenticoProvider threadEvents>` (`ThreadEventsSource`: `load(thread, from, to)`, `subscribe`), `ThreadEvent`, `placeEvents` |
74
+ | **Images in sight and events going on** (CR-020) — the images pasted or attached to a message stay as small previews after it is sent (kept with the chat, opened larger on a click); an event of the host still going on has a spinner | `entry.attachmentPreviews`, `imagePreviews`, `ThreadEvent.running` |
74
75
  | **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` |
75
76
  | **Controls** — the actions of the prompt of a subagent (e.g. "Finish"), its slash commands (e.g. `/to-spec`, sent as plain text to the executor) and what the host shows above it, from a hook of the host | `registerSubagentControls` |
76
77
  | **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,29 +1,29 @@
1
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
2
 
3
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 ee(e){return S.flatMap(t=>t(e))}function w(e){let{$schema:t,...n}=(0,c.zodToJsonSchema)(e,{target:`jsonSchema7`,$refStrategy:`none`});return n}function T(e,t,n,r){return{name:e,description:t,inputSchema:w(n),...r?{outputSchema:w(r)}:{}}}function E(e){let t=w(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 D={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.`,toolRejected:`Not done: the person rejected this action{reason}. Do not call it again unless they ask for it.`,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.`,chatTitle:`Write a title for this chat, as a list of chats shows it: 3 to 6 words saying what it is about, in the language the person writes in. Answer with the title only: no quotes, no final period.
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 ee(e){return S.flatMap(t=>t(e))}function w(e){let{$schema:t,...n}=(0,c.zodToJsonSchema)(e,{target:`jsonSchema7`,$refStrategy:`none`});return n}function T(e,t,n,r){return{name:e,description:t,inputSchema:w(n),...r?{outputSchema:w(r)}:{}}}function E(e){let t=w(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 te={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.`,toolRejected:`Not done: the person rejected this action{reason}. Do not call it again unless they ask for it.`,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.`,chatTitle:`Write a title for this chat, as a list of chats shows it: 3 to 6 words saying what it is about, in the language the person writes in. Answer with the title only: no quotes, no final period.
5
5
 
6
- {chat}`},O={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.`,toolRejected:`Non fatto: la persona ha rifiutato questa azione{reason}. Non richiamarla se non te lo chiede.`,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.`,chatTitle:`Scrivi un titolo per questa chat, come lo mostra un elenco di chat: da 3 a 6 parole che dicono di cosa parla, nella lingua in cui scrive la persona. Rispondi solo con il titolo: niente virgolette, niente punto finale.
6
+ {chat}`},D={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.`,toolRejected:`Non fatto: la persona ha rifiutato questa azione{reason}. Non richiamarla se non te lo chiede.`,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.`,chatTitle:`Scrivi un titolo per questa chat, come lo mostra un elenco di chat: da 3 a 6 parole che dicono di cosa parla, nella lingua in cui scrive la persona. Rispondi solo con il titolo: niente virgolette, niente punto finale.
7
7
 
8
- {chat}`},k=D;function A(e){k={...k,...e}}function j(){return k}function M(){k=D}function N(e,t){return`${e} ${t.map(e=>e.required?`--${e.key} <${e.type}>`:`[--${e.key} <${e.type}>]`).join(` `)}`.trim()}function te(e,t){let n=E(t),r=N(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`,P(t.describeOutput(),4),(t.example,``),t.example?` EXAMPLE`:``,t.example?` ${t.example}`:``].filter(e=>e!==``).join(`
8
+ {chat}`},O=te;function k(e){O={...O,...e}}function A(){return O}function j(){O=te}function M(e,t){return`${e} ${t.map(e=>e.required?`--${e.key} <${e.type}>`:`[--${e.key} <${e.type}>]`).join(` `)}`.trim()}function N(e,t){let n=E(t),r=M(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`,P(t.describeOutput(),4),(t.example,``),t.example?` EXAMPLE`:``,t.example?` ${t.example}`:``].filter(e=>e!==``).join(`
9
9
  `)}function P(e,t){let n=` `.repeat(t);return e.split(`
10
10
  `).map(e=>e&&n+e).join(`
11
- `)}function F(e){return[`NAME`,` ${e.id} — ${e.label}`,``,`DESCRIPTION`,P(e.description,2),``,...e.commands.map(t=>te(e.id,t))].join(`
12
- `)}function ne(e){return e.length===0?j().noToolsAvailable:e.map(e=>`${e.id} [${e.commands.map(e=>e.name).join(`|`)}] — ${e.label}: ${e.commands.map(e=>e.summary).join(` / `)}`).join(`
13
- `)}var I={id:`closing-summary`,get text(){return j().closingSummary}},L={[I.id]:I};function R(e,t){if(!t||t.length===0)return e;let n=t.map(e=>L[e]?.text).filter(e=>!!e);return n.length===0?e:`${e}\n\n${n.join(`
14
- `)}`}function z(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 B(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 re(n)??n}function re(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 V=`json-export`,H={id:V,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)}}},U={};function ie(e){U=e}function W(){return{[H.id]:H,...U}}var G={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.`,approvalHeader:`Approval`,approve:`Approve`,reject:`Reject`,approveQuestion:`Approve? {action}`,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`,reasoningNow:`Reasoning…`,reasonedFor:`Reasoned for {seconds} s`,reasoned:`Reasoned`,processDetails:`Reasoning and steps`,stepsLabel:`Steps of the agent`,newInstance:`New "{label}" instance`,chatHistory:`Chat history`,earlierSession:`Earlier session`,thisSession:`This session`,continueSession:`Continue this session`,sessionOf:`Session of {at}`,eventMore:`More`,eventLess:`Less`,eventOpen:`Open`,showEvents:`Show what the agents did`,hideEvents:`Conversation only`,cardView:`View`,cardClose:`Close`,renameChat:`Rename`,chatTitleLabel:`Title`,chatTitleHint:`Empty: the title written from the chat.`,chatStarted:`Started {at}`,chatLastMessage:`last message {at}`,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`,editMessage:`Edit`,editingMessage:`Editing a message: sent, the chat goes back to it.`,cancelEdit:`Cancel`,rewindTitle:`Go back to this message?`,rewindText:`What came after it leaves the chat and the memory of the agent. What its steps did stays done:`,stop:`Stop`},K={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().`,approvalHeader:`Approvazione`,approve:`Approva`,reject:`Rifiuta`,approveQuestion:`Approvi? {action}`,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`,reasoningNow:`Sta ragionando…`,reasonedFor:`Ha ragionato {seconds} s`,reasoned:`Ha ragionato`,processDetails:`Ragionamento e passi`,stepsLabel:`Passi dell'agente`,newInstance:`Nuova istanza di "{label}"`,chatHistory:`Storico chat`,earlierSession:`Sessione precedente`,thisSession:`Questa sessione`,continueSession:`Continua questa sessione`,sessionOf:`Sessione del {at}`,eventMore:`Di più`,eventLess:`Meno`,eventOpen:`Apri`,showEvents:`Mostra cosa hanno fatto gli agenti`,hideEvents:`Solo la conversazione`,cardView:`Vedi`,cardClose:`Chiudi`,renameChat:`Rinomina`,chatTitleLabel:`Titolo`,chatTitleHint:`Vuoto: il titolo scritto dalla chat.`,chatStarted:`Iniziata il {at}`,chatLastMessage:`ultimo messaggio il {at}`,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`,editMessage:`Modifica`,editingMessage:`Modifichi un messaggio: inviato, la chat torna a quel punto.`,cancelEdit:`Annulla`,rewindTitle:`Tornare a questo messaggio?`,rewindText:`Ciò che è venuto dopo lascia la chat e la memoria dell'agente. Ciò che hanno fatto i suoi passi resta fatto:`,stop:`Ferma`},ae={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.`,approvalHeader:`Freigabe`,approve:`Freigeben`,reject:`Ablehnen`,approveQuestion:`Freigeben? {action}`,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`,reasoningNow:`Denkt nach…`,reasonedFor:`{seconds} s nachgedacht`,reasoned:`Nachgedacht`,processDetails:`Überlegungen und Schritte`,stepsLabel:`Schritte des Agenten`,newInstance:`Neue Instanz von "{label}"`,chatHistory:`Chatverlauf`,earlierSession:`Vorherige Sitzung`,thisSession:`Diese Sitzung`,continueSession:`Diese Sitzung fortsetzen`,sessionOf:`Sitzung vom {at}`,eventMore:`Mehr`,eventLess:`Weniger`,eventOpen:`Öffnen`,showEvents:`Zeigen, was die Agenten getan haben`,hideEvents:`Nur das Gespräch`,cardView:`Ansehen`,cardClose:`Schließen`,renameChat:`Umbenennen`,chatTitleLabel:`Titel`,chatTitleHint:`Leer: der aus dem Chat geschriebene Titel.`,chatStarted:`Begonnen am {at}`,chatLastMessage:`letzte Nachricht am {at}`,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`,editMessage:`Bearbeiten`,editingMessage:`Du bearbeitest eine Nachricht: gesendet, geht der Chat dorthin zurück.`,cancelEdit:`Abbrechen`,rewindTitle:`Zu dieser Nachricht zurückgehen?`,rewindText:`Was danach kam, verlässt den Chat und das Gedächtnis des Agenten. Was seine Schritte getan haben, bleibt getan:`,stop:`Stoppen`},oe=`llmnative.agentico.entityChat`,q;function se(e){oe=e.storageKey,q=e.backend}var ce=()=>!!q,le=({synced:e,...t})=>t;function ue(e){if(!q)return;let t=X(e.scopeId,e.subagentId,e.entityId);Promise.resolve(q.save(le(e))).then(()=>{let e=fe(),n=e.find(e=>X(e.scopeId,e.subagentId,e.entityId)===t);n&&!n.synced&&me(e.map(e=>e===n?{...e,synced:!0}:e))},()=>void 0)}async function J(e){if(!q)return;let t=(await q.load(e)).map(de).filter(t=>t!==null&&t.scopeId===e),n=e=>e.changedAt??e.savedAt,r=fe(),i=r.filter(t=>t.scopeId!==e),a=r.filter(t=>t.scopeId===e),o=t.map(e=>{let t=a.find(t=>X(t.scopeId,t.subagentId,t.entityId)===X(e.scopeId,e.subagentId,e.entityId));return t&&n(t)>n(e)?(ue(t),t):{...e,synced:!0}}),s=a.filter(e=>!e.synced&&!t.some(t=>X(t.scopeId,t.subagentId,t.entityId)===X(e.scopeId,e.subagentId,e.entityId)));me([...i,...o,...s]);for(let e of s)ue(e)}function de(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 fe(){try{let e=localStorage.getItem(oe);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(de).filter(e=>e!==null):[]}catch{return[]}}var Y=new Set;function pe(e){return Y.add(e),()=>{Y.delete(e)}}function me(e){try{localStorage.setItem(oe,JSON.stringify(e))}catch{}for(let e of[...Y])e()}var X=(e,t,n)=>`${e}:${t}:${n}`;function he(e,t,n){let r=X(e,t,n);return fe().find(e=>X(e.scopeId,e.subagentId,e.entityId)===r)??null}function ge(e){let t=X(e.scopeId,e.subagentId,e.entityId),n=fe(),r=n.find(e=>X(e.scopeId,e.subagentId,e.entityId)===t),i=Date.now(),a=n.filter(e=>e!==r),o={...e,savedAt:i,changedAt:i,startedAt:r?Q(r):i,...r?.name?{name:r.name,namedBy:r.namedBy}:{},...r?.synced?{synced:!0}:{}};a.push(o),me(a),ue(o)}var _e=new Set([G,K,ae].map(e=>e.retryMessage.trim().toLowerCase())),ve=e=>e.kind===`user`&&!!e.detail?.trim()&&!e.retry&&!_e.has(e.detail.trim().toLowerCase()),ye=e=>{let t=(e.activity.find(ve)?.detail??``).trim().split(`
15
- `)[0].trim();return t.length>80?`${t.slice(0,80).trimEnd()}…`:t},Z=e=>e.name||ye(e)||e.title||e.entityId,be=e=>e.activity.some(ve),xe=e=>e.kind===`user`&&!ve(e)&&!!e.detail?.trim();function Se(e,t,n,r,i=`person`){let a=X(e,t,n),o=fe(),s=o.find(e=>X(e.scopeId,e.subagentId,e.entityId)===a);if(!s||i===`model`&&s.namedBy===`person`)return!1;let c=r.trim().replace(/\s+/g,` `).slice(0,120),{name:l,namedBy:u,...d}=s,f=c?{...d,name:c,namedBy:i,changedAt:Date.now()}:{...d,changedAt:Date.now()};return me(o.map(e=>e===s?f:e)),ue(f),!0}var Q=e=>e.startedAt??e.savedAt;function Ce(e,t,n){let r=X(e,t,n);me(fe().filter(e=>X(e.scopeId,e.subagentId,e.entityId)!==r)),q&&Promise.resolve(q.remove(e,t,n)).catch(()=>void 0)}function we(e){return fe().filter(t=>t.scopeId===e).sort((e,t)=>Q(t)-Q(e))}var Te=(e,t)=>`entitychat-${e}-${t}`;function Ee(e){return x(e.subagentId)?.thread?.(e.params)||void 0}function De(e,t,n){let r=we(e),i=n?r.find(e=>Te(e.subagentId,e.entityId)===n):void 0,a=i?Q(i):1/0;return r.filter(e=>e!==i&&Q(e)<a&&Ee(e)===t).sort((e,t)=>Q(t)-Q(e))}function Oe(e,t){let n=Array.from({length:e.length+1},()=>[]),r=[],i=-1/0;for(let t of e)t!==void 0&&(i=t),r.push(i);for(let i of[...t].sort((e,t)=>e.at-t.at)){let t=r.findIndex(e=>e>i.at);n[t===-1?e.length:t].push(i)}return n}var ke={en:{agentico:G},it:{agentico:K},de:{agentico:ae}};function $(){let{dict:e}=(0,l.useI18n)(),t=e.agentico;return t?{...G,...t}:G}var Ae=`agentico-orchestrator`,je=(0,u.createContext)(null);function Me({children:e,scope:t=null,person:n=null,threadEvents:r=null}){let[i,a]=(0,u.useState)(null),o=(0,u.useRef)(null);(0,u.useEffect)(()=>{o.current=i},[i]);let[s,c]=(0,u.useState)(!1),l=t?.id;(0,u.useEffect)(()=>{l&&J(l).catch(()=>void 0)},[l]);let f=(0,u.useCallback)(e=>{let t=o.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;a(n)},[]),p=(0,u.useCallback)(e=>{a(t=>t&&t.id===e?null:t)},[]),m=(0,u.useCallback)(()=>c(e=>!e),[]),h=(0,u.useCallback)(()=>c(!0),[]),[g,_]=(0,u.useState)(null),[v,y]=(0,u.useState)(void 0),[b,S]=(0,u.useState)(void 0),[C,ee]=(0,u.useState)(void 0),[w,T]=(0,u.useState)(null),[E,D]=(0,u.useState)(null),[O,k]=(0,u.useState)(void 0),[A,M]=(0,u.useState)([]),N=(0,u.useCallback)((e,t,n=null)=>{M(r=>{let i=r.filter(t=>t.id!==e);return t?[...i,{id:e,text:t,card:n}]:i})},[]),te=A.length>0?A[A.length-1]:null,[P,F]=(0,u.useState)([]),ne=(0,u.useCallback)((e,t)=>{F(n=>{let r=n.filter(t=>t.id!==e);return t?[...r,{id:e,...t}]:r})},[]),I=(0,u.useMemo)(()=>P.map(e=>({subagentId:e.subagentId,componentKey:e.componentKey,onResult:e.onResult,pinnedEntityId:e.pinnedEntityId})),[P]),L=(0,u.useMemo)(()=>{let e=new Map;for(let t of P)e.set(t.subagentId,{subagentId:t.subagentId,componentKey:t.componentKey,onResult:t.onResult,contextInfo:t.contextInfo});return[...e.values()]},[P]),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]),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(`
16
- `);return`${j().multipleCandidates}\n\n${e}`},[R])??te?.text??null,re=R.length>0?null:te?.card??null,V=(0,u.useMemo)(()=>[...new Set(I.map(e=>e.subagentId))],[I]),H=V.length===1?V[0]:V.length===0?te?.card?.subagentId??null:null,U=(0,u.useCallback)((e,t)=>{h();let n=o.current;if(n?.id===`agentico-orchestrator`)return;let r=H&&n?.id.startsWith(`subagent-${H}-`)?n:void 0;D(r?{taskId:r.id,activity:[...r.precedingActivity??[],...r.agent.activity]}:null),_(e),y(t?.extraDestinations),S(t?.attachments),ee(t?.model),k(t?.scopedSubagentId),T(crypto.randomUUID())},[h,H]),ie=(0,u.useCallback)((e,t,n,r,i,s)=>{if(!n||!r)return;let c=o.current;if(!c||c.id!==n)return;let l=c.agent.snapshot();l&&(ge({scopeId:r,subagentId:e,entityId:t,params:i,title:s,history:l.history,activity:[...c.precedingActivity??[],...l.activity]}),a(e=>e&&e.id===n?{...e,savedToDisk:!0}:e))},[]),[W,G]=(0,u.useState)(null),[K,ae]=(0,u.useState)(null),oe=(0,u.useCallback)((e,t,n)=>{h(),G({subagentId:e,entityId:t,snapshot:n}),ae(crypto.randomUUID())},[h]),[q,se]=(0,u.useState)(null),[ce,le]=(0,u.useState)(null),ue=(0,u.useCallback)((e,t)=>{h(),p(Ae),se({subagentId:e,extraDestinations:t}),le(crypto.randomUUID())},[h,p]),[de,fe]=(0,u.useState)(null),[Y,pe]=(0,u.useState)(null),me=(0,u.useCallback)((e,t,n)=>{se(null),fe({subagentId:e,params:t,extraDestinations:n}),pe(crypto.randomUUID())},[]),[X,he]=(0,u.useState)(null),[_e,ve]=(0,u.useState)(null),ye=(0,u.useCallback)((e,t,n)=>{h(),he({subagentId:e,params:t,...n}),ve(crypto.randomUUID())},[h]),Z=(0,u.useCallback)(()=>{let e=o.current;e&&e.onDismiss()},[]),be=(0,u.useMemo)(()=>({scope:t,person:n,threadEvents:r,task:i,isOpen:s,openTask:f,closeTask:p,toggleOpen:m,pendingGoal:g,startOrchestrator:U,pageContext:B,pageContextCard:re,setPageContext:N,scopedSubagentId:H,pendingScopedSubagentId:O,componentAnchors:I,anchoredUserMessages:z,registerComponentAnchor:ne,openPanel:h,pendingExtraDestinations:v,pendingAttachments:b,pendingModel:C,orchestratorRunId:w,pendingCarryOver:E,commitEntityChat:ie,resumeEntityChat:oe,pendingResume:W,resumeRunId:K,dismissForeignTask:Z,pendingManualEntry:q,manualEntryRunId:ce,startManualEntry:ue,pendingResumeWithAI:de,resumeWithAIRunId:Y,resumeWithAI:me,startSubagent:ye,pendingStart:X,startRunId:_e}),[t,n,r,i,s,f,p,m,g,U,B,re,N,H,O,I,z,ne,h,v,b,C,w,E,ie,oe,W,K,Z,q,ce,ue,de,Y,me,ye,X,_e]);return(0,d.jsx)(je.Provider,{value:be,children:e})}function Ne(){let e=(0,u.useContext)(je);if(!e)throw Error(`useAgentico must be used inside AgenticoProvider`);return e}var Pe=`llmnative.agentico.threadEvents`;function Fe(){let[e,t]=(0,u.useState)(()=>{try{return localStorage.getItem(Pe)!==`off`}catch{return!0}});return[e,e=>{t(e);try{localStorage.setItem(Pe,e?`on`:`off`)}catch{}}]}function Ie(e,t,n,r=!0){let{threadEvents:i}=Ne(),[a,o]=(0,u.useState)([]);return(0,u.useEffect)(()=>{if(!i||!e||!r){o([]);return}let a=!0,s=()=>{Promise.resolve(i.load(e,t,n)).then(e=>{a&&o(e.filter(e=>e.at>=t&&e.at<n))},()=>void 0)};s();let c=i.subscribe?.(e,s);return()=>{a=!1,c?.()}},[i,e,t,n,r]),a}function Le({event:e}){let t=$(),{locale:n}=(0,l.useI18n)(),[r,i]=(0,u.useState)(!1),a=new Date(e.at).toLocaleString(n,{dateStyle:`short`,timeStyle:`short`});return(0,d.jsxs)(`li`,{className:`flex items-start gap-2 py-1 text-xs`,"aria-label":`${e.author.name}: ${e.title}`,children:[(0,d.jsx)(`span`,{className:`flex w-6 shrink-0 justify-center pt-px`,children:(0,d.jsx)(qe,{author:e.author})}),(0,d.jsxs)(`div`,{className:`min-w-0 flex-1 rounded-md border border-border/60 bg-muted/30 px-2 py-1`,children:[(0,d.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5`,children:[(0,d.jsx)(`span`,{className:`font-medium text-foreground`,children:e.author.name}),e.icon&&(0,d.jsx)(l.Icon,{name:e.icon,size:12,className:`shrink-0 text-muted-foreground`}),(0,d.jsx)(`span`,{className:`min-w-0 break-words text-muted-foreground`,children:e.title}),e.badge&&(0,d.jsx)(l.Badge,{variant:e.badge.variant??`light`,children:e.badge.label}),(0,d.jsxs)(`span`,{className:`ms-auto flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground`,children:[(0,d.jsx)(`time`,{dateTime:new Date(e.at).toISOString(),children:a}),e.body&&(0,d.jsx)(`button`,{type:`button`,onClick:()=>i(e=>!e),"aria-expanded":r,title:r?t.eventLess:t.eventMore,className:`rounded hover:text-foreground`,children:(0,d.jsx)(l.Icon,{name:r?`chevron-up`:`chevron-down`,size:12})}),e.href&&(0,d.jsx)(`a`,{href:e.href,target:`_blank`,rel:`noreferrer`,title:t.eventOpen,"aria-label":t.eventOpen,className:`rounded hover:text-foreground`,children:(0,d.jsx)(l.Icon,{name:`external-link`,size:12})})]})]}),r&&e.body&&(0,d.jsx)(l.ChatMarkdown,{content:e.body,tone:`muted`,className:`mt-1 break-words text-xs leading-relaxed`})]})]})}function Re(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(...Re(u)),l}function ze(e){let t=[],n=/```(\w+)?\n?([\s\S]*?)```/g,r=0,i;for(;i=n.exec(e);)i.index>r&&t.push(...Re(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(...Re(e.slice(r))),t}function Be({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 Ve({text:e,tone:t}){let n=ze(e);return(0,d.jsx)(d.Fragment,{children:n.map((e,n)=>e.type===`code`?(0,d.jsx)(Be,{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 He(){let[e]=(0,u.useState)(()=>Date.now()),[t,n]=(0,u.useState)(e);(0,u.useEffect)(()=>{let e=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(e)},[]);let r=Math.floor((t-e)/1e3);return r<10?null:(0,d.jsxs)(`span`,{className:`tabular-nums`,children:[` · `,Math.floor(r/60),`:`,String(r%60).padStart(2,`0`)]})}function Ue({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 We(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 Ge=96,Ke=e=>e.some(e=>e.status===`stopped`||e.status===`error`);function qe({author:e,size:t=20}){return e.avatarUrl?(0,d.jsx)(l.ImageAvatar,{src:e.avatarUrl,title:e.name,alt:e.name,width:t,height:t}):(0,d.jsx)(l.Identicon,{value:e.name,size:t,title:e.name})}var Je=`w-6`;function Ye(e){if(!e||e.kind!==`thinking`||!e.parts)return[];let t=[];for(let n of e.parts){if(n.type!==`reasoning`&&n.type!==`tool`)break;t.push(n)}return t}function Xe({parts:e,open:t,onToggle:n}){let r=$(),i=e.filter(e=>e.type===`reasoning`),a=e.filter(e=>e.type===`tool`),o=i.some(e=>e.streaming),s=a.filter(e=>e.status===`running`).at(-1),c=Math.round(i.reduce((e,t)=>e+(t.duration??0),0)),u=[...i.length?[o?r.reasoningNow:c>0?(0,l.interpolate)(r.reasonedFor,{seconds:c}):r.reasoned]:[],...a.length?[s?.label??(a.length===1?r.oneStep:(0,l.interpolate)(r.steps,{count:a.length}))]:[]],f=o||!!s,p=a.some(e=>e.status===`error`);return(0,d.jsxs)(`button`,{type:`button`,onClick:n,"aria-expanded":t,title:r.processDetails,className:`inline-flex min-w-0 items-center gap-1 rounded text-xs text-muted-foreground hover:text-foreground`,children:[(0,d.jsx)(l.Icon,{name:f?`loader-circle`:p?`circle-alert`:i.length?`brain`:`list-checks`,size:12,className:`shrink-0 ${f?`animate-spin`:``}`}),(0,d.jsx)(`span`,{className:`truncate`,children:u.join(` · `)}),(0,d.jsx)(l.Icon,{name:t?`chevron-up`:`chevron-down`,size:12,className:`shrink-0`})]})}function Ze({entry:e,pinned:t=!0,actions:n,cut:r=!1,showAuthor:i=!1}){let a=$(),o=(0,u.useRef)(null),[s,c]=(0,u.useState)(!1),[f,p]=(0,u.useState)(!1);(0,u.useLayoutEffect)(()=>{let e=o.current;e&&p(e.scrollHeight>97)},[e.detail,e.attachmentNames]);let m=f&&!s,h=n?.available(e)&&r?(0,d.jsx)(l.ActionButton,{icon:`rotate-ccw`,ariaLabel:a.retry,title:a.retry,variant:`link`,className:`p-1 text-muted-foreground hover:text-foreground`,disabled:n.disabled,onClick:()=>n.onRetry(e)}):null,g=n?.available(e)?(0,d.jsx)(`span`,{className:`opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100`,children:(0,d.jsx)(l.ActionButton,{icon:`pencil`,ariaLabel:a.editMessage,title:a.editMessage,variant:`link`,className:`p-1 text-muted-foreground hover:text-foreground`,disabled:n.disabled,onClick:()=>n.onEdit(e)})}):null,_=t=>(0,d.jsxs)(`div`,{className:`${t?`w-full`:`max-w-[85%]`} rounded-lg bg-primary/10 text-xs text-foreground`,children:[(0,d.jsxs)(`div`,{ref:o,className:`space-y-1 px-2.5 pt-1.5 ${m?`overflow-hidden`:``}`,style:m?{maxHeight:Ge}: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)(Ve,{text:e.detail??``})]}),f&&(0,d.jsxs)(`button`,{type:`button`,onClick:()=>c(e=>!e),className:`relative flex w-full items-center justify-center rounded-b-lg py-1 text-muted-foreground hover:bg-primary/15`,title:s?`Comprimi`:`Espandi`,children:[m&&(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:s?`chevron-up`:`chevron-down`,size:12})]})]});return i?(0,d.jsxs)(`div`,{className:`${t?`sticky top-0 z-20 border-b border-border/40`:``} group flex items-start gap-2 bg-background py-1.5`,children:[(0,d.jsxs)(`span`,{className:`flex shrink-0 flex-col items-center ${Je}`,children:[e.author?(0,d.jsx)(qe,{author:e.author}):(0,d.jsx)(`span`,{className:`flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground`,"aria-hidden":!0,children:(0,d.jsx)(l.Icon,{name:`user`,size:12})}),h,g]}),(0,d.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[e.author&&(0,d.jsx)(`div`,{className:`pb-0.5 text-xs font-medium text-foreground`,children:e.author.name}),_(!0)]})]}):(0,d.jsxs)(`div`,{className:`${t?`sticky top-0 z-20 border-b border-border/40`:``} group flex items-start justify-end gap-1 bg-background py-1.5`,children:[n?.available(e)&&(0,d.jsxs)(`span`,{className:`flex shrink-0 items-center`,children:[h,g]}),_(!1)]})}var Qe={running:`loader-circle`,done:`check`,error:`x`,stopped:`circle-slash`};function $e({steps:e}){let t=$(),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:Qe[e.status]}))}]})}function et({entry:e,part:t,questions:n}){let r=$(),[i,a]=(0,u.useState)(!1),o=!!(n?.onCardAction&&n.canAnswer(e.id)&&!t.outcome),s=t.outcome?.status===`done`?`text-success`:t.outcome?.status===`error`?`text-destructive`:`text-muted-foreground`;return(0,d.jsxs)(l.Card,{headerClassName:`flex items-center justify-between gap-2 px-3 py-2`,bodyClassName:`px-3 py-2`,header:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(`span`,{className:`min-w-0 text-xs font-semibold text-foreground`,children:t.title}),t.badge&&(0,d.jsx)(l.Badge,{variant:t.badge.variant??`info`,children:t.badge.label})]}),footer:(0,d.jsxs)(`div`,{className:`space-y-1.5 px-3 py-2`,children:[(0,d.jsxs)(`div`,{className:`flex items-center gap-1`,children:[t.details&&(0,d.jsx)(l.ActionButton,{icon:`eye`,ariaLabel:r.cardView,title:r.cardView,variant:`outline-secondary`,onClick:()=>a(!0)}),(t.actions??[]).filter(e=>e.variant!==`primary`&&e.icon).map(r=>(0,d.jsx)(l.LoadingButton,{icon:r.icon,ariaLabel:r.label,title:r.label,variant:r.variant??`outline-secondary`,disabled:!o,onClick:()=>n.onCardAction(e.id,t.id,r.id)},r.id)),(0,d.jsx)(`span`,{className:`ms-auto flex items-center gap-1`,children:(t.actions??[]).filter(e=>e.variant===`primary`||!e.icon).map(r=>(0,d.jsx)(l.LoadingButton,{...r.icon?{icon:r.icon}:{},label:r.label,variant:r.variant??`outline-primary`,disabled:!o,onClick:()=>n.onCardAction(e.id,t.id,r.id)},r.id))})]}),t.outcome&&(0,d.jsxs)(`p`,{className:`text-xs ${s}`,children:[t.outcome.text,t.outcome.link&&(0,d.jsxs)(d.Fragment,{children:[` `,(0,d.jsx)(`a`,{className:`underline`,href:t.outcome.link.url,target:`_blank`,rel:`noopener noreferrer`,children:t.outcome.link.label})]})]})]}),children:[t.body?(0,d.jsx)(l.ChatMarkdown,{content:t.body,className:`break-words text-xs leading-relaxed text-foreground`}):null,i&&t.details&&(0,d.jsx)(l.Modal,{title:t.title,position:`right`,size:`lg`,onClose:()=>a(!1),footer:(0,d.jsx)(l.ActionButton,{label:r.cardClose,variant:`outline-secondary`,onClick:()=>a(!1)}),children:(0,d.jsx)(l.ChatMarkdown,{content:t.details,className:`break-words text-sm leading-relaxed text-foreground`})})]})}function tt(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 nt({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 rt({entry:e,questions:t,hiddenPartId:n,skip:r}){let i=(e.parts??[]).filter(e=>(e.type!==`questions`||e.id!==n)&&!r?.has(e.id)),a=[];for(let e of i){let t=a.at(-1);e.type===`tool`?t&&`steps`in t?t.steps.push(e):a.push({key:`tool-${e.id}`,steps:[e]}):a.push({key:`${e.type}-${e.id}`,part:e})}return(0,d.jsx)(`div`,{className:`space-y-2`,children:a.map(n=>{if(`steps`in n)return(0,d.jsx)($e,{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):r.type===`card`?(0,d.jsx)(et,{entry:e,part:r,questions:t},n.key):(0,d.jsx)(nt,{entry:e,part:r,questions:t},n.key)})})}function it({entry:e,questions:t,hiddenPartId:n,skip:r}){let i=$();if(e.kind===`thinking`&&e.parts){let a=e.status===`error`||e.status===`stopped`||e.status===`running`,o=r?e.parts.filter(e=>!r.has(e.id)).length:e.parts.length;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[o>0&&(0,d.jsx)(rt,{entry:e,questions:t,hiddenPartId:n,skip:r}),a&&(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5 ${o>0?`mt-1`:``}`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(Ue,{status:e.status})}),(0,d.jsxs)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:[We(e,i),e.status===`running`&&(0,d.jsx)(He,{})]})]})]})}let a=e.kind===`thinking`&&e.detail?ze(e.detail):[],o=a.filter(e=>e.type===`code`),s=a.filter(e=>e.type===`text`&&e.content.trim()),c=e.kind===`thinking`?We(e,i):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)(Ue,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:c})]}),o.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-1`,children:o.map((e,t)=>(0,d.jsx)(Be,{content:e.content,language:e.language},t))}),s.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-2`,children:s.map((e,t)=>(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:`muted`,className:`break-words text-xs leading-relaxed`},t))})]})}function at({parts:e}){return(0,d.jsx)(`div`,{className:`mb-1 space-y-1 border-l-2 border-border pl-2 text-xs text-muted-foreground`,children:e.map(e=>e.type===`reasoning`?(0,d.jsx)(l.ChatMarkdown,{content:e.text,tone:`muted`,streaming:e.streaming,className:`break-words text-xs leading-relaxed`},e.id):e.type===`tool`?(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,d.jsx)(l.Icon,{name:Qe[e.status],size:12,className:`mt-0.5 shrink-0 ${e.status===`running`?`animate-spin`:``}`}),(0,d.jsx)(`span`,{className:`min-w-0 break-words ${e.status===`error`?`text-destructive`:``}`,children:e.label})]},e.id):null)})}function ot({speaker:e,entries:t,questions:n,docked:r}){let i=Ye(t[0]),a=i.length?new Set(i.map(e=>e.id)):void 0,[o,s]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`flex items-start gap-2 pt-1.5`,children:[(0,d.jsx)(`span`,{className:`flex shrink-0 justify-center pt-px ${Je}`,children:(0,d.jsx)(qe,{author:e})}),(0,d.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,d.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-2 pb-0.5`,children:[(0,d.jsx)(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.name}),i.length>0&&(0,d.jsx)(Xe,{parts:i,open:o,onToggle:()=>s(e=>!e)})]}),o&&i.length>0&&(0,d.jsx)(at,{parts:i}),(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:t.map((e,t)=>(0,d.jsx)(it,{entry:e,questions:n,hiddenPartId:r?.entry.id===e.id?r.part.id:void 0,...t===0&&a?{skip:a}:{}},e.id))})]})]})}function st({activity:e,questions:t,docked:n,pinUserMessages:r=!0,messageActions:i,speaker:a,showAuthors:o,events:s}){if(e.length===0&&!s?.length)return null;let c=o??(!!a||e.some(e=>e.kind===`user`&&e.author)),l=[];for(let t of e)t.kind===`user`||l.length===0?l.push(t.kind===`user`?{user:t,entries:[]}:{entries:[t]}):l[l.length-1].entries.push(t);let f=Oe(l.map(e=>(e.user??e.entries[0])?.at),s??[]);return(0,d.jsxs)(`ul`,{className:`space-y-0.5`,children:[l.map((e,o)=>(0,d.jsxs)(u.default.Fragment,{children:[f[o].map(e=>(0,d.jsx)(Le,{event:e},e.id)),(0,d.jsxs)(`li`,{children:[e.user&&(0,d.jsx)(Ze,{entry:e.user,pinned:r,actions:i,cut:Ke(e.entries),showAuthor:c}),a&&e.entries.length>0?(0,d.jsx)(ot,{speaker:a,entries:e.entries,questions:t,docked:n}):e.entries.length>0&&(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:e.entries.map(e=>(0,d.jsx)(it,{entry:e,questions:t,hiddenPartId:n?.entry.id===e.id?n.part.id:void 0},e.id))})]})]},e.user?.id??e.entries[0]?.id)),f[l.length].map(e=>(0,d.jsx)(Le,{event:e},e.id))]})}var ct=420,lt=320,ut=`60vw`,dt=`agentico:panel-width`;function ft(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 pt(e,t,n){return Math.round(Math.min(Math.max(e,t),Math.max(t,n)))}function mt(){try{let e=window.localStorage.getItem(dt),t=e===null?NaN:Number(e);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function ht(e){try{e===null?window.localStorage.removeItem(dt):window.localStorage.setItem(dt,String(e))}catch{}}function gt(){return typeof window>`u`?1/0:window.innerWidth}function _t({defaultWidth:e=420,minWidth:t=320,maxWidth:n=ut,onWidthChange:r}){let[i,a]=(0,u.useState)(gt),[o,s]=(0,u.useState)(()=>mt()??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,ft(n,i)),d=pt(o,c,l);return(0,u.useEffect)(()=>{r?.(d)},[d]),{width:d,min:c,max:l,set:(0,u.useCallback)(e=>s(pt(e,c,l)),[c,l]),commit:(0,u.useCallback)(e=>ht(pt(e,c,l)),[c,l]),reset:(0,u.useCallback)(()=>{s(e),ht(null)},[e])}}function vt({width:e,min:t,max:n,onResize:r,onCommit:i,onReset:a}){let o=$(),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 yt({className:e=``}){let{isOpen:t,toggleOpen:n,task:r}=Ne(),i=$(),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 bt=`llmnative-cms.selectedAIModel`;function xt(){try{return localStorage.getItem(bt)??``}catch{return``}}function St(e){try{e?localStorage.setItem(bt,e):localStorage.removeItem(bt)}catch{}}function Ct(){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)(xt);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:(St(``),``))}).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=>{St(e),s(e)}}}var wt=`approval`;function Tt(e,t){return typeof e.needsApproval==`function`?e.needsApproval(t):e.needsApproval===!0}function Et(e,t,n){let r=e[0]?.values??[],i=r.filter(e=>e!==t&&e!==n).join(` `).trim();return{approved:r.includes(t)&&!r.includes(n),...i?{reason:i}:{}}}var Dt=20,Ot=26e4;function kt(e){return e.filter(e=>!l.PromptUtils.isTextAttachment(e.mimeType)||e.base64.length<=Ot)}function At(e){return e.map(e=>e.status!==`running`&&!e.parts?.some(e=>e.type===`tool`&&e.status===`running`||(e.type===`text`||e.type===`reasoning`)&&e.streaming)?e:{...e,status:e.status===`running`?`stopped`:e.status,...e.parts?{parts:e.parts.map(e=>e.type===`tool`&&e.status===`running`?{...e,status:`stopped`}:(e.type===`text`||e.type===`reasoning`)&&e.streaming?{...e,streaming:!1}:e)}:{}})}function jt(e,t={}){let{defaultEnabled:n=!1}=t,r=(0,u.useRef)(t.author);r.current=t.author;let[i,a]=(0,u.useState)(n),{hasProviders:o,modelsByProvider:s,modelsLoading:c,selectedModel:d,setSelectedModel:p}=Ct(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),[x,S]=(0,u.useState)(!1),[C,ee]=(0,u.useState)([]),T=(0,u.useRef)([]),E=(e,t)=>{ee(n=>{let r=typeof e==`function`?e(n):e;if(t?.stamp!==!1){let e=new Set(n.map(e=>e.id)),t=t=>t.at===void 0&&!e.has(t.id);if(r.some(t)){let e=Date.now();r=r.map(n=>t(n)?{...n,at:e}:n)}}return T.current=r,r})},D=(0,u.useRef)(new Map),O=$(),k=(0,u.useRef)(O);k.current=O;let A=(0,u.useRef)(null),M=(0,u.useRef)(!1),N=(0,u.useRef)(null),te=(0,u.useRef)(null),P=(0,u.useRef)(null),F=()=>{P.current?.abort()},ne=(0,l.useAIProviderRegistry)()?.registry??{},[I,L]=(0,u.useState)(void 0),B=(0,u.useRef)(void 0),re=(e,t)=>{if(!t)return!1;if(!e)return!0;let n=(0,l.parseAIModelRef)(t);return!!n&&e.includes(n.provider)},V=(0,u.useMemo)(()=>I?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,t.filter(e=>I.includes(e.provider))]).filter(([,e])=>e.length)):s,[I,s]),H=re(I,d)?d:Object.values(V).flat()[0]?.id??``,U=i&&H?(0,l.parseAIModelRef)(H):null,ie=U?ne[U.provider]:null,W=e.executor,G=!!W?.alongside,K=!!W&&!G,ae=!W||!!W.canRewind,oe=!!W?.attachments,q=async e=>oe&&e?.length?Promise.all(e.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,se=(0,u.useRef)([]),ce=e=>!!e&&se.current.some(t=>t.value===e),le=(0,u.useRef)(!1),[ue,J]=(0,u.useState)([]),[de,fe]=(0,u.useState)(``),Y=(0,u.useRef)(``),pe=e=>{Y.current=e,fe(e)},me=e=>{let t=W?.models?.(e)??[];se.current=t,J(t);let n=W?.catalogProviders?.(e);B.current=n,L(n);let r=G&&!re(n,d)?t[0]?.value:void 0;pe(W?.defaultModel?.(e)??r??``)},X=async(e,t,n,r,i)=>{let a=A.current;if(!a||!W)return b(k.current.noActiveSession),null;let o=new AbortController;P.current=o;let s=crypto.randomUUID();E(e=>[...e,{id:s,kind:`thinking`,label:k.current.thinking,status:`running`,parts:[]}]);let c=new Map,l=e=>Math.max(1,Math.round((Date.now()-(c.get(e)??Date.now()))/1e3)),u=e=>({...e,streaming:!1,duration:e.duration??l(e.id)}),d=(e,t)=>E(n=>n.map(n=>{if(n.id!==s)return n;let r=e(n.parts??[]),i=h(r);return{...n,parts:r,...t?{status:t}:{},...i?{detail:i}:{}}})),p=e=>d(t=>m(t,e,u)),g=!1,_=(e,t)=>{t?.id&&t.id!==`text`&&(g=!0),p({type:`text`,id:t?.id??`text`,text:e,streaming:!t?.done})},v=(e,t)=>{let n=t?.id??`reasoning`;c.has(n)||c.set(n,Date.now()),p({type:`reasoning`,id:n,text:e,streaming:!t?.done,...t?.duration===void 0?t?.done?{duration:l(n)}:{}:{duration:t.duration}})},y=e=>p({type:`tool`,id:e.id,label:e.label,status:e.status}),x=e=>p({...e,type:`card`}),S=new Set,C=0,ee=()=>{for(let e of S){let t=D.current.get(e);D.current.delete(e),t?.reject(new DOMException(`The turn was stopped.`,`AbortError`))}S.clear()};o.signal.addEventListener(`abort`,ee);let w=(e,t)=>{C+=1;let n=t?.id??`questions-${C}`;p({type:`questions`,id:n,questions:e});let r=`${s}:${n}`;return o.signal.aborted?Promise.reject(new DOMException(`The turn was stopped.`,`AbortError`)):(S.add(r),new Promise((e,t)=>{D.current.set(r,{resolve:e,reject:t})}))},O=(e,t)=>{d(n=>(t&&!g?m(n,{type:`text`,id:f,text:t,streaming:!1},u):n).map(t=>t.type===`reasoning`&&t.streaming?u(t):t.type===`text`&&t.streaming?{...t,streaming:!1}:t.type===`tool`&&t.status===`running`&&e!==`done`?{...t,status:`stopped`}:t),e),o.signal.removeEventListener(`abort`,ee);for(let e of S)D.current.delete(e);S.clear()},j=e||r?.historyText||``;try{let c=N.current;N.current=null;let l=T.current,u=l.findIndex(e=>e.id===te.current),d=c?{activity:c.fresh?c.activity:(u>=0?l.slice(0,u):l).filter(e=>e.id!==s)}:void 0,f=await W.turn({params:a.params,context:a.context,text:e,first:t,signal:o.signal,...d?{rewound:d}:{},...i?.length?{attachments:i}:{},...n||Y.current?{model:n||Y.current}:{},...r?{answers:{id:r.id,answers:r.answers}}:{},onText:_,onReasoning:v,onStep:y,onQuestions:w,onCard:x});return O(`done`,f.text),a.history=[...a.history,...j?[{role:`user`,content:j}]:[],{role:`assistant`,content:f.text}],f.result??null}catch(e){return a.history=[...a.history,...j?[{role:`user`,content:j}]:[]],o.signal.aborted?(O(`stopped`),null):(O(`error`),b(z(e)),null)}finally{P.current=null}},he=async(t,n,r)=>{let i=T.current.find(e=>e.id===t)?.parts?.find(e=>e.type===`card`&&e.id===n),a=A.current;if(!i||!a||!e.onCardAction)return;let o;try{o=await e.onCardAction(a.params,i,r)}catch(e){o={status:`error`,text:z(e)}}o&&E(e=>e.map(e=>e.id===t?{...e,parts:e.parts?.map(e=>e.type===`card`&&e.id===n?{...e,outcome:o}:e)}:e))},ge=async(e,t,n)=>{let r=T.current.find(t=>t.id===e)?.parts?.find(e=>e.type===`questions`&&e.id===t);if(!r||r.type!==`questions`)throw b(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(M.current)throw b(k.current.requestInProgress),Error(k.current.requestInProgress);if(!K||!A.current)throw b(k.current.noActiveSession),Error(k.current.noActiveSession);M.current=!0,v(!0),b(null),i();try{return await X(``,!1,void 0,{id:t,answers:n,historyText:g(r.questions,n)})}finally{M.current=!1,v(!1)}},_e=async(t,n,r)=>{let i=B.current,a=Object.values(s).flat().find(e=>!i||i.includes(e.provider))?.id,o=r&&re(i,r)?r:re(i,H)?void 0:a,c=o?(0,l.parseAIModelRef)(o):U,u=c&&A.current?W?.catalogReasoning?.(A.current.params,c.provider):void 0,d=u?{reasoning:u}:{},f=A.current;if(!f)return b(k.current.noActiveSession),null;let p=o?(0,l.parseAIModelRef)(o):U,m=p?ne[p.provider]:null;if(!m||!p)return b(k.current.noProviderAvailable),null;n?.length&&(f.attachmentsRef.current=[...f.attachmentsRef.current??[],...n]);let h=(n??[]).filter(e=>l.PromptUtils.isTextAttachment(e.mimeType)).map(e=>e.base64.length<=Ot?`\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(``),g=kt(n??[]),_=f.tools.map(e=>({name:e.name,description:e.description,inputSchema:w(e.inputSchema)})),v=(e,t,n,r)=>{let i=k.current,a=`approval-${e}`,o=t.describeApproval?.(n)??t.describeInvocation?.(n)??t.name;E(e=>[...e,{id:a,kind:`thinking`,label:i.approvalHeader,status:`running`,parts:[{type:`questions`,id:wt,questions:[{header:i.approvalHeader,question:i.approveQuestion.replace(`{action}`,o),options:[{label:i.approve},{label:i.reject}],custom:!0}]}]}]);let s=`${a}:${wt}`;return new Promise((e,t)=>{let n=()=>{D.current.delete(s),S(a,`stopped`),t(new DOMException(`The turn was stopped.`,`AbortError`))};if(r.aborted){n();return}r.addEventListener(`abort`,n,{once:!0}),D.current.set(s,{resolve:t=>{r.removeEventListener(`abort`,n),S(a,`done`),e(Et(t,i.approve,i.reject))},reject:t})})},y=new Map(f.tools.map(e=>[e.name,e])),x=new AbortController;P.current=x;let S=(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=f.history,r=t;for(let t=0;t<Dt;t++){let i=crypto.randomUUID();E(e=>[...e,{id:i,kind:`thinking`,label:k.current.thinking,status:`running`}]);let a;try{a=await m.complete({prompt:r,model:p.model,...d,history:n,tools:_.length?_:void 0,signal:x.signal,attachments:t===0?g:void 0,logId:f.logId})}catch(t){return f.history=[...n,...r?[{role:`user`,content:r+h}]:[]],x.signal.aborted?(S(i,`stopped`),e.fallback(f.params,f.context)):(S(i,`error`),b(z(t)),null)}if(f.history=[...n,...r?[{role:`user`,content:r+h}]:[]],!a)return x.signal.aborted?(S(i,`stopped`),e.fallback(f.params,f.context)):(S(i,`error`),b(k.current.noProviderResponse),null);if(a.type===`text`)return S(i,`done`,a.text),e.conversational&&a.text.trim()&&E(e=>e.map(e=>e.id===i?{...e,parts:[{type:`text`,id:`text`,text:a.text}]}:e)),f.history=[...n,...r?[{role:`user`,content:r+h}]:[],{role:`assistant`,content:a.text}],e.parseResponse(a.text,f.params,f.context)||(console.error(`[useAgent] parseResponse ha restituito null — la risposta del modello non è nel formato atteso da questo subagent. Uso il fallback deterministico.`,{responseLength:a.text.length,responsePreview:a.text.length>2e3?`${a.text.slice(0,1e3)}\n…[troncato qui nel log, ${a.text.length} caratteri totali]…\n${a.text.slice(-1e3)}`:a.text,params:f.params}),b(k.current.invalidResponse),e.fallback(f.params,f.context));let o=a.toolCalls.map(e=>{let t=y.get(e.name);return t?.describeIntent??t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`});S(i,`done`,a.text||void 0,a.text?void 0:o);let s=new Map;for(let t of a.toolCalls){let n=y.get(t.name);if(n&&Tt(n,t.input))try{s.set(t.id,await v(t.id,n,t.input,x.signal))}catch{return e.fallback(f.params,f.context)}}let c=await Promise.all(a.toolCalls.map(async e=>{let t=y.get(e.name),n=t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`,r=s.get(e.id);if(r&&!r.approved){E(t=>[...t,{id:e.id,kind:`tool`,label:n,status:`stopped`}]);let t=j().toolRejected.replace(`{reason}`,r.reason?` (${r.reason})`:``);return{toolCallId:e.id,name:e.name,output:t,isError:!0}}if(E(t=>[...t,{id:e.id,kind:`tool`,label:n,status:`running`}]),!t)return S(e.id,`error`),{toolCallId:e.id,name:e.name,output:`Tool sconosciuto: ${e.name}`,isError:!0};try{let n=await t.execute(e.input);S(e.id,`done`);let r=t.card?.(e.input,n);return r&&E(t=>[...t,{id:`card-${e.id}`,kind:`thinking`,label:``,status:`done`,parts:[{...r,type:`card`}]}]),{toolCallId:e.id,name:e.name,output:n}}catch(t){return S(e.id,`error`),{toolCallId:e.id,name:e.name,output:z(t),isError:!0}}}));n=[...n,...r?[{role:`user`,content:r+h}]:[],{role:`assistant`,content:a.text,toolCalls:a.toolCalls},{role:`tool_result`,results:c}],r=``}let i=crypto.randomUUID();E(e=>[...e,{id:i,kind:`thinking`,label:k.current.thinking,status:`running`}]);let a;try{a=await m.complete({...d,prompt:R(j().stopCallingTools,e.microPromptIds),model:p.model,history:n,signal:x.signal,logId:f.logId})}catch{a=null}if(a?.type===`text`){S(i,`done`,a.text),f.history=[...n,{role:`assistant`,content:a.text}];let t=e.parseResponse(a.text,f.params,f.context);if(t)return t}else S(i,x.signal.aborted?`stopped`:`error`),f.history=n;return x.signal.aborted||b(k.current.tooManyToolTurns),e.fallback(f.params,f.context)}finally{P.current=null}},ve=async(t,n)=>{if(M.current)return b(k.current.requestInProgress),null;M.current=!0,b(null),E(n?.openingMessage?[{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:n.openingMessage,...r.current?{author:r.current}:{},...n.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]:[]),v(!0);try{let r=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,r,a)??[];if(A.current={params:t,context:r,tools:o,history:[],logId:crypto.randomUUID(),attachmentsRef:a},K)return S(!0),me(t),await X(n?.openingMessage??``,!0,void 0,void 0,await q(n?.attachments));if(G){me(t),le.current=!1;let e=n?.model||Y.current;if(ce(e))return S(!0),le.current=!0,await X(n?.openingMessage??``,!0,e,void 0,await q(n?.attachments))}let s=n?.model||void 0,c=s?!!ne[(0,l.parseAIModelRef)(s)?.provider??``]:!!ie;if(!i||!c){S(!1);let n=e.fallback(t,r);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.aiDisabledFallback}]),n}S(!0);let u=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,d=R(e.buildPrompt(t,r),e.microPromptIds);return await _e(d,u,s)}catch(e){return b(z(e)),null}finally{M.current=!1,v(!1)}},ye=async(t,n)=>{if(M.current){b(k.current.requestInProgress);return}M.current=!0,b(null),E(At(n.activity),{stamp:!1}),v(!0);try{let r=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,r,a)??[];A.current={params:t,context:r,tools:o,history:n.history,logId:crypto.randomUUID(),attachmentsRef:a},(K||G)&&me(t),le.current=!1,S(K||G||i&&!!ie)}catch(e){b(z(e))}finally{M.current=!1,v(!1)}},Z=async(t,n)=>{if(M.current)return b(k.current.requestInProgress),null;if(b(null),!t.trim())return b(`Messaggio vuoto.`),null;let i=A.current;if(!i)return b(k.current.noActiveSession),null;M.current=!0,v(!0);let a=crypto.randomUUID();te.current=a,E(e=>[...e,{id:a,kind:`user`,label:`Tu`,status:`done`,detail:t,...r.current?{author:r.current}:{},...n?.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{},...n?.retry?{retry:!0}:{},historyAt:i.history.length}]);try{if(K)return await X(t,!1,n?.model||void 0,void 0,await q(n?.attachments));let r=n?.model||(G?Y.current:``);if(G&&ce(r)){let e=!le.current;return le.current=!0,await X(t,e,r,void 0,await q(n?.attachments))}N.current&&={...N.current,fresh:!1};let a=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,o=R(e.buildFollowUpPrompt(t,i.params,i.context),e.microPromptIds);return await _e(o,a,n?.model||void 0)}catch(e){return b(z(e)),null}finally{M.current=!1,v(!1)}},be=e=>{let t=A.current,n=C.findIndex(t=>t.id===e),r=C[n],i=r?.detail?.trim();if(!ae||!t||!r||r.kind!==`user`||!i)return;if(r.historyAt!==void 0)return r.historyAt;let a=C.slice(0,n).filter(e=>e.kind===`user`&&e.detail?.trim()===i).length,o=0;for(let e=0;e<t.history.length;e+=1){let n=t.history[e];if(n.role===`user`&&n.content.includes(i)){if(o===a)return e;o+=1}}return n===C.map(e=>e.kind===`user`).lastIndexOf(!0)?t.history.length:void 0},xe=e=>be(e)!==void 0,Se=async(e,t)=>{if(M.current)return b(k.current.requestInProgress),null;let n=A.current,r=C.findIndex(t=>t.id===e),i=C[r],a=be(e);if(!n||!i||a===void 0)return null;let o=(t??i.detail??``).trim();if(!o)return null;let s=C.slice(0,r);return n.history=n.history.slice(0,a),N.current={activity:s,fresh:!0},E(s),Z(o)},Q=()=>{let t=A.current;if(!t)return null;b(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},Ce=()=>A.current?{history:A.current.history,activity:C}:null;return{enabled:i,setEnabled:a,hasProviders:o,selectedModel:K||G&&de?de:H,setSelectedModel:K?pe:G?e=>{ce(e)?pe(e):(pe(``),p(e))}:p,modelsByProvider:V,modelsLoading:c,running:_,error:y,canContinue:x,remote:K,remoteModels:ue,alongside:G,...W?.catalogGroup?{catalogGroup:W.catalogGroup}:{},activity:C,run:ve,resume:ye,sendMessage:Z,stop:F,runFallback:Q,snapshot:Ce,answerQuestions:ge,cardAction:he,rewind:Se,canRewind:ae,rewindable:xe,executorAttachments:oe,offersFallback:e.offersFallback!==!1}}function Mt(){let e=j();return[e.responseRulesHeading,...e.responseRules.map(e=>`- ${e}`)].join(`
17
- `)}function Nt(e,t,n){let r=j(),i=n?`\n${r.pageContextHeading}\n${r.pageContextIntro}\n${n}\n`:``;return`${r.orchestratorIntro}
11
+ `)}function F(e){return[`NAME`,` ${e.id} — ${e.label}`,``,`DESCRIPTION`,P(e.description,2),``,...e.commands.map(t=>N(e.id,t))].join(`
12
+ `)}function ne(e){return e.length===0?A().noToolsAvailable:e.map(e=>`${e.id} [${e.commands.map(e=>e.name).join(`|`)}] — ${e.label}: ${e.commands.map(e=>e.summary).join(` / `)}`).join(`
13
+ `)}var I={id:`closing-summary`,get text(){return A().closingSummary}},L={[I.id]:I};function R(e,t){if(!t||t.length===0)return e;let n=t.map(e=>L[e]?.text).filter(e=>!!e);return n.length===0?e:`${e}\n\n${n.join(`
14
+ `)}`}function z(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 re(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 ie(n)??n}function ie(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 ae(e){H=e}function oe(){return{[V.id]:V,...H}}var U={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.`,approvalHeader:`Approval`,approve:`Approve`,reject:`Reject`,approveQuestion:`Approve? {action}`,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`,reasoningNow:`Reasoning…`,reasonedFor:`Reasoned for {seconds} s`,reasoned:`Reasoned`,processDetails:`Reasoning and steps`,stepsLabel:`Steps of the agent`,newInstance:`New "{label}" instance`,chatHistory:`Chat history`,earlierSession:`Earlier session`,thisSession:`This session`,continueSession:`Continue this session`,sessionOf:`Session of {at}`,eventMore:`More`,eventLess:`Less`,eventOpen:`Open`,eventRunning:`In progress`,showEvents:`Show what the agents did`,hideEvents:`Conversation only`,cardView:`View`,cardClose:`Close`,renameChat:`Rename`,chatTitleLabel:`Title`,chatTitleHint:`Empty: the title written from the chat.`,chatStarted:`Started {at}`,chatLastMessage:`last message {at}`,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`,editMessage:`Edit`,editingMessage:`Editing a message: sent, the chat goes back to it.`,cancelEdit:`Cancel`,rewindTitle:`Go back to this message?`,rewindText:`What came after it leaves the chat and the memory of the agent. What its steps did stays done:`,stop:`Stop`},W={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().`,approvalHeader:`Approvazione`,approve:`Approva`,reject:`Rifiuta`,approveQuestion:`Approvi? {action}`,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`,reasoningNow:`Sta ragionando…`,reasonedFor:`Ha ragionato {seconds} s`,reasoned:`Ha ragionato`,processDetails:`Ragionamento e passi`,stepsLabel:`Passi dell'agente`,newInstance:`Nuova istanza di "{label}"`,chatHistory:`Storico chat`,earlierSession:`Sessione precedente`,thisSession:`Questa sessione`,continueSession:`Continua questa sessione`,sessionOf:`Sessione del {at}`,eventMore:`Di più`,eventLess:`Meno`,eventOpen:`Apri`,eventRunning:`In corso`,showEvents:`Mostra cosa hanno fatto gli agenti`,hideEvents:`Solo la conversazione`,cardView:`Vedi`,cardClose:`Chiudi`,renameChat:`Rinomina`,chatTitleLabel:`Titolo`,chatTitleHint:`Vuoto: il titolo scritto dalla chat.`,chatStarted:`Iniziata il {at}`,chatLastMessage:`ultimo messaggio il {at}`,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`,editMessage:`Modifica`,editingMessage:`Modifichi un messaggio: inviato, la chat torna a quel punto.`,cancelEdit:`Annulla`,rewindTitle:`Tornare a questo messaggio?`,rewindText:`Ciò che è venuto dopo lascia la chat e la memoria dell'agente. Ciò che hanno fatto i suoi passi resta fatto:`,stop:`Ferma`},G={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.`,approvalHeader:`Freigabe`,approve:`Freigeben`,reject:`Ablehnen`,approveQuestion:`Freigeben? {action}`,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`,reasoningNow:`Denkt nach…`,reasonedFor:`{seconds} s nachgedacht`,reasoned:`Nachgedacht`,processDetails:`Überlegungen und Schritte`,stepsLabel:`Schritte des Agenten`,newInstance:`Neue Instanz von "{label}"`,chatHistory:`Chatverlauf`,earlierSession:`Vorherige Sitzung`,thisSession:`Diese Sitzung`,continueSession:`Diese Sitzung fortsetzen`,sessionOf:`Sitzung vom {at}`,eventMore:`Mehr`,eventLess:`Weniger`,eventOpen:`Öffnen`,eventRunning:`Läuft`,showEvents:`Zeigen, was die Agenten getan haben`,hideEvents:`Nur das Gespräch`,cardView:`Ansehen`,cardClose:`Schließen`,renameChat:`Umbenennen`,chatTitleLabel:`Titel`,chatTitleHint:`Leer: der aus dem Chat geschriebene Titel.`,chatStarted:`Begonnen am {at}`,chatLastMessage:`letzte Nachricht am {at}`,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`,editMessage:`Bearbeiten`,editingMessage:`Du bearbeitest eine Nachricht: gesendet, geht der Chat dorthin zurück.`,cancelEdit:`Abbrechen`,rewindTitle:`Zu dieser Nachricht zurückgehen?`,rewindText:`Was danach kam, verlässt den Chat und das Gedächtnis des Agenten. Was seine Schritte getan haben, bleibt getan:`,stop:`Stoppen`},se=`llmnative.agentico.entityChat`,K;function ce(e){se=e.storageKey,K=e.backend}var le=()=>!!K,ue=({synced:e,...t})=>t;function q(e){if(!K)return;let t=X(e.scopeId,e.subagentId,e.entityId);Promise.resolve(K.save(ue(e))).then(()=>{let e=fe(),n=e.find(e=>X(e.scopeId,e.subagentId,e.entityId)===t);n&&!n.synced&&Y(e.map(e=>e===n?{...e,synced:!0}:e))},()=>void 0)}async function J(e){if(!K)return;let t=(await K.load(e)).map(de).filter(t=>t!==null&&t.scopeId===e),n=e=>e.changedAt??e.savedAt,r=fe(),i=r.filter(t=>t.scopeId!==e),a=r.filter(t=>t.scopeId===e),o=t.map(e=>{let t=a.find(t=>X(t.scopeId,t.subagentId,t.entityId)===X(e.scopeId,e.subagentId,e.entityId));return t&&n(t)>n(e)?(q(t),t):{...e,synced:!0}}),s=a.filter(e=>!e.synced&&!t.some(t=>X(t.scopeId,t.subagentId,t.entityId)===X(e.scopeId,e.subagentId,e.entityId)));Y([...i,...o,...s]);for(let e of s)q(e)}function de(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 fe(){try{let e=localStorage.getItem(se);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(de).filter(e=>e!==null):[]}catch{return[]}}var pe=new Set;function me(e){return pe.add(e),()=>{pe.delete(e)}}function Y(e){try{localStorage.setItem(se,JSON.stringify(e))}catch{}for(let e of[...pe])e()}var X=(e,t,n)=>`${e}:${t}:${n}`;function he(e,t,n){let r=X(e,t,n);return fe().find(e=>X(e.scopeId,e.subagentId,e.entityId)===r)??null}function ge(e){let t=X(e.scopeId,e.subagentId,e.entityId),n=fe(),r=n.find(e=>X(e.scopeId,e.subagentId,e.entityId)===t),i=Date.now(),a=n.filter(e=>e!==r),o={...e,savedAt:i,changedAt:i,startedAt:r?Q(r):i,...r?.name?{name:r.name,namedBy:r.namedBy}:{},...r?.synced?{synced:!0}:{}};a.push(o),Y(a),q(o)}var _e=new Set([U,W,G].map(e=>e.retryMessage.trim().toLowerCase())),ve=e=>e.kind===`user`&&!!e.detail?.trim()&&!e.retry&&!_e.has(e.detail.trim().toLowerCase()),ye=e=>{let t=(e.activity.find(ve)?.detail??``).trim().split(`
15
+ `)[0].trim();return t.length>80?`${t.slice(0,80).trimEnd()}…`:t},Z=e=>e.name||ye(e)||e.title||e.entityId,be=e=>e.activity.some(ve),xe=e=>e.kind===`user`&&!ve(e)&&!!e.detail?.trim();function Se(e,t,n,r,i=`person`){let a=X(e,t,n),o=fe(),s=o.find(e=>X(e.scopeId,e.subagentId,e.entityId)===a);if(!s||i===`model`&&s.namedBy===`person`)return!1;let c=r.trim().replace(/\s+/g,` `).slice(0,120),{name:l,namedBy:u,...d}=s,f=c?{...d,name:c,namedBy:i,changedAt:Date.now()}:{...d,changedAt:Date.now()};return Y(o.map(e=>e===s?f:e)),q(f),!0}var Q=e=>e.startedAt??e.savedAt;function Ce(e,t,n){let r=X(e,t,n);Y(fe().filter(e=>X(e.scopeId,e.subagentId,e.entityId)!==r)),K&&Promise.resolve(K.remove(e,t,n)).catch(()=>void 0)}function we(e){return fe().filter(t=>t.scopeId===e).sort((e,t)=>Q(t)-Q(e))}var Te=(e,t)=>`entitychat-${e}-${t}`;function Ee(e){return x(e.subagentId)?.thread?.(e.params)||void 0}function De(e,t,n){let r=we(e),i=n?r.find(e=>Te(e.subagentId,e.entityId)===n):void 0,a=i?Q(i):1/0;return r.filter(e=>e!==i&&Q(e)<a&&Ee(e)===t).sort((e,t)=>Q(t)-Q(e))}function Oe(e,t){let n=Array.from({length:e.length+1},()=>[]),r=[],i=-1/0;for(let t of e)t!==void 0&&(i=t),r.push(i);for(let i of[...t].sort((e,t)=>e.at-t.at)){let t=r.findIndex(e=>e>i.at);n[t===-1?e.length:t].push(i)}return n}var ke=480,Ae=4;async function je(e,t){if(e.type.startsWith(`image/`)&&typeof document<`u`&&typeof createImageBitmap==`function`)try{let n=await createImageBitmap(e),r=Math.min(1,t/Math.max(n.width,n.height)),i=document.createElement(`canvas`);i.width=Math.max(1,Math.round(n.width*r)),i.height=Math.max(1,Math.round(n.height*r));let a=i.getContext(`2d`);return a?(a.fillStyle=`#fff`,a.fillRect(0,0,i.width,i.height),a.drawImage(n,0,0,i.width,i.height),n.close?.(),i.toDataURL(`image/jpeg`,.8)):void 0}catch{return}}async function Me(e,t=480,n=4){let r=e.filter(e=>e.type.startsWith(`image/`)).slice(0,n);return(await Promise.all(r.map(async e=>({name:e.name,src:await je(e,t)})))).filter(e=>!!e.src)}var Ne={en:{agentico:U},it:{agentico:W},de:{agentico:G}};function $(){let{dict:e}=(0,l.useI18n)(),t=e.agentico;return t?{...U,...t}:U}var Pe=`agentico-orchestrator`,Fe=(0,u.createContext)(null);function Ie({children:e,scope:t=null,person:n=null,threadEvents:r=null}){let[i,a]=(0,u.useState)(null),o=(0,u.useRef)(null);(0,u.useEffect)(()=>{o.current=i},[i]);let[s,c]=(0,u.useState)(!1),l=t?.id;(0,u.useEffect)(()=>{l&&J(l).catch(()=>void 0)},[l]);let f=(0,u.useCallback)(e=>{let t=o.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;a(n)},[]),p=(0,u.useCallback)(e=>{a(t=>t&&t.id===e?null:t)},[]),m=(0,u.useCallback)(()=>c(e=>!e),[]),h=(0,u.useCallback)(()=>c(!0),[]),[g,_]=(0,u.useState)(null),[v,y]=(0,u.useState)(void 0),[b,S]=(0,u.useState)(void 0),[C,ee]=(0,u.useState)(void 0),[w,T]=(0,u.useState)(null),[E,te]=(0,u.useState)(null),[D,O]=(0,u.useState)(void 0),[k,j]=(0,u.useState)([]),M=(0,u.useCallback)((e,t,n=null)=>{j(r=>{let i=r.filter(t=>t.id!==e);return t?[...i,{id:e,text:t,card:n}]:i})},[]),N=k.length>0?k[k.length-1]:null,[P,F]=(0,u.useState)([]),ne=(0,u.useCallback)((e,t)=>{F(n=>{let r=n.filter(t=>t.id!==e);return t?[...r,{id:e,...t}]:r})},[]),I=(0,u.useMemo)(()=>P.map(e=>({subagentId:e.subagentId,componentKey:e.componentKey,onResult:e.onResult,pinnedEntityId:e.pinnedEntityId})),[P]),L=(0,u.useMemo)(()=>{let e=new Map;for(let t of P)e.set(t.subagentId,{subagentId:t.subagentId,componentKey:t.componentKey,onResult:t.onResult,contextInfo:t.contextInfo});return[...e.values()]},[P]),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]),re=(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(`
16
+ `);return`${A().multipleCandidates}\n\n${e}`},[R])??N?.text??null,ie=R.length>0?null:N?.card??null,B=(0,u.useMemo)(()=>[...new Set(I.map(e=>e.subagentId))],[I]),V=B.length===1?B[0]:B.length===0?N?.card?.subagentId??null:null,H=(0,u.useCallback)((e,t)=>{h();let n=o.current;if(n?.id===`agentico-orchestrator`)return;let r=V&&n?.id.startsWith(`subagent-${V}-`)?n:void 0;te(r?{taskId:r.id,activity:[...r.precedingActivity??[],...r.agent.activity]}:null),_(e),y(t?.extraDestinations),S(t?.attachments),ee(t?.model),O(t?.scopedSubagentId),T(crypto.randomUUID())},[h,V]),ae=(0,u.useCallback)((e,t,n,r,i,s)=>{if(!n||!r)return;let c=o.current;if(!c||c.id!==n)return;let l=c.agent.snapshot();l&&(ge({scopeId:r,subagentId:e,entityId:t,params:i,title:s,history:l.history,activity:[...c.precedingActivity??[],...l.activity]}),a(e=>e&&e.id===n?{...e,savedToDisk:!0}:e))},[]),[oe,U]=(0,u.useState)(null),[W,G]=(0,u.useState)(null),se=(0,u.useCallback)((e,t,n)=>{h(),U({subagentId:e,entityId:t,snapshot:n}),G(crypto.randomUUID())},[h]),[K,ce]=(0,u.useState)(null),[le,ue]=(0,u.useState)(null),q=(0,u.useCallback)((e,t)=>{h(),p(Pe),ce({subagentId:e,extraDestinations:t}),ue(crypto.randomUUID())},[h,p]),[de,fe]=(0,u.useState)(null),[pe,me]=(0,u.useState)(null),Y=(0,u.useCallback)((e,t,n)=>{ce(null),fe({subagentId:e,params:t,extraDestinations:n}),me(crypto.randomUUID())},[]),[X,he]=(0,u.useState)(null),[_e,ve]=(0,u.useState)(null),ye=(0,u.useCallback)((e,t,n)=>{h(),he({subagentId:e,params:t,...n}),ve(crypto.randomUUID())},[h]),Z=(0,u.useCallback)(()=>{let e=o.current;e&&e.onDismiss()},[]),be=(0,u.useMemo)(()=>({scope:t,person:n,threadEvents:r,task:i,isOpen:s,openTask:f,closeTask:p,toggleOpen:m,pendingGoal:g,startOrchestrator:H,pageContext:re,pageContextCard:ie,setPageContext:M,scopedSubagentId:V,pendingScopedSubagentId:D,componentAnchors:I,anchoredUserMessages:z,registerComponentAnchor:ne,openPanel:h,pendingExtraDestinations:v,pendingAttachments:b,pendingModel:C,orchestratorRunId:w,pendingCarryOver:E,commitEntityChat:ae,resumeEntityChat:se,pendingResume:oe,resumeRunId:W,dismissForeignTask:Z,pendingManualEntry:K,manualEntryRunId:le,startManualEntry:q,pendingResumeWithAI:de,resumeWithAIRunId:pe,resumeWithAI:Y,startSubagent:ye,pendingStart:X,startRunId:_e}),[t,n,r,i,s,f,p,m,g,H,re,ie,M,V,D,I,z,ne,h,v,b,C,w,E,ae,se,oe,W,Z,K,le,q,de,pe,Y,ye,X,_e]);return(0,d.jsx)(Fe.Provider,{value:be,children:e})}function Le(){let e=(0,u.useContext)(Fe);if(!e)throw Error(`useAgentico must be used inside AgenticoProvider`);return e}var Re=`llmnative.agentico.threadEvents`;function ze(){let[e,t]=(0,u.useState)(()=>{try{return localStorage.getItem(Re)!==`off`}catch{return!0}});return[e,e=>{t(e);try{localStorage.setItem(Re,e?`on`:`off`)}catch{}}]}function Be(e,t,n,r=!0){let{threadEvents:i}=Le(),[a,o]=(0,u.useState)([]);return(0,u.useEffect)(()=>{if(!i||!e||!r){o([]);return}let a=!0,s=()=>{Promise.resolve(i.load(e,t,n)).then(e=>{a&&o(e.filter(e=>e.at>=t&&e.at<n))},()=>void 0)};s();let c=i.subscribe?.(e,s);return()=>{a=!1,c?.()}},[i,e,t,n,r]),a}function Ve({event:e}){let t=$(),{locale:n}=(0,l.useI18n)(),[r,i]=(0,u.useState)(!1),a=new Date(e.at).toLocaleString(n,{dateStyle:`short`,timeStyle:`short`});return(0,d.jsxs)(`li`,{className:`flex items-start gap-2 py-1 text-xs`,"aria-label":`${e.author.name}: ${e.title}`,"aria-busy":e.running||void 0,children:[(0,d.jsx)(`span`,{className:`flex w-6 shrink-0 justify-center pt-px`,children:(0,d.jsx)(Qe,{author:e.author})}),(0,d.jsxs)(`div`,{className:`min-w-0 flex-1 rounded-md border px-2 py-1 ${e.running?`border-primary/40 bg-primary/5`:`border-border/60 bg-muted/30`}`,children:[(0,d.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5`,children:[(0,d.jsx)(`span`,{className:`font-medium text-foreground`,children:e.author.name}),e.running?(0,d.jsx)(l.Icon,{name:`loader-circle`,size:12,className:`shrink-0 animate-spin text-primary`,"aria-label":t.eventRunning}):e.icon&&(0,d.jsx)(l.Icon,{name:e.icon,size:12,className:`shrink-0 text-muted-foreground`}),(0,d.jsx)(`span`,{className:`min-w-0 break-words text-muted-foreground`,children:e.title}),e.badge&&(0,d.jsx)(l.Badge,{variant:e.badge.variant??`light`,children:e.badge.label}),(0,d.jsxs)(`span`,{className:`ms-auto flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground`,children:[(0,d.jsx)(`time`,{dateTime:new Date(e.at).toISOString(),children:a}),e.body&&(0,d.jsx)(`button`,{type:`button`,onClick:()=>i(e=>!e),"aria-expanded":r,title:r?t.eventLess:t.eventMore,className:`rounded hover:text-foreground`,children:(0,d.jsx)(l.Icon,{name:r?`chevron-up`:`chevron-down`,size:12})}),e.href&&(0,d.jsx)(`a`,{href:e.href,target:`_blank`,rel:`noreferrer`,title:t.eventOpen,"aria-label":t.eventOpen,className:`rounded hover:text-foreground`,children:(0,d.jsx)(l.Icon,{name:`external-link`,size:12})})]})]}),r&&e.body&&(0,d.jsx)(l.ChatMarkdown,{content:e.body,tone:`muted`,className:`mt-1 break-words text-xs leading-relaxed`})]})]})}function He(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(...He(u)),l}function Ue(e){let t=[],n=/```(\w+)?\n?([\s\S]*?)```/g,r=0,i;for(;i=n.exec(e);)i.index>r&&t.push(...He(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(...He(e.slice(r))),t}function We({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 Ge({text:e,tone:t}){let n=Ue(e);return(0,d.jsx)(d.Fragment,{children:n.map((e,n)=>e.type===`code`?(0,d.jsx)(We,{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 Ke(){let[e]=(0,u.useState)(()=>Date.now()),[t,n]=(0,u.useState)(e);(0,u.useEffect)(()=>{let e=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(e)},[]);let r=Math.floor((t-e)/1e3);return r<10?null:(0,d.jsxs)(`span`,{className:`tabular-nums`,children:[` · `,Math.floor(r/60),`:`,String(r%60).padStart(2,`0`)]})}function qe({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 Je(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,Xe=e=>e.some(e=>e.status===`stopped`||e.status===`error`);function Ze({previews:e}){let[t,n]=(0,u.useState)(null);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.map(e=>(0,d.jsx)(`button`,{type:`button`,onClick:()=>n(e),title:e.name,className:`overflow-hidden rounded-md border border-border/60 bg-background`,children:(0,d.jsx)(`img`,{src:e.src,alt:e.name,className:`block max-h-40 max-w-full object-contain`})},e.name))}),t&&(0,d.jsx)(l.Modal,{title:t.name,size:`lg`,onClose:()=>n(null),children:(0,d.jsx)(`img`,{src:t.src,alt:t.name,className:`mx-auto block max-h-[70vh] max-w-full object-contain`})})]})}function Qe({author:e,size:t=20}){return e.avatarUrl?(0,d.jsx)(l.ImageAvatar,{src:e.avatarUrl,title:e.name,alt:e.name,width:t,height:t}):(0,d.jsx)(l.Identicon,{value:e.name,size:t,title:e.name})}var $e=`w-6`;function et(e){if(!e||e.kind!==`thinking`||!e.parts)return[];let t=[];for(let n of e.parts){if(n.type!==`reasoning`&&n.type!==`tool`)break;t.push(n)}return t}function tt({parts:e,open:t,onToggle:n}){let r=$(),i=e.filter(e=>e.type===`reasoning`),a=e.filter(e=>e.type===`tool`),o=i.some(e=>e.streaming),s=a.filter(e=>e.status===`running`).at(-1),c=Math.round(i.reduce((e,t)=>e+(t.duration??0),0)),u=[...i.length?[o?r.reasoningNow:c>0?(0,l.interpolate)(r.reasonedFor,{seconds:c}):r.reasoned]:[],...a.length?[s?.label??(a.length===1?r.oneStep:(0,l.interpolate)(r.steps,{count:a.length}))]:[]],f=o||!!s,p=a.some(e=>e.status===`error`);return(0,d.jsxs)(`button`,{type:`button`,onClick:n,"aria-expanded":t,title:r.processDetails,className:`inline-flex min-w-0 items-center gap-1 rounded text-xs text-muted-foreground hover:text-foreground`,children:[(0,d.jsx)(l.Icon,{name:f?`loader-circle`:p?`circle-alert`:i.length?`brain`:`list-checks`,size:12,className:`shrink-0 ${f?`animate-spin`:``}`}),(0,d.jsx)(`span`,{className:`truncate`,children:u.join(` · `)}),(0,d.jsx)(l.Icon,{name:t?`chevron-up`:`chevron-down`,size:12,className:`shrink-0`})]})}function nt({entry:e,pinned:t=!0,actions:n,cut:r=!1,showAuthor:i=!1}){let a=$(),o=(0,u.useRef)(null),[s,c]=(0,u.useState)(!1),[f,p]=(0,u.useState)(!1);(0,u.useLayoutEffect)(()=>{let e=o.current;e&&p(e.scrollHeight>97)},[e.detail,e.attachmentNames]);let m=f&&!s,h=n?.available(e)&&r?(0,d.jsx)(l.ActionButton,{icon:`rotate-ccw`,ariaLabel:a.retry,title:a.retry,variant:`link`,className:`p-1 text-muted-foreground hover:text-foreground`,disabled:n.disabled,onClick:()=>n.onRetry(e)}):null,g=n?.available(e)?(0,d.jsx)(`span`,{className:`opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100`,children:(0,d.jsx)(l.ActionButton,{icon:`pencil`,ariaLabel:a.editMessage,title:a.editMessage,variant:`link`,className:`p-1 text-muted-foreground hover:text-foreground`,disabled:n.disabled,onClick:()=>n.onEdit(e)})}):null,_=t=>(0,d.jsxs)(`div`,{className:`${t?`w-full`:`max-w-[85%]`} rounded-lg bg-primary/10 text-xs text-foreground`,children:[(0,d.jsxs)(`div`,{ref:o,className:`space-y-1 px-2.5 pt-1.5 ${m?`overflow-hidden`:``}`,style:m?{maxHeight:Ye}:void 0,children:[e.attachmentPreviews&&e.attachmentPreviews.length>0&&(0,d.jsx)(Ze,{previews:e.attachmentPreviews}),e.attachmentNames&&e.attachmentNames.some(t=>!e.attachmentPreviews?.some(e=>e.name===t))&&(0,d.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.attachmentNames.filter(t=>!e.attachmentPreviews?.some(e=>e.name===t)).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??``})]}),f&&(0,d.jsxs)(`button`,{type:`button`,onClick:()=>c(e=>!e),className:`relative flex w-full items-center justify-center rounded-b-lg py-1 text-muted-foreground hover:bg-primary/15`,title:s?`Comprimi`:`Espandi`,children:[m&&(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:s?`chevron-up`:`chevron-down`,size:12})]})]});return i?(0,d.jsxs)(`div`,{className:`${t?`sticky top-0 z-20 border-b border-border/40`:``} group flex items-start gap-2 bg-background py-1.5`,children:[(0,d.jsxs)(`span`,{className:`flex shrink-0 flex-col items-center ${$e}`,children:[e.author?(0,d.jsx)(Qe,{author:e.author}):(0,d.jsx)(`span`,{className:`flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground`,"aria-hidden":!0,children:(0,d.jsx)(l.Icon,{name:`user`,size:12})}),h,g]}),(0,d.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[e.author&&(0,d.jsx)(`div`,{className:`pb-0.5 text-xs font-medium text-foreground`,children:e.author.name}),_(!0)]})]}):(0,d.jsxs)(`div`,{className:`${t?`sticky top-0 z-20 border-b border-border/40`:``} group flex items-start justify-end gap-1 bg-background py-1.5`,children:[n?.available(e)&&(0,d.jsxs)(`span`,{className:`flex shrink-0 items-center`,children:[h,g]}),_(!1)]})}var rt={running:`loader-circle`,done:`check`,error:`x`,stopped:`circle-slash`};function it({steps:e}){let t=$(),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:rt[e.status]}))}]})}function at({entry:e,part:t,questions:n}){let r=$(),[i,a]=(0,u.useState)(!1),o=!!(n?.onCardAction&&n.canAnswer(e.id)&&!t.outcome),s=t.outcome?.status===`done`?`text-success`:t.outcome?.status===`error`?`text-destructive`:`text-muted-foreground`;return(0,d.jsxs)(l.Card,{headerClassName:`flex items-center justify-between gap-2 px-3 py-2`,bodyClassName:`px-3 py-2`,header:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(`span`,{className:`min-w-0 text-xs font-semibold text-foreground`,children:t.title}),t.badge&&(0,d.jsx)(l.Badge,{variant:t.badge.variant??`info`,children:t.badge.label})]}),footer:(0,d.jsxs)(`div`,{className:`space-y-1.5 px-3 py-2`,children:[(0,d.jsxs)(`div`,{className:`flex items-center gap-1`,children:[t.details&&(0,d.jsx)(l.ActionButton,{icon:`eye`,ariaLabel:r.cardView,title:r.cardView,variant:`outline-secondary`,onClick:()=>a(!0)}),(t.actions??[]).filter(e=>e.variant!==`primary`&&e.icon).map(r=>(0,d.jsx)(l.LoadingButton,{icon:r.icon,ariaLabel:r.label,title:r.label,variant:r.variant??`outline-secondary`,disabled:!o,onClick:()=>n.onCardAction(e.id,t.id,r.id)},r.id)),(0,d.jsx)(`span`,{className:`ms-auto flex items-center gap-1`,children:(t.actions??[]).filter(e=>e.variant===`primary`||!e.icon).map(r=>(0,d.jsx)(l.LoadingButton,{...r.icon?{icon:r.icon}:{},label:r.label,variant:r.variant??`outline-primary`,disabled:!o,onClick:()=>n.onCardAction(e.id,t.id,r.id)},r.id))})]}),t.outcome&&(0,d.jsxs)(`p`,{className:`text-xs ${s}`,children:[t.outcome.text,t.outcome.link&&(0,d.jsxs)(d.Fragment,{children:[` `,(0,d.jsx)(`a`,{className:`underline`,href:t.outcome.link.url,target:`_blank`,rel:`noopener noreferrer`,children:t.outcome.link.label})]})]})]}),children:[t.body?(0,d.jsx)(l.ChatMarkdown,{content:t.body,className:`break-words text-xs leading-relaxed text-foreground`}):null,i&&t.details&&(0,d.jsx)(l.Modal,{title:t.title,position:`right`,size:`lg`,onClose:()=>a(!1),footer:(0,d.jsx)(l.ActionButton,{label:r.cardClose,variant:`outline-secondary`,onClick:()=>a(!1)}),children:(0,d.jsx)(l.ChatMarkdown,{content:t.details,className:`break-words text-sm leading-relaxed text-foreground`})})]})}function ot(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 st({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 ct({entry:e,questions:t,hiddenPartId:n,skip:r}){let i=(e.parts??[]).filter(e=>(e.type!==`questions`||e.id!==n)&&!r?.has(e.id)),a=[];for(let e of i){let t=a.at(-1);e.type===`tool`?t&&`steps`in t?t.steps.push(e):a.push({key:`tool-${e.id}`,steps:[e]}):a.push({key:`${e.type}-${e.id}`,part:e})}return(0,d.jsx)(`div`,{className:`space-y-2`,children:a.map(n=>{if(`steps`in n)return(0,d.jsx)(it,{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):r.type===`card`?(0,d.jsx)(at,{entry:e,part:r,questions:t},n.key):(0,d.jsx)(st,{entry:e,part:r,questions:t},n.key)})})}function lt({entry:e,questions:t,hiddenPartId:n,skip:r}){let i=$();if(e.kind===`thinking`&&e.parts){let a=e.status===`error`||e.status===`stopped`||e.status===`running`,o=r?e.parts.filter(e=>!r.has(e.id)).length:e.parts.length;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[o>0&&(0,d.jsx)(ct,{entry:e,questions:t,hiddenPartId:n,skip:r}),a&&(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5 ${o>0?`mt-1`:``}`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(qe,{status:e.status})}),(0,d.jsxs)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:[Je(e,i),e.status===`running`&&(0,d.jsx)(Ke,{})]})]})]})}let a=e.kind===`thinking`&&e.detail?Ue(e.detail):[],o=a.filter(e=>e.type===`code`),s=a.filter(e=>e.type===`text`&&e.content.trim()),c=e.kind===`thinking`?Je(e,i):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)(qe,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:c})]}),o.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-1`,children:o.map((e,t)=>(0,d.jsx)(We,{content:e.content,language:e.language},t))}),s.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-2`,children:s.map((e,t)=>(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:`muted`,className:`break-words text-xs leading-relaxed`},t))})]})}function ut({parts:e}){return(0,d.jsx)(`div`,{className:`mb-1 space-y-1 border-l-2 border-border pl-2 text-xs text-muted-foreground`,children:e.map(e=>e.type===`reasoning`?(0,d.jsx)(l.ChatMarkdown,{content:e.text,tone:`muted`,streaming:e.streaming,className:`break-words text-xs leading-relaxed`},e.id):e.type===`tool`?(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,d.jsx)(l.Icon,{name:rt[e.status],size:12,className:`mt-0.5 shrink-0 ${e.status===`running`?`animate-spin`:``}`}),(0,d.jsx)(`span`,{className:`min-w-0 break-words ${e.status===`error`?`text-destructive`:``}`,children:e.label})]},e.id):null)})}function dt({speaker:e,entries:t,questions:n,docked:r}){let i=et(t[0]),a=i.length?new Set(i.map(e=>e.id)):void 0,[o,s]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`flex items-start gap-2 pt-1.5`,children:[(0,d.jsx)(`span`,{className:`flex shrink-0 justify-center pt-px ${$e}`,children:(0,d.jsx)(Qe,{author:e})}),(0,d.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,d.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-2 pb-0.5`,children:[(0,d.jsx)(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.name}),i.length>0&&(0,d.jsx)(tt,{parts:i,open:o,onToggle:()=>s(e=>!e)})]}),o&&i.length>0&&(0,d.jsx)(ut,{parts:i}),(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:t.map((e,t)=>(0,d.jsx)(lt,{entry:e,questions:n,hiddenPartId:r?.entry.id===e.id?r.part.id:void 0,...t===0&&a?{skip:a}:{}},e.id))})]})]})}function ft({activity:e,questions:t,docked:n,pinUserMessages:r=!0,messageActions:i,speaker:a,showAuthors:o,events:s}){if(e.length===0&&!s?.length)return null;let c=o??(!!a||e.some(e=>e.kind===`user`&&e.author)),l=[];for(let t of e)t.kind===`user`||l.length===0?l.push(t.kind===`user`?{user:t,entries:[]}:{entries:[t]}):l[l.length-1].entries.push(t);let f=Oe(l.map(e=>(e.user??e.entries[0])?.at),s??[]);return(0,d.jsxs)(`ul`,{className:`space-y-0.5`,children:[l.map((e,o)=>(0,d.jsxs)(u.default.Fragment,{children:[f[o].map(e=>(0,d.jsx)(Ve,{event:e},e.id)),(0,d.jsxs)(`li`,{children:[e.user&&(0,d.jsx)(nt,{entry:e.user,pinned:r,actions:i,cut:Xe(e.entries),showAuthor:c}),a&&e.entries.length>0?(0,d.jsx)(dt,{speaker:a,entries:e.entries,questions:t,docked:n}):e.entries.length>0&&(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:e.entries.map(e=>(0,d.jsx)(lt,{entry:e,questions:t,hiddenPartId:n?.entry.id===e.id?n.part.id:void 0},e.id))})]})]},e.user?.id??e.entries[0]?.id)),f[l.length].map(e=>(0,d.jsx)(Ve,{event:e},e.id))]})}var pt=420,mt=320,ht=`60vw`,gt=`agentico:panel-width`;function _t(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 vt(e,t,n){return Math.round(Math.min(Math.max(e,t),Math.max(t,n)))}function yt(){try{let e=window.localStorage.getItem(gt),t=e===null?NaN:Number(e);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function bt(e){try{e===null?window.localStorage.removeItem(gt):window.localStorage.setItem(gt,String(e))}catch{}}function xt(){return typeof window>`u`?1/0:window.innerWidth}function St({defaultWidth:e=420,minWidth:t=320,maxWidth:n=ht,onWidthChange:r}){let[i,a]=(0,u.useState)(xt),[o,s]=(0,u.useState)(()=>yt()??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,_t(n,i)),d=vt(o,c,l);return(0,u.useEffect)(()=>{r?.(d)},[d]),{width:d,min:c,max:l,set:(0,u.useCallback)(e=>s(vt(e,c,l)),[c,l]),commit:(0,u.useCallback)(e=>bt(vt(e,c,l)),[c,l]),reset:(0,u.useCallback)(()=>{s(e),bt(null)},[e])}}function Ct({width:e,min:t,max:n,onResize:r,onCommit:i,onReset:a}){let o=$(),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 wt({className:e=``}){let{isOpen:t,toggleOpen:n,task:r}=Le(),i=$(),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 Tt=`llmnative-cms.selectedAIModel`;function Et(){try{return localStorage.getItem(Tt)??``}catch{return``}}function Dt(e){try{e?localStorage.setItem(Tt,e):localStorage.removeItem(Tt)}catch{}}function Ot(){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)(Et);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:(Dt(``),``))}).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=>{Dt(e),s(e)}}}var kt=`approval`;function At(e,t){return typeof e.needsApproval==`function`?e.needsApproval(t):e.needsApproval===!0}function jt(e,t,n){let r=e[0]?.values??[],i=r.filter(e=>e!==t&&e!==n).join(` `).trim();return{approved:r.includes(t)&&!r.includes(n),...i?{reason:i}:{}}}var Mt=20,Nt=26e4;function Pt(e){return e.filter(e=>!l.PromptUtils.isTextAttachment(e.mimeType)||e.base64.length<=Nt)}function Ft(e){return e.map(e=>e.status!==`running`&&!e.parts?.some(e=>e.type===`tool`&&e.status===`running`||(e.type===`text`||e.type===`reasoning`)&&e.streaming)?e:{...e,status:e.status===`running`?`stopped`:e.status,...e.parts?{parts:e.parts.map(e=>e.type===`tool`&&e.status===`running`?{...e,status:`stopped`}:(e.type===`text`||e.type===`reasoning`)&&e.streaming?{...e,streaming:!1}:e)}:{}})}function It(e,t={}){let{defaultEnabled:n=!1}=t,r=(0,u.useRef)(t.author);r.current=t.author;let[i,a]=(0,u.useState)(n),{hasProviders:o,modelsByProvider:s,modelsLoading:c,selectedModel:d,setSelectedModel:p}=Ot(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),[x,S]=(0,u.useState)(!1),[C,ee]=(0,u.useState)([]),T=(0,u.useRef)([]),E=(e,t)=>{ee(n=>{let r=typeof e==`function`?e(n):e;if(t?.stamp!==!1){let e=new Set(n.map(e=>e.id)),t=t=>t.at===void 0&&!e.has(t.id);if(r.some(t)){let e=Date.now();r=r.map(n=>t(n)?{...n,at:e}:n)}}return T.current=r,r})},te=(e,t)=>{t?.some(e=>e.type.startsWith(`image/`))&&Me(t).then(t=>{t.length&&E(n=>n.map(n=>n.id===e?{...n,attachmentPreviews:t}:n))})},D=(0,u.useRef)(new Map),O=$(),k=(0,u.useRef)(O);k.current=O;let j=(0,u.useRef)(null),M=(0,u.useRef)(!1),N=(0,u.useRef)(null),P=(0,u.useRef)(null),F=(0,u.useRef)(null),ne=()=>{F.current?.abort()},I=(0,l.useAIProviderRegistry)()?.registry??{},[L,re]=(0,u.useState)(void 0),ie=(0,u.useRef)(void 0),B=(e,t)=>{if(!t)return!1;if(!e)return!0;let n=(0,l.parseAIModelRef)(t);return!!n&&e.includes(n.provider)},V=(0,u.useMemo)(()=>L?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,t.filter(e=>L.includes(e.provider))]).filter(([,e])=>e.length)):s,[L,s]),H=B(L,d)?d:Object.values(V).flat()[0]?.id??``,ae=i&&H?(0,l.parseAIModelRef)(H):null,oe=ae?I[ae.provider]:null,U=e.executor,W=!!U?.alongside,G=!!U&&!W,se=!U||!!U.canRewind,K=!!U?.attachments,ce=async e=>K&&e?.length?Promise.all(e.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,le=(0,u.useRef)([]),ue=e=>!!e&&le.current.some(t=>t.value===e),q=(0,u.useRef)(!1),[J,de]=(0,u.useState)([]),[fe,pe]=(0,u.useState)(``),me=(0,u.useRef)(``),Y=e=>{me.current=e,pe(e)},X=e=>{let t=U?.models?.(e)??[];le.current=t,de(t);let n=U?.catalogProviders?.(e);ie.current=n,re(n);let r=W&&!B(n,d)?t[0]?.value:void 0;Y(U?.defaultModel?.(e)??r??``)},he=async(e,t,n,r,i)=>{let a=j.current;if(!a||!U)return b(k.current.noActiveSession),null;let o=new AbortController;F.current=o;let s=crypto.randomUUID();E(e=>[...e,{id:s,kind:`thinking`,label:k.current.thinking,status:`running`,parts:[]}]);let c=new Map,l=e=>Math.max(1,Math.round((Date.now()-(c.get(e)??Date.now()))/1e3)),u=e=>({...e,streaming:!1,duration:e.duration??l(e.id)}),d=(e,t)=>E(n=>n.map(n=>{if(n.id!==s)return n;let r=e(n.parts??[]),i=h(r);return{...n,parts:r,...t?{status:t}:{},...i?{detail:i}:{}}})),p=e=>d(t=>m(t,e,u)),g=!1,_=(e,t)=>{t?.id&&t.id!==`text`&&(g=!0),p({type:`text`,id:t?.id??`text`,text:e,streaming:!t?.done})},v=(e,t)=>{let n=t?.id??`reasoning`;c.has(n)||c.set(n,Date.now()),p({type:`reasoning`,id:n,text:e,streaming:!t?.done,...t?.duration===void 0?t?.done?{duration:l(n)}:{}:{duration:t.duration}})},y=e=>p({type:`tool`,id:e.id,label:e.label,status:e.status}),x=e=>p({...e,type:`card`}),S=new Set,C=0,ee=()=>{for(let e of S){let t=D.current.get(e);D.current.delete(e),t?.reject(new DOMException(`The turn was stopped.`,`AbortError`))}S.clear()};o.signal.addEventListener(`abort`,ee);let w=(e,t)=>{C+=1;let n=t?.id??`questions-${C}`;p({type:`questions`,id:n,questions:e});let r=`${s}:${n}`;return o.signal.aborted?Promise.reject(new DOMException(`The turn was stopped.`,`AbortError`)):(S.add(r),new Promise((e,t)=>{D.current.set(r,{resolve:e,reject:t})}))},te=(e,t)=>{d(n=>(t&&!g?m(n,{type:`text`,id:f,text:t,streaming:!1},u):n).map(t=>t.type===`reasoning`&&t.streaming?u(t):t.type===`text`&&t.streaming?{...t,streaming:!1}:t.type===`tool`&&t.status===`running`&&e!==`done`?{...t,status:`stopped`}:t),e),o.signal.removeEventListener(`abort`,ee);for(let e of S)D.current.delete(e);S.clear()},O=e||r?.historyText||``;try{let c=N.current;N.current=null;let l=T.current,u=l.findIndex(e=>e.id===P.current),d=c?{activity:c.fresh?c.activity:(u>=0?l.slice(0,u):l).filter(e=>e.id!==s)}:void 0,f=await U.turn({params:a.params,context:a.context,text:e,first:t,signal:o.signal,...d?{rewound:d}:{},...i?.length?{attachments:i}:{},...n||me.current?{model:n||me.current}:{},...r?{answers:{id:r.id,answers:r.answers}}:{},onText:_,onReasoning:v,onStep:y,onQuestions:w,onCard:x});return te(`done`,f.text),a.history=[...a.history,...O?[{role:`user`,content:O}]:[],{role:`assistant`,content:f.text}],f.result??null}catch(e){return a.history=[...a.history,...O?[{role:`user`,content:O}]:[]],o.signal.aborted?(te(`stopped`),null):(te(`error`),b(z(e)),null)}finally{F.current=null}},ge=async(t,n,r)=>{let i=T.current.find(e=>e.id===t)?.parts?.find(e=>e.type===`card`&&e.id===n),a=j.current;if(!i||!a||!e.onCardAction)return;let o;try{o=await e.onCardAction(a.params,i,r)}catch(e){o={status:`error`,text:z(e)}}o&&E(e=>e.map(e=>e.id===t?{...e,parts:e.parts?.map(e=>e.type===`card`&&e.id===n?{...e,outcome:o}:e)}:e))},_e=async(e,t,n)=>{let r=T.current.find(t=>t.id===e)?.parts?.find(e=>e.type===`questions`&&e.id===t);if(!r||r.type!==`questions`)throw b(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(M.current)throw b(k.current.requestInProgress),Error(k.current.requestInProgress);if(!G||!j.current)throw b(k.current.noActiveSession),Error(k.current.noActiveSession);M.current=!0,v(!0),b(null),i();try{return await he(``,!1,void 0,{id:t,answers:n,historyText:g(r.questions,n)})}finally{M.current=!1,v(!1)}},ve=async(t,n,r)=>{let i=ie.current,a=Object.values(s).flat().find(e=>!i||i.includes(e.provider))?.id,o=r&&B(i,r)?r:B(i,H)?void 0:a,c=o?(0,l.parseAIModelRef)(o):ae,u=c&&j.current?U?.catalogReasoning?.(j.current.params,c.provider):void 0,d=u?{reasoning:u}:{},f=j.current;if(!f)return b(k.current.noActiveSession),null;let p=o?(0,l.parseAIModelRef)(o):ae,m=p?I[p.provider]:null;if(!m||!p)return b(k.current.noProviderAvailable),null;n?.length&&(f.attachmentsRef.current=[...f.attachmentsRef.current??[],...n]);let h=(n??[]).filter(e=>l.PromptUtils.isTextAttachment(e.mimeType)).map(e=>e.base64.length<=Nt?`\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(``),g=Pt(n??[]),_=f.tools.map(e=>({name:e.name,description:e.description,inputSchema:w(e.inputSchema)})),v=(e,t,n,r)=>{let i=k.current,a=`approval-${e}`,o=t.describeApproval?.(n)??t.describeInvocation?.(n)??t.name;E(e=>[...e,{id:a,kind:`thinking`,label:i.approvalHeader,status:`running`,parts:[{type:`questions`,id:kt,questions:[{header:i.approvalHeader,question:i.approveQuestion.replace(`{action}`,o),options:[{label:i.approve},{label:i.reject}],custom:!0}]}]}]);let s=`${a}:${kt}`;return new Promise((e,t)=>{let n=()=>{D.current.delete(s),S(a,`stopped`),t(new DOMException(`The turn was stopped.`,`AbortError`))};if(r.aborted){n();return}r.addEventListener(`abort`,n,{once:!0}),D.current.set(s,{resolve:t=>{r.removeEventListener(`abort`,n),S(a,`done`),e(jt(t,i.approve,i.reject))},reject:t})})},y=new Map(f.tools.map(e=>[e.name,e])),x=new AbortController;F.current=x;let S=(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=f.history,r=t;for(let t=0;t<Mt;t++){let i=crypto.randomUUID();E(e=>[...e,{id:i,kind:`thinking`,label:k.current.thinking,status:`running`}]);let a;try{a=await m.complete({prompt:r,model:p.model,...d,history:n,tools:_.length?_:void 0,signal:x.signal,attachments:t===0?g:void 0,logId:f.logId})}catch(t){return f.history=[...n,...r?[{role:`user`,content:r+h}]:[]],x.signal.aborted?(S(i,`stopped`),e.fallback(f.params,f.context)):(S(i,`error`),b(z(t)),null)}if(f.history=[...n,...r?[{role:`user`,content:r+h}]:[]],!a)return x.signal.aborted?(S(i,`stopped`),e.fallback(f.params,f.context)):(S(i,`error`),b(k.current.noProviderResponse),null);if(a.type===`text`)return S(i,`done`,a.text),e.conversational&&a.text.trim()&&E(e=>e.map(e=>e.id===i?{...e,parts:[{type:`text`,id:`text`,text:a.text}]}:e)),f.history=[...n,...r?[{role:`user`,content:r+h}]:[],{role:`assistant`,content:a.text}],e.parseResponse(a.text,f.params,f.context)||(console.error(`[useAgent] parseResponse ha restituito null — la risposta del modello non è nel formato atteso da questo subagent. Uso il fallback deterministico.`,{responseLength:a.text.length,responsePreview:a.text.length>2e3?`${a.text.slice(0,1e3)}\n…[troncato qui nel log, ${a.text.length} caratteri totali]…\n${a.text.slice(-1e3)}`:a.text,params:f.params}),b(k.current.invalidResponse),e.fallback(f.params,f.context));let o=a.toolCalls.map(e=>{let t=y.get(e.name);return t?.describeIntent??t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`});S(i,`done`,a.text||void 0,a.text?void 0:o);let s=new Map;for(let t of a.toolCalls){let n=y.get(t.name);if(n&&At(n,t.input))try{s.set(t.id,await v(t.id,n,t.input,x.signal))}catch{return e.fallback(f.params,f.context)}}let c=await Promise.all(a.toolCalls.map(async e=>{let t=y.get(e.name),n=t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`,r=s.get(e.id);if(r&&!r.approved){E(t=>[...t,{id:e.id,kind:`tool`,label:n,status:`stopped`}]);let t=A().toolRejected.replace(`{reason}`,r.reason?` (${r.reason})`:``);return{toolCallId:e.id,name:e.name,output:t,isError:!0}}if(E(t=>[...t,{id:e.id,kind:`tool`,label:n,status:`running`}]),!t)return S(e.id,`error`),{toolCallId:e.id,name:e.name,output:`Tool sconosciuto: ${e.name}`,isError:!0};try{let n=await t.execute(e.input);S(e.id,`done`);let r=t.card?.(e.input,n);return r&&E(t=>[...t,{id:`card-${e.id}`,kind:`thinking`,label:``,status:`done`,parts:[{...r,type:`card`}]}]),{toolCallId:e.id,name:e.name,output:n}}catch(t){return S(e.id,`error`),{toolCallId:e.id,name:e.name,output:z(t),isError:!0}}}));n=[...n,...r?[{role:`user`,content:r+h}]:[],{role:`assistant`,content:a.text,toolCalls:a.toolCalls},{role:`tool_result`,results:c}],r=``}let i=crypto.randomUUID();E(e=>[...e,{id:i,kind:`thinking`,label:k.current.thinking,status:`running`}]);let a;try{a=await m.complete({...d,prompt:R(A().stopCallingTools,e.microPromptIds),model:p.model,history:n,signal:x.signal,logId:f.logId})}catch{a=null}if(a?.type===`text`){S(i,`done`,a.text),f.history=[...n,{role:`assistant`,content:a.text}];let t=e.parseResponse(a.text,f.params,f.context);if(t)return t}else S(i,x.signal.aborted?`stopped`:`error`),f.history=n;return x.signal.aborted||b(k.current.tooManyToolTurns),e.fallback(f.params,f.context)}finally{F.current=null}},ye=async(t,n)=>{if(M.current)return b(k.current.requestInProgress),null;M.current=!0,b(null);let a=crypto.randomUUID();n?.openingMessage&&te(a,n.attachments),E(n?.openingMessage?[{id:a,kind:`user`,label:`Tu`,status:`done`,detail:n.openingMessage,...r.current?{author:r.current}:{},...n.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]:[]),v(!0);try{let r=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,r,a)??[];if(j.current={params:t,context:r,tools:o,history:[],logId:crypto.randomUUID(),attachmentsRef:a},G)return S(!0),X(t),await he(n?.openingMessage??``,!0,void 0,void 0,await ce(n?.attachments));if(W){X(t),q.current=!1;let e=n?.model||me.current;if(ue(e))return S(!0),q.current=!0,await he(n?.openingMessage??``,!0,e,void 0,await ce(n?.attachments))}let s=n?.model||void 0,c=s?!!I[(0,l.parseAIModelRef)(s)?.provider??``]:!!oe;if(!i||!c){S(!1);let n=e.fallback(t,r);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.aiDisabledFallback}]),n}S(!0);let u=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,d=R(e.buildPrompt(t,r),e.microPromptIds);return await ve(d,u,s)}catch(e){return b(z(e)),null}finally{M.current=!1,v(!1)}},Z=async(t,n)=>{if(M.current){b(k.current.requestInProgress);return}M.current=!0,b(null),E(Ft(n.activity),{stamp:!1}),v(!0);try{let r=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,r,a)??[];j.current={params:t,context:r,tools:o,history:n.history,logId:crypto.randomUUID(),attachmentsRef:a},(G||W)&&X(t),q.current=!1,S(G||W||i&&!!oe)}catch(e){b(z(e))}finally{M.current=!1,v(!1)}},be=async(t,n)=>{if(M.current)return b(k.current.requestInProgress),null;if(b(null),!t.trim())return b(`Messaggio vuoto.`),null;let i=j.current;if(!i)return b(k.current.noActiveSession),null;M.current=!0,v(!0);let a=crypto.randomUUID();P.current=a,te(a,n?.attachments),E(e=>[...e,{id:a,kind:`user`,label:`Tu`,status:`done`,detail:t,...r.current?{author:r.current}:{},...n?.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{},...n?.retry?{retry:!0}:{},historyAt:i.history.length}]);try{if(G)return await he(t,!1,n?.model||void 0,void 0,await ce(n?.attachments));let r=n?.model||(W?me.current:``);if(W&&ue(r)){let e=!q.current;return q.current=!0,await he(t,e,r,void 0,await ce(n?.attachments))}N.current&&={...N.current,fresh:!1};let a=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,o=R(e.buildFollowUpPrompt(t,i.params,i.context),e.microPromptIds);return await ve(o,a,n?.model||void 0)}catch(e){return b(z(e)),null}finally{M.current=!1,v(!1)}},xe=e=>{let t=j.current,n=C.findIndex(t=>t.id===e),r=C[n],i=r?.detail?.trim();if(!se||!t||!r||r.kind!==`user`||!i)return;if(r.historyAt!==void 0)return r.historyAt;let a=C.slice(0,n).filter(e=>e.kind===`user`&&e.detail?.trim()===i).length,o=0;for(let e=0;e<t.history.length;e+=1){let n=t.history[e];if(n.role===`user`&&n.content.includes(i)){if(o===a)return e;o+=1}}return n===C.map(e=>e.kind===`user`).lastIndexOf(!0)?t.history.length:void 0},Se=e=>xe(e)!==void 0,Q=async(e,t)=>{if(M.current)return b(k.current.requestInProgress),null;let n=j.current,r=C.findIndex(t=>t.id===e),i=C[r],a=xe(e);if(!n||!i||a===void 0)return null;let o=(t??i.detail??``).trim();if(!o)return null;let s=C.slice(0,r);return n.history=n.history.slice(0,a),N.current={activity:s,fresh:!0},E(s),be(o)},Ce=()=>{let t=j.current;if(!t)return null;b(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},we=()=>j.current?{history:j.current.history,activity:C}:null;return{enabled:i,setEnabled:a,hasProviders:o,selectedModel:G||W&&fe?fe:H,setSelectedModel:G?Y:W?e=>{ue(e)?Y(e):(Y(``),p(e))}:p,modelsByProvider:V,modelsLoading:c,running:_,error:y,canContinue:x,remote:G,remoteModels:J,alongside:W,...U?.catalogGroup?{catalogGroup:U.catalogGroup}:{},activity:C,run:ye,resume:Z,sendMessage:be,stop:ne,runFallback:Ce,snapshot:we,answerQuestions:_e,cardAction:ge,rewind:Q,canRewind:se,rewindable:Se,executorAttachments:K,offersFallback:e.offersFallback!==!1}}function Lt(){let e=A();return[e.responseRulesHeading,...e.responseRules.map(e=>`- ${e}`)].join(`
17
+ `)}function Rt(e,t,n){let r=A(),i=n?`\n${r.pageContextHeading}\n${r.pageContextIntro}\n${n}\n`:``;return`${r.orchestratorIntro}
18
18
 
19
19
  ${r.toolsHeading}
20
20
  ${t}
21
21
  ${i}
22
- ${Mt()}
22
+ ${Lt()}
23
23
 
24
24
  ${r.userRequestHeading}
25
- ${e}`}function Pt(e,t){return t?{kind:`handoff`,...t}:{kind:`chat`,message:e}}function Ft(e){return b().filter(t=>!t.onlyWhenAnchored||e===t.id)}function It(e){return{buildContext(e){return{cliCatalog:ne(Ft(e.scopedSubagentId)),handoff:{current:null},collected:{}}},buildPrompt({userGoal:e,pageContext:t},{cliCatalog:n}){return Nt(e,n,t)},buildFollowUpPrompt(e,t,{cliCatalog:n}){return`${e}\n\n${Mt()}\n\n${j().toolsHeading}\n${n}`},parseResponse(e,t,n){let r=n.handoff.current;return n.handoff.current=null,Pt(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=ee({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=Ft(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)(j().handoffQueued,{label:t.label})}}})));return[...o,...s]}}}function Lt(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=$(),c=Ne(),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(H.id,H);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,Lt(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 zt={};function Bt(e){Object.assign(zt,e)}function Vt(e){return zt[e]}function Ht({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 Ut(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 Wt={};function Gt(e){Object.assign(Wt,e)}function Kt(e){return Wt[e]}function qt(e,t=6e3){let n=e.filter(e=>(e.kind===`user`||e.kind===`thinking`)&&e.detail?.trim()&&!xe(e)).map(e=>`${e.kind===`user`?`Person`:`Agent`}: ${e.detail.trim()}`).join(`
25
+ ${e}`}function zt(e,t){return t?{kind:`handoff`,...t}:{kind:`chat`,message:e}}function Bt(e){return b().filter(t=>!t.onlyWhenAnchored||e===t.id)}function Vt(e){return{buildContext(e){return{cliCatalog:ne(Bt(e.scopedSubagentId)),handoff:{current:null},collected:{}}},buildPrompt({userGoal:e,pageContext:t},{cliCatalog:n}){return Rt(e,n,t)},buildFollowUpPrompt(e,t,{cliCatalog:n}){return`${e}\n\n${Lt()}\n\n${A().toolsHeading}\n${n}`},parseResponse(e,t,n){let r=n.handoff.current;return n.handoff.current=null,zt(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=ee({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=Bt(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)(A().handoffQueued,{label:t.label})}}})));return[...o,...s]}}}function Ht(e,t){return e.deriveHistoryTitle?.(t)??e.label}function Ut({manifest:e,result:t,meta:n,taskId:r,initiallyApplied:i,onApplied:a,extraDestinations:o}){let s=$(),c=Le(),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=oe(),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,Ht(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 Wt={};function Gt(e){Object.assign(Wt,e)}function Kt(e){return Wt[e]}function qt({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 Jt(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 Yt={};function Xt(e){Object.assign(Yt,e)}function Zt(e){return Yt[e]}function Qt(e,t=6e3){let n=e.filter(e=>(e.kind===`user`||e.kind===`thinking`)&&e.detail?.trim()&&!xe(e)).map(e=>`${e.kind===`user`?`Person`:`Agent`}: ${e.detail.trim()}`).join(`
26
26
 
27
- `);return n.length>t?`${n.slice(0,t*.7)}\n\n[…]\n\n${n.slice(-t*.3)}`:n}function Jt(e){return(e.trim().split(`
28
- `).map(e=>e.trim()).find(Boolean)??``).replace(/^(title|titolo)\s*:\s*/i,``).replace(/^#+\s*/,``).replace(/^["'«“]+|["'»”]+$/g,``).replace(/[.。]+$/,``).trim().slice(0,80)}function Yt(e,t){try{return e.definition.executor?.catalogProviders?.(e.toParams(t))}catch{return}}function Xt(e,t,n,r,i){let a=Yt(e,t),o=e=>{let t=e?(0,l.parseAIModelRef)(e):null;return!(!t||!i[t.provider]||a&&!a.includes(t.provider))};return o(n)?n:Object.values(r).flat().map(e=>e.id).find(o)}function Zt(e){let t=(0,l.useAIProviderRegistry)()?.registry??{},{modelsByProvider:n,selectedModel:r}=Ct(),i=(0,u.useRef)({registry:t,modelsByProvider:n,selectedModel:r});i.current={registry:t,modelsByProvider:n,selectedModel:r};let a=(0,u.useRef)(new Set),o=(0,u.useCallback)(async(t,n,r)=>{if(!e)return!1;let o=he(e,t,n),s=x(t),c=`${e}:${t}:${n}`;if(!o||!s?.autoTitle||o.name||!be(o)||a.current.has(c))return!1;let{registry:u,modelsByProvider:d,selectedModel:f}=i.current,p=Xt(s,o.params,r??f,d,u),m=p?(0,l.parseAIModelRef)(p):null;if(!m)return!1;a.current.add(c);try{let r=await u[m.provider].complete({prompt:j().chatTitle.replace(`{chat}`,qt(o.activity)),model:m.model,history:[]}),i=r&&r.type===`text`?Jt(r.text):``;return i?Se(e,t,n,i,`model`):!1}catch{return!1}finally{a.current.delete(c)}},[e]),s=Object.keys(n).length>0;return(0,u.useEffect)(()=>{e&&s&&!Qt.has(e)&&(Qt.add(e),(async()=>{for(let t of we(e)){let n=x(t.subagentId);if(n?.autoTitle){if(n.definition.conversational&&!be(t)){Ce(e,t.subagentId,t.entityId);continue}t.name||await o(t.subagentId,t.entityId)}}})())},[e,s,o]),o}var Qt=new Set,$t=()=>({});function en({manifest:e,params:t,extraDestinations:n,precedingActivity:r,taskId:i,resumeSeed:a,model:o,openingMessage:s}){let c=Ne(),f=jt(e.definition,{defaultEnabled:!0,...c.person?{author:c.person}:{}}),p=e.thread?.(t)||void 0,m=e.speaker?.(t),h=c.scope,g=(0,l.useProxy)(),_=(0,u.useRef)(i??`subagent-${e.id}-${crypto.randomUUID()}`).current,[v,y]=(0,u.useState)(null),b=t=>{e.definition.conversational||y(t)},[x,S]=(0,u.useState)([]),[C,ee]=(0,u.useState)(null),w=Vt(e.id),T=w?.kind===`selection`?w:null,[E,D]=(0,u.useState)(null),O=(0,u.useRef)(!1),k=(0,u.useRef)(0),A=(0,u.useRef)(null);v&&v!==A.current&&(A.current=v,k.current=(r?.length??0)+f.activity.length);let j=(0,u.useRef)(!1),M=f.remote||!f.hasProviders||f.selectedModel!==``;(0,u.useEffect)(()=>{!O.current&&M&&(O.current=!0,a?(B.current=!0,f.resume(e.toParams(t),a)):(o&&f.setSelectedModel(o),f.run(e.toParams(t),{model:o,openingMessage:s}).then(e=>{e&&b(e)})))},[M]),(0,u.useEffect)(()=>{if(!v||!h)return;let n=e.autoApplyDestinationIds??[],r=c.componentAnchors.find(t=>t.subagentId===e.id&&t.pinnedEntityId)?.pinnedEntityId,i=W();n.forEach(n=>{let a=i[n];a&&(ee(null),a.apply(v,{scopeId:h.id,dataProvider:h.dataProvider,storageProvider:h.storageProvider,proxyFetch:g},{...t,pinnedEntityId:r}).then(n=>{n?.id&&c.commitEntityChat(e.id,n.id,_,h.id,t,Lt(e,t))}).catch(e=>ee(e instanceof Error?e.message:String(e))))})},[v,f.activity,h]),(0,u.useEffect)(()=>{v&&T&&D(T.defaultSelection(v))},[v,T]);let N=(e,t)=>{D(n=>n&&{...n,[e]:t})},te=e=>b(e),P=(0,u.useMemo)(()=>v&&T&&E?T.applySelection(v,E):v,[v,T,E]),F=(0,u.useMemo)(()=>c.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[c.componentAnchors,e.id]),ne=(0,u.useMemo)(()=>Ut(F,t,_),[F,t,_]),I=(0,u.useMemo)(()=>ne?[ne,...n??[]]:n,[ne,n]),L=e.chatEntityId?.(t),R=Zt(h?.id),z=(0,u.useRef)(!1),B=(0,u.useRef)(!1);(0,u.useEffect)(()=>{let n=!z.current&&f.running,i=z.current&&!f.running;if(z.current=f.running,!n&&!i||!L||!h)return;if(B.current){i&&(B.current=!1);return}let a=f.snapshot();if(!a)return;let o=[...r??[],...a.activity];e.autoTitle&&e.definition.conversational&&!be({activity:o})||(ge({scopeId:h.id,subagentId:e.id,entityId:L,params:t,title:Lt(e,t),history:a.history,activity:o}),i&&e.autoTitle&&R(e.id,L,f.selectedModel))},[f.running]);let re=()=>{j.current=!0,f.running&&f.stop(),c.closeTask(_)},V=(0,u.useRef)(Kt(e.id)??$t).current,H=V({params:t,taskId:_,running:f.running,close:re}),U=e=>{S(t=>t.includes(e)?t:[...t,e])};return(0,u.useEffect)(()=>{j.current||c.openTask({id:_,title:Lt(e,t),icon:e.icon,agent:f,onApplied:e=>b(e),precedingActivity:r,panelExtraAnchorIndex:k.current,onDismiss:re,...p?{thread:p}:{},...m?{speaker:m}:{},...L?{savedToDisk:!0}:{},panelActions:H.content,composerActions:H.actions,composerCommands:H.commands,panelExtra:v?(0,d.jsxs)(d.Fragment,{children:[T&&E?(0,d.jsx)(T.Report,{result:v,selection:E,onChange:N}):w?.kind===`editable`?(0,d.jsx)(w.Report,{result:v,onResultChange:te}):(0,d.jsx)(Ht,{result:P}),C&&(0,d.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Salvataggio automatico non riuscito: `,C]}),(0,d.jsx)(Rt,{manifest:e,result:P,meta:t,taskId:_,initiallyApplied:x,onApplied:U,extraDestinations:I})]}):void 0})},[f.activity,f.running,f.error,f.canContinue,f.selectedModel,f.modelsByProvider,f.hasProviders,f.remoteModels,c.openTask,c.componentAnchors,_,e,t,v,P,E,x,n,r,C,H.content,H.actions,H.commands]),(0,u.useEffect)(()=>()=>{c.closeTask(_)},[c.closeTask,_]),null}function tn({userGoal:e}){let t=$(),n=(0,u.useMemo)(()=>It({unavailable:t.orchestratorUnavailable,continueWithoutAi:t.orchestratorContinueWithoutAi,preparing:t.orchestratorPreparing,collecting:t.orchestratorCollecting}),[]),r=Ne(),i=jt(n,{defaultEnabled:!0,...r.person?{author:r.person}:{}}),[a,o]=(0,u.useState)(null),s=(0,u.useRef)(!1),c=!i.hasProviders||i.selectedModel!==``,l=(0,u.useRef)(r.pendingExtraDestinations),f=(0,u.useRef)(r.pendingAttachments),p=(0,u.useRef)(r.pendingModel),m=(0,u.useRef)(r.pendingScopedSubagentId??r.scopedSubagentId??void 0),h=(0,u.useRef)(r.pendingCarryOver),g=(0,u.useRef)(!1),_=e=>{e&&typeof e==`object`&&e.kind===`handoff`&&(o(e),r.closeTask(Ae))};(0,u.useEffect)(()=>{!s.current&&c&&(s.current=!0,p.current&&i.setSelectedModel(p.current),i.run({userGoal:e,pageContext:r.pageContext,scopedSubagentId:m.current??null},{attachments:f.current,model:p.current,openingMessage:e}).then(e=>{e&&_(e)}))},[c]),(0,u.useEffect)(()=>{g.current||r.openTask({id:Ae,title:`Agentico`,icon:`bot`,agent:i,onApplied:_,scopedSubagentId:m.current,precedingActivity:h.current?.activity,onDismiss:()=>{g.current=!0,i.running&&i.stop(),r.closeTask(Ae)}})},[i.activity,i.running,i.error,i.canContinue,i.selectedModel,i.modelsByProvider,i.hasProviders,r.openTask]),(0,u.useEffect)(()=>()=>{r.closeTask(Ae)},[r.closeTask]);let v=(0,u.useMemo)(()=>[...h.current?.activity??[],...i.activity],[i.activity]);if(!a)return null;let y=x(a.subagentId);return y?(0,d.jsx)(en,{manifest:y,params:a.params,extraDestinations:l.current,model:p.current||void 0,taskId:h.current?.taskId,precedingActivity:v}):null}function nn({manifest:e,extraDestinations:t}){let n=Ne(),r=jt(e.definition,{defaultEnabled:!1,...n.person?{author:n.person}:{}}),i=$(),a=(0,u.useRef)(`manual-${e.id}-${crypto.randomUUID()}`).current,[o,s]=(0,u.useState)(null),[c,f]=(0,u.useState)([]),p=Vt(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 n;try{n=e.manualEntry.fromRawText(t)}catch(e){console.error(`[ManualEntryRunner] manualEntry.fromRawText ha rifiutato il testo:`,e);return}v(n),f([]),r.run(n,{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]),ee=e=>{f(t=>t.includes(e)?t:[...t,e])},w=(0,u.useMemo)(()=>n.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[n.componentAnchors,e.id]),T=(0,u.useMemo)(()=>_?Ut(w,_,a):null,[w,_,a]),E=(0,u.useMemo)(()=>T?[T,...t??[]]:t,[T,t]);return(0,u.useEffect)(()=>{y.current||n.openTask({id:a,title:e.label,icon:e.icon,agent:r,onApplied:e=>s(e),manualEntry:e.manualEntry?{prompt:e.manualEntry.prompt,onSubmit:b}:void 0,onDismiss:()=>{y.current=!0,r.running&&r.stop(),n.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)(Ht,{result:C}),(0,d.jsx)(Rt,{manifest:e,result:C,meta:_??{},taskId:a,initiallyApplied:c,onApplied:ee,extraDestinations:E}),r.hasProviders&&(0,d.jsx)(l.ActionButton,{label:i.resumeWithAi,variant:`outline-secondary`,className:`text-xs`,onClick:()=>{_&&n.resumeWithAI(e.id,_,t)}})]}):void 0})},[r.activity,r.running,r.error,r.hasProviders,n.componentAnchors,o,C,h,c,_]),(0,u.useEffect)(()=>()=>{n.closeTask(a)},[]),null}function rn({title:e,meta:t,action:n}){return(0,d.jsxs)(`div`,{role:`separator`,"aria-label":e,className:`my-3 flex items-center gap-2 text-[11px] text-muted-foreground`,children:[(0,d.jsx)(`span`,{className:`h-px flex-1 bg-border`}),(0,d.jsxs)(`span`,{className:`flex min-w-0 max-w-[75%] flex-col items-center text-center`,children:[(0,d.jsx)(`span`,{className:`max-w-full truncate font-medium text-foreground`,children:e}),t&&(0,d.jsx)(`span`,{children:t}),n]}),(0,d.jsx)(`span`,{className:`h-px flex-1 bg-border`})]})}function an({chat:e,thread:t,from:n,showEvents:r}){let i=Ie(t,n,e.savedAt,r);return(0,d.jsx)(st,{activity:e.activity,pinUserMessages:!1,speaker:x(e.subagentId)?.speaker?.(e.params),events:i})}function on({scopeId:e,thread:t,taskId:n,scrollRef:r,onLoad:i,onContinue:a,busy:o=!1,showEvents:s=!0}){let c=$(),{locale:f}=(0,l.useI18n)(),[p,m]=(0,u.useState)(0);(0,u.useEffect)(()=>pe(()=>m(e=>e+1)),[]);let h=(0,u.useMemo)(()=>De(e,t,n),[e,t,n,p]),[g,_]=(0,u.useState)(0);(0,u.useEffect)(()=>_(0),[n,t]);let v=g<h.length,y=(0,u.useRef)(null),b=()=>{let e=r.current;e&&(y.current={height:e.scrollHeight,top:e.scrollTop}),i?.(),_(e=>Math.min(e+1,h.length))},x=(0,u.useRef)(b);x.current=b,(0,u.useLayoutEffect)(()=>{let e=r.current,t=y.current;y.current=null,e&&t&&(e.scrollTop=t.top+(e.scrollHeight-t.height))},[g,r]);let S=(0,u.useRef)(null);if((0,u.useEffect)(()=>{let e=r.current,t=S.current;if(!e||!t||!v||typeof IntersectionObserver>`u`)return;let n=e.scrollTop,i=!1,a=()=>{e.scrollTop<n&&(i=!0),n=e.scrollTop};e.addEventListener(`scroll`,a,{passive:!0});let o=new IntersectionObserver(e=>{i&&e.some(e=>e.isIntersecting)&&(i=!1,x.current())},{root:e,rootMargin:`40px 0px 0px 0px`});return o.observe(t),()=>{e.removeEventListener(`scroll`,a),o.disconnect()}},[r,v,g]),!h.length)return null;let C=e=>new Date(e).toLocaleString(f,{dateStyle:`medium`,timeStyle:`short`}),ee=h.slice(0,g).reverse(),w=e=>{let t=h[h.indexOf(e)+1];return t?t.savedAt:Q(e)};return(0,d.jsxs)(`div`,{children:[v&&(0,d.jsx)(`div`,{ref:S,className:`flex justify-center pb-1`,children:(0,d.jsx)(l.ActionButton,{icon:`history`,label:c.earlierSession,variant:`link`,className:`text-xs`,onClick:b})}),ee.map(e=>(0,d.jsxs)(`section`,{"aria-label":Z(e),children:[(0,d.jsx)(rn,{title:Z(e),meta:(0,l.interpolate)(c.sessionOf,{at:C(Q(e))}),action:(0,d.jsx)(l.ActionButton,{label:c.continueSession,variant:`link`,className:`text-[11px]`,disabled:o,onClick:()=>a(e)})}),(0,d.jsx)(an,{chat:e,thread:t,from:w(e),showEvents:s})]},`${e.subagentId}:${e.entityId}`)),g>0&&(0,d.jsx)(rn,{title:c.thisSession})]})}function sn(e,t){return Object.values(e).flat().map(e=>{let n=t?.(e.provider,e.providerLabel??e.provider);return{label:e.model,value:e.id,pricing:e.pricing??null,group:n?.group??e.providerLabel??e.provider,...n?.badge?{groupBadge:n.badge}:{}}})}function cn({task:e,editing:t,onCancelEdit:n,onSendEdit:r}){let i=$(),[a,o]=(0,u.useState)(``),{agent:s,onApplied:c,manualEntry:f}=e,p=s.running;(0,u.useEffect)(()=>{t&&o(t.detail??``)},[t]);let m=e=>{if(o(``),t&&r){r(t,e.text);return}if(f){f.onSubmit(e.text);return}s.sendMessage(e.text,{attachments:e.files,model:e.model}).then(e=>{e&&c(e)})},h=!!f||s.remote&&s.remoteModels.length===0,g=s.alongside&&s.remoteModels.some(e=>e.value===s.selectedModel),_=!h&&!s.remote&&!g&&s.hasProviders&&!s.selectedModel,v=h?[]:s.remote?s.remoteModels:s.alongside?[...s.remoteModels,...sn(s.modelsByProvider,s.catalogGroup)]:sn(s.modelsByProvider);return(0,d.jsxs)(d.Fragment,{children:[t&&(0,d.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,d.jsx)(l.Icon,{name:`pencil`,size:12,className:`shrink-0`}),(0,d.jsx)(`span`,{className:`flex-1`,children:i.editingMessage}),(0,d.jsx)(l.ActionButton,{label:i.cancelEdit,variant:`link`,className:`p-0 text-xs`,onClick:()=>{o(``),n?.()}})]}),(0,d.jsx)(l.Chatbot,{value:a,onChange:o,placeholder:f?.prompt??i.messagePlaceholder,running:p,onStop:s.stop,disabled:!a.trim()||_,onSubmit:m,attachments:!f&&(s.remote||g?s.executorAttachments:!0),models:v,selectedModel:h?``:s.selectedModel,actions:e.composerActions,commands:e.composerCommands,onModelChange:s.setSelectedModel,modelPlaceholder:i.selectModelPlaceholder,minHeight:44,maxHeight:220})]})}function ln(){let{startOrchestrator:e}=Ne(),t=$(),[n,r]=(0,u.useState)(``),{hasProviders:i,modelsByProvider:a,selectedModel:o,setSelectedModel:s}=Ct(),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:sn(a),selectedModel:o,onModelChange:s,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function un({chat:e,onClose:t}){let n=$(),r=(0,l.useFormController)();return(0,d.jsx)(l.Modal,{title:n.renameChat,size:`sm`,onClose:t,onSave:()=>(Se(e.scopeId,e.subagentId,e.entityId,String(r.record?.title??Z(e)),`person`),t(),Promise.resolve(!0)),children:(0,d.jsxs)(l.Form,{appearance:`empty`,controller:r,defaultValues:{title:Z(e)},footer:!1,children:[(0,d.jsx)(l.Input,{name:`title`,label:n.chatTitleLabel,placeholder:e.title}),(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:n.chatTitleHint})]})})}function dn(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 fn({card:e}){let t=$();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 pn({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 mn({scopeId:e,currentTaskId:t,open:n,onOpenChange:r,onSelect:i,onNewChat:a,onArchivedCurrent:o}){let s=$(),{locale:c}=(0,l.useI18n)(),[f,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(0);(0,u.useEffect)(()=>pe(()=>h(e=>e+1)),[]);let g=(0,u.useMemo)(()=>n?we(e):[],[e,n,m]),[_,v]=(0,u.useState)(null),y=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}Ce(e,n.subagentId,n.entityId),t===Te(n.subagentId,n.entityId)&&o(),h(e=>e+1)}},b=(0,u.useMemo)(()=>{let e=f.trim().toLowerCase();return e?g.filter(t=>{let n=x(t.subagentId)?.label??t.subagentId;return Z(t).toLowerCase().includes(e)||n.toLowerCase().includes(e)}):g},[g,f]);return(0,d.jsxs)(d.Fragment,{children:[(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:b.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}):b.map(e=>{let n=x(e.subagentId),a=t===Te(e.subagentId,e.entityId);return(0,d.jsx)(l.DropdownItem,{icon:a?`check`:n?.icon??`bot`,className:a?`bg-accent font-semibold text-primary`:void 0,actions:[{icon:`pencil`,label:s.renameChat,onClick:()=>{r(!1),v(e)}},{icon:`archive`,label:s.archiveChat,onClick:()=>void y(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.jsx)(`span`,{className:`min-w-0 truncate`,title:`${n?.label??e.subagentId} · ${Z(e)}`,children:Z(e)}),(0,d.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,title:`${s.chatStarted.replace(`{at}`,new Date(Q(e)).toLocaleString(c))} · ${s.chatLastMessage.replace(`{at}`,new Date(e.savedAt).toLocaleString(c))}`,children:dn(Q(e),c)})]})},`${e.subagentId}:${e.entityId}`)})}),_&&(0,d.jsx)(un,{chat:_,onClose:()=>v(null)})]})}function hn({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:ee,pendingStart:w,startRunId:T,scope:E,threadEvents:D}=Ne(),O=$(),k=(0,u.useRef)(null),[A,j]=(0,u.useState)(!1),[M,N]=(0,u.useState)(null),[te,P]=(0,u.useState)(null);(0,u.useEffect)(()=>{N(null),P(null)},[i?.id]),Zt(E?.id);let F=_t({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}),ne=()=>{(!i||i.agent.running||i.savedToDisk||window.confirm(O.unsavedConversationConfirm))&&(g(),j(!1))},I=i?[...i.precedingActivity??[],...i.agent.activity]:[],L=I.length,R=Math.max(0,Math.min(i?.panelExtraAnchorIndex??L,L)),z=I.slice(0,R),B=I.slice(R),re=!!(i&&!i.agent.running&&i.agent.error),[V,H]=Fe(),U=(0,u.useRef)({at:Date.now()});U.current.id!==i?.id&&(U.current={id:i?.id,at:Date.now()});let ie=(0,u.useMemo)(()=>{if(!E||!i?.thread)return U.current.at;let e=De(E.id,i.thread,i.id)[0];if(e)return e.savedAt;let t=we(E.id).find(e=>Te(e.subagentId,e.entityId)===i.id);return t?Q(t):I.find(e=>e.at!==void 0)?.at??U.current.at},[E?.id,i?.thread,i?.id,L===0]),W=Ie(i?.thread,ie,1/0,V),G=B.find(e=>e.at!==void 0)?.at,K=B.length===0||G===void 0?W:W.filter(e=>e.at<G),ae=B.length===0||G===void 0?[]:W.filter(e=>e.at>=G),oe=(e,t)=>{i&&(N(null),i.agent.rewind(e.id,t).then(e=>{e&&i.onApplied(e)}))},q=e=>{let t=i?.agent.activity??[],n=t.slice(t.findIndex(t=>t.id===e.id)+1).flatMap(e=>[...e.kind===`tool`&&e.status===`done`?[e.label]:[],...(e.parts??[]).flatMap(e=>e.type===`tool`&&e.status===`done`?[e.label]:[])]);return[...new Set(n.filter(Boolean))]},se=(e,t)=>{let n=q(e);n.length?P({entry:e,steps:n,...t===void 0?{}:{text:t}}):oe(e,t)},ce=i?{available:e=>i.agent.activity.some(t=>t.id===e.id)&&i.agent.rewindable(e.id),disabled:i.agent.running,onRetry:e=>se(e),onEdit:e=>N(e)}:void 0,le=new Set(i?.agent.activity.map(e=>e.id)??[]),ue=i?{canAnswer:e=>le.has(e),onAnswer:(e,t,n)=>i.agent.answerQuestions(e,t,n).then(e=>{e&&i.onApplied(e)}),onCardAction:(e,t,n)=>i.agent.cardAction(e,t,n)}:void 0,J=ue?tt(I,ue.canAnswer):null,de=i?.id===`agentico-orchestrator`&&i.scopedSubagentId?x(i.scopedSubagentId):void 0,fe=de?.manualEntry?de:null,Y=(0,u.useRef)(!0);(0,u.useEffect)(()=>{let e=k.current;if(!e)return;let t=()=>{Y.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&&(Y.current=!0,e.scrollTop=e.scrollHeight)},[i?.id]);let pe=I.at(-1)?.detail?.length??0;(0,u.useEffect)(()=>{let e=k.current;e&&Y.current&&(e.scrollTop=e.scrollHeight)},[L,re,pe]);let me=(0,u.useRef)(null);(0,u.useEffect)(()=>{let e=k.current,t=me.current;if(!e||!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>{Y.current&&(e.scrollTop=e.scrollHeight)});return n.observe(t),()=>n.disconnect()},[i?.id,a]);let X=o?(0,d.jsx)(tn,{userGoal:o},s):null,he=m?x(m.subagentId):void 0,ge=m&&he?(0,d.jsx)(en,{manifest:he,params:m.snapshot.params,taskId:Te(m.subagentId,m.entityId),resumeSeed:{history:m.snapshot.history,activity:m.snapshot.activity}},h):null,_e=v?x(v.subagentId):void 0,ve=v&&_e?(0,d.jsx)(nn,{manifest:_e,extraDestinations:v.extraDestinations},y):null,ye=C?x(C.subagentId):void 0,Z=C&&ye?(0,d.jsx)(en,{manifest:ye,params:C.params,extraDestinations:C.extraDestinations},ee):null,be=w?x(w.subagentId):void 0,xe=w&&be?(0,d.jsx)(en,{manifest:be,params:w.params,taskId:w.taskId,openingMessage:w.openingMessage},T):null;return a?(0,d.jsxs)(d.Fragment,{children:[X,ge,ve,Z,xe,(0,d.jsxs)(`div`,{style:{width:F.width},className:`relative flex h-full shrink-0 flex-col border-l border-border bg-background`,children:[(0,d.jsx)(vt,{width:F.width,min:F.min,max:F.max,onResize:F.set,onCommit:F.commit,onReset:F.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`}),i?.thread&&D&&(0,d.jsx)(l.ActionButton,{icon:V?`activity`:`message-square`,ariaLabel:V?O.hideEvents:O.showEvents,title:V?O.hideEvents:O.showEvents,variant:`link`,className:`p-1 ${V?`text-primary`:`text-muted-foreground`}`,onClick:()=>H(!V)}),E&&(0,d.jsx)(mn,{scopeId:E.id,currentTaskId:i?.id??null,open:A,onOpenChange:j,onNewChat:ne,onSelect:(e,t,n)=>_(e,t,n),onArchivedCurrent:g}),(0,d.jsx)(yt,{})]}),(0,d.jsx)(`div`,{ref:k,className:`flex-1 overflow-y-auto px-3 pb-2 ${J?`min-h-24`:`min-h-0`}`,children:(0,d.jsx)(`div`,{ref:me,className:`pt-2`,children:i?(0,d.jsxs)(d.Fragment,{children:[E&&i.thread&&(0,d.jsx)(on,{scopeId:E.id,thread:i.thread,taskId:i.id,scrollRef:k,busy:i.agent.running,showEvents:V,onLoad:()=>{Y.current=!1},onContinue:e=>_(e.subagentId,e.entityId,e)}),i.manualEntry&&I.length===0&&(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i.manualEntry.prompt}),(0,d.jsx)(st,{activity:z,questions:ue,docked:J,pinUserMessages:!J,messageActions:ce,speaker:i.speaker,events:K}),i.panelExtra&&(0,d.jsx)(`div`,{className:`mt-3`,children:i.panelExtra}),B.length>0&&(0,d.jsx)(st,{activity:B,questions:ue,docked:J,pinUserMessages:!J,messageActions:ce,speaker:i.speaker,events:ae}),!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:()=>{let e=[...i.agent.activity].reverse().find(e=>e.kind===`user`);if(e&&i.agent.rewindable(e.id)){se(e);return}i.agent.sendMessage(O.retryMessage,{retry:!0}).then(e=>{e&&i.onApplied(e)})}}),!i.agent.remote&&i.agent.offersFallback!==!1&&(0,d.jsx)(l.ActionButton,{label:O.continueWithoutAi,variant:`secondary`,className:`shrink-0`,onClick:()=>{if(fe){b(fe.id,S);return}let e=i.agent.runFallback();e&&i.onApplied(e)}})]})]}):p.length>0?(0,d.jsx)(pn,{messages:p}):f?(0,d.jsx)(fn,{card:f}):(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c??O.orchestratorStarterHint})})}),i&&J?(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)(nt,{entry:J.entry,part:J.part,questions:ue,autoFocus:!0},`${J.entry.id}:${J.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)(cn,{task:i,editing:M,onCancelEdit:()=>N(null),onSendEdit:(e,t)=>se(e,t)},i.id):(0,d.jsx)(ln,{})]}),te&&(0,d.jsxs)(l.ModalYesNo,{title:O.rewindTitle,onClose:()=>P(null),onYes:async()=>(oe(te.entry,te.text),!0),children:[(0,d.jsx)(`p`,{className:`text-sm`,children:O.rewindText}),(0,d.jsx)(`ul`,{className:`mt-2 list-disc space-y-0.5 ps-5 text-sm text-muted-foreground`,children:te.steps.slice(0,8).map(e=>(0,d.jsx)(`li`,{children:e},e))})]})]})]}):(0,d.jsxs)(d.Fragment,{children:[X,ge,ve,Z,xe]})}function gn(e,t){let{setPageContext:n}=Ne(),r=(0,u.useRef)(crypto.randomUUID()).current;(0,u.useEffect)(()=>(n(r,e,t??null),()=>n(r,null)),[e,t])}function _n(e,t,n,r,i=!0,a){let{registerComponentAnchor:o}=Ne(),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=ut,exports.AGENTICO_MIN_WIDTH=lt,exports.AGENTICO_WIDTH=ct,exports.AGENTICO_WIDTH_STORAGE_KEY=dt,exports.Agentico=hn,exports.AgenticoProvider=Me,exports.AgenticoToggle=yt,exports.DEFAULT_REASONING_PART_ID=p,exports.DEFAULT_TEXT_PART_ID=f,exports.JSON_EXPORT_DESTINATION_ID=V,exports.MICRO_PROMPT_REGISTRY=L,exports.ORCHESTRATOR_TASK_ID=Ae,exports.SUMMARY_MICRO_PROMPT=I,exports.agenticoDe=ae,exports.agenticoEn=G,exports.agenticoIt=K,exports.agenticoPromptsEn=D,exports.agenticoPromptsIt=O,exports.agenticoTranslations=ke,exports.applyMicroPrompts=R,exports.chatHasPersonMessage=be,exports.chatStartedAt=Q,exports.chatThreadOf=Ee,exports.chatTitle=Z,exports.configureAgenticoPrompts=A,exports.configureEntityChatStore=se,exports.createCrossAgentTools=ee,exports.defineSubagent=_,exports.earlierSessions=De,exports.entityChatTaskId=Te,exports.extractErrorMessage=z,exports.extractJsonBlock=B,exports.findSubagentManifest=x,exports.formatQuestionAnswers=g,exports.getAgenticoPrompts=j,exports.getDestinationRegistry=W,exports.getEntityChat=he,exports.getSubagentControls=Kt,exports.getSubagentRegistry=b,exports.getSubagentReport=Vt,exports.hasEntityChatBackend=ce,exports.jsonExportDestination=H,exports.listEntityChats=we,exports.messagePartsText=h,exports.onEntityChatsChange=pe,exports.placeEvents=Oe,exports.registerCrossAgentTools=C,exports.registerDestinations=ie,exports.registerSubagentControls=Gt,exports.registerSubagentReports=Bt,exports.registerSubagents=y,exports.removeEntityChat=Ce,exports.renameEntityChat=Se,exports.renderRegistryCli=ne,exports.renderSubagentCli=F,exports.resetAgenticoPrompts=M,exports.saveEntityChat=ge,exports.syncEntityChats=J,exports.toJsonSchema=w,exports.toMcpTool=T,exports.upsertMessagePart=m,exports.useAgent=jt,exports.useAgentico=Ne,exports.useAgenticoI18n=$,exports.useAgenticoPageContext=gn,exports.useSubagentComponentContext=_n;
27
+ `);return n.length>t?`${n.slice(0,t*.7)}\n\n[…]\n\n${n.slice(-t*.3)}`:n}function $t(e){return(e.trim().split(`
28
+ `).map(e=>e.trim()).find(Boolean)??``).replace(/^(title|titolo)\s*:\s*/i,``).replace(/^#+\s*/,``).replace(/^["'«“]+|["'»”]+$/g,``).replace(/[.。]+$/,``).trim().slice(0,80)}function en(e,t){try{return e.definition.executor?.catalogProviders?.(e.toParams(t))}catch{return}}function tn(e,t,n,r,i){let a=en(e,t),o=e=>{let t=e?(0,l.parseAIModelRef)(e):null;return!(!t||!i[t.provider]||a&&!a.includes(t.provider))};return o(n)?n:Object.values(r).flat().map(e=>e.id).find(o)}function nn(e){let t=(0,l.useAIProviderRegistry)()?.registry??{},{modelsByProvider:n,selectedModel:r}=Ot(),i=(0,u.useRef)({registry:t,modelsByProvider:n,selectedModel:r});i.current={registry:t,modelsByProvider:n,selectedModel:r};let a=(0,u.useRef)(new Set),o=(0,u.useCallback)(async(t,n,r)=>{if(!e)return!1;let o=he(e,t,n),s=x(t),c=`${e}:${t}:${n}`;if(!o||!s?.autoTitle||o.name||!be(o)||a.current.has(c))return!1;let{registry:u,modelsByProvider:d,selectedModel:f}=i.current,p=tn(s,o.params,r??f,d,u),m=p?(0,l.parseAIModelRef)(p):null;if(!m)return!1;a.current.add(c);try{let r=await u[m.provider].complete({prompt:A().chatTitle.replace(`{chat}`,Qt(o.activity)),model:m.model,history:[]}),i=r&&r.type===`text`?$t(r.text):``;return i?Se(e,t,n,i,`model`):!1}catch{return!1}finally{a.current.delete(c)}},[e]),s=Object.keys(n).length>0;return(0,u.useEffect)(()=>{e&&s&&!rn.has(e)&&(rn.add(e),(async()=>{for(let t of we(e)){let n=x(t.subagentId);if(n?.autoTitle){if(n.definition.conversational&&!be(t)){Ce(e,t.subagentId,t.entityId);continue}t.name||await o(t.subagentId,t.entityId)}}})())},[e,s,o]),o}var rn=new Set,an=()=>({});function on({manifest:e,params:t,extraDestinations:n,precedingActivity:r,taskId:i,resumeSeed:a,model:o,openingMessage:s}){let c=Le(),f=It(e.definition,{defaultEnabled:!0,...c.person?{author:c.person}:{}}),p=e.thread?.(t)||void 0,m=e.speaker?.(t),h=c.scope,g=(0,l.useProxy)(),_=(0,u.useRef)(i??`subagent-${e.id}-${crypto.randomUUID()}`).current,[v,y]=(0,u.useState)(null),b=t=>{e.definition.conversational||y(t)},[x,S]=(0,u.useState)([]),[C,ee]=(0,u.useState)(null),w=Kt(e.id),T=w?.kind===`selection`?w:null,[E,te]=(0,u.useState)(null),D=(0,u.useRef)(!1),O=(0,u.useRef)(0),k=(0,u.useRef)(null);v&&v!==k.current&&(k.current=v,O.current=(r?.length??0)+f.activity.length);let A=(0,u.useRef)(!1),j=f.remote||!f.hasProviders||f.selectedModel!==``;(0,u.useEffect)(()=>{!D.current&&j&&(D.current=!0,a?(re.current=!0,f.resume(e.toParams(t),a)):(o&&f.setSelectedModel(o),f.run(e.toParams(t),{model:o,openingMessage:s}).then(e=>{e&&b(e)})))},[j]),(0,u.useEffect)(()=>{if(!v||!h)return;let n=e.autoApplyDestinationIds??[],r=c.componentAnchors.find(t=>t.subagentId===e.id&&t.pinnedEntityId)?.pinnedEntityId,i=oe();n.forEach(n=>{let a=i[n];a&&(ee(null),a.apply(v,{scopeId:h.id,dataProvider:h.dataProvider,storageProvider:h.storageProvider,proxyFetch:g},{...t,pinnedEntityId:r}).then(n=>{n?.id&&c.commitEntityChat(e.id,n.id,_,h.id,t,Ht(e,t))}).catch(e=>ee(e instanceof Error?e.message:String(e))))})},[v,f.activity,h]),(0,u.useEffect)(()=>{v&&T&&te(T.defaultSelection(v))},[v,T]);let M=(e,t)=>{te(n=>n&&{...n,[e]:t})},N=e=>b(e),P=(0,u.useMemo)(()=>v&&T&&E?T.applySelection(v,E):v,[v,T,E]),F=(0,u.useMemo)(()=>c.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[c.componentAnchors,e.id]),ne=(0,u.useMemo)(()=>Jt(F,t,_),[F,t,_]),I=(0,u.useMemo)(()=>ne?[ne,...n??[]]:n,[ne,n]),L=e.chatEntityId?.(t),R=nn(h?.id),z=(0,u.useRef)(!1),re=(0,u.useRef)(!1);(0,u.useEffect)(()=>{let n=!z.current&&f.running,i=z.current&&!f.running;if(z.current=f.running,!n&&!i||!L||!h)return;if(re.current){i&&(re.current=!1);return}let a=f.snapshot();if(!a)return;let o=[...r??[],...a.activity];e.autoTitle&&e.definition.conversational&&!be({activity:o})||(ge({scopeId:h.id,subagentId:e.id,entityId:L,params:t,title:Ht(e,t),history:a.history,activity:o}),i&&e.autoTitle&&R(e.id,L,f.selectedModel))},[f.running]);let ie=()=>{A.current=!0,f.running&&f.stop(),c.closeTask(_)},B=(0,u.useRef)(Zt(e.id)??an).current,V=B({params:t,taskId:_,running:f.running,close:ie}),H=e=>{S(t=>t.includes(e)?t:[...t,e])};return(0,u.useEffect)(()=>{A.current||c.openTask({id:_,title:Ht(e,t),icon:e.icon,agent:f,onApplied:e=>b(e),precedingActivity:r,panelExtraAnchorIndex:O.current,onDismiss:ie,...p?{thread:p}:{},...m?{speaker:m}:{},...L?{savedToDisk:!0}:{},panelActions:V.content,composerActions:V.actions,composerCommands:V.commands,panelExtra:v?(0,d.jsxs)(d.Fragment,{children:[T&&E?(0,d.jsx)(T.Report,{result:v,selection:E,onChange:M}):w?.kind===`editable`?(0,d.jsx)(w.Report,{result:v,onResultChange:N}):(0,d.jsx)(qt,{result:P}),C&&(0,d.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Salvataggio automatico non riuscito: `,C]}),(0,d.jsx)(Ut,{manifest:e,result:P,meta:t,taskId:_,initiallyApplied:x,onApplied:H,extraDestinations:I})]}):void 0})},[f.activity,f.running,f.error,f.canContinue,f.selectedModel,f.modelsByProvider,f.hasProviders,f.remoteModels,c.openTask,c.componentAnchors,_,e,t,v,P,E,x,n,r,C,V.content,V.actions,V.commands]),(0,u.useEffect)(()=>()=>{c.closeTask(_)},[c.closeTask,_]),null}function sn({userGoal:e}){let t=$(),n=(0,u.useMemo)(()=>Vt({unavailable:t.orchestratorUnavailable,continueWithoutAi:t.orchestratorContinueWithoutAi,preparing:t.orchestratorPreparing,collecting:t.orchestratorCollecting}),[]),r=Le(),i=It(n,{defaultEnabled:!0,...r.person?{author:r.person}:{}}),[a,o]=(0,u.useState)(null),s=(0,u.useRef)(!1),c=!i.hasProviders||i.selectedModel!==``,l=(0,u.useRef)(r.pendingExtraDestinations),f=(0,u.useRef)(r.pendingAttachments),p=(0,u.useRef)(r.pendingModel),m=(0,u.useRef)(r.pendingScopedSubagentId??r.scopedSubagentId??void 0),h=(0,u.useRef)(r.pendingCarryOver),g=(0,u.useRef)(!1),_=e=>{e&&typeof e==`object`&&e.kind===`handoff`&&(o(e),r.closeTask(Pe))};(0,u.useEffect)(()=>{!s.current&&c&&(s.current=!0,p.current&&i.setSelectedModel(p.current),i.run({userGoal:e,pageContext:r.pageContext,scopedSubagentId:m.current??null},{attachments:f.current,model:p.current,openingMessage:e}).then(e=>{e&&_(e)}))},[c]),(0,u.useEffect)(()=>{g.current||r.openTask({id:Pe,title:`Agentico`,icon:`bot`,agent:i,onApplied:_,scopedSubagentId:m.current,precedingActivity:h.current?.activity,onDismiss:()=>{g.current=!0,i.running&&i.stop(),r.closeTask(Pe)}})},[i.activity,i.running,i.error,i.canContinue,i.selectedModel,i.modelsByProvider,i.hasProviders,r.openTask]),(0,u.useEffect)(()=>()=>{r.closeTask(Pe)},[r.closeTask]);let v=(0,u.useMemo)(()=>[...h.current?.activity??[],...i.activity],[i.activity]);if(!a)return null;let y=x(a.subagentId);return y?(0,d.jsx)(on,{manifest:y,params:a.params,extraDestinations:l.current,model:p.current||void 0,taskId:h.current?.taskId,precedingActivity:v}):null}function cn({manifest:e,extraDestinations:t}){let n=Le(),r=It(e.definition,{defaultEnabled:!1,...n.person?{author:n.person}:{}}),i=$(),a=(0,u.useRef)(`manual-${e.id}-${crypto.randomUUID()}`).current,[o,s]=(0,u.useState)(null),[c,f]=(0,u.useState)([]),p=Kt(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 n;try{n=e.manualEntry.fromRawText(t)}catch(e){console.error(`[ManualEntryRunner] manualEntry.fromRawText ha rifiutato il testo:`,e);return}v(n),f([]),r.run(n,{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]),ee=e=>{f(t=>t.includes(e)?t:[...t,e])},w=(0,u.useMemo)(()=>n.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[n.componentAnchors,e.id]),T=(0,u.useMemo)(()=>_?Jt(w,_,a):null,[w,_,a]),E=(0,u.useMemo)(()=>T?[T,...t??[]]:t,[T,t]);return(0,u.useEffect)(()=>{y.current||n.openTask({id:a,title:e.label,icon:e.icon,agent:r,onApplied:e=>s(e),manualEntry:e.manualEntry?{prompt:e.manualEntry.prompt,onSubmit:b}:void 0,onDismiss:()=>{y.current=!0,r.running&&r.stop(),n.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)(qt,{result:C}),(0,d.jsx)(Ut,{manifest:e,result:C,meta:_??{},taskId:a,initiallyApplied:c,onApplied:ee,extraDestinations:E}),r.hasProviders&&(0,d.jsx)(l.ActionButton,{label:i.resumeWithAi,variant:`outline-secondary`,className:`text-xs`,onClick:()=>{_&&n.resumeWithAI(e.id,_,t)}})]}):void 0})},[r.activity,r.running,r.error,r.hasProviders,n.componentAnchors,o,C,h,c,_]),(0,u.useEffect)(()=>()=>{n.closeTask(a)},[]),null}function ln({title:e,meta:t,action:n}){return(0,d.jsxs)(`div`,{role:`separator`,"aria-label":e,className:`my-3 flex items-center gap-2 text-[11px] text-muted-foreground`,children:[(0,d.jsx)(`span`,{className:`h-px flex-1 bg-border`}),(0,d.jsxs)(`span`,{className:`flex min-w-0 max-w-[75%] flex-col items-center text-center`,children:[(0,d.jsx)(`span`,{className:`max-w-full truncate font-medium text-foreground`,children:e}),t&&(0,d.jsx)(`span`,{children:t}),n]}),(0,d.jsx)(`span`,{className:`h-px flex-1 bg-border`})]})}function un({chat:e,thread:t,from:n,showEvents:r}){let i=Be(t,n,e.savedAt,r);return(0,d.jsx)(ft,{activity:e.activity,pinUserMessages:!1,speaker:x(e.subagentId)?.speaker?.(e.params),events:i})}function dn({scopeId:e,thread:t,taskId:n,scrollRef:r,onLoad:i,onContinue:a,busy:o=!1,showEvents:s=!0}){let c=$(),{locale:f}=(0,l.useI18n)(),[p,m]=(0,u.useState)(0);(0,u.useEffect)(()=>me(()=>m(e=>e+1)),[]);let h=(0,u.useMemo)(()=>De(e,t,n),[e,t,n,p]),[g,_]=(0,u.useState)(0);(0,u.useEffect)(()=>_(0),[n,t]);let v=g<h.length,y=(0,u.useRef)(null),b=()=>{let e=r.current;e&&(y.current={height:e.scrollHeight,top:e.scrollTop}),i?.(),_(e=>Math.min(e+1,h.length))},x=(0,u.useRef)(b);x.current=b,(0,u.useLayoutEffect)(()=>{let e=r.current,t=y.current;y.current=null,e&&t&&(e.scrollTop=t.top+(e.scrollHeight-t.height))},[g,r]);let S=(0,u.useRef)(null);if((0,u.useEffect)(()=>{let e=r.current,t=S.current;if(!e||!t||!v||typeof IntersectionObserver>`u`)return;let n=e.scrollTop,i=!1,a=()=>{e.scrollTop<n&&(i=!0),n=e.scrollTop};e.addEventListener(`scroll`,a,{passive:!0});let o=new IntersectionObserver(e=>{i&&e.some(e=>e.isIntersecting)&&(i=!1,x.current())},{root:e,rootMargin:`40px 0px 0px 0px`});return o.observe(t),()=>{e.removeEventListener(`scroll`,a),o.disconnect()}},[r,v,g]),!h.length)return null;let C=e=>new Date(e).toLocaleString(f,{dateStyle:`medium`,timeStyle:`short`}),ee=h.slice(0,g).reverse(),w=e=>{let t=h[h.indexOf(e)+1];return t?t.savedAt:Q(e)};return(0,d.jsxs)(`div`,{children:[v&&(0,d.jsx)(`div`,{ref:S,className:`flex justify-center pb-1`,children:(0,d.jsx)(l.ActionButton,{icon:`history`,label:c.earlierSession,variant:`link`,className:`text-xs`,onClick:b})}),ee.map(e=>(0,d.jsxs)(`section`,{"aria-label":Z(e),children:[(0,d.jsx)(ln,{title:Z(e),meta:(0,l.interpolate)(c.sessionOf,{at:C(Q(e))}),action:(0,d.jsx)(l.ActionButton,{label:c.continueSession,variant:`link`,className:`text-[11px]`,disabled:o,onClick:()=>a(e)})}),(0,d.jsx)(un,{chat:e,thread:t,from:w(e),showEvents:s})]},`${e.subagentId}:${e.entityId}`)),g>0&&(0,d.jsx)(ln,{title:c.thisSession})]})}function fn(e,t){return Object.values(e).flat().map(e=>{let n=t?.(e.provider,e.providerLabel??e.provider);return{label:e.model,value:e.id,pricing:e.pricing??null,group:n?.group??e.providerLabel??e.provider,...n?.badge?{groupBadge:n.badge}:{}}})}function pn({task:e,editing:t,onCancelEdit:n,onSendEdit:r}){let i=$(),[a,o]=(0,u.useState)(``),{agent:s,onApplied:c,manualEntry:f}=e,p=s.running;(0,u.useEffect)(()=>{t&&o(t.detail??``)},[t]);let m=e=>{if(o(``),t&&r){r(t,e.text);return}if(f){f.onSubmit(e.text);return}s.sendMessage(e.text,{attachments:e.files,model:e.model}).then(e=>{e&&c(e)})},h=!!f||s.remote&&s.remoteModels.length===0,g=s.alongside&&s.remoteModels.some(e=>e.value===s.selectedModel),_=!h&&!s.remote&&!g&&s.hasProviders&&!s.selectedModel,v=h?[]:s.remote?s.remoteModels:s.alongside?[...s.remoteModels,...fn(s.modelsByProvider,s.catalogGroup)]:fn(s.modelsByProvider);return(0,d.jsxs)(d.Fragment,{children:[t&&(0,d.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,d.jsx)(l.Icon,{name:`pencil`,size:12,className:`shrink-0`}),(0,d.jsx)(`span`,{className:`flex-1`,children:i.editingMessage}),(0,d.jsx)(l.ActionButton,{label:i.cancelEdit,variant:`link`,className:`p-0 text-xs`,onClick:()=>{o(``),n?.()}})]}),(0,d.jsx)(l.Chatbot,{value:a,onChange:o,placeholder:f?.prompt??i.messagePlaceholder,running:p,onStop:s.stop,disabled:!a.trim()||_,onSubmit:m,attachments:!f&&(s.remote||g?s.executorAttachments:!0),models:v,selectedModel:h?``:s.selectedModel,actions:e.composerActions,commands:e.composerCommands,onModelChange:s.setSelectedModel,modelPlaceholder:i.selectModelPlaceholder,minHeight:44,maxHeight:220})]})}function mn(){let{startOrchestrator:e}=Le(),t=$(),[n,r]=(0,u.useState)(``),{hasProviders:i,modelsByProvider:a,selectedModel:o,setSelectedModel:s}=Ot(),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:fn(a),selectedModel:o,onModelChange:s,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function hn({chat:e,onClose:t}){let n=$(),r=(0,l.useFormController)();return(0,d.jsx)(l.Modal,{title:n.renameChat,size:`sm`,onClose:t,onSave:()=>(Se(e.scopeId,e.subagentId,e.entityId,String(r.record?.title??Z(e)),`person`),t(),Promise.resolve(!0)),children:(0,d.jsxs)(l.Form,{appearance:`empty`,controller:r,defaultValues:{title:Z(e)},footer:!1,children:[(0,d.jsx)(l.Input,{name:`title`,label:n.chatTitleLabel,placeholder:e.title}),(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:n.chatTitleHint})]})})}function gn(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 _n({card:e}){let t=$();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 vn({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 yn({scopeId:e,currentTaskId:t,open:n,onOpenChange:r,onSelect:i,onNewChat:a,onArchivedCurrent:o}){let s=$(),{locale:c}=(0,l.useI18n)(),[f,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(0);(0,u.useEffect)(()=>me(()=>h(e=>e+1)),[]);let g=(0,u.useMemo)(()=>n?we(e):[],[e,n,m]),[_,v]=(0,u.useState)(null),y=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}Ce(e,n.subagentId,n.entityId),t===Te(n.subagentId,n.entityId)&&o(),h(e=>e+1)}},b=(0,u.useMemo)(()=>{let e=f.trim().toLowerCase();return e?g.filter(t=>{let n=x(t.subagentId)?.label??t.subagentId;return Z(t).toLowerCase().includes(e)||n.toLowerCase().includes(e)}):g},[g,f]);return(0,d.jsxs)(d.Fragment,{children:[(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:b.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}):b.map(e=>{let n=x(e.subagentId),a=t===Te(e.subagentId,e.entityId);return(0,d.jsx)(l.DropdownItem,{icon:a?`check`:n?.icon??`bot`,className:a?`bg-accent font-semibold text-primary`:void 0,actions:[{icon:`pencil`,label:s.renameChat,onClick:()=>{r(!1),v(e)}},{icon:`archive`,label:s.archiveChat,onClick:()=>void y(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.jsx)(`span`,{className:`min-w-0 truncate`,title:`${n?.label??e.subagentId} · ${Z(e)}`,children:Z(e)}),(0,d.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,title:`${s.chatStarted.replace(`{at}`,new Date(Q(e)).toLocaleString(c))} · ${s.chatLastMessage.replace(`{at}`,new Date(e.savedAt).toLocaleString(c))}`,children:gn(Q(e),c)})]})},`${e.subagentId}:${e.entityId}`)})}),_&&(0,d.jsx)(hn,{chat:_,onClose:()=>v(null)})]})}function bn({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:ee,pendingStart:w,startRunId:T,scope:E,threadEvents:te}=Le(),D=$(),O=(0,u.useRef)(null),[k,A]=(0,u.useState)(!1),[j,M]=(0,u.useState)(null),[N,P]=(0,u.useState)(null);(0,u.useEffect)(()=>{M(null),P(null)},[i?.id]),nn(E?.id);let F=St({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}),ne=()=>{(!i||i.agent.running||i.savedToDisk||window.confirm(D.unsavedConversationConfirm))&&(g(),A(!1))},I=i?[...i.precedingActivity??[],...i.agent.activity]:[],L=I.length,R=Math.max(0,Math.min(i?.panelExtraAnchorIndex??L,L)),z=I.slice(0,R),re=I.slice(R),ie=!!(i&&!i.agent.running&&i.agent.error),[B,V]=ze(),H=(0,u.useRef)({at:Date.now()});H.current.id!==i?.id&&(H.current={id:i?.id,at:Date.now()});let ae=(0,u.useMemo)(()=>{if(!E||!i?.thread)return H.current.at;let e=De(E.id,i.thread,i.id)[0];if(e)return e.savedAt;let t=we(E.id).find(e=>Te(e.subagentId,e.entityId)===i.id);return t?Q(t):I.find(e=>e.at!==void 0)?.at??H.current.at},[E?.id,i?.thread,i?.id,L===0]),oe=Be(i?.thread,ae,1/0,B),U=re.find(e=>e.at!==void 0)?.at,W=re.length===0||U===void 0?oe:oe.filter(e=>e.at<U),G=re.length===0||U===void 0?[]:oe.filter(e=>e.at>=U),se=(e,t)=>{i&&(M(null),i.agent.rewind(e.id,t).then(e=>{e&&i.onApplied(e)}))},K=e=>{let t=i?.agent.activity??[],n=t.slice(t.findIndex(t=>t.id===e.id)+1).flatMap(e=>[...e.kind===`tool`&&e.status===`done`?[e.label]:[],...(e.parts??[]).flatMap(e=>e.type===`tool`&&e.status===`done`?[e.label]:[])]);return[...new Set(n.filter(Boolean))]},ce=(e,t)=>{let n=K(e);n.length?P({entry:e,steps:n,...t===void 0?{}:{text:t}}):se(e,t)},le=i?{available:e=>i.agent.activity.some(t=>t.id===e.id)&&i.agent.rewindable(e.id),disabled:i.agent.running,onRetry:e=>ce(e),onEdit:e=>M(e)}:void 0,ue=new Set(i?.agent.activity.map(e=>e.id)??[]),q=i?{canAnswer:e=>ue.has(e),onAnswer:(e,t,n)=>i.agent.answerQuestions(e,t,n).then(e=>{e&&i.onApplied(e)}),onCardAction:(e,t,n)=>i.agent.cardAction(e,t,n)}:void 0,J=q?ot(I,q.canAnswer):null,de=i?.id===`agentico-orchestrator`&&i.scopedSubagentId?x(i.scopedSubagentId):void 0,fe=de?.manualEntry?de:null,pe=(0,u.useRef)(!0);(0,u.useEffect)(()=>{let e=O.current;if(!e)return;let t=()=>{pe.current=e.scrollHeight-e.scrollTop-e.clientHeight<80};return e.addEventListener(`scroll`,t),()=>e.removeEventListener(`scroll`,t)},[i?.id]),(0,u.useEffect)(()=>{let e=O.current;e&&(pe.current=!0,e.scrollTop=e.scrollHeight)},[i?.id]);let me=I.at(-1)?.detail?.length??0;(0,u.useEffect)(()=>{let e=O.current;e&&pe.current&&(e.scrollTop=e.scrollHeight)},[L,ie,me]);let Y=(0,u.useRef)(null);(0,u.useEffect)(()=>{let e=O.current,t=Y.current;if(!e||!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>{pe.current&&(e.scrollTop=e.scrollHeight)});return n.observe(t),()=>n.disconnect()},[i?.id,a]);let X=o?(0,d.jsx)(sn,{userGoal:o},s):null,he=m?x(m.subagentId):void 0,ge=m&&he?(0,d.jsx)(on,{manifest:he,params:m.snapshot.params,taskId:Te(m.subagentId,m.entityId),resumeSeed:{history:m.snapshot.history,activity:m.snapshot.activity}},h):null,_e=v?x(v.subagentId):void 0,ve=v&&_e?(0,d.jsx)(cn,{manifest:_e,extraDestinations:v.extraDestinations},y):null,ye=C?x(C.subagentId):void 0,Z=C&&ye?(0,d.jsx)(on,{manifest:ye,params:C.params,extraDestinations:C.extraDestinations},ee):null,be=w?x(w.subagentId):void 0,xe=w&&be?(0,d.jsx)(on,{manifest:be,params:w.params,taskId:w.taskId,openingMessage:w.openingMessage},T):null;return a?(0,d.jsxs)(d.Fragment,{children:[X,ge,ve,Z,xe,(0,d.jsxs)(`div`,{style:{width:F.width},className:`relative flex h-full shrink-0 flex-col border-l border-border bg-background`,children:[(0,d.jsx)(Ct,{width:F.width,min:F.min,max:F.max,onResize:F.set,onCommit:F.commit,onReset:F.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`}),i?.thread&&te&&(0,d.jsx)(l.ActionButton,{icon:B?`activity`:`message-square`,ariaLabel:B?D.hideEvents:D.showEvents,title:B?D.hideEvents:D.showEvents,variant:`link`,className:`p-1 ${B?`text-primary`:`text-muted-foreground`}`,onClick:()=>V(!B)}),E&&(0,d.jsx)(yn,{scopeId:E.id,currentTaskId:i?.id??null,open:k,onOpenChange:A,onNewChat:ne,onSelect:(e,t,n)=>_(e,t,n),onArchivedCurrent:g}),(0,d.jsx)(wt,{})]}),(0,d.jsx)(`div`,{ref:O,className:`flex-1 overflow-y-auto px-3 pb-2 ${J?`min-h-24`:`min-h-0`}`,children:(0,d.jsx)(`div`,{ref:Y,className:`pt-2`,children:i?(0,d.jsxs)(d.Fragment,{children:[E&&i.thread&&(0,d.jsx)(dn,{scopeId:E.id,thread:i.thread,taskId:i.id,scrollRef:O,busy:i.agent.running,showEvents:B,onLoad:()=>{pe.current=!1},onContinue:e=>_(e.subagentId,e.entityId,e)}),i.manualEntry&&I.length===0&&(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i.manualEntry.prompt}),(0,d.jsx)(ft,{activity:z,questions:q,docked:J,pinUserMessages:!J,messageActions:le,speaker:i.speaker,events:W}),i.panelExtra&&(0,d.jsx)(`div`,{className:`mt-3`,children:i.panelExtra}),re.length>0&&(0,d.jsx)(ft,{activity:re,questions:q,docked:J,pinUserMessages:!J,messageActions:le,speaker:i.speaker,events:G}),!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:D.retry,variant:`secondary`,className:`shrink-0`,onClick:()=>{let e=[...i.agent.activity].reverse().find(e=>e.kind===`user`);if(e&&i.agent.rewindable(e.id)){ce(e);return}i.agent.sendMessage(D.retryMessage,{retry:!0}).then(e=>{e&&i.onApplied(e)})}}),!i.agent.remote&&i.agent.offersFallback!==!1&&(0,d.jsx)(l.ActionButton,{label:D.continueWithoutAi,variant:`secondary`,className:`shrink-0`,onClick:()=>{if(fe){b(fe.id,S);return}let e=i.agent.runFallback();e&&i.onApplied(e)}})]})]}):p.length>0?(0,d.jsx)(vn,{messages:p}):f?(0,d.jsx)(_n,{card:f}):(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c??D.orchestratorStarterHint})})}),i&&J?(0,d.jsxs)(`section`,{"aria-label":D.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)(st,{entry:J.entry,part:J.part,questions:q,autoFocus:!0},`${J.entry.id}:${J.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:D.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)(pn,{task:i,editing:j,onCancelEdit:()=>M(null),onSendEdit:(e,t)=>ce(e,t)},i.id):(0,d.jsx)(mn,{})]}),N&&(0,d.jsxs)(l.ModalYesNo,{title:D.rewindTitle,onClose:()=>P(null),onYes:async()=>(se(N.entry,N.text),!0),children:[(0,d.jsx)(`p`,{className:`text-sm`,children:D.rewindText}),(0,d.jsx)(`ul`,{className:`mt-2 list-disc space-y-0.5 ps-5 text-sm text-muted-foreground`,children:N.steps.slice(0,8).map(e=>(0,d.jsx)(`li`,{children:e},e))})]})]})]}):(0,d.jsxs)(d.Fragment,{children:[X,ge,ve,Z,xe]})}function xn(e,t){let{setPageContext:n}=Le(),r=(0,u.useRef)(crypto.randomUUID()).current;(0,u.useEffect)(()=>(n(r,e,t??null),()=>n(r,null)),[e,t])}function Sn(e,t,n,r,i=!0,a){let{registerComponentAnchor:o}=Le(),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=ht,exports.AGENTICO_MIN_WIDTH=mt,exports.AGENTICO_WIDTH=pt,exports.AGENTICO_WIDTH_STORAGE_KEY=gt,exports.Agentico=bn,exports.AgenticoProvider=Ie,exports.AgenticoToggle=wt,exports.DEFAULT_REASONING_PART_ID=p,exports.DEFAULT_TEXT_PART_ID=f,exports.JSON_EXPORT_DESTINATION_ID=B,exports.MICRO_PROMPT_REGISTRY=L,exports.ORCHESTRATOR_TASK_ID=Pe,exports.PREVIEW_LIMIT=Ae,exports.PREVIEW_MAX=ke,exports.SUMMARY_MICRO_PROMPT=I,exports.agenticoDe=G,exports.agenticoEn=U,exports.agenticoIt=W,exports.agenticoPromptsEn=te,exports.agenticoPromptsIt=D,exports.agenticoTranslations=Ne,exports.applyMicroPrompts=R,exports.chatHasPersonMessage=be,exports.chatStartedAt=Q,exports.chatThreadOf=Ee,exports.chatTitle=Z,exports.configureAgenticoPrompts=k,exports.configureEntityChatStore=ce,exports.createCrossAgentTools=ee,exports.defineSubagent=_,exports.earlierSessions=De,exports.entityChatTaskId=Te,exports.extractErrorMessage=z,exports.extractJsonBlock=re,exports.findSubagentManifest=x,exports.formatQuestionAnswers=g,exports.getAgenticoPrompts=A,exports.getDestinationRegistry=oe,exports.getEntityChat=he,exports.getSubagentControls=Zt,exports.getSubagentRegistry=b,exports.getSubagentReport=Kt,exports.hasEntityChatBackend=le,exports.imagePreviews=Me,exports.jsonExportDestination=V,exports.listEntityChats=we,exports.messagePartsText=h,exports.onEntityChatsChange=me,exports.placeEvents=Oe,exports.registerCrossAgentTools=C,exports.registerDestinations=ae,exports.registerSubagentControls=Xt,exports.registerSubagentReports=Gt,exports.registerSubagents=y,exports.removeEntityChat=Ce,exports.renameEntityChat=Se,exports.renderRegistryCli=ne,exports.renderSubagentCli=F,exports.resetAgenticoPrompts=j,exports.saveEntityChat=ge,exports.syncEntityChats=J,exports.toJsonSchema=w,exports.toMcpTool=T,exports.upsertMessagePart=m,exports.useAgent=It,exports.useAgentico=Le,exports.useAgenticoI18n=$,exports.useAgenticoPageContext=xn,exports.useSubagentComponentContext=Sn;
29
29
  //# sourceMappingURL=index.js.map