@llmnative/agentico 0.16.0 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,25 +5,25 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
5
5
 
6
6
  {chat}`},k={orchestratorIntro:`Sei Agentico, l'orchestratore dei tool di questa applicazione. Il tuo compito è capire cosa vuole ottenere l'utente e, una volta raccolti tutti i parametri necessari, avviare il tool giusto tra quelli elencati sotto — non eseguirlo tu stesso "a parole", invocalo come strumento.`,responseRules:[`PRIMA di chiedere qualunque parametro, controlla il "Contesto pagina" (se presente) qui sotto: se un parametro richiesto dal comando è già lì o si può dedurre da lì con ragionevole certezza (es. l'utente sta guardando lo storico di un tool specifico, o un'esecuzione passata con parametri simili), USALO direttamente — non chiederlo di nuovo all'utente. Chiedi solo i parametri che NON emergono in nessun modo dal contesto.`,`Il comando "<subagent>_<comando>" con cui chiudi è quello che fa il lavoro di analisi vero (matching, generazione, estrazione — qualunque cosa il suo comando descriva) — MAI provare a produrlo tu stesso in chat una volta raccolti i dati grezzi.`,`Se mancano davvero parametri (non deducibili dal contesto né da un tool di raccolta dati) per uno dei comandi elencati, fai domande in linguaggio naturale, una alla volta, finché non hai raccolto tutto.`,`Quando hai TUTTI i parametri richiesti di UN comando (raccolti dall'utente, dedotti dal contesto, o ottenuti da un tool di raccolta dati), invoca davvero lo strumento con quel nome ("<subagent>_<comando>") passandogli i parametri — non limitarti a descriverlo a parole, e non sostituirti al lavoro che quel comando è progettato per fare.`,`Invoca al massimo un comando per turno.`,`Se la richiesta dell'utente non è coperta da nessuno dei tool elencati, dillo chiaramente invece di inventarne uno.`,`IMPORTANTE: quando invochi un comando "<subagent>_<comando>", il tuo commento in QUESTO turno deve annunciare solo l'AVVIO del lavoro (es. "Avvio l'estrazione…", "Sto preparando il mapping…") — MAI descriverne l'esito come già ottenuto (colori, font, loghi, mapping, o qualunque altro dato del risultato) e MAI dire che qualcosa "si è aperto" o "è pronto da rivedere". Il vero lavoro parte DOPO questo turno, in una sessione che tu non vedrai mai: qualunque tua descrizione dell'esito a questo punto sarebbe un'invenzione, anche se il tool ha risposto senza errori.`,`Dopo aver invocato un comando, non proporre spontaneamente altri subagent scollegati dalla richiesta corrente — l'utente aprirà lui una nuova conversazione se gli servirà altro.`],responseRulesHeading:`## Come rispondere`,toolsHeading:`## Tool disponibili`,pageContextHeading:`## Contesto pagina`,pageContextIntro:`L'utente sta interagendo da questo punto dell'app — usalo per capire a cosa si riferisce se non è esplicito nella richiesta:`,userRequestHeading:`## Richiesta dell'utente`,noToolsAvailable:`Nessun tool disponibile.`,stopCallingTools:`Basta chiamare tool. Rispondi ORA con il risultato finale, nel formato richiesto, usando tutte le informazioni raccolte finora.`,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}`},A=O;function j(e){A={...A,...e}}function M(){return A}function N(){A=O}function P(e,t){return`${e} ${t.map(e=>e.required?`--${e.key} <${e.type}>`:`[--${e.key} <${e.type}>]`).join(` `)}`.trim()}function F(e,t){let n=D(t),r=P(t.name,n),i=n.map(e=>` --${e.key} <${e.type}> (${e.required?`required`:`optional`})${e.description?` — ${e.description}`:``}`);return[`COMMAND: ${e} ${t.name}`,` ${t.summary}`,``,` USAGE`,` ${e} ${r}`,(i.length,``),i.length?` PARAMS`:``,...i,``,` OUTPUT`,I(t.describeOutput(),4),(t.example,``),t.example?` EXAMPLE`:``,t.example?` ${t.example}`:``].filter(e=>e!==``).join(`
9
- `)}function I(e,t){let n=` `.repeat(t);return e.split(`
8
+ {chat}`},A=O;function j(e){A={...A,...e}}function M(){return A}function N(){A=O}function P(e,t){return`${e} ${t.map(e=>e.required?`--${e.key} <${e.type}>`:`[--${e.key} <${e.type}>]`).join(` `)}`.trim()}function ee(e,t){let n=D(t),r=P(t.name,n),i=n.map(e=>` --${e.key} <${e.type}> (${e.required?`required`:`optional`})${e.description?` — ${e.description}`:``}`);return[`COMMAND: ${e} ${t.name}`,` ${t.summary}`,``,` USAGE`,` ${e} ${r}`,(i.length,``),i.length?` PARAMS`:``,...i,``,` OUTPUT`,F(t.describeOutput(),4),(t.example,``),t.example?` EXAMPLE`:``,t.example?` ${t.example}`:``].filter(e=>e!==``).join(`
9
+ `)}function F(e,t){let n=` `.repeat(t);return e.split(`
10
10
  `).map(e=>e&&n+e).join(`
11
- `)}function ee(e){return[`NAME`,` ${e.id} — ${e.label}`,``,`DESCRIPTION`,I(e.description,2),``,...e.commands.map(t=>F(e.id,t))].join(`
12
- `)}function L(e){return e.length===0?M().noToolsAvailable:e.map(e=>`${e.id} [${e.commands.map(e=>e.name).join(`|`)}] — ${e.label}: ${e.commands.map(e=>e.summary).join(` / `)}`).join(`
13
- `)}var R={id:`closing-summary`,get text(){return M().closingSummary}},z={[R.id]:R};function te(e,t){if(!t||t.length===0)return e;let n=t.map(e=>z[e]?.text).filter(e=>!!e);return n.length===0?e:`${e}\n\n${n.join(`
14
- `)}`}function B(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 ne(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 V(n)??n}function V(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 re=`json-export`,H={id:re,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)}}},ie={};function U(e){ie=e}function W(){return{[H.id]:H,...ie}}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`,stepsLabel:`Steps of the agent`,newInstance:`New "{label}" instance`,chatHistory:`Chat history`,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`},ae={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`,stepsLabel:`Passi dell'agente`,newInstance:`Nuova istanza di "{label}"`,chatHistory:`Storico chat`,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`},oe={modelLabel:`Modell`,modelsLoading:`Wird geladen…`,noModelsAvailable:`Keine Modelle verfügbar`,noProviderConnected:`Kein AI-Provider verbunden`,selectModelPlaceholder:`Modell wählen…`,orchestratorStarterHint:`Sag Agentico, was du erreichen willst — es wählt das passende Werkzeug und fragt nach den nötigen Angaben.`,orchestratorStarterPlaceholder:`Beschreibe, was du tun möchtest…`,destinationPickerTitle:`Ergebnis speichern in…`,destinationApplying:`Wird gespeichert…`,destinationNoScope:`Kein Ziel ausgewählt — vor dem Speichern eines auswählen.`,unknownDestination:`Unbekanntes Ziel: {id}`,exportJson:`Als JSON exportieren`,orchestratorUnavailable:`AI nicht verfügbar — öffne das benötigte Werkzeug direkt auf seiner Seite.`,orchestratorContinueWithoutAi:`Weiter ohne AI.`,orchestratorPreparing:`{label} wird vorbereitet…`,orchestratorCollecting:`Parameter für {label} werden gesammelt…`,thinking:`Denke nach…`,stopped:`Vom Benutzer abgebrochen.`,toolRequest:`Werkzeugausführung angefordert`,modelRequestError:`Fehler bei der Anfrage an das Modell`,noProviderResponse:`Keine Antwort vom AI-Provider.`,noActiveSession:`Keine aktive Sitzung — zuerst run() aufrufen.`,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`,stepsLabel:`Schritte des Agenten`,newInstance:`Neue Instanz von "{label}"`,chatHistory:`Chatverlauf`,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`},K=`llmnative.agentico.entityChat`,q;function se(e){K=e.storageKey,q=e.backend}var J=()=>!!q,ce=({synced:e,...t})=>t;function le(e){if(!q)return;let t=Q(e.scopeId,e.subagentId,e.entityId);Promise.resolve(q.save(ce(e))).then(()=>{let e=Y(),n=e.find(e=>Q(e.scopeId,e.subagentId,e.entityId)===t);n&&!n.synced&&Z(e.map(e=>e===n?{...e,synced:!0}:e))},()=>void 0)}async function ue(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=Y(),i=r.filter(t=>t.scopeId!==e),a=r.filter(t=>t.scopeId===e),o=t.map(e=>{let t=a.find(t=>Q(t.scopeId,t.subagentId,t.entityId)===Q(e.scopeId,e.subagentId,e.entityId));return t&&n(t)>n(e)?(le(t),t):{...e,synced:!0}}),s=a.filter(e=>!e.synced&&!t.some(t=>Q(t.scopeId,t.subagentId,t.entityId)===Q(e.scopeId,e.subagentId,e.entityId)));Z([...i,...o,...s]);for(let e of s)le(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 Y(){try{let e=localStorage.getItem(K);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(de).filter(e=>e!==null):[]}catch{return[]}}var X=new Set;function fe(e){return X.add(e),()=>{X.delete(e)}}function Z(e){try{localStorage.setItem(K,JSON.stringify(e))}catch{}for(let e of[...X])e()}var Q=(e,t,n)=>`${e}:${t}:${n}`;function pe(e,t,n){let r=Q(e,t,n);return Y().find(e=>Q(e.scopeId,e.subagentId,e.entityId)===r)??null}function me(e){let t=Q(e.scopeId,e.subagentId,e.entityId),n=Y(),r=n.find(e=>Q(e.scopeId,e.subagentId,e.entityId)===t),i=Date.now(),a=n.filter(e=>e!==r),o={...e,savedAt:i,changedAt:i,startedAt:r?Se(r):i,...r?.name?{name:r.name,namedBy:r.namedBy}:{},...r?.synced?{synced:!0}:{}};a.push(o),Z(a),le(o)}var he=new Set([G,ae,oe].map(e=>e.retryMessage.trim().toLowerCase())),ge=e=>e.kind===`user`&&!!e.detail?.trim()&&!e.retry&&!he.has(e.detail.trim().toLowerCase()),_e=e=>{let t=(e.activity.find(ge)?.detail??``).trim().split(`
15
- `)[0].trim();return t.length>80?`${t.slice(0,80).trimEnd()}…`:t},ve=e=>e.name||_e(e)||e.title||e.entityId,ye=e=>e.activity.some(ge),be=e=>e.kind===`user`&&!ge(e)&&!!e.detail?.trim();function xe(e,t,n,r,i=`person`){let a=Q(e,t,n),o=Y(),s=o.find(e=>Q(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 Z(o.map(e=>e===s?f:e)),le(f),!0}var Se=e=>e.startedAt??e.savedAt;function Ce(e,t,n){let r=Q(e,t,n);Z(Y().filter(e=>Q(e.scopeId,e.subagentId,e.entityId)!==r)),q&&Promise.resolve(q.remove(e,t,n)).catch(()=>void 0)}function we(e){return Y().filter(t=>t.scopeId===e).sort((e,t)=>Se(t)-Se(e))}var Te=(e,t)=>`entitychat-${e}-${t}`,Ee={en:{agentico:G},it:{agentico:ae},de:{agentico:oe}};function $(){let{dict:e}=(0,l.useI18n)(),t=e.agentico;return t?{...G,...t}:G}var De=`agentico-orchestrator`,Oe=(0,u.createContext)(null);function ke({children:e,scope:t=null}){let[n,r]=(0,u.useState)(null),i=(0,u.useRef)(null);(0,u.useEffect)(()=>{i.current=n},[n]);let[a,o]=(0,u.useState)(!1),s=t?.id;(0,u.useEffect)(()=>{s&&ue(s).catch(()=>void 0)},[s]);let c=(0,u.useCallback)(e=>{let t=i.current;t&&t.id!==e.id&&t.onDismiss();let n=t&&t.id===e.id&&t.savedToDisk&&e.savedToDisk===void 0?{...e,savedToDisk:!0}:e;r(n)},[]),l=(0,u.useCallback)(e=>{r(t=>t&&t.id===e?null:t)},[]),f=(0,u.useCallback)(()=>o(e=>!e),[]),p=(0,u.useCallback)(()=>o(!0),[]),[m,h]=(0,u.useState)(null),[g,_]=(0,u.useState)(void 0),[v,y]=(0,u.useState)(void 0),[b,S]=(0,u.useState)(void 0),[C,w]=(0,u.useState)(null),[T,E]=(0,u.useState)(null),[D,O]=(0,u.useState)(void 0),[k,A]=(0,u.useState)([]),j=(0,u.useCallback)((e,t,n=null)=>{A(r=>{let i=r.filter(t=>t.id!==e);return t?[...i,{id:e,text:t,card:n}]:i})},[]),N=k.length>0?k[k.length-1]:null,[P,F]=(0,u.useState)([]),I=(0,u.useCallback)((e,t)=>{F(n=>{let r=n.filter(t=>t.id!==e);return t?[...r,{id:e,...t}]:r})},[]),ee=(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]),te=(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`${M().multipleCandidates}\n\n${e}`},[R])??N?.text??null,B=R.length>0?null:N?.card??null,ne=(0,u.useMemo)(()=>[...new Set(ee.map(e=>e.subagentId))],[ee]),V=ne.length===1?ne[0]:ne.length===0?N?.card?.subagentId??null:null,re=(0,u.useCallback)((e,t)=>{p();let n=i.current;if(n?.id===`agentico-orchestrator`)return;let r=V&&n?.id.startsWith(`subagent-${V}-`)?n:void 0;E(r?{taskId:r.id,activity:[...r.precedingActivity??[],...r.agent.activity]}:null),h(e),_(t?.extraDestinations),y(t?.attachments),S(t?.model),O(t?.scopedSubagentId),w(crypto.randomUUID())},[p,V]),H=(0,u.useCallback)((e,t,n,a,o,s)=>{if(!n||!a)return;let c=i.current;if(!c||c.id!==n)return;let l=c.agent.snapshot();l&&(me({scopeId:a,subagentId:e,entityId:t,params:o,title:s,history:l.history,activity:[...c.precedingActivity??[],...l.activity]}),r(e=>e&&e.id===n?{...e,savedToDisk:!0}:e))},[]),[ie,U]=(0,u.useState)(null),[W,G]=(0,u.useState)(null),ae=(0,u.useCallback)((e,t,n)=>{p(),U({subagentId:e,entityId:t,snapshot:n}),G(crypto.randomUUID())},[p]),[oe,K]=(0,u.useState)(null),[q,se]=(0,u.useState)(null),J=(0,u.useCallback)((e,t)=>{p(),l(De),K({subagentId:e,extraDestinations:t}),se(crypto.randomUUID())},[p,l]),[ce,le]=(0,u.useState)(null),[de,Y]=(0,u.useState)(null),X=(0,u.useCallback)((e,t,n)=>{K(null),le({subagentId:e,params:t,extraDestinations:n}),Y(crypto.randomUUID())},[]),[fe,Z]=(0,u.useState)(null),[Q,pe]=(0,u.useState)(null),he=(0,u.useCallback)((e,t,n)=>{p(),Z({subagentId:e,params:t,...n}),pe(crypto.randomUUID())},[p]),ge=(0,u.useCallback)(()=>{let e=i.current;e&&e.onDismiss()},[]),_e=(0,u.useMemo)(()=>({scope:t,task:n,isOpen:a,openTask:c,closeTask:l,toggleOpen:f,pendingGoal:m,startOrchestrator:re,pageContext:te,pageContextCard:B,setPageContext:j,scopedSubagentId:V,pendingScopedSubagentId:D,componentAnchors:ee,anchoredUserMessages:z,registerComponentAnchor:I,openPanel:p,pendingExtraDestinations:g,pendingAttachments:v,pendingModel:b,orchestratorRunId:C,pendingCarryOver:T,commitEntityChat:H,resumeEntityChat:ae,pendingResume:ie,resumeRunId:W,dismissForeignTask:ge,pendingManualEntry:oe,manualEntryRunId:q,startManualEntry:J,pendingResumeWithAI:ce,resumeWithAIRunId:de,resumeWithAI:X,startSubagent:he,pendingStart:fe,startRunId:Q}),[t,n,a,c,l,f,m,re,te,B,j,V,D,ee,z,I,p,g,v,b,C,T,H,ae,ie,W,ge,oe,q,J,ce,de,X,he,fe,Q]);return(0,d.jsx)(Oe.Provider,{value:_e,children:e})}function Ae(){let e=(0,u.useContext)(Oe);if(!e)throw Error(`useAgentico must be used inside AgenticoProvider`);return e}function je(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(...je(u)),l}function Me(e){let t=[],n=/```(\w+)?\n?([\s\S]*?)```/g,r=0,i;for(;i=n.exec(e);)i.index>r&&t.push(...je(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(...je(e.slice(r))),t}function Ne({content:e,language:t}){let[n,r]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`relative cursor-pointer rounded-md ${n?`max-h-80 overflow-y-auto`:`max-h-28 overflow-hidden`}`,onClick:()=>r(e=>!e),title:n?`Clic per comprimere`:`Clic per espandere`,children:[(0,d.jsx)(l.Code,{language:t,showCopy:n,background:`transparent`,className:`!text-[11px]`,children:e}),!n&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-muted/30 to-transparent`})]})}function Pe({text:e,tone:t}){let n=Me(e);return(0,d.jsx)(d.Fragment,{children:n.map((e,n)=>e.type===`code`?(0,d.jsx)(Ne,{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 Fe(){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 Ie({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 Le(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 Re=96,ze=e=>e.some(e=>e.status===`stopped`||e.status===`error`);function Be({entry:e,pinned:t=!0,actions:n,cut:r=!1}){let i=$(),a=(0,u.useRef)(null),[o,s]=(0,u.useState)(!1),[c,f]=(0,u.useState)(!1);(0,u.useLayoutEffect)(()=>{let e=a.current;e&&f(e.scrollHeight>97)},[e.detail,e.attachmentNames]);let p=c&&!o;return(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:[r&&(0,d.jsx)(l.ActionButton,{icon:`rotate-ccw`,ariaLabel:i.retry,title:i.retry,variant:`link`,className:`p-1 text-muted-foreground hover:text-foreground`,disabled:n.disabled,onClick:()=>n.onRetry(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:i.editMessage,title:i.editMessage,variant:`link`,className:`p-1 text-muted-foreground hover:text-foreground`,disabled:n.disabled,onClick:()=>n.onEdit(e)})})]}),(0,d.jsxs)(`div`,{className:`max-w-[85%] rounded-lg bg-primary/10 text-xs text-foreground`,children:[(0,d.jsxs)(`div`,{ref:a,className:`space-y-1 px-2.5 pt-1.5 ${p?`overflow-hidden`:``}`,style:p?{maxHeight:Re}: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)(Pe,{text:e.detail??``})]}),c&&(0,d.jsxs)(`button`,{type:`button`,onClick:()=>s(e=>!e),className:`relative flex w-full items-center justify-center rounded-b-lg py-1 text-muted-foreground hover:bg-primary/15`,title:o?`Comprimi`:`Espandi`,children:[p&&(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:o?`chevron-up`:`chevron-down`,size:12})]})]})]})}var Ve={running:`loader-circle`,done:`check`,error:`x`,stopped:`circle-slash`};function He({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:Ve[e.status]}))}]})}function Ue({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 We(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 Ge({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 Ke({entry:e,questions:t,hiddenPartId:n}){let r=(e.parts??[]).filter(e=>e.type!==`questions`||e.id!==n),i=[];for(let e of r){let t=i.at(-1);e.type===`tool`?t&&`steps`in t?t.steps.push(e):i.push({key:`tool-${e.id}`,steps:[e]}):i.push({key:`${e.type}-${e.id}`,part:e})}return(0,d.jsx)(`div`,{className:`space-y-2`,children:i.map(n=>{if(`steps`in n)return(0,d.jsx)(He,{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)(Ue,{entry:e,part:r,questions:t},n.key):(0,d.jsx)(Ge,{entry:e,part:r,questions:t},n.key)})})}function qe({entry:e,questions:t,hiddenPartId:n}){let r=$();if(e.kind===`thinking`&&e.parts){let i=e.status===`error`||e.status===`stopped`||e.status===`running`;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[e.parts.length>0&&(0,d.jsx)(Ke,{entry:e,questions:t,hiddenPartId:n}),i&&(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5 ${e.parts.length>0?`mt-1`:``}`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(Ie,{status:e.status})}),(0,d.jsxs)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:[Le(e,r),e.status===`running`&&(0,d.jsx)(Fe,{})]})]})]})}let i=e.kind===`thinking`&&e.detail?Me(e.detail):[],a=i.filter(e=>e.type===`code`),o=i.filter(e=>e.type===`text`&&e.content.trim()),s=e.kind===`thinking`?Le(e,r):e.label;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(Ie,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:s})]}),a.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-1`,children:a.map((e,t)=>(0,d.jsx)(Ne,{content:e.content,language:e.language},t))}),o.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-2`,children:o.map((e,t)=>(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:`muted`,className:`break-words text-xs leading-relaxed`},t))})]})}function Je({activity:e,questions:t,docked:n,pinUserMessages:r=!0,messageActions:i}){if(e.length===0)return null;let a=[];for(let t of e)t.kind===`user`||a.length===0?a.push(t.kind===`user`?{user:t,entries:[]}:{entries:[t]}):a[a.length-1].entries.push(t);return(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:a.map(e=>(0,d.jsxs)(`li`,{children:[e.user&&(0,d.jsx)(Be,{entry:e.user,pinned:r,actions:i,cut:ze(e.entries)}),e.entries.length>0&&(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:e.entries.map(e=>(0,d.jsx)(qe,{entry:e,questions:t,hiddenPartId:n?.entry.id===e.id?n.part.id:void 0},e.id))})]},e.user?.id??e.entries[0]?.id))})}var Ye=420,Xe=320,Ze=`60vw`,Qe=`agentico:panel-width`;function $e(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 et(e,t,n){return Math.round(Math.min(Math.max(e,t),Math.max(t,n)))}function tt(){try{let e=window.localStorage.getItem(Qe),t=e===null?NaN:Number(e);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function nt(e){try{e===null?window.localStorage.removeItem(Qe):window.localStorage.setItem(Qe,String(e))}catch{}}function rt(){return typeof window>`u`?1/0:window.innerWidth}function it({defaultWidth:e=420,minWidth:t=320,maxWidth:n=Ze,onWidthChange:r}){let[i,a]=(0,u.useState)(rt),[o,s]=(0,u.useState)(()=>tt()??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,$e(n,i)),d=et(o,c,l);return(0,u.useEffect)(()=>{r?.(d)},[d]),{width:d,min:c,max:l,set:(0,u.useCallback)(e=>s(et(e,c,l)),[c,l]),commit:(0,u.useCallback)(e=>nt(et(e,c,l)),[c,l]),reset:(0,u.useCallback)(()=>{s(e),nt(null)},[e])}}function at({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 ot({className:e=``}){let{isOpen:t,toggleOpen:n,task:r}=Ae(),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 st=`llmnative-cms.selectedAIModel`;function ct(){try{return localStorage.getItem(st)??``}catch{return``}}function lt(e){try{e?localStorage.setItem(st,e):localStorage.removeItem(st)}catch{}}function ut(){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)(ct);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:(lt(``),``))}).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=>{lt(e),s(e)}}}var dt=`approval`;function ft(e,t){return typeof e.needsApproval==`function`?e.needsApproval(t):e.needsApproval===!0}function pt(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,ht=26e4;function gt(e){return e.filter(e=>!l.PromptUtils.isTextAttachment(e.mimeType)||e.base64.length<=ht)}function _t(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 vt(e,t={}){let{defaultEnabled:n=!1}=t,[r,i]=(0,u.useState)(n),{hasProviders:a,modelsByProvider:o,modelsLoading:s,selectedModel:c,setSelectedModel:d}=ut(),[p,_]=(0,u.useState)(!1),[v,y]=(0,u.useState)(null),[b,x]=(0,u.useState)(!1),[S,C]=(0,u.useState)([]),w=(0,u.useRef)([]),E=e=>{C(t=>{let n=typeof e==`function`?e(t):e;return w.current=n,n})},D=(0,u.useRef)(new Map),O=$(),k=(0,u.useRef)(O);k.current=O;let A=(0,u.useRef)(null),j=(0,u.useRef)(!1),N=(0,u.useRef)(null),P=(0,u.useRef)(null),F=(0,u.useRef)(null),I=()=>{F.current?.abort()},ee=(0,l.useAIProviderRegistry)()?.registry??{},[L,R]=(0,u.useState)(void 0),z=(0,u.useRef)(void 0),ne=(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(o).map(([e,t])=>[e,t.filter(e=>L.includes(e.provider))]).filter(([,e])=>e.length)):o,[L,o]),re=ne(L,c)?c:Object.values(V).flat()[0]?.id??``,H=r&&re?(0,l.parseAIModelRef)(re):null,ie=H?ee[H.provider]:null,U=e.executor,W=!!U?.alongside,G=!!U&&!W,ae=!U||!!U.canRewind,oe=!!U?.attachments,K=async e=>oe&&e?.length?Promise.all(e.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,q=(0,u.useRef)([]),se=e=>!!e&&q.current.some(t=>t.value===e),J=(0,u.useRef)(!1),[ce,le]=(0,u.useState)([]),[ue,de]=(0,u.useState)(``),Y=(0,u.useRef)(``),X=e=>{Y.current=e,de(e)},fe=e=>{let t=U?.models?.(e)??[];q.current=t,le(t);let n=U?.catalogProviders?.(e);z.current=n,R(n);let r=W&&!ne(n,c)?t[0]?.value:void 0;X(U?.defaultModel?.(e)??r??``)},Z=async(e,t,n,r,i)=>{let a=A.current;if(!a||!U)return y(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}})},b=e=>p({type:`tool`,id:e.id,label:e.label,status:e.status}),x=e=>p({...e,type:`card`}),S=new Set,C=0,T=()=>{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`,T);let O=(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})}))},j=(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`,T);for(let e of S)D.current.delete(e);S.clear()},M=e||r?.historyText||``;try{let c=N.current;N.current=null;let l=w.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||Y.current?{model:n||Y.current}:{},...r?{answers:{id:r.id,answers:r.answers}}:{},onText:_,onReasoning:v,onStep:b,onQuestions:O,onCard:x});return j(`done`,f.text),a.history=[...a.history,...M?[{role:`user`,content:M}]:[],{role:`assistant`,content:f.text}],f.result??null}catch(e){return a.history=[...a.history,...M?[{role:`user`,content:M}]:[]],o.signal.aborted?(j(`stopped`),null):(j(`error`),y(B(e)),null)}finally{F.current=null}},Q=async(t,n,r)=>{let i=w.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:B(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))},pe=async(e,t,n)=>{let r=w.current.find(t=>t.id===e)?.parts?.find(e=>e.type===`questions`&&e.id===t);if(!r||r.type!==`questions`)throw y(k.current.noActiveSession),Error(k.current.noActiveSession);let i=()=>E(r=>r.map(r=>r.id===e?{...r,parts:r.parts?.map(e=>e.type===`questions`&&e.id===t?{...e,answers:n}:e)}:r)),a=`${e}:${t}`,o=D.current.get(a);if(o)return D.current.delete(a),i(),o.resolve(n),null;if(j.current)throw y(k.current.requestInProgress),Error(k.current.requestInProgress);if(!G||!A.current)throw y(k.current.noActiveSession),Error(k.current.noActiveSession);j.current=!0,_(!0),y(null),i();try{return await Z(``,!1,void 0,{id:t,answers:n,historyText:g(r.questions,n)})}finally{j.current=!1,_(!1)}},me=async(t,n,r)=>{let i=z.current,a=Object.values(o).flat().find(e=>!i||i.includes(e.provider))?.id,s=r&&ne(i,r)?r:ne(i,re)?void 0:a,c=s?(0,l.parseAIModelRef)(s):H,u=c&&A.current?U?.catalogReasoning?.(A.current.params,c.provider):void 0,d=u?{reasoning:u}:{},f=A.current;if(!f)return y(k.current.noActiveSession),null;let p=s?(0,l.parseAIModelRef)(s):H,m=p?ee[p.provider]:null;if(!m||!p)return y(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<=ht?`\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=gt(n??[]),_=f.tools.map(e=>({name:e.name,description:e.description,inputSchema:T(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:dt,questions:[{header:i.approvalHeader,question:i.approveQuestion.replace(`{action}`,o),options:[{label:i.approve},{label:i.reject}],custom:!0}]}]}]);let s=`${a}:${dt}`;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(pt(t,i.approve,i.reject))},reject:t})})},b=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`),y(B(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`),y(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}),y(k.current.invalidResponse),e.fallback(f.params,f.context));let o=a.toolCalls.map(e=>{let t=b.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=b.get(t.name);if(n&&ft(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=b.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=M().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:B(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:te(M().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||y(k.current.tooManyToolTurns),e.fallback(f.params,f.context)}finally{F.current=null}},he=async(t,n)=>{if(j.current)return y(k.current.requestInProgress),null;j.current=!0,y(null),E(n?.openingMessage?[{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:n.openingMessage,...n.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]:[]),_(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];if(A.current={params:t,context:i,tools:o,history:[],logId:crypto.randomUUID(),attachmentsRef:a},G)return x(!0),fe(t),await Z(n?.openingMessage??``,!0,void 0,void 0,await K(n?.attachments));if(W){fe(t),J.current=!1;let e=n?.model||Y.current;if(se(e))return x(!0),J.current=!0,await Z(n?.openingMessage??``,!0,e,void 0,await K(n?.attachments))}let s=n?.model||void 0,c=s?!!ee[(0,l.parseAIModelRef)(s)?.provider??``]:!!ie;if(!r||!c){x(!1);let n=e.fallback(t,i);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.aiDisabledFallback}]),n}x(!0);let u=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,d=te(e.buildPrompt(t,i),e.microPromptIds);return await me(d,u,s)}catch(e){return y(B(e)),null}finally{j.current=!1,_(!1)}},ge=async(t,n)=>{if(j.current){y(k.current.requestInProgress);return}j.current=!0,y(null),E(_t(n.activity)),_(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];A.current={params:t,context:i,tools:o,history:n.history,logId:crypto.randomUUID(),attachmentsRef:a},(G||W)&&fe(t),J.current=!1,x(G||W||r&&!!ie)}catch(e){y(B(e))}finally{j.current=!1,_(!1)}},_e=async(t,n)=>{if(j.current)return y(k.current.requestInProgress),null;if(y(null),!t.trim())return y(`Messaggio vuoto.`),null;let r=A.current;if(!r)return y(k.current.noActiveSession),null;j.current=!0,_(!0);let i=crypto.randomUUID();P.current=i,E(e=>[...e,{id:i,kind:`user`,label:`Tu`,status:`done`,detail:t,...n?.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{},...n?.retry?{retry:!0}:{},historyAt:r.history.length}]);try{if(G)return await Z(t,!1,n?.model||void 0,void 0,await K(n?.attachments));let i=n?.model||(W?Y.current:``);if(W&&se(i)){let e=!J.current;return J.current=!0,await Z(t,e,i,void 0,await K(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=te(e.buildFollowUpPrompt(t,r.params,r.context),e.microPromptIds);return await me(o,a,n?.model||void 0)}catch(e){return y(B(e)),null}finally{j.current=!1,_(!1)}},ve=e=>{let t=A.current,n=S.findIndex(t=>t.id===e),r=S[n],i=r?.detail?.trim();if(!ae||!t||!r||r.kind!==`user`||!i)return;if(r.historyAt!==void 0)return r.historyAt;let a=S.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===S.map(e=>e.kind===`user`).lastIndexOf(!0)?t.history.length:void 0},ye=e=>ve(e)!==void 0,be=async(e,t)=>{if(j.current)return y(k.current.requestInProgress),null;let n=A.current,r=S.findIndex(t=>t.id===e),i=S[r],a=ve(e);if(!n||!i||a===void 0)return null;let o=(t??i.detail??``).trim();if(!o)return null;let s=S.slice(0,r);return n.history=n.history.slice(0,a),N.current={activity:s,fresh:!0},E(s),_e(o)},xe=()=>{let t=A.current;if(!t)return null;y(null);let n=e.fallback(t.params,t.context);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.continueWithoutAiFallback}]),n},Se=()=>A.current?{history:A.current.history,activity:S}:null;return{enabled:r,setEnabled:i,hasProviders:a,selectedModel:G||W&&ue?ue:re,setSelectedModel:G?X:W?e=>{se(e)?X(e):(X(``),d(e))}:d,modelsByProvider:V,modelsLoading:s,running:p,error:v,canContinue:b,remote:G,remoteModels:ce,alongside:W,...U?.catalogGroup?{catalogGroup:U.catalogGroup}:{},activity:S,run:he,resume:ge,sendMessage:_e,stop:I,runFallback:xe,snapshot:Se,answerQuestions:pe,cardAction:Q,rewind:be,canRewind:ae,rewindable:ye,executorAttachments:oe,offersFallback:e.offersFallback!==!1}}function yt(){let e=M();return[e.responseRulesHeading,...e.responseRules.map(e=>`- ${e}`)].join(`
17
- `)}function bt(e,t,n){let r=M(),i=n?`\n${r.pageContextHeading}\n${r.pageContextIntro}\n${n}\n`:``;return`${r.orchestratorIntro}
11
+ `)}function te(e){return[`NAME`,` ${e.id} — ${e.label}`,``,`DESCRIPTION`,F(e.description,2),``,...e.commands.map(t=>ee(e.id,t))].join(`
12
+ `)}function I(e){return e.length===0?M().noToolsAvailable:e.map(e=>`${e.id} [${e.commands.map(e=>e.name).join(`|`)}] — ${e.label}: ${e.commands.map(e=>e.summary).join(` / `)}`).join(`
13
+ `)}var L={id:`closing-summary`,get text(){return M().closingSummary}},R={[L.id]:L};function ne(e,t){if(!t||t.length===0)return e;let n=t.map(e=>R[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 B(n)??n}function B(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)}}},ie={};function ae(e){ie=e}function U(){return{[H.id]:H,...ie}}var W={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`,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}`,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`},G={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`,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}`,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`},oe={modelLabel:`Modell`,modelsLoading:`Wird geladen…`,noModelsAvailable:`Keine Modelle verfügbar`,noProviderConnected:`Kein AI-Provider verbunden`,selectModelPlaceholder:`Modell wählen…`,orchestratorStarterHint:`Sag Agentico, was du erreichen willst — es wählt das passende Werkzeug und fragt nach den nötigen Angaben.`,orchestratorStarterPlaceholder:`Beschreibe, was du tun möchtest…`,destinationPickerTitle:`Ergebnis speichern in…`,destinationApplying:`Wird gespeichert…`,destinationNoScope:`Kein Ziel ausgewählt — vor dem Speichern eines auswählen.`,unknownDestination:`Unbekanntes Ziel: {id}`,exportJson:`Als JSON exportieren`,orchestratorUnavailable:`AI nicht verfügbar — öffne das benötigte Werkzeug direkt auf seiner Seite.`,orchestratorContinueWithoutAi:`Weiter ohne AI.`,orchestratorPreparing:`{label} wird vorbereitet…`,orchestratorCollecting:`Parameter für {label} werden gesammelt…`,thinking:`Denke nach…`,stopped:`Vom Benutzer abgebrochen.`,toolRequest:`Werkzeugausführung angefordert`,modelRequestError:`Fehler bei der Anfrage an das Modell`,noProviderResponse:`Keine Antwort vom AI-Provider.`,noActiveSession:`Keine aktive Sitzung — zuerst run() aufrufen.`,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`,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}`,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`},K=`llmnative.agentico.entityChat`,q;function se(e){K=e.storageKey,q=e.backend}var ce=()=>!!q,le=({synced:e,...t})=>t;function ue(e){if(!q)return;let t=Z(e.scopeId,e.subagentId,e.entityId);Promise.resolve(q.save(le(e))).then(()=>{let e=J(),n=e.find(e=>Z(e.scopeId,e.subagentId,e.entityId)===t);n&&!n.synced&&X(e.map(e=>e===n?{...e,synced:!0}:e))},()=>void 0)}async function de(e){if(!q)return;let t=(await q.load(e)).map(fe).filter(t=>t!==null&&t.scopeId===e),n=e=>e.changedAt??e.savedAt,r=J(),i=r.filter(t=>t.scopeId!==e),a=r.filter(t=>t.scopeId===e),o=t.map(e=>{let t=a.find(t=>Z(t.scopeId,t.subagentId,t.entityId)===Z(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=>Z(t.scopeId,t.subagentId,t.entityId)===Z(e.scopeId,e.subagentId,e.entityId)));X([...i,...o,...s]);for(let e of s)ue(e)}function fe(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 J(){try{let e=localStorage.getItem(K);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(fe).filter(e=>e!==null):[]}catch{return[]}}var Y=new Set;function pe(e){return Y.add(e),()=>{Y.delete(e)}}function X(e){try{localStorage.setItem(K,JSON.stringify(e))}catch{}for(let e of[...Y])e()}var Z=(e,t,n)=>`${e}:${t}:${n}`;function me(e,t,n){let r=Z(e,t,n);return J().find(e=>Z(e.scopeId,e.subagentId,e.entityId)===r)??null}function he(e){let t=Z(e.scopeId,e.subagentId,e.entityId),n=J(),r=n.find(e=>Z(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),X(a),ue(o)}var ge=new Set([W,G,oe].map(e=>e.retryMessage.trim().toLowerCase())),_e=e=>e.kind===`user`&&!!e.detail?.trim()&&!e.retry&&!ge.has(e.detail.trim().toLowerCase()),ve=e=>{let t=(e.activity.find(_e)?.detail??``).trim().split(`
15
+ `)[0].trim();return t.length>80?`${t.slice(0,80).trimEnd()}…`:t},ye=e=>e.name||ve(e)||e.title||e.entityId,be=e=>e.activity.some(_e),xe=e=>e.kind===`user`&&!_e(e)&&!!e.detail?.trim();function Se(e,t,n,r,i=`person`){let a=Z(e,t,n),o=J(),s=o.find(e=>Z(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 X(o.map(e=>e===s?f:e)),ue(f),!0}var Q=e=>e.startedAt??e.savedAt;function Ce(e,t,n){let r=Z(e,t,n);X(J().filter(e=>Z(e.scopeId,e.subagentId,e.entityId)!==r)),q&&Promise.resolve(q.remove(e,t,n)).catch(()=>void 0)}function we(e){return J().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))}var Oe={en:{agentico:W},it:{agentico:G},de:{agentico:oe}};function $(){let{dict:e}=(0,l.useI18n)(),t=e.agentico;return t?{...W,...t}:W}var ke=`agentico-orchestrator`,Ae=(0,u.createContext)(null);function je({children:e,scope:t=null,person:n=null}){let[r,i]=(0,u.useState)(null),a=(0,u.useRef)(null);(0,u.useEffect)(()=>{a.current=r},[r]);let[o,s]=(0,u.useState)(!1),c=t?.id;(0,u.useEffect)(()=>{c&&de(c).catch(()=>void 0)},[c]);let l=(0,u.useCallback)(e=>{let t=a.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;i(n)},[]),f=(0,u.useCallback)(e=>{i(t=>t&&t.id===e?null:t)},[]),p=(0,u.useCallback)(()=>s(e=>!e),[]),m=(0,u.useCallback)(()=>s(!0),[]),[h,g]=(0,u.useState)(null),[_,v]=(0,u.useState)(void 0),[y,b]=(0,u.useState)(void 0),[S,C]=(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,j]=(0,u.useState)([]),N=(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})},[]),P=A.length>0?A[A.length-1]:null,[ee,F]=(0,u.useState)([]),te=(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)(()=>ee.map(e=>({subagentId:e.subagentId,componentKey:e.componentKey,onResult:e.onResult,pinnedEntityId:e.pinnedEntityId})),[ee]),L=(0,u.useMemo)(()=>{let e=new Map;for(let t of ee)e.set(t.subagentId,{subagentId:t.subagentId,componentKey:t.componentKey,onResult:t.onResult,contextInfo:t.contextInfo});return[...e.values()]},[ee]),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]),ne=(0,u.useMemo)(()=>R.map(e=>e.userMessage),[R]),z=(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`${M().multipleCandidates}\n\n${e}`},[R])??P?.text??null,re=R.length>0?null:P?.card??null,B=(0,u.useMemo)(()=>[...new Set(I.map(e=>e.subagentId))],[I]),V=B.length===1?B[0]:B.length===0?P?.card?.subagentId??null:null,H=(0,u.useCallback)((e,t)=>{m();let n=a.current;if(n?.id===`agentico-orchestrator`)return;let r=V&&n?.id.startsWith(`subagent-${V}-`)?n:void 0;D(r?{taskId:r.id,activity:[...r.precedingActivity??[],...r.agent.activity]}:null),g(e),v(t?.extraDestinations),b(t?.attachments),C(t?.model),k(t?.scopedSubagentId),T(crypto.randomUUID())},[m,V]),ie=(0,u.useCallback)((e,t,n,r,o,s)=>{if(!n||!r)return;let c=a.current;if(!c||c.id!==n)return;let l=c.agent.snapshot();l&&(he({scopeId:r,subagentId:e,entityId:t,params:o,title:s,history:l.history,activity:[...c.precedingActivity??[],...l.activity]}),i(e=>e&&e.id===n?{...e,savedToDisk:!0}:e))},[]),[ae,U]=(0,u.useState)(null),[W,G]=(0,u.useState)(null),oe=(0,u.useCallback)((e,t,n)=>{m(),U({subagentId:e,entityId:t,snapshot:n}),G(crypto.randomUUID())},[m]),[K,q]=(0,u.useState)(null),[se,ce]=(0,u.useState)(null),le=(0,u.useCallback)((e,t)=>{m(),f(ke),q({subagentId:e,extraDestinations:t}),ce(crypto.randomUUID())},[m,f]),[ue,fe]=(0,u.useState)(null),[J,Y]=(0,u.useState)(null),pe=(0,u.useCallback)((e,t,n)=>{q(null),fe({subagentId:e,params:t,extraDestinations:n}),Y(crypto.randomUUID())},[]),[X,Z]=(0,u.useState)(null),[me,ge]=(0,u.useState)(null),_e=(0,u.useCallback)((e,t,n)=>{m(),Z({subagentId:e,params:t,...n}),ge(crypto.randomUUID())},[m]),ve=(0,u.useCallback)(()=>{let e=a.current;e&&e.onDismiss()},[]),ye=(0,u.useMemo)(()=>({scope:t,person:n,task:r,isOpen:o,openTask:l,closeTask:f,toggleOpen:p,pendingGoal:h,startOrchestrator:H,pageContext:z,pageContextCard:re,setPageContext:N,scopedSubagentId:V,pendingScopedSubagentId:O,componentAnchors:I,anchoredUserMessages:ne,registerComponentAnchor:te,openPanel:m,pendingExtraDestinations:_,pendingAttachments:y,pendingModel:S,orchestratorRunId:w,pendingCarryOver:E,commitEntityChat:ie,resumeEntityChat:oe,pendingResume:ae,resumeRunId:W,dismissForeignTask:ve,pendingManualEntry:K,manualEntryRunId:se,startManualEntry:le,pendingResumeWithAI:ue,resumeWithAIRunId:J,resumeWithAI:pe,startSubagent:_e,pendingStart:X,startRunId:me}),[t,n,r,o,l,f,p,h,H,z,re,N,V,O,I,ne,te,m,_,y,S,w,E,ie,oe,ae,W,ve,K,se,le,ue,J,pe,_e,X,me]);return(0,d.jsx)(Ae.Provider,{value:ye,children:e})}function Me(){let e=(0,u.useContext)(Ae);if(!e)throw Error(`useAgentico must be used inside AgenticoProvider`);return e}function Ne(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(...Ne(u)),l}function Pe(e){let t=[],n=/```(\w+)?\n?([\s\S]*?)```/g,r=0,i;for(;i=n.exec(e);)i.index>r&&t.push(...Ne(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(...Ne(e.slice(r))),t}function Fe({content:e,language:t}){let[n,r]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`relative cursor-pointer rounded-md ${n?`max-h-80 overflow-y-auto`:`max-h-28 overflow-hidden`}`,onClick:()=>r(e=>!e),title:n?`Clic per comprimere`:`Clic per espandere`,children:[(0,d.jsx)(l.Code,{language:t,showCopy:n,background:`transparent`,className:`!text-[11px]`,children:e}),!n&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-muted/30 to-transparent`})]})}function Ie({text:e,tone:t}){let n=Pe(e);return(0,d.jsx)(d.Fragment,{children:n.map((e,n)=>e.type===`code`?(0,d.jsx)(Fe,{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 Le(){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 Re({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 ze(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 Be=96,Ve=e=>e.some(e=>e.status===`stopped`||e.status===`error`);function He({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})}function Ue({speaker:e}){return(0,d.jsxs)(`div`,{className:`flex items-center gap-1.5 pt-1 text-xs font-medium text-foreground`,children:[(0,d.jsx)(He,{author:e,size:18}),(0,d.jsx)(`span`,{className:`truncate`,children:e.name})]})}function We({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;return(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:[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)}),(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)})})]}),i&&(0,d.jsx)(`span`,{className:`mt-0.5 shrink-0`,children:e.author?(0,d.jsx)(He,{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})})}),(0,d.jsxs)(`div`,{className:`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:Be}: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)(Ie,{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})]})]})]})}var Ge={running:`loader-circle`,done:`check`,error:`x`,stopped:`circle-slash`};function Ke({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:Ge[e.status]}))}]})}function qe({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 Je(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 Ye({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 Xe({entry:e,questions:t,hiddenPartId:n}){let r=(e.parts??[]).filter(e=>e.type!==`questions`||e.id!==n),i=[];for(let e of r){let t=i.at(-1);e.type===`tool`?t&&`steps`in t?t.steps.push(e):i.push({key:`tool-${e.id}`,steps:[e]}):i.push({key:`${e.type}-${e.id}`,part:e})}return(0,d.jsx)(`div`,{className:`space-y-2`,children:i.map(n=>{if(`steps`in n)return(0,d.jsx)(Ke,{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)(qe,{entry:e,part:r,questions:t},n.key):(0,d.jsx)(Ye,{entry:e,part:r,questions:t},n.key)})})}function Ze({entry:e,questions:t,hiddenPartId:n}){let r=$();if(e.kind===`thinking`&&e.parts){let i=e.status===`error`||e.status===`stopped`||e.status===`running`;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[e.parts.length>0&&(0,d.jsx)(Xe,{entry:e,questions:t,hiddenPartId:n}),i&&(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5 ${e.parts.length>0?`mt-1`:``}`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(Re,{status:e.status})}),(0,d.jsxs)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:[ze(e,r),e.status===`running`&&(0,d.jsx)(Le,{})]})]})]})}let i=e.kind===`thinking`&&e.detail?Pe(e.detail):[],a=i.filter(e=>e.type===`code`),o=i.filter(e=>e.type===`text`&&e.content.trim()),s=e.kind===`thinking`?ze(e,r):e.label;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(Re,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:s})]}),a.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-1`,children:a.map((e,t)=>(0,d.jsx)(Fe,{content:e.content,language:e.language},t))}),o.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-2`,children:o.map((e,t)=>(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:`muted`,className:`break-words text-xs leading-relaxed`},t))})]})}function Qe({activity:e,questions:t,docked:n,pinUserMessages:r=!0,messageActions:i,speaker:a,showAuthors:o}){if(e.length===0)return null;let s=o??(!!a||e.some(e=>e.kind===`user`&&e.author)),c=[];for(let t of e)t.kind===`user`||c.length===0?c.push(t.kind===`user`?{user:t,entries:[]}:{entries:[t]}):c[c.length-1].entries.push(t);return(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:c.map(e=>(0,d.jsxs)(`li`,{children:[e.user&&(0,d.jsx)(We,{entry:e.user,pinned:r,actions:i,cut:Ve(e.entries),showAuthor:s}),a&&e.entries.length>0&&(0,d.jsx)(Ue,{speaker:a}),e.entries.length>0&&(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:e.entries.map(e=>(0,d.jsx)(Ze,{entry:e,questions:t,hiddenPartId:n?.entry.id===e.id?n.part.id:void 0},e.id))})]},e.user?.id??e.entries[0]?.id))})}var $e=420,et=320,tt=`60vw`,nt=`agentico:panel-width`;function rt(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 it(e,t,n){return Math.round(Math.min(Math.max(e,t),Math.max(t,n)))}function at(){try{let e=window.localStorage.getItem(nt),t=e===null?NaN:Number(e);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function ot(e){try{e===null?window.localStorage.removeItem(nt):window.localStorage.setItem(nt,String(e))}catch{}}function st(){return typeof window>`u`?1/0:window.innerWidth}function ct({defaultWidth:e=420,minWidth:t=320,maxWidth:n=tt,onWidthChange:r}){let[i,a]=(0,u.useState)(st),[o,s]=(0,u.useState)(()=>at()??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,rt(n,i)),d=it(o,c,l);return(0,u.useEffect)(()=>{r?.(d)},[d]),{width:d,min:c,max:l,set:(0,u.useCallback)(e=>s(it(e,c,l)),[c,l]),commit:(0,u.useCallback)(e=>ot(it(e,c,l)),[c,l]),reset:(0,u.useCallback)(()=>{s(e),ot(null)},[e])}}function lt({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 ut({className:e=``}){let{isOpen:t,toggleOpen:n,task:r}=Me(),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 dt=`llmnative-cms.selectedAIModel`;function ft(){try{return localStorage.getItem(dt)??``}catch{return``}}function pt(e){try{e?localStorage.setItem(dt,e):localStorage.removeItem(dt)}catch{}}function mt(){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)(ft);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:(pt(``),``))}).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=>{pt(e),s(e)}}}var ht=`approval`;function gt(e,t){return typeof e.needsApproval==`function`?e.needsApproval(t):e.needsApproval===!0}function _t(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 vt=20,yt=26e4;function bt(e){return e.filter(e=>!l.PromptUtils.isTextAttachment(e.mimeType)||e.base64.length<=yt)}function xt(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 St(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}=mt(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),[x,S]=(0,u.useState)(!1),[C,w]=(0,u.useState)([]),E=(0,u.useRef)([]),D=e=>{w(t=>{let n=typeof e==`function`?e(t):e;return E.current=n,n})},O=(0,u.useRef)(new Map),k=$(),A=(0,u.useRef)(k);A.current=k;let j=(0,u.useRef)(null),N=(0,u.useRef)(!1),P=(0,u.useRef)(null),ee=(0,u.useRef)(null),F=(0,u.useRef)(null),te=()=>{F.current?.abort()},I=(0,l.useAIProviderRegistry)()?.registry??{},[L,R]=(0,u.useState)(void 0),re=(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??``,ie=i&&H?(0,l.parseAIModelRef)(H):null,ae=ie?I[ie.provider]:null,U=e.executor,W=!!U?.alongside,G=!!U&&!W,oe=!U||!!U.canRewind,K=!!U?.attachments,q=async e=>K&&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,de]=(0,u.useState)([]),[fe,J]=(0,u.useState)(``),Y=(0,u.useRef)(``),pe=e=>{Y.current=e,J(e)},X=e=>{let t=U?.models?.(e)??[];se.current=t,de(t);let n=U?.catalogProviders?.(e);re.current=n,R(n);let r=W&&!B(n,d)?t[0]?.value:void 0;pe(U?.defaultModel?.(e)??r??``)},Z=async(e,t,n,r,i)=>{let a=j.current;if(!a||!U)return b(A.current.noActiveSession),null;let o=new AbortController;F.current=o;let s=crypto.randomUUID();D(e=>[...e,{id:s,kind:`thinking`,label:A.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)=>D(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,w=()=>{for(let e of S){let t=O.current.get(e);O.current.delete(e),t?.reject(new DOMException(`The turn was stopped.`,`AbortError`))}S.clear()};o.signal.addEventListener(`abort`,w);let T=(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)=>{O.current.set(r,{resolve:e,reject:t})}))},k=(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`,w);for(let e of S)O.current.delete(e);S.clear()},M=e||r?.historyText||``;try{let c=P.current;P.current=null;let l=E.current,u=l.findIndex(e=>e.id===ee.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||Y.current?{model:n||Y.current}:{},...r?{answers:{id:r.id,answers:r.answers}}:{},onText:_,onReasoning:v,onStep:y,onQuestions:T,onCard:x});return k(`done`,f.text),a.history=[...a.history,...M?[{role:`user`,content:M}]:[],{role:`assistant`,content:f.text}],f.result??null}catch(e){return a.history=[...a.history,...M?[{role:`user`,content:M}]:[]],o.signal.aborted?(k(`stopped`),null):(k(`error`),b(z(e)),null)}finally{F.current=null}},me=async(t,n,r)=>{let i=E.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&&D(e=>e.map(e=>e.id===t?{...e,parts:e.parts?.map(e=>e.type===`card`&&e.id===n?{...e,outcome:o}:e)}:e))},he=async(e,t,n)=>{let r=E.current.find(t=>t.id===e)?.parts?.find(e=>e.type===`questions`&&e.id===t);if(!r||r.type!==`questions`)throw b(A.current.noActiveSession),Error(A.current.noActiveSession);let i=()=>D(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=O.current.get(a);if(o)return O.current.delete(a),i(),o.resolve(n),null;if(N.current)throw b(A.current.requestInProgress),Error(A.current.requestInProgress);if(!G||!j.current)throw b(A.current.noActiveSession),Error(A.current.noActiveSession);N.current=!0,v(!0),b(null),i();try{return await Z(``,!1,void 0,{id:t,answers:n,historyText:g(r.questions,n)})}finally{N.current=!1,v(!1)}},ge=async(t,n,r)=>{let i=re.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):ie,u=c&&j.current?U?.catalogReasoning?.(j.current.params,c.provider):void 0,d=u?{reasoning:u}:{},f=j.current;if(!f)return b(A.current.noActiveSession),null;let p=o?(0,l.parseAIModelRef)(o):ie,m=p?I[p.provider]:null;if(!m||!p)return b(A.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<=yt?`\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=bt(n??[]),_=f.tools.map(e=>({name:e.name,description:e.description,inputSchema:T(e.inputSchema)})),v=(e,t,n,r)=>{let i=A.current,a=`approval-${e}`,o=t.describeApproval?.(n)??t.describeInvocation?.(n)??t.name;D(e=>[...e,{id:a,kind:`thinking`,label:i.approvalHeader,status:`running`,parts:[{type:`questions`,id:ht,questions:[{header:i.approvalHeader,question:i.approveQuestion.replace(`{action}`,o),options:[{label:i.approve},{label:i.reject}],custom:!0}]}]}]);let s=`${a}:${ht}`;return new Promise((e,t)=>{let n=()=>{O.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}),O.current.set(s,{resolve:t=>{r.removeEventListener(`abort`,n),S(a,`done`),e(_t(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)=>D(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<vt;t++){let i=crypto.randomUUID();D(e=>[...e,{id:i,kind:`thinking`,label:A.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(A.current.noProviderResponse),null);if(a.type===`text`)return S(i,`done`,a.text),e.conversational&&a.text.trim()&&D(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(A.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&&gt(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){D(t=>[...t,{id:e.id,kind:`tool`,label:n,status:`stopped`}]);let t=M().toolRejected.replace(`{reason}`,r.reason?` (${r.reason})`:``);return{toolCallId:e.id,name:e.name,output:t,isError:!0}}if(D(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&&D(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();D(e=>[...e,{id:i,kind:`thinking`,label:A.current.thinking,status:`running`}]);let a;try{a=await m.complete({...d,prompt:ne(M().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(A.current.tooManyToolTurns),e.fallback(f.params,f.context)}finally{F.current=null}},_e=async(t,n)=>{if(N.current)return b(A.current.requestInProgress),null;N.current=!0,b(null),D(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(j.current={params:t,context:r,tools:o,history:[],logId:crypto.randomUUID(),attachmentsRef:a},G)return S(!0),X(t),await Z(n?.openingMessage??``,!0,void 0,void 0,await q(n?.attachments));if(W){X(t),le.current=!1;let e=n?.model||Y.current;if(ce(e))return S(!0),le.current=!0,await Z(n?.openingMessage??``,!0,e,void 0,await q(n?.attachments))}let s=n?.model||void 0,c=s?!!I[(0,l.parseAIModelRef)(s)?.provider??``]:!!ae;if(!i||!c){S(!1);let n=e.fallback(t,r);return D(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??A.current.aiDisabledFallback}]),n}S(!0);let u=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,d=ne(e.buildPrompt(t,r),e.microPromptIds);return await ge(d,u,s)}catch(e){return b(z(e)),null}finally{N.current=!1,v(!1)}},ve=async(t,n)=>{if(N.current){b(A.current.requestInProgress);return}N.current=!0,b(null),D(xt(n.activity)),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),le.current=!1,S(G||W||i&&!!ae)}catch(e){b(z(e))}finally{N.current=!1,v(!1)}},ye=async(t,n)=>{if(N.current)return b(A.current.requestInProgress),null;if(b(null),!t.trim())return b(`Messaggio vuoto.`),null;let i=j.current;if(!i)return b(A.current.noActiveSession),null;N.current=!0,v(!0);let a=crypto.randomUUID();ee.current=a,D(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 Z(t,!1,n?.model||void 0,void 0,await q(n?.attachments));let r=n?.model||(W?Y.current:``);if(W&&ce(r)){let e=!le.current;return le.current=!0,await Z(t,e,r,void 0,await q(n?.attachments))}P.current&&={...P.current,fresh:!1};let a=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,o=ne(e.buildFollowUpPrompt(t,i.params,i.context),e.microPromptIds);return await ge(o,a,n?.model||void 0)}catch(e){return b(z(e)),null}finally{N.current=!1,v(!1)}},be=e=>{let t=j.current,n=C.findIndex(t=>t.id===e),r=C[n],i=r?.detail?.trim();if(!oe||!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(N.current)return b(A.current.requestInProgress),null;let n=j.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),P.current={activity:s,fresh:!0},D(s),ye(o)},Q=()=>{let t=j.current;if(!t)return null;b(null);let n=e.fallback(t.params,t.context);return D(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??A.current.continueWithoutAiFallback}]),n},Ce=()=>j.current?{history:j.current.history,activity:C}:null;return{enabled:i,setEnabled:a,hasProviders:o,selectedModel:G||W&&fe?fe:H,setSelectedModel:G?pe:W?e=>{ce(e)?pe(e):(pe(``),p(e))}:p,modelsByProvider:V,modelsLoading:c,running:_,error:y,canContinue:x,remote:G,remoteModels:ue,alongside:W,...U?.catalogGroup?{catalogGroup:U.catalogGroup}:{},activity:C,run:_e,resume:ve,sendMessage:ye,stop:te,runFallback:Q,snapshot:Ce,answerQuestions:he,cardAction:me,rewind:Se,canRewind:oe,rewindable:xe,executorAttachments:K,offersFallback:e.offersFallback!==!1}}function Ct(){let e=M();return[e.responseRulesHeading,...e.responseRules.map(e=>`- ${e}`)].join(`
17
+ `)}function wt(e,t,n){let r=M(),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
- ${yt()}
22
+ ${Ct()}
23
23
 
24
24
  ${r.userRequestHeading}
25
- ${e}`}function xt(e,t){return t?{kind:`handoff`,...t}:{kind:`chat`,message:e}}function St(e){return b().filter(t=>!t.onlyWhenAnchored||e===t.id)}function Ct(e){return{buildContext(e){return{cliCatalog:L(St(e.scopedSubagentId)),handoff:{current:null},collected:{}}},buildPrompt({userGoal:e,pageContext:t},{cliCatalog:n}){return bt(e,n,t)},buildFollowUpPrompt(e,t,{cliCatalog:n}){return`${e}\n\n${yt()}\n\n${M().toolsHeading}\n${n}`},parseResponse(e,t,n){let r=n.handoff.current;return n.handoff.current=null,xt(e,r)},fallback(){return{kind:`chat`,message:e.unavailable}},describeFallback(t){return t.kind===`chat`?t.message:e.continueWithoutAi},getTools(t,n,r){let i=w({attachmentsRef:r,collected:n.collected,proxyFetch:l.proxyFetch}),a=t.scopedSubagentId?x(t.scopedSubagentId):null,o=a?i.filter(e=>(a.crossAgentToolIds??[]).includes(e.name)):i,s=St(t.scopedSubagentId).flatMap(t=>t.commands.map(r=>({name:`${t.id}_${r.name}`,description:`${t.label}: ${r.summary}`,inputSchema:r.inputSchema,describeInvocation:()=>(0,l.interpolate)(e.preparing,{label:t.label}),describeIntent:(0,l.interpolate)(e.collecting,{label:t.label}),async execute(e){let i=t.withCollected?t.withCollected({...e},n.collected):e;return n.handoff.current={subagentId:t.id,command:r.name,params:i},{status:`queued`,note:(0,l.interpolate)(M().handoffQueued,{label:t.label})}}})));return[...o,...s]}}}function wt(e,t){return e.deriveHistoryTitle?.(t)??e.label}function Tt({manifest:e,result:t,meta:n,taskId:r,initiallyApplied:i,onApplied:a,extraDestinations:o}){let s=$(),c=Ae(),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,wt(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 Et={};function Dt(e){Object.assign(Et,e)}function Ot(e){return Et[e]}function kt({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 At(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 jt={};function Mt(e){Object.assign(jt,e)}function Nt(e){return jt[e]}function Pt(e,t=6e3){let n=e.filter(e=>(e.kind===`user`||e.kind===`thinking`)&&e.detail?.trim()&&!be(e)).map(e=>`${e.kind===`user`?`Person`:`Agent`}: ${e.detail.trim()}`).join(`
25
+ ${e}`}function Tt(e,t){return t?{kind:`handoff`,...t}:{kind:`chat`,message:e}}function Et(e){return b().filter(t=>!t.onlyWhenAnchored||e===t.id)}function Dt(e){return{buildContext(e){return{cliCatalog:I(Et(e.scopedSubagentId)),handoff:{current:null},collected:{}}},buildPrompt({userGoal:e,pageContext:t},{cliCatalog:n}){return wt(e,n,t)},buildFollowUpPrompt(e,t,{cliCatalog:n}){return`${e}\n\n${Ct()}\n\n${M().toolsHeading}\n${n}`},parseResponse(e,t,n){let r=n.handoff.current;return n.handoff.current=null,Tt(e,r)},fallback(){return{kind:`chat`,message:e.unavailable}},describeFallback(t){return t.kind===`chat`?t.message:e.continueWithoutAi},getTools(t,n,r){let i=w({attachmentsRef:r,collected:n.collected,proxyFetch:l.proxyFetch}),a=t.scopedSubagentId?x(t.scopedSubagentId):null,o=a?i.filter(e=>(a.crossAgentToolIds??[]).includes(e.name)):i,s=Et(t.scopedSubagentId).flatMap(t=>t.commands.map(r=>({name:`${t.id}_${r.name}`,description:`${t.label}: ${r.summary}`,inputSchema:r.inputSchema,describeInvocation:()=>(0,l.interpolate)(e.preparing,{label:t.label}),describeIntent:(0,l.interpolate)(e.collecting,{label:t.label}),async execute(e){let i=t.withCollected?t.withCollected({...e},n.collected):e;return n.handoff.current={subagentId:t.id,command:r.name,params:i},{status:`queued`,note:(0,l.interpolate)(M().handoffQueued,{label:t.label})}}})));return[...o,...s]}}}function Ot(e,t){return e.deriveHistoryTitle?.(t)??e.label}function kt({manifest:e,result:t,meta:n,taskId:r,initiallyApplied:i,onApplied:a,extraDestinations:o}){let s=$(),c=Me(),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=U(),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,Ot(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 At={};function jt(e){Object.assign(At,e)}function Mt(e){return At[e]}function Nt({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 Pt(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 Ft={};function It(e){Object.assign(Ft,e)}function Lt(e){return Ft[e]}function Rt(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 Ft(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 It(e,t){try{return e.definition.executor?.catalogProviders?.(e.toParams(t))}catch{return}}function Lt(e,t,n,r,i){let a=It(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 Rt(e){let t=(0,l.useAIProviderRegistry)()?.registry??{},{modelsByProvider:n,selectedModel:r}=ut(),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=pe(e,t,n),s=x(t),c=`${e}:${t}:${n}`;if(!o||!s?.autoTitle||o.name||!ye(o)||a.current.has(c))return!1;let{registry:u,modelsByProvider:d,selectedModel:f}=i.current,p=Lt(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:M().chatTitle.replace(`{chat}`,Pt(o.activity)),model:m.model,history:[]}),i=r&&r.type===`text`?Ft(r.text):``;return i?xe(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&&!zt.has(e)&&(zt.add(e),(async()=>{for(let t of we(e)){let n=x(t.subagentId);if(n?.autoTitle){if(n.definition.conversational&&!ye(t)){Ce(e,t.subagentId,t.entityId);continue}t.name||await o(t.subagentId,t.entityId)}}})())},[e,s,o]),o}var zt=new Set,Bt=()=>({});function Vt({manifest:e,params:t,extraDestinations:n,precedingActivity:r,taskId:i,resumeSeed:a,model:o,openingMessage:s}){let c=vt(e.definition,{defaultEnabled:!0}),f=Ae(),p=f.scope,m=(0,l.useProxy)(),h=(0,u.useRef)(i??`subagent-${e.id}-${crypto.randomUUID()}`).current,[g,_]=(0,u.useState)(null),v=t=>{e.definition.conversational||_(t)},[y,b]=(0,u.useState)([]),[x,S]=(0,u.useState)(null),C=Ot(e.id),w=C?.kind===`selection`?C:null,[T,E]=(0,u.useState)(null),D=(0,u.useRef)(!1),O=(0,u.useRef)(0),k=(0,u.useRef)(null);g&&g!==k.current&&(k.current=g,O.current=(r?.length??0)+c.activity.length);let A=(0,u.useRef)(!1),j=c.remote||!c.hasProviders||c.selectedModel!==``;(0,u.useEffect)(()=>{!D.current&&j&&(D.current=!0,a?(te.current=!0,c.resume(e.toParams(t),a)):(o&&c.setSelectedModel(o),c.run(e.toParams(t),{model:o,openingMessage:s}).then(e=>{e&&v(e)})))},[j]),(0,u.useEffect)(()=>{if(!g||!p)return;let n=e.autoApplyDestinationIds??[],r=f.componentAnchors.find(t=>t.subagentId===e.id&&t.pinnedEntityId)?.pinnedEntityId,i=W();n.forEach(n=>{let a=i[n];a&&(S(null),a.apply(g,{scopeId:p.id,dataProvider:p.dataProvider,storageProvider:p.storageProvider,proxyFetch:m},{...t,pinnedEntityId:r}).then(n=>{n?.id&&f.commitEntityChat(e.id,n.id,h,p.id,t,wt(e,t))}).catch(e=>S(e instanceof Error?e.message:String(e))))})},[g,c.activity,p]),(0,u.useEffect)(()=>{g&&w&&E(w.defaultSelection(g))},[g,w]);let M=(e,t)=>{E(n=>n&&{...n,[e]:t})},N=e=>v(e),P=(0,u.useMemo)(()=>g&&w&&T?w.applySelection(g,T):g,[g,w,T]),F=(0,u.useMemo)(()=>f.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[f.componentAnchors,e.id]),I=(0,u.useMemo)(()=>At(F,t,h),[F,t,h]),ee=(0,u.useMemo)(()=>I?[I,...n??[]]:n,[I,n]),L=e.chatEntityId?.(t),R=Rt(p?.id),z=(0,u.useRef)(!1),te=(0,u.useRef)(!1);(0,u.useEffect)(()=>{let n=!z.current&&c.running,i=z.current&&!c.running;if(z.current=c.running,!n&&!i||!L||!p)return;if(te.current){i&&(te.current=!1);return}let a=c.snapshot();if(!a)return;let o=[...r??[],...a.activity];e.autoTitle&&e.definition.conversational&&!ye({activity:o})||(me({scopeId:p.id,subagentId:e.id,entityId:L,params:t,title:wt(e,t),history:a.history,activity:o}),i&&e.autoTitle&&R(e.id,L,c.selectedModel))},[c.running]);let B=()=>{A.current=!0,c.running&&c.stop(),f.closeTask(h)},ne=(0,u.useRef)(Nt(e.id)??Bt).current,V=ne({params:t,taskId:h,running:c.running,close:B}),re=e=>{b(t=>t.includes(e)?t:[...t,e])};return(0,u.useEffect)(()=>{A.current||f.openTask({id:h,title:wt(e,t),icon:e.icon,agent:c,onApplied:e=>v(e),precedingActivity:r,panelExtraAnchorIndex:O.current,onDismiss:B,...L?{savedToDisk:!0}:{},panelActions:V.content,composerActions:V.actions,composerCommands:V.commands,panelExtra:g?(0,d.jsxs)(d.Fragment,{children:[w&&T?(0,d.jsx)(w.Report,{result:g,selection:T,onChange:M}):C?.kind===`editable`?(0,d.jsx)(C.Report,{result:g,onResultChange:N}):(0,d.jsx)(kt,{result:P}),x&&(0,d.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Salvataggio automatico non riuscito: `,x]}),(0,d.jsx)(Tt,{manifest:e,result:P,meta:t,taskId:h,initiallyApplied:y,onApplied:re,extraDestinations:ee})]}):void 0})},[c.activity,c.running,c.error,c.canContinue,c.selectedModel,c.modelsByProvider,c.hasProviders,c.remoteModels,f.openTask,f.componentAnchors,h,e,t,g,P,T,y,n,r,x,V.content,V.actions,V.commands]),(0,u.useEffect)(()=>()=>{f.closeTask(h)},[f.closeTask,h]),null}function Ht({userGoal:e}){let t=$(),n=vt((0,u.useMemo)(()=>Ct({unavailable:t.orchestratorUnavailable,continueWithoutAi:t.orchestratorContinueWithoutAi,preparing:t.orchestratorPreparing,collecting:t.orchestratorCollecting}),[]),{defaultEnabled:!0}),r=Ae(),[i,a]=(0,u.useState)(null),o=(0,u.useRef)(!1),s=!n.hasProviders||n.selectedModel!==``,c=(0,u.useRef)(r.pendingExtraDestinations),l=(0,u.useRef)(r.pendingAttachments),f=(0,u.useRef)(r.pendingModel),p=(0,u.useRef)(r.pendingScopedSubagentId??r.scopedSubagentId??void 0),m=(0,u.useRef)(r.pendingCarryOver),h=(0,u.useRef)(!1),g=e=>{e&&typeof e==`object`&&e.kind===`handoff`&&(a(e),r.closeTask(De))};(0,u.useEffect)(()=>{!o.current&&s&&(o.current=!0,f.current&&n.setSelectedModel(f.current),n.run({userGoal:e,pageContext:r.pageContext,scopedSubagentId:p.current??null},{attachments:l.current,model:f.current,openingMessage:e}).then(e=>{e&&g(e)}))},[s]),(0,u.useEffect)(()=>{h.current||r.openTask({id:De,title:`Agentico`,icon:`bot`,agent:n,onApplied:g,scopedSubagentId:p.current,precedingActivity:m.current?.activity,onDismiss:()=>{h.current=!0,n.running&&n.stop(),r.closeTask(De)}})},[n.activity,n.running,n.error,n.canContinue,n.selectedModel,n.modelsByProvider,n.hasProviders,r.openTask]),(0,u.useEffect)(()=>()=>{r.closeTask(De)},[r.closeTask]);let _=(0,u.useMemo)(()=>[...m.current?.activity??[],...n.activity],[n.activity]);if(!i)return null;let v=x(i.subagentId);return v?(0,d.jsx)(Vt,{manifest:v,params:i.params,extraDestinations:c.current,model:f.current||void 0,taskId:m.current?.taskId,precedingActivity:_}):null}function Ut({manifest:e,extraDestinations:t}){let n=vt(e.definition,{defaultEnabled:!1}),r=$(),i=Ae(),a=(0,u.useRef)(`manual-${e.id}-${crypto.randomUUID()}`).current,[o,s]=(0,u.useState)(null),[c,f]=(0,u.useState)([]),p=Ot(e.id),m=p?.kind===`selection`?p:null,[h,g]=(0,u.useState)(null),[_,v]=(0,u.useState)(null),y=(0,u.useRef)(!1),b=t=>{if(!e.manualEntry)return;let r;try{r=e.manualEntry.fromRawText(t)}catch(e){console.error(`[ManualEntryRunner] manualEntry.fromRawText ha rifiutato il testo:`,e);return}v(r),f([]),n.run(r,{openingMessage:t}).then(e=>{e&&s(e)})};(0,u.useEffect)(()=>{o&&m&&g(m.defaultSelection(o))},[o,m]);let x=(e,t)=>{g(n=>n&&{...n,[e]:t})},S=e=>s(e),C=(0,u.useMemo)(()=>o&&m&&h?m.applySelection(o,h):o,[o,m,h]),w=e=>{f(t=>t.includes(e)?t:[...t,e])},T=(0,u.useMemo)(()=>i.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[i.componentAnchors,e.id]),E=(0,u.useMemo)(()=>_?At(T,_,a):null,[T,_,a]),D=(0,u.useMemo)(()=>E?[E,...t??[]]:t,[E,t]);return(0,u.useEffect)(()=>{y.current||i.openTask({id:a,title:e.label,icon:e.icon,agent:n,onApplied:e=>s(e),manualEntry:e.manualEntry?{prompt:e.manualEntry.prompt,onSubmit:b}:void 0,onDismiss:()=>{y.current=!0,n.running&&n.stop(),i.closeTask(a)},panelExtra:o?(0,d.jsxs)(`div`,{className:`space-y-2`,children:[m&&h?(0,d.jsx)(m.Report,{result:o,selection:h,onChange:x}):p?.kind===`editable`?(0,d.jsx)(p.Report,{result:o,onResultChange:S}):(0,d.jsx)(kt,{result:C}),(0,d.jsx)(Tt,{manifest:e,result:C,meta:_??{},taskId:a,initiallyApplied:c,onApplied:w,extraDestinations:D}),n.hasProviders&&(0,d.jsx)(l.ActionButton,{label:r.resumeWithAi,variant:`outline-secondary`,className:`text-xs`,onClick:()=>{_&&i.resumeWithAI(e.id,_,t)}})]}):void 0})},[n.activity,n.running,n.error,n.hasProviders,i.componentAnchors,o,C,h,c,_]),(0,u.useEffect)(()=>()=>{i.closeTask(a)},[]),null}function Wt(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 Gt({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,...Wt(s.modelsByProvider,s.catalogGroup)]:Wt(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 Kt(){let{startOrchestrator:e}=Ae(),t=$(),[n,r]=(0,u.useState)(``),{hasProviders:i,modelsByProvider:a,selectedModel:o,setSelectedModel:s}=ut(),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:Wt(a),selectedModel:o,onModelChange:s,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function qt({chat:e,onClose:t}){let n=$(),r=(0,l.useFormController)();return(0,d.jsx)(l.Modal,{title:n.renameChat,size:`sm`,onClose:t,onSave:()=>(xe(e.scopeId,e.subagentId,e.entityId,String(r.record?.title??ve(e)),`person`),t(),Promise.resolve(!0)),children:(0,d.jsxs)(l.Form,{appearance:`empty`,controller:r,defaultValues:{title:ve(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 Jt(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 Yt({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 Xt({messages:e}){return(0,d.jsx)(`div`,{className:`space-y-2 rounded-lg border border-border/60 p-3`,children:e.map((e,t)=>(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e},t))})}function Zt({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)(()=>fe(()=>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 ve(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} · ${ve(e)}`,children:ve(e)}),(0,d.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,title:`${s.chatStarted.replace(`{at}`,new Date(Se(e)).toLocaleString(c))} · ${s.chatLastMessage.replace(`{at}`,new Date(e.savedAt).toLocaleString(c))}`,children:Jt(Se(e),c)})]})},`${e.subagentId}:${e.entityId}`)})}),_&&(0,d.jsx)(qt,{chat:_,onClose:()=>v(null)})]})}function Qt({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}={}){let{task:i,isOpen:a,pendingGoal:o,orchestratorRunId:s,pageContext:c,pageContextCard:f,anchoredUserMessages:p,pendingResume:m,resumeRunId:h,dismissForeignTask:g,resumeEntityChat:_,pendingManualEntry:v,manualEntryRunId:y,startManualEntry:b,pendingExtraDestinations:S,pendingResumeWithAI:C,resumeWithAIRunId:w,pendingStart:T,startRunId:E,scope:D}=Ae(),O=$(),k=(0,u.useRef)(null),[A,j]=(0,u.useState)(!1),[M,N]=(0,u.useState)(null),[P,F]=(0,u.useState)(null);(0,u.useEffect)(()=>{N(null),F(null)},[i?.id]),Rt(D?.id);let I=it({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}),ee=()=>{(!i||i.agent.running||i.savedToDisk||window.confirm(O.unsavedConversationConfirm))&&(g(),j(!1))},L=i?[...i.precedingActivity??[],...i.agent.activity]:[],R=L.length,z=Math.max(0,Math.min(i?.panelExtraAnchorIndex??R,R)),te=L.slice(0,z),B=L.slice(z),ne=!!(i&&!i.agent.running&&i.agent.error),V=(e,t)=>{i&&(N(null),i.agent.rewind(e.id,t).then(e=>{e&&i.onApplied(e)}))},re=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))]},H=(e,t)=>{let n=re(e);n.length?F({entry:e,steps:n,...t===void 0?{}:{text:t}}):V(e,t)},ie=i?{available:e=>i.agent.activity.some(t=>t.id===e.id)&&i.agent.rewindable(e.id),disabled:i.agent.running,onRetry:e=>H(e),onEdit:e=>N(e)}:void 0,U=new Set(i?.agent.activity.map(e=>e.id)??[]),W=i?{canAnswer:e=>U.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,G=W?We(L,W.canAnswer):null,ae=i?.id===`agentico-orchestrator`&&i.scopedSubagentId?x(i.scopedSubagentId):void 0,oe=ae?.manualEntry?ae:null,K=(0,u.useRef)(!0);(0,u.useEffect)(()=>{let e=k.current;if(!e)return;let t=()=>{K.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&&(K.current=!0,e.scrollTop=e.scrollHeight)},[i?.id]);let q=L.at(-1)?.detail?.length??0;(0,u.useEffect)(()=>{let e=k.current;e&&K.current&&(e.scrollTop=e.scrollHeight)},[R,ne,q]);let se=(0,u.useRef)(null);(0,u.useEffect)(()=>{let e=k.current,t=se.current;if(!e||!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>{K.current&&(e.scrollTop=e.scrollHeight)});return n.observe(t),()=>n.disconnect()},[i?.id,a]);let J=o?(0,d.jsx)(Ht,{userGoal:o},s):null,ce=m?x(m.subagentId):void 0,le=m&&ce?(0,d.jsx)(Vt,{manifest:ce,params:m.snapshot.params,taskId:Te(m.subagentId,m.entityId),resumeSeed:{history:m.snapshot.history,activity:m.snapshot.activity}},h):null,ue=v?x(v.subagentId):void 0,de=v&&ue?(0,d.jsx)(Ut,{manifest:ue,extraDestinations:v.extraDestinations},y):null,Y=C?x(C.subagentId):void 0,X=C&&Y?(0,d.jsx)(Vt,{manifest:Y,params:C.params,extraDestinations:C.extraDestinations},w):null,fe=T?x(T.subagentId):void 0,Z=T&&fe?(0,d.jsx)(Vt,{manifest:fe,params:T.params,taskId:T.taskId,openingMessage:T.openingMessage},E):null;return a?(0,d.jsxs)(d.Fragment,{children:[J,le,de,X,Z,(0,d.jsxs)(`div`,{style:{width:I.width},className:`relative flex h-full shrink-0 flex-col border-l border-border bg-background`,children:[(0,d.jsx)(at,{width:I.width,min:I.min,max:I.max,onResize:I.set,onCommit:I.commit,onReset:I.reset}),(0,d.jsxs)(`div`,{className:`flex min-h-[60px] items-center gap-1 border-b border-border/60 px-4 py-3`,children:[(0,d.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-lg font-semibold leading-tight`,children:i?i.title:`Agentico`}),D&&(0,d.jsx)(Zt,{scopeId:D.id,currentTaskId:i?.id??null,open:A,onOpenChange:j,onNewChat:ee,onSelect:(e,t,n)=>_(e,t,n),onArchivedCurrent:g}),(0,d.jsx)(ot,{})]}),(0,d.jsx)(`div`,{ref:k,className:`flex-1 overflow-y-auto px-3 pb-2 ${G?`min-h-24`:`min-h-0`}`,children:(0,d.jsx)(`div`,{ref:se,className:`pt-2`,children:i?(0,d.jsxs)(d.Fragment,{children:[i.manualEntry&&L.length===0&&(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i.manualEntry.prompt}),(0,d.jsx)(Je,{activity:te,questions:W,docked:G,pinUserMessages:!G,messageActions:ie}),i.panelExtra&&(0,d.jsx)(`div`,{className:`mt-3`,children:i.panelExtra}),B.length>0&&(0,d.jsx)(Je,{activity:B,questions:W,docked:G,pinUserMessages:!G,messageActions:ie}),!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)){H(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(oe){b(oe.id,S);return}let e=i.agent.runFallback();e&&i.onApplied(e)}})]})]}):p.length>0?(0,d.jsx)(Xt,{messages:p}):f?(0,d.jsx)(Yt,{card:f}):(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c??O.orchestratorStarterHint})})}),i&&G?(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)(Ge,{entry:G.entry,part:G.part,questions:W,autoFocus:!0},`${G.entry.id}:${G.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)(Gt,{task:i,editing:M,onCancelEdit:()=>N(null),onSendEdit:(e,t)=>H(e,t)},i.id):(0,d.jsx)(Kt,{})]}),P&&(0,d.jsxs)(l.ModalYesNo,{title:O.rewindTitle,onClose:()=>F(null),onYes:async()=>(V(P.entry,P.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:P.steps.slice(0,8).map(e=>(0,d.jsx)(`li`,{children:e},e))})]})]})]}):(0,d.jsxs)(d.Fragment,{children:[J,le,de,X,Z]})}function $t(e,t){let{setPageContext:n}=Ae(),r=(0,u.useRef)(crypto.randomUUID()).current;(0,u.useEffect)(()=>(n(r,e,t??null),()=>n(r,null)),[e,t])}function en(e,t,n,r,i=!0,a){let{registerComponentAnchor:o}=Ae(),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=Ze,exports.AGENTICO_MIN_WIDTH=Xe,exports.AGENTICO_WIDTH=Ye,exports.AGENTICO_WIDTH_STORAGE_KEY=Qe,exports.Agentico=Qt,exports.AgenticoProvider=ke,exports.AgenticoToggle=ot,exports.DEFAULT_REASONING_PART_ID=p,exports.DEFAULT_TEXT_PART_ID=f,exports.JSON_EXPORT_DESTINATION_ID=re,exports.MICRO_PROMPT_REGISTRY=z,exports.ORCHESTRATOR_TASK_ID=De,exports.SUMMARY_MICRO_PROMPT=R,exports.agenticoDe=oe,exports.agenticoEn=G,exports.agenticoIt=ae,exports.agenticoPromptsEn=O,exports.agenticoPromptsIt=k,exports.agenticoTranslations=Ee,exports.applyMicroPrompts=te,exports.chatHasPersonMessage=ye,exports.chatStartedAt=Se,exports.chatTitle=ve,exports.configureAgenticoPrompts=j,exports.configureEntityChatStore=se,exports.createCrossAgentTools=w,exports.defineSubagent=_,exports.entityChatTaskId=Te,exports.extractErrorMessage=B,exports.extractJsonBlock=ne,exports.findSubagentManifest=x,exports.formatQuestionAnswers=g,exports.getAgenticoPrompts=M,exports.getDestinationRegistry=W,exports.getEntityChat=pe,exports.getSubagentControls=Nt,exports.getSubagentRegistry=b,exports.getSubagentReport=Ot,exports.hasEntityChatBackend=J,exports.jsonExportDestination=H,exports.listEntityChats=we,exports.messagePartsText=h,exports.onEntityChatsChange=fe,exports.registerCrossAgentTools=C,exports.registerDestinations=U,exports.registerSubagentControls=Mt,exports.registerSubagentReports=Dt,exports.registerSubagents=y,exports.removeEntityChat=Ce,exports.renameEntityChat=xe,exports.renderRegistryCli=L,exports.renderSubagentCli=ee,exports.resetAgenticoPrompts=N,exports.saveEntityChat=me,exports.syncEntityChats=ue,exports.toJsonSchema=T,exports.toMcpTool=E,exports.upsertMessagePart=m,exports.useAgent=vt,exports.useAgentico=Ae,exports.useAgenticoI18n=$,exports.useAgenticoPageContext=$t,exports.useSubagentComponentContext=en;
27
+ `);return n.length>t?`${n.slice(0,t*.7)}\n\n[…]\n\n${n.slice(-t*.3)}`:n}function zt(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 Bt(e,t){try{return e.definition.executor?.catalogProviders?.(e.toParams(t))}catch{return}}function Vt(e,t,n,r,i){let a=Bt(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 Ht(e){let t=(0,l.useAIProviderRegistry)()?.registry??{},{modelsByProvider:n,selectedModel:r}=mt(),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=me(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=Vt(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:M().chatTitle.replace(`{chat}`,Rt(o.activity)),model:m.model,history:[]}),i=r&&r.type===`text`?zt(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&&!Ut.has(e)&&(Ut.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 Ut=new Set,Wt=()=>({});function Gt({manifest:e,params:t,extraDestinations:n,precedingActivity:r,taskId:i,resumeSeed:a,model:o,openingMessage:s}){let c=Me(),f=St(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,w]=(0,u.useState)(null),T=Mt(e.id),E=T?.kind===`selection`?T:null,[D,O]=(0,u.useState)(null),k=(0,u.useRef)(!1),A=(0,u.useRef)(0),j=(0,u.useRef)(null);v&&v!==j.current&&(j.current=v,A.current=(r?.length??0)+f.activity.length);let M=(0,u.useRef)(!1),N=f.remote||!f.hasProviders||f.selectedModel!==``;(0,u.useEffect)(()=>{!k.current&&N&&(k.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)})))},[N]),(0,u.useEffect)(()=>{if(!v||!h)return;let n=e.autoApplyDestinationIds??[],r=c.componentAnchors.find(t=>t.subagentId===e.id&&t.pinnedEntityId)?.pinnedEntityId,i=U();n.forEach(n=>{let a=i[n];a&&(w(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,Ot(e,t))}).catch(e=>w(e instanceof Error?e.message:String(e))))})},[v,f.activity,h]),(0,u.useEffect)(()=>{v&&E&&O(E.defaultSelection(v))},[v,E]);let P=(e,t)=>{O(n=>n&&{...n,[e]:t})},ee=e=>b(e),F=(0,u.useMemo)(()=>v&&E&&D?E.applySelection(v,D):v,[v,E,D]),te=(0,u.useMemo)(()=>c.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[c.componentAnchors,e.id]),I=(0,u.useMemo)(()=>Pt(te,t,_),[te,t,_]),L=(0,u.useMemo)(()=>I?[I,...n??[]]:n,[I,n]),R=e.chatEntityId?.(t),ne=Ht(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||!R||!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})||(he({scopeId:h.id,subagentId:e.id,entityId:R,params:t,title:Ot(e,t),history:a.history,activity:o}),i&&e.autoTitle&&ne(e.id,R,f.selectedModel))},[f.running]);let B=()=>{M.current=!0,f.running&&f.stop(),c.closeTask(_)},V=(0,u.useRef)(Lt(e.id)??Wt).current,H=V({params:t,taskId:_,running:f.running,close:B}),ie=e=>{S(t=>t.includes(e)?t:[...t,e])};return(0,u.useEffect)(()=>{M.current||c.openTask({id:_,title:Ot(e,t),icon:e.icon,agent:f,onApplied:e=>b(e),precedingActivity:r,panelExtraAnchorIndex:A.current,onDismiss:B,...p?{thread:p}:{},...m?{speaker:m}:{},...R?{savedToDisk:!0}:{},panelActions:H.content,composerActions:H.actions,composerCommands:H.commands,panelExtra:v?(0,d.jsxs)(d.Fragment,{children:[E&&D?(0,d.jsx)(E.Report,{result:v,selection:D,onChange:P}):T?.kind===`editable`?(0,d.jsx)(T.Report,{result:v,onResultChange:ee}):(0,d.jsx)(Nt,{result:F}),C&&(0,d.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Salvataggio automatico non riuscito: `,C]}),(0,d.jsx)(kt,{manifest:e,result:F,meta:t,taskId:_,initiallyApplied:x,onApplied:ie,extraDestinations:L})]}):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,F,D,x,n,r,C,H.content,H.actions,H.commands]),(0,u.useEffect)(()=>()=>{c.closeTask(_)},[c.closeTask,_]),null}function Kt({userGoal:e}){let t=$(),n=(0,u.useMemo)(()=>Dt({unavailable:t.orchestratorUnavailable,continueWithoutAi:t.orchestratorContinueWithoutAi,preparing:t.orchestratorPreparing,collecting:t.orchestratorCollecting}),[]),r=Me(),i=St(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(ke))};(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:ke,title:`Agentico`,icon:`bot`,agent:i,onApplied:_,scopedSubagentId:m.current,precedingActivity:h.current?.activity,onDismiss:()=>{g.current=!0,i.running&&i.stop(),r.closeTask(ke)}})},[i.activity,i.running,i.error,i.canContinue,i.selectedModel,i.modelsByProvider,i.hasProviders,r.openTask]),(0,u.useEffect)(()=>()=>{r.closeTask(ke)},[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)(Gt,{manifest:y,params:a.params,extraDestinations:l.current,model:p.current||void 0,taskId:h.current?.taskId,precedingActivity:v}):null}function qt({manifest:e,extraDestinations:t}){let n=Me(),r=St(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=Mt(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]),w=e=>{f(t=>t.includes(e)?t:[...t,e])},T=(0,u.useMemo)(()=>n.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[n.componentAnchors,e.id]),E=(0,u.useMemo)(()=>_?Pt(T,_,a):null,[T,_,a]),D=(0,u.useMemo)(()=>E?[E,...t??[]]:t,[E,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)(Nt,{result:C}),(0,d.jsx)(kt,{manifest:e,result:C,meta:_??{},taskId:a,initiallyApplied:c,onApplied:w,extraDestinations:D}),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 Jt({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 Yt({scopeId:e,thread:t,taskId:n,scrollRef:r,onLoad:i,onContinue:a,busy:o=!1}){let s=$(),{locale:c}=(0,l.useI18n)(),[f,p]=(0,u.useState)(0);(0,u.useEffect)(()=>pe(()=>p(e=>e+1)),[]);let m=(0,u.useMemo)(()=>De(e,t,n),[e,t,n,f]),[h,g]=(0,u.useState)(0);(0,u.useEffect)(()=>g(0),[n,t]);let _=h<m.length,v=(0,u.useRef)(null),y=()=>{let e=r.current;e&&(v.current={height:e.scrollHeight,top:e.scrollTop}),i?.(),g(e=>Math.min(e+1,m.length))},b=(0,u.useRef)(y);b.current=y,(0,u.useLayoutEffect)(()=>{let e=r.current,t=v.current;v.current=null,e&&t&&(e.scrollTop=t.top+(e.scrollHeight-t.height))},[h,r]);let S=(0,u.useRef)(null);if((0,u.useEffect)(()=>{let e=r.current,t=S.current;if(!e||!t||!_||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,b.current())},{root:e,rootMargin:`40px 0px 0px 0px`});return o.observe(t),()=>{e.removeEventListener(`scroll`,a),o.disconnect()}},[r,_,h]),!m.length)return null;let C=e=>new Date(e).toLocaleString(c,{dateStyle:`medium`,timeStyle:`short`}),w=m.slice(0,h).reverse();return(0,d.jsxs)(`div`,{children:[_&&(0,d.jsx)(`div`,{ref:S,className:`flex justify-center pb-1`,children:(0,d.jsx)(l.ActionButton,{icon:`history`,label:s.earlierSession,variant:`link`,className:`text-xs`,onClick:y})}),w.map(e=>(0,d.jsxs)(`section`,{"aria-label":ye(e),children:[(0,d.jsx)(Jt,{title:ye(e),meta:(0,l.interpolate)(s.sessionOf,{at:C(Q(e))}),action:(0,d.jsx)(l.ActionButton,{label:s.continueSession,variant:`link`,className:`text-[11px]`,disabled:o,onClick:()=>a(e)})}),(0,d.jsx)(Qe,{activity:e.activity,pinUserMessages:!1,speaker:x(e.subagentId)?.speaker?.(e.params)})]},`${e.subagentId}:${e.entityId}`)),h>0&&(0,d.jsx)(Jt,{title:s.thisSession})]})}function Xt(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 Zt({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,...Xt(s.modelsByProvider,s.catalogGroup)]:Xt(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 Qt(){let{startOrchestrator:e}=Me(),t=$(),[n,r]=(0,u.useState)(``),{hasProviders:i,modelsByProvider:a,selectedModel:o,setSelectedModel:s}=mt(),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:Xt(a),selectedModel:o,onModelChange:s,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function $t({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??ye(e)),`person`),t(),Promise.resolve(!0)),children:(0,d.jsxs)(l.Form,{appearance:`empty`,controller:r,defaultValues:{title:ye(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 en(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 tn({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 nn({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 rn({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 ye(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} · ${ye(e)}`,children:ye(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:en(Q(e),c)})]})},`${e.subagentId}:${e.entityId}`)})}),_&&(0,d.jsx)($t,{chat:_,onClose:()=>v(null)})]})}function an({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}={}){let{task:i,isOpen:a,pendingGoal:o,orchestratorRunId:s,pageContext:c,pageContextCard:f,anchoredUserMessages:p,pendingResume:m,resumeRunId:h,dismissForeignTask:g,resumeEntityChat:_,pendingManualEntry:v,manualEntryRunId:y,startManualEntry:b,pendingExtraDestinations:S,pendingResumeWithAI:C,resumeWithAIRunId:w,pendingStart:T,startRunId:E,scope:D}=Me(),O=$(),k=(0,u.useRef)(null),[A,j]=(0,u.useState)(!1),[M,N]=(0,u.useState)(null),[P,ee]=(0,u.useState)(null);(0,u.useEffect)(()=>{N(null),ee(null)},[i?.id]),Ht(D?.id);let F=ct({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}),te=()=>{(!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)),ne=I.slice(0,R),z=I.slice(R),re=!!(i&&!i.agent.running&&i.agent.error),B=(e,t)=>{i&&(N(null),i.agent.rewind(e.id,t).then(e=>{e&&i.onApplied(e)}))},V=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))]},H=(e,t)=>{let n=V(e);n.length?ee({entry:e,steps:n,...t===void 0?{}:{text:t}}):B(e,t)},ie=i?{available:e=>i.agent.activity.some(t=>t.id===e.id)&&i.agent.rewindable(e.id),disabled:i.agent.running,onRetry:e=>H(e),onEdit:e=>N(e)}:void 0,ae=new Set(i?.agent.activity.map(e=>e.id)??[]),U=i?{canAnswer:e=>ae.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,W=U?Je(I,U.canAnswer):null,G=i?.id===`agentico-orchestrator`&&i.scopedSubagentId?x(i.scopedSubagentId):void 0,oe=G?.manualEntry?G:null,K=(0,u.useRef)(!0);(0,u.useEffect)(()=>{let e=k.current;if(!e)return;let t=()=>{K.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&&(K.current=!0,e.scrollTop=e.scrollHeight)},[i?.id]);let q=I.at(-1)?.detail?.length??0;(0,u.useEffect)(()=>{let e=k.current;e&&K.current&&(e.scrollTop=e.scrollHeight)},[L,re,q]);let se=(0,u.useRef)(null);(0,u.useEffect)(()=>{let e=k.current,t=se.current;if(!e||!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>{K.current&&(e.scrollTop=e.scrollHeight)});return n.observe(t),()=>n.disconnect()},[i?.id,a]);let ce=o?(0,d.jsx)(Kt,{userGoal:o},s):null,le=m?x(m.subagentId):void 0,ue=m&&le?(0,d.jsx)(Gt,{manifest:le,params:m.snapshot.params,taskId:Te(m.subagentId,m.entityId),resumeSeed:{history:m.snapshot.history,activity:m.snapshot.activity}},h):null,de=v?x(v.subagentId):void 0,fe=v&&de?(0,d.jsx)(qt,{manifest:de,extraDestinations:v.extraDestinations},y):null,J=C?x(C.subagentId):void 0,Y=C&&J?(0,d.jsx)(Gt,{manifest:J,params:C.params,extraDestinations:C.extraDestinations},w):null,pe=T?x(T.subagentId):void 0,X=T&&pe?(0,d.jsx)(Gt,{manifest:pe,params:T.params,taskId:T.taskId,openingMessage:T.openingMessage},E):null;return a?(0,d.jsxs)(d.Fragment,{children:[ce,ue,fe,Y,X,(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)(lt,{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`}),D&&(0,d.jsx)(rn,{scopeId:D.id,currentTaskId:i?.id??null,open:A,onOpenChange:j,onNewChat:te,onSelect:(e,t,n)=>_(e,t,n),onArchivedCurrent:g}),(0,d.jsx)(ut,{})]}),(0,d.jsx)(`div`,{ref:k,className:`flex-1 overflow-y-auto px-3 pb-2 ${W?`min-h-24`:`min-h-0`}`,children:(0,d.jsx)(`div`,{ref:se,className:`pt-2`,children:i?(0,d.jsxs)(d.Fragment,{children:[D&&i.thread&&(0,d.jsx)(Yt,{scopeId:D.id,thread:i.thread,taskId:i.id,scrollRef:k,busy:i.agent.running,onLoad:()=>{K.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)(Qe,{activity:ne,questions:U,docked:W,pinUserMessages:!W,messageActions:ie,speaker:i.speaker}),i.panelExtra&&(0,d.jsx)(`div`,{className:`mt-3`,children:i.panelExtra}),z.length>0&&(0,d.jsx)(Qe,{activity:z,questions:U,docked:W,pinUserMessages:!W,messageActions:ie,speaker:i.speaker}),!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)){H(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(oe){b(oe.id,S);return}let e=i.agent.runFallback();e&&i.onApplied(e)}})]})]}):p.length>0?(0,d.jsx)(nn,{messages:p}):f?(0,d.jsx)(tn,{card:f}):(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c??O.orchestratorStarterHint})})}),i&&W?(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)(Ye,{entry:W.entry,part:W.part,questions:U,autoFocus:!0},`${W.entry.id}:${W.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)(Zt,{task:i,editing:M,onCancelEdit:()=>N(null),onSendEdit:(e,t)=>H(e,t)},i.id):(0,d.jsx)(Qt,{})]}),P&&(0,d.jsxs)(l.ModalYesNo,{title:O.rewindTitle,onClose:()=>ee(null),onYes:async()=>(B(P.entry,P.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:P.steps.slice(0,8).map(e=>(0,d.jsx)(`li`,{children:e},e))})]})]})]}):(0,d.jsxs)(d.Fragment,{children:[ce,ue,fe,Y,X]})}function on(e,t){let{setPageContext:n}=Me(),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}=Me(),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=tt,exports.AGENTICO_MIN_WIDTH=et,exports.AGENTICO_WIDTH=$e,exports.AGENTICO_WIDTH_STORAGE_KEY=nt,exports.Agentico=an,exports.AgenticoProvider=je,exports.AgenticoToggle=ut,exports.DEFAULT_REASONING_PART_ID=p,exports.DEFAULT_TEXT_PART_ID=f,exports.JSON_EXPORT_DESTINATION_ID=V,exports.MICRO_PROMPT_REGISTRY=R,exports.ORCHESTRATOR_TASK_ID=ke,exports.SUMMARY_MICRO_PROMPT=L,exports.agenticoDe=oe,exports.agenticoEn=W,exports.agenticoIt=G,exports.agenticoPromptsEn=O,exports.agenticoPromptsIt=k,exports.agenticoTranslations=Oe,exports.applyMicroPrompts=ne,exports.chatHasPersonMessage=be,exports.chatStartedAt=Q,exports.chatThreadOf=Ee,exports.chatTitle=ye,exports.configureAgenticoPrompts=j,exports.configureEntityChatStore=se,exports.createCrossAgentTools=w,exports.defineSubagent=_,exports.earlierSessions=De,exports.entityChatTaskId=Te,exports.extractErrorMessage=z,exports.extractJsonBlock=re,exports.findSubagentManifest=x,exports.formatQuestionAnswers=g,exports.getAgenticoPrompts=M,exports.getDestinationRegistry=U,exports.getEntityChat=me,exports.getSubagentControls=Lt,exports.getSubagentRegistry=b,exports.getSubagentReport=Mt,exports.hasEntityChatBackend=ce,exports.jsonExportDestination=H,exports.listEntityChats=we,exports.messagePartsText=h,exports.onEntityChatsChange=pe,exports.registerCrossAgentTools=C,exports.registerDestinations=ae,exports.registerSubagentControls=It,exports.registerSubagentReports=jt,exports.registerSubagents=y,exports.removeEntityChat=Ce,exports.renameEntityChat=Se,exports.renderRegistryCli=I,exports.renderSubagentCli=te,exports.resetAgenticoPrompts=N,exports.saveEntityChat=he,exports.syncEntityChats=de,exports.toJsonSchema=T,exports.toMcpTool=E,exports.upsertMessagePart=m,exports.useAgent=St,exports.useAgentico=Me,exports.useAgenticoI18n=$,exports.useAgenticoPageContext=on,exports.useSubagentComponentContext=sn;
29
29
  //# sourceMappingURL=index.js.map