@llmnative/agentico 0.17.1 → 0.17.2
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 +7 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +365 -262
- package/dist/index.mjs.map +1 -1
- package/dist/types/i18n/types.d.ts +8 -0
- package/llms.txt +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -11,19 +11,19 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
11
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
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
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(`
|
|
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`,reasoningNow:`Reasoning…`,reasonedFor:`Reasoned for {seconds} s`,reasoned:`Reasoned`,processDetails:`Reasoning and steps`,stepsLabel:`Steps of the agent`,newInstance:`New "{label}" instance`,chatHistory:`Chat history`,earlierSession:`Earlier session`,thisSession:`This session`,continueSession:`Continue this session`,sessionOf:`Session of {at}`,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`,reasoningNow:`Sta ragionando…`,reasonedFor:`Ha ragionato {seconds} s`,reasoned:`Ha ragionato`,processDetails:`Ragionamento e passi`,stepsLabel:`Passi dell'agente`,newInstance:`Nuova istanza di "{label}"`,chatHistory:`Storico chat`,earlierSession:`Sessione precedente`,thisSession:`Questa sessione`,continueSession:`Continua questa sessione`,sessionOf:`Sessione del {at}`,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`,reasoningNow:`Denkt nach…`,reasonedFor:`{seconds} s nachgedacht`,reasoned:`Nachgedacht`,processDetails:`Überlegungen und Schritte`,stepsLabel:`Schritte des Agenten`,newInstance:`Neue Instanz von "{label}"`,chatHistory:`Chatverlauf`,earlierSession:`Vorherige Sitzung`,thisSession:`Diese Sitzung`,continueSession:`Diese Sitzung fortsetzen`,sessionOf:`Sitzung vom {at}`,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
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&>(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
|
|
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})}var Ue=`w-6`;function We(e){if(!e||e.kind!==`thinking`||!e.parts)return[];let t=[];for(let n of e.parts){if(n.type!==`reasoning`&&n.type!==`tool`)break;t.push(n)}return t}function Ge({parts:e,open:t,onToggle:n}){let r=$(),i=e.filter(e=>e.type===`reasoning`),a=e.filter(e=>e.type===`tool`),o=i.some(e=>e.streaming),s=a.filter(e=>e.status===`running`).at(-1),c=Math.round(i.reduce((e,t)=>e+(t.duration??0),0)),u=[...i.length?[o?r.reasoningNow:c>0?(0,l.interpolate)(r.reasonedFor,{seconds:c}):r.reasoned]:[],...a.length?[s?.label??(a.length===1?r.oneStep:(0,l.interpolate)(r.steps,{count:a.length}))]:[]],f=o||!!s,p=a.some(e=>e.status===`error`);return(0,d.jsxs)(`button`,{type:`button`,onClick:n,"aria-expanded":t,title:r.processDetails,className:`inline-flex min-w-0 items-center gap-1 rounded text-xs text-muted-foreground hover:text-foreground`,children:[(0,d.jsx)(l.Icon,{name:f?`loader-circle`:p?`circle-alert`:i.length?`brain`:`list-checks`,size:12,className:`shrink-0 ${f?`animate-spin`:``}`}),(0,d.jsx)(`span`,{className:`truncate`,children:u.join(` · `)}),(0,d.jsx)(l.Icon,{name:t?`chevron-up`:`chevron-down`,size:12,className:`shrink-0`})]})}function Ke({entry:e,pinned:t=!0,actions:n,cut:r=!1,showAuthor:i=!1}){let a=$(),o=(0,u.useRef)(null),[s,c]=(0,u.useState)(!1),[f,p]=(0,u.useState)(!1);(0,u.useLayoutEffect)(()=>{let e=o.current;e&&p(e.scrollHeight>97)},[e.detail,e.attachmentNames]);let m=f&&!s,h=n?.available(e)&&r?(0,d.jsx)(l.ActionButton,{icon:`rotate-ccw`,ariaLabel:a.retry,title:a.retry,variant:`link`,className:`p-1 text-muted-foreground hover:text-foreground`,disabled:n.disabled,onClick:()=>n.onRetry(e)}):null,g=n?.available(e)?(0,d.jsx)(`span`,{className:`opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100`,children:(0,d.jsx)(l.ActionButton,{icon:`pencil`,ariaLabel:a.editMessage,title:a.editMessage,variant:`link`,className:`p-1 text-muted-foreground hover:text-foreground`,disabled:n.disabled,onClick:()=>n.onEdit(e)})}):null,_=t=>(0,d.jsxs)(`div`,{className:`${t?`w-full`:`max-w-[85%]`} rounded-lg bg-primary/10 text-xs text-foreground`,children:[(0,d.jsxs)(`div`,{ref:o,className:`space-y-1 px-2.5 pt-1.5 ${m?`overflow-hidden`:``}`,style:m?{maxHeight: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})]})]});return i?(0,d.jsxs)(`div`,{className:`${t?`sticky top-0 z-20 border-b border-border/40`:``} group flex items-start gap-2 bg-background py-1.5`,children:[(0,d.jsxs)(`span`,{className:`flex shrink-0 flex-col items-center ${Ue}`,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})}),h,g]}),(0,d.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[e.author&&(0,d.jsx)(`div`,{className:`pb-0.5 text-xs font-medium text-foreground`,children:e.author.name}),_(!0)]})]}):(0,d.jsxs)(`div`,{className:`${t?`sticky top-0 z-20 border-b border-border/40`:``} group flex items-start justify-end gap-1 bg-background py-1.5`,children:[n?.available(e)&&(0,d.jsxs)(`span`,{className:`flex shrink-0 items-center`,children:[h,g]}),_(!1)]})}var qe={running:`loader-circle`,done:`check`,error:`x`,stopped:`circle-slash`};function Je({steps:e}){let t=$(),n=e.filter(e=>e.status===`running`).at(-1),r=e.some(e=>e.status===`error`),i=n?.label??(e.length===1?t.oneStep:(0,l.interpolate)(t.steps,{count:e.length}));return(0,d.jsx)(l.Tree,{ariaLabel:t.stepsLabel,selectedId:null,itemClassName:`py-0.5 text-xs text-muted-foreground`,nodes:[{id:`steps-${e[0]?.id??``}`,label:i,icon:n?`loader-circle`:r?`circle-alert`:`list-checks`,children:e.map(e=>({id:e.id,label:(0,d.jsx)(`span`,{className:e.status===`error`?`text-destructive`:void 0,children:e.label}),icon:qe[e.status]}))}]})}function Ye({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 Xe(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 Ze({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 Qe({entry:e,questions:t,hiddenPartId:n,skip:r}){let i=(e.parts??[]).filter(e=>(e.type!==`questions`||e.id!==n)&&!r?.has(e.id)),a=[];for(let e of i){let t=a.at(-1);e.type===`tool`?t&&`steps`in t?t.steps.push(e):a.push({key:`tool-${e.id}`,steps:[e]}):a.push({key:`${e.type}-${e.id}`,part:e})}return(0,d.jsx)(`div`,{className:`space-y-2`,children:a.map(n=>{if(`steps`in n)return(0,d.jsx)(Je,{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)(Ye,{entry:e,part:r,questions:t},n.key):(0,d.jsx)(Ze,{entry:e,part:r,questions:t},n.key)})})}function $e({entry:e,questions:t,hiddenPartId:n,skip:r}){let i=$();if(e.kind===`thinking`&&e.parts){let a=e.status===`error`||e.status===`stopped`||e.status===`running`,o=r?e.parts.filter(e=>!r.has(e.id)).length:e.parts.length;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[o>0&&(0,d.jsx)(Qe,{entry:e,questions:t,hiddenPartId:n,skip:r}),a&&(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5 ${o>0?`mt-1`:``}`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(Re,{status:e.status})}),(0,d.jsxs)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:[ze(e,i),e.status===`running`&&(0,d.jsx)(Le,{})]})]})]})}let a=e.kind===`thinking`&&e.detail?Pe(e.detail):[],o=a.filter(e=>e.type===`code`),s=a.filter(e=>e.type===`text`&&e.content.trim()),c=e.kind===`thinking`?ze(e,i):e.label;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(Re,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:c})]}),o.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-1`,children:o.map((e,t)=>(0,d.jsx)(Fe,{content:e.content,language:e.language},t))}),s.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-2`,children:s.map((e,t)=>(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:`muted`,className:`break-words text-xs leading-relaxed`},t))})]})}function et({parts:e}){return(0,d.jsx)(`div`,{className:`mb-1 space-y-1 border-l-2 border-border pl-2 text-xs text-muted-foreground`,children:e.map(e=>e.type===`reasoning`?(0,d.jsx)(l.ChatMarkdown,{content:e.text,tone:`muted`,streaming:e.streaming,className:`break-words text-xs leading-relaxed`},e.id):e.type===`tool`?(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,d.jsx)(l.Icon,{name:qe[e.status],size:12,className:`mt-0.5 shrink-0 ${e.status===`running`?`animate-spin`:``}`}),(0,d.jsx)(`span`,{className:`min-w-0 break-words ${e.status===`error`?`text-destructive`:``}`,children:e.label})]},e.id):null)})}function tt({speaker:e,entries:t,questions:n,docked:r}){let i=We(t[0]),a=i.length?new Set(i.map(e=>e.id)):void 0,[o,s]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`flex items-start gap-2 pt-1.5`,children:[(0,d.jsx)(`span`,{className:`flex shrink-0 justify-center pt-px ${Ue}`,children:(0,d.jsx)(He,{author:e})}),(0,d.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,d.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-2 pb-0.5`,children:[(0,d.jsx)(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.name}),i.length>0&&(0,d.jsx)(Ge,{parts:i,open:o,onToggle:()=>s(e=>!e)})]}),o&&i.length>0&&(0,d.jsx)(et,{parts:i}),(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:t.map((e,t)=>(0,d.jsx)($e,{entry:e,questions:n,hiddenPartId:r?.entry.id===e.id?r.part.id:void 0,...t===0&&a?{skip:a}:{}},e.id))})]})]})}function nt({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)(Ke,{entry:e.user,pinned:r,actions:i,cut:Ve(e.entries),showAuthor:s}),a&&e.entries.length>0?(0,d.jsx)(tt,{speaker:a,entries:e.entries,questions:t,docked:n}):e.entries.length>0&&(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:e.entries.map(e=>(0,d.jsx)($e,{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 rt=420,it=320,at=`60vw`,ot=`agentico:panel-width`;function st(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 ct(e,t,n){return Math.round(Math.min(Math.max(e,t),Math.max(t,n)))}function lt(){try{let e=window.localStorage.getItem(ot),t=e===null?NaN:Number(e);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function ut(e){try{e===null?window.localStorage.removeItem(ot):window.localStorage.setItem(ot,String(e))}catch{}}function dt(){return typeof window>`u`?1/0:window.innerWidth}function ft({defaultWidth:e=420,minWidth:t=320,maxWidth:n=at,onWidthChange:r}){let[i,a]=(0,u.useState)(dt),[o,s]=(0,u.useState)(()=>lt()??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,st(n,i)),d=ct(o,c,l);return(0,u.useEffect)(()=>{r?.(d)},[d]),{width:d,min:c,max:l,set:(0,u.useCallback)(e=>s(ct(e,c,l)),[c,l]),commit:(0,u.useCallback)(e=>ut(ct(e,c,l)),[c,l]),reset:(0,u.useCallback)(()=>{s(e),ut(null)},[e])}}function pt({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 mt({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 ht=`llmnative-cms.selectedAIModel`;function gt(){try{return localStorage.getItem(ht)??``}catch{return``}}function _t(e){try{e?localStorage.setItem(ht,e):localStorage.removeItem(ht)}catch{}}function vt(){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)(gt);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:(_t(``),``))}).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=>{_t(e),s(e)}}}var yt=`approval`;function bt(e,t){return typeof e.needsApproval==`function`?e.needsApproval(t):e.needsApproval===!0}function xt(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 St=20,Ct=26e4;function wt(e){return e.filter(e=>!l.PromptUtils.isTextAttachment(e.mimeType)||e.base64.length<=Ct)}function Tt(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 Et(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}=vt(),[_,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<=Ct?`\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=wt(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:yt,questions:[{header:i.approvalHeader,question:i.approveQuestion.replace(`{action}`,o),options:[{label:i.approve},{label:i.reject}],custom:!0}]}]}]);let s=`${a}:${yt}`;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(xt(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<St;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&&bt(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(Tt(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 Dt(){let e=M();return[e.responseRulesHeading,...e.responseRules.map(e=>`- ${e}`)].join(`
|
|
17
|
+
`)}function Ot(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
|
-
${
|
|
22
|
+
${Dt()}
|
|
23
23
|
|
|
24
24
|
${r.userRequestHeading}
|
|
25
|
-
${e}`}function
|
|
25
|
+
${e}`}function kt(e,t){return t?{kind:`handoff`,...t}:{kind:`chat`,message:e}}function At(e){return b().filter(t=>!t.onlyWhenAnchored||e===t.id)}function jt(e){return{buildContext(e){return{cliCatalog:I(At(e.scopedSubagentId)),handoff:{current:null},collected:{}}},buildPrompt({userGoal:e,pageContext:t},{cliCatalog:n}){return Ot(e,n,t)},buildFollowUpPrompt(e,t,{cliCatalog:n}){return`${e}\n\n${Dt()}\n\n${M().toolsHeading}\n${n}`},parseResponse(e,t,n){let r=n.handoff.current;return n.handoff.current=null,kt(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=At(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 Mt(e,t){return e.deriveHistoryTitle?.(t)??e.label}function Nt({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,Mt(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 Pt={};function Ft(e){Object.assign(Pt,e)}function It(e){return Pt[e]}function Lt({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 Rt(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 zt={};function Bt(e){Object.assign(zt,e)}function Vt(e){return zt[e]}function Ht(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
|
|
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;
|
|
27
|
+
`);return n.length>t?`${n.slice(0,t*.7)}\n\n[…]\n\n${n.slice(-t*.3)}`:n}function Ut(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 Wt(e,t){try{return e.definition.executor?.catalogProviders?.(e.toParams(t))}catch{return}}function Gt(e,t,n,r,i){let a=Wt(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 Kt(e){let t=(0,l.useAIProviderRegistry)()?.registry??{},{modelsByProvider:n,selectedModel:r}=vt(),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=Gt(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}`,Ht(o.activity)),model:m.model,history:[]}),i=r&&r.type===`text`?Ut(r.text):``;return i?Se(e,t,n,i,`model`):!1}catch{return!1}finally{a.current.delete(c)}},[e]),s=Object.keys(n).length>0;return(0,u.useEffect)(()=>{e&&s&&!qt.has(e)&&(qt.add(e),(async()=>{for(let t of we(e)){let n=x(t.subagentId);if(n?.autoTitle){if(n.definition.conversational&&!be(t)){Ce(e,t.subagentId,t.entityId);continue}t.name||await o(t.subagentId,t.entityId)}}})())},[e,s,o]),o}var qt=new Set,Jt=()=>({});function Yt({manifest:e,params:t,extraDestinations:n,precedingActivity:r,taskId:i,resumeSeed:a,model:o,openingMessage:s}){let c=Me(),f=Et(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=It(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,Mt(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)(()=>Rt(te,t,_),[te,t,_]),L=(0,u.useMemo)(()=>I?[I,...n??[]]:n,[I,n]),R=e.chatEntityId?.(t),ne=Kt(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:Mt(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)(Vt(e.id)??Jt).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:Mt(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)(Lt,{result:F}),C&&(0,d.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Salvataggio automatico non riuscito: `,C]}),(0,d.jsx)(Nt,{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 Xt({userGoal:e}){let t=$(),n=(0,u.useMemo)(()=>jt({unavailable:t.orchestratorUnavailable,continueWithoutAi:t.orchestratorContinueWithoutAi,preparing:t.orchestratorPreparing,collecting:t.orchestratorCollecting}),[]),r=Me(),i=Et(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)(Yt,{manifest:y,params:a.params,extraDestinations:l.current,model:p.current||void 0,taskId:h.current?.taskId,precedingActivity:v}):null}function Zt({manifest:e,extraDestinations:t}){let n=Me(),r=Et(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=It(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)(()=>_?Rt(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)(Lt,{result:C}),(0,d.jsx)(Nt,{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 Qt({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 $t({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)(Qt,{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)(nt,{activity:e.activity,pinUserMessages:!1,speaker:x(e.subagentId)?.speaker?.(e.params)})]},`${e.subagentId}:${e.entityId}`)),h>0&&(0,d.jsx)(Qt,{title:s.thisSession})]})}function en(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 tn({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,...en(s.modelsByProvider,s.catalogGroup)]:en(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 nn(){let{startOrchestrator:e}=Me(),t=$(),[n,r]=(0,u.useState)(``),{hasProviders:i,modelsByProvider:a,selectedModel:o,setSelectedModel:s}=vt(),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:en(a),selectedModel:o,onModelChange:s,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function rn({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 an(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 on({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 sn({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 cn({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:an(Q(e),c)})]})},`${e.subagentId}:${e.entityId}`)})}),_&&(0,d.jsx)(rn,{chat:_,onClose:()=>v(null)})]})}function ln({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]),Kt(D?.id);let F=ft({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?Xe(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)(Xt,{userGoal:o},s):null,le=m?x(m.subagentId):void 0,ue=m&&le?(0,d.jsx)(Yt,{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)(Zt,{manifest:de,extraDestinations:v.extraDestinations},y):null,J=C?x(C.subagentId):void 0,Y=C&&J?(0,d.jsx)(Yt,{manifest:J,params:C.params,extraDestinations:C.extraDestinations},w):null,pe=T?x(T.subagentId):void 0,X=T&&pe?(0,d.jsx)(Yt,{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)(pt,{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)(cn,{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)(mt,{})]}),(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)($t,{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)(nt,{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)(nt,{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)(sn,{messages:p}):f?(0,d.jsx)(on,{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)(Ze,{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)(tn,{task:i,editing:M,onCancelEdit:()=>N(null),onSendEdit:(e,t)=>H(e,t)},i.id):(0,d.jsx)(nn,{})]}),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 un(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 dn(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=at,exports.AGENTICO_MIN_WIDTH=it,exports.AGENTICO_WIDTH=rt,exports.AGENTICO_WIDTH_STORAGE_KEY=ot,exports.Agentico=ln,exports.AgenticoProvider=je,exports.AgenticoToggle=mt,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=Vt,exports.getSubagentRegistry=b,exports.getSubagentReport=It,exports.hasEntityChatBackend=ce,exports.jsonExportDestination=H,exports.listEntityChats=we,exports.messagePartsText=h,exports.onEntityChatsChange=pe,exports.registerCrossAgentTools=C,exports.registerDestinations=ae,exports.registerSubagentControls=Bt,exports.registerSubagentReports=Ft,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=Et,exports.useAgentico=Me,exports.useAgenticoI18n=$,exports.useAgenticoPageContext=un,exports.useSubagentComponentContext=dn;
|
|
29
29
|
//# sourceMappingURL=index.js.map
|