@llmnative/agentico 0.13.0 → 0.13.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 CHANGED
@@ -13,17 +13,17 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
13
13
  `)}var R={id:`closing-summary`,get text(){return M().closingSummary}},z={[R.id]:R};function B(e,t){if(!t||t.length===0)return e;let n=t.map(e=>z[e]?.text).filter(e=>!!e);return n.length===0?e:`${e}\n\n${n.join(`
14
14
  `)}`}function V(e){if(e instanceof Error)return e.message;if(typeof e==`object`&&e){let t=e;if(typeof t.error==`string`)return t.error;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.message==`string`)return e.message}if(typeof t.message==`string`)return t.message;if(typeof t.status==`number`)return`HTTP ${t.status}`;try{return JSON.stringify(e)}catch{}}return String(e)}function H(e){let t=e.match(/```(?:json)?\s*\n?([\s\S]*?)```/i);if(t)return t[1].trim();let n=e.replace(/^```json\s*/i,``).replace(/^```\s*/i,``).replace(/```\s*$/,``).trim();return U(n)??n}function U(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 W=`json-export`,G={id:W,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)}}},K={};function q(e){K=e}function te(){return{[G.id]:G,...K}}var J={modelLabel:`Model`,modelsLoading:`Loading…`,noModelsAvailable:`No models available`,noProviderConnected:`No AI provider connected`,selectModelPlaceholder:`Choose a model…`,orchestratorStarterHint:`Tell Agentico what you want to do — it will pick the right tool and ask for what it needs.`,orchestratorStarterPlaceholder:`Describe what you want to do…`,destinationPickerTitle:`Save result to…`,destinationApplying:`Saving…`,destinationNoScope:`Nothing selected to save into — select one before saving.`,unknownDestination:`Unknown destination: {id}`,exportJson:`Export as JSON`,orchestratorUnavailable:`AI not available — open the tool you need directly from its page.`,orchestratorContinueWithoutAi:`Continuing without AI.`,orchestratorPreparing:`Preparing {label}…`,orchestratorCollecting:`Collecting the parameters for {label}…`,thinking:`Thinking…`,stopped:`Stopped by the user.`,toolRequest:`Requested to run some tools`,modelRequestError:`Error in the request to the model`,noProviderResponse:`No response from the AI provider.`,noActiveSession:`No active session — call run() first.`,approvalHeader:`Approval`,approve:`Approve`,reject:`Reject`,approveQuestion:`Approve? {action}`,requestInProgress:`Another request is already running.`,invalidResponse:`Invalid AI response.`,responseReceived:`Response received`,noProviderAvailable:`No AI provider available.`,tooManyToolTurns:`Too many consecutive tool-calling turns — using the deterministic result collected so far.`,aiDisabledFallback:`AI disabled — using the deterministic result.`,continueWithoutAiFallback:`Continuing without AI — using the deterministic result.`,oneStep:`1 step`,steps:`{count} steps`,stepsLabel:`Steps of the agent`,newInstance:`New "{label}" instance`,chatHistory:`Chat history`,cardView:`View`,cardClose:`Close`,renameChat:`Rename`,chatTitleLabel:`Title`,chatTitleHint:`Empty: the title written from the chat.`,chatStarted:`Started {at}`,chatLastMessage:`last message {at}`,newChat:`New chat`,searchChats:`Search chats…`,messagePlaceholder:`Write a message…`,unsavedConversationConfirm:`This conversation has not been saved and will be lost. Continue?`,noSavedChats:`No saved chats yet.`,archiveChat:`Archive`,noResults:`No results.`,retry:`Retry`,retryMessage:`Retry.`,continueWithoutAi:`Continue without AI`,resumeWithAi:`Resume with AI`,openPanel:`Open agent panel`,closePanel:`Close agent panel`,resizePanel:`Resize the agent panel`,resizePanelHint:`Drag to resize, double-click to reset`,pendingQuestions:`Questions of the agent`,stop:`Stop`},Y={modelLabel:`Modello`,modelsLoading:`Caricamento…`,noModelsAvailable:`Nessun modello disponibile`,noProviderConnected:`Nessun provider AI connesso`,selectModelPlaceholder:`Scegli un modello…`,orchestratorStarterHint:`Dì ad Agentico cosa vuoi fare — sceglierà lo strumento giusto e ti chiederà cosa serve.`,orchestratorStarterPlaceholder:`Descrivi cosa vuoi fare…`,destinationPickerTitle:`Salva risultato in…`,destinationApplying:`Salvataggio…`,destinationNoScope:`Nessuna destinazione selezionata — selezionane una prima di salvare.`,unknownDestination:`Destinazione sconosciuta: {id}`,exportJson:`Esporta come JSON`,orchestratorUnavailable:`AI non disponibile — apri il tool che ti serve direttamente dalla sua pagina.`,orchestratorContinueWithoutAi:`Continuo senza AI.`,orchestratorPreparing:`Preparo {label}…`,orchestratorCollecting:`Sto raccogliendo i parametri per {label}…`,thinking:`Sto pensando…`,stopped:`Interrotto dall'utente.`,toolRequest:`Richiesta di eseguire dei tool`,modelRequestError:`Errore nella richiesta al modello`,noProviderResponse:`Nessuna risposta dal provider AI.`,noActiveSession:`Nessuna sessione attiva — chiama prima run().`,approvalHeader:`Approvazione`,approve:`Approva`,reject:`Rifiuta`,approveQuestion:`Approvi? {action}`,requestInProgress:`Un'altra richiesta è già in corso.`,invalidResponse:`Risposta AI non valida.`,responseReceived:`Risposta ricevuta`,noProviderAvailable:`Nessun provider AI disponibile.`,tooManyToolTurns:`Troppi turni di tool-calling consecutivi — uso il risultato deterministico raccolto finora.`,aiDisabledFallback:`AI disabilitata — uso il risultato deterministico.`,continueWithoutAiFallback:`Continuo senza AI — uso il risultato deterministico.`,oneStep:`1 passo`,steps:`{count} passi`,stepsLabel:`Passi dell'agente`,newInstance:`Nuova istanza di "{label}"`,chatHistory:`Storico chat`,cardView:`Vedi`,cardClose:`Chiudi`,renameChat:`Rinomina`,chatTitleLabel:`Titolo`,chatTitleHint:`Vuoto: il titolo scritto dalla chat.`,chatStarted:`Iniziata il {at}`,chatLastMessage:`ultimo messaggio il {at}`,newChat:`Nuova chat`,searchChats:`Cerca nelle chat…`,messagePlaceholder:`Scrivi un messaggio…`,unsavedConversationConfirm:`Questa conversazione non è stata salvata e andrà persa. Continuare?`,noSavedChats:`Nessuna chat salvata ancora.`,archiveChat:`Archivia`,noResults:`Nessun risultato.`,retry:`Riprova`,retryMessage:`Riprova.`,continueWithoutAi:`Continua senza AI`,resumeWithAi:`Riprendi con AI`,openPanel:`Apri pannello agente`,closePanel:`Chiudi pannello agente`,resizePanel:`Ridimensiona il pannello dell'agente`,resizePanelHint:`Trascina per ridimensionare, doppio clic per ripristinare`,pendingQuestions:`Domande dell'agente`,stop:`Ferma`},ne={modelLabel:`Modell`,modelsLoading:`Wird geladen…`,noModelsAvailable:`Keine Modelle verfügbar`,noProviderConnected:`Kein AI-Provider verbunden`,selectModelPlaceholder:`Modell wählen…`,orchestratorStarterHint:`Sag Agentico, was du erreichen willst — es wählt das passende Werkzeug und fragt nach den nötigen Angaben.`,orchestratorStarterPlaceholder:`Beschreibe, was du tun möchtest…`,destinationPickerTitle:`Ergebnis speichern in…`,destinationApplying:`Wird gespeichert…`,destinationNoScope:`Kein Ziel ausgewählt — vor dem Speichern eines auswählen.`,unknownDestination:`Unbekanntes Ziel: {id}`,exportJson:`Als JSON exportieren`,orchestratorUnavailable:`AI nicht verfügbar — öffne das benötigte Werkzeug direkt auf seiner Seite.`,orchestratorContinueWithoutAi:`Weiter ohne AI.`,orchestratorPreparing:`{label} wird vorbereitet…`,orchestratorCollecting:`Parameter für {label} werden gesammelt…`,thinking:`Denke nach…`,stopped:`Vom Benutzer abgebrochen.`,toolRequest:`Werkzeugausführung angefordert`,modelRequestError:`Fehler bei der Anfrage an das Modell`,noProviderResponse:`Keine Antwort vom AI-Provider.`,noActiveSession:`Keine aktive Sitzung — zuerst run() aufrufen.`,approvalHeader:`Freigabe`,approve:`Freigeben`,reject:`Ablehnen`,approveQuestion:`Freigeben? {action}`,requestInProgress:`Eine andere Anfrage läuft bereits.`,invalidResponse:`Ungültige AI-Antwort.`,responseReceived:`Antwort erhalten`,noProviderAvailable:`Kein AI-Provider verfügbar.`,tooManyToolTurns:`Zu viele aufeinanderfolgende Werkzeugaufrufe — das bisher gesammelte deterministische Ergebnis wird verwendet.`,aiDisabledFallback:`AI deaktiviert — das deterministische Ergebnis wird verwendet.`,continueWithoutAiFallback:`Weiter ohne AI — das deterministische Ergebnis wird verwendet.`,oneStep:`1 Schritt`,steps:`{count} Schritte`,stepsLabel:`Schritte des Agenten`,newInstance:`Neue Instanz von "{label}"`,chatHistory:`Chatverlauf`,cardView:`Ansehen`,cardClose:`Schließen`,renameChat:`Umbenennen`,chatTitleLabel:`Titel`,chatTitleHint:`Leer: der aus dem Chat geschriebene Titel.`,chatStarted:`Begonnen am {at}`,chatLastMessage:`letzte Nachricht am {at}`,newChat:`Neuer Chat`,searchChats:`Chats durchsuchen…`,messagePlaceholder:`Nachricht schreiben…`,unsavedConversationConfirm:`Diese Unterhaltung wurde nicht gespeichert und geht verloren. Fortfahren?`,noSavedChats:`Noch keine gespeicherten Chats.`,archiveChat:`Archivieren`,noResults:`Keine Ergebnisse.`,retry:`Erneut versuchen`,retryMessage:`Erneut versuchen.`,continueWithoutAi:`Ohne AI fortfahren`,resumeWithAi:`Mit AI fortsetzen`,openPanel:`Agentenbereich öffnen`,closePanel:`Agentenbereich schließen`,resizePanel:`Agent-Bereich in der Größe ändern`,resizePanelHint:`Ziehen zum Ändern der Größe, Doppelklick zum Zurücksetzen`,pendingQuestions:`Fragen des Agenten`,stop:`Stoppen`},re=`llmnative.agentico.entityChat`,X;function ie(e){re=e.storageKey,X=e.backend}var Z=()=>!!X,ae=({synced:e,...t})=>t;function oe(e){if(!X)return;let t=Q(e.scopeId,e.subagentId,e.entityId);Promise.resolve(X.save(ae(e))).then(()=>{let e=le(),n=e.find(e=>Q(e.scopeId,e.subagentId,e.entityId)===t);n&&!n.synced&&fe(e.map(e=>e===n?{...e,synced:!0}:e))},()=>void 0)}async function se(e){if(!X)return;let t=(await X.load(e)).map(ce).filter(t=>t!==null&&t.scopeId===e),n=e=>e.changedAt??e.savedAt,r=le(),i=r.filter(t=>t.scopeId!==e),a=r.filter(t=>t.scopeId===e),o=t.map(e=>{let t=a.find(t=>Q(t.scopeId,t.subagentId,t.entityId)===Q(e.scopeId,e.subagentId,e.entityId));return t&&n(t)>n(e)?(oe(t),t):{...e,synced:!0}}),s=a.filter(e=>!e.synced&&!t.some(t=>Q(t.scopeId,t.subagentId,t.entityId)===Q(e.scopeId,e.subagentId,e.entityId)));fe([...i,...o,...s]);for(let e of s)oe(e)}function ce(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 le(){try{let e=localStorage.getItem(re);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(ce).filter(e=>e!==null):[]}catch{return[]}}var ue=new Set;function de(e){return ue.add(e),()=>{ue.delete(e)}}function fe(e){try{localStorage.setItem(re,JSON.stringify(e))}catch{}for(let e of[...ue])e()}var Q=(e,t,n)=>`${e}:${t}:${n}`;function pe(e,t,n){let r=Q(e,t,n);return le().find(e=>Q(e.scopeId,e.subagentId,e.entityId)===r)??null}function me(e){let t=Q(e.scopeId,e.subagentId,e.entityId),n=le(),r=n.find(e=>Q(e.scopeId,e.subagentId,e.entityId)===t),i=Date.now(),a=n.filter(e=>e!==r),o={...e,savedAt:i,changedAt:i,startedAt:r?Se(r):i,...r?.name?{name:r.name,namedBy:r.namedBy}:{},...r?.synced?{synced:!0}:{}};a.push(o),fe(a),oe(o)}var he=new Set([J,Y,ne].map(e=>e.retryMessage.trim().toLowerCase())),ge=e=>e.kind===`user`&&!!e.detail?.trim()&&!e.retry&&!he.has(e.detail.trim().toLowerCase()),_e=e=>{let t=(e.activity.find(ge)?.detail??``).trim().split(`
15
15
  `)[0].trim();return t.length>80?`${t.slice(0,80).trimEnd()}…`:t},ve=e=>e.name||_e(e)||e.title||e.entityId,ye=e=>e.activity.some(ge),be=e=>e.kind===`user`&&!ge(e)&&!!e.detail?.trim();function xe(e,t,n,r,i=`person`){let a=Q(e,t,n),o=le(),s=o.find(e=>Q(e.scopeId,e.subagentId,e.entityId)===a);if(!s||i===`model`&&s.namedBy===`person`)return!1;let c=r.trim().replace(/\s+/g,` `).slice(0,120),{name:l,namedBy:u,...d}=s,f=c?{...d,name:c,namedBy:i,changedAt:Date.now()}:{...d,changedAt:Date.now()};return fe(o.map(e=>e===s?f:e)),oe(f),!0}var Se=e=>e.startedAt??e.savedAt;function Ce(e,t,n){let r=Q(e,t,n);fe(le().filter(e=>Q(e.scopeId,e.subagentId,e.entityId)!==r)),X&&Promise.resolve(X.remove(e,t,n)).catch(()=>void 0)}function we(e){return le().filter(t=>t.scopeId===e).sort((e,t)=>Se(t)-Se(e))}var Te=(e,t)=>`entitychat-${e}-${t}`,Ee={en:{agentico:J},it:{agentico:Y},de:{agentico:ne}};function $(){let{dict:e}=(0,l.useI18n)(),t=e.agentico;return t?{...J,...t}:J}var De=`agentico-orchestrator`,Oe=(0,u.createContext)(null);function ke({children:e,scope:t=null}){let[n,r]=(0,u.useState)(null),i=(0,u.useRef)(null);(0,u.useEffect)(()=>{i.current=n},[n]);let[a,o]=(0,u.useState)(!1),s=t?.id;(0,u.useEffect)(()=>{s&&se(s).catch(()=>void 0)},[s]);let c=(0,u.useCallback)(e=>{let t=i.current;t&&t.id!==e.id&&t.onDismiss();let n=t&&t.id===e.id&&t.savedToDisk&&e.savedToDisk===void 0?{...e,savedToDisk:!0}:e;r(n)},[]),l=(0,u.useCallback)(e=>{r(t=>t&&t.id===e?null:t)},[]),f=(0,u.useCallback)(()=>o(e=>!e),[]),p=(0,u.useCallback)(()=>o(!0),[]),[m,h]=(0,u.useState)(null),[g,_]=(0,u.useState)(void 0),[v,y]=(0,u.useState)(void 0),[b,S]=(0,u.useState)(void 0),[C,w]=(0,u.useState)(null),[T,E]=(0,u.useState)(null),[D,O]=(0,u.useState)(void 0),[k,A]=(0,u.useState)([]),j=(0,u.useCallback)((e,t,n=null)=>{A(r=>{let i=r.filter(t=>t.id!==e);return t?[...i,{id:e,text:t,card:n}]:i})},[]),N=k.length>0?k[k.length-1]:null,[P,F]=(0,u.useState)([]),I=(0,u.useCallback)((e,t)=>{F(n=>{let r=n.filter(t=>t.id!==e);return t?[...r,{id:e,...t}]:r})},[]),ee=(0,u.useMemo)(()=>P.map(e=>({subagentId:e.subagentId,componentKey:e.componentKey,onResult:e.onResult,pinnedEntityId:e.pinnedEntityId})),[P]),L=(0,u.useMemo)(()=>{let e=new Map;for(let t of P)e.set(t.subagentId,{subagentId:t.subagentId,componentKey:t.componentKey,onResult:t.onResult,contextInfo:t.contextInfo});return[...e.values()]},[P]),R=(0,u.useMemo)(()=>L.map(e=>{let t=x(e.subagentId)?.componentContexts?.[e.componentKey];if(!t)return null;let n=e.contextInfo?`${t.agenticoHint}\n${e.contextInfo}`:t.agenticoHint;return{subagentId:e.subagentId,agenticoHint:n,userMessage:t.userMessage}}).filter(e=>e!==null),[L]),z=(0,u.useMemo)(()=>R.map(e=>e.userMessage),[R]),B=(0,u.useMemo)(()=>{if(R.length===0)return null;if(R.length===1)return R[0].agenticoHint;let e=R.map((e,t)=>`${t+1}. ${e.agenticoHint}`).join(`
16
- `);return`${M().multipleCandidates}\n\n${e}`},[R])??N?.text??null,V=R.length>0?null:N?.card??null,H=(0,u.useMemo)(()=>[...new Set(ee.map(e=>e.subagentId))],[ee]),U=H.length===1?H[0]:H.length===0?N?.card?.subagentId??null:null,W=(0,u.useCallback)((e,t)=>{p();let n=i.current;if(n?.id===`agentico-orchestrator`)return;let r=U&&n?.id.startsWith(`subagent-${U}-`)?n:void 0;E(r?{taskId:r.id,activity:[...r.precedingActivity??[],...r.agent.activity]}:null),h(e),_(t?.extraDestinations),y(t?.attachments),S(t?.model),O(t?.scopedSubagentId),w(crypto.randomUUID())},[p,U]),G=(0,u.useCallback)((e,t,n,a,o,s)=>{if(!n||!a)return;let c=i.current;if(!c||c.id!==n)return;let l=c.agent.snapshot();l&&(me({scopeId:a,subagentId:e,entityId:t,params:o,title:s,history:l.history,activity:[...c.precedingActivity??[],...l.activity]}),r(e=>e&&e.id===n?{...e,savedToDisk:!0}:e))},[]),[K,q]=(0,u.useState)(null),[te,J]=(0,u.useState)(null),Y=(0,u.useCallback)((e,t,n)=>{p(),q({subagentId:e,entityId:t,snapshot:n}),J(crypto.randomUUID())},[p]),[ne,re]=(0,u.useState)(null),[X,ie]=(0,u.useState)(null),Z=(0,u.useCallback)((e,t)=>{p(),l(De),re({subagentId:e,extraDestinations:t}),ie(crypto.randomUUID())},[p,l]),[ae,oe]=(0,u.useState)(null),[ce,le]=(0,u.useState)(null),ue=(0,u.useCallback)((e,t,n)=>{re(null),oe({subagentId:e,params:t,extraDestinations:n}),le(crypto.randomUUID())},[]),[de,fe]=(0,u.useState)(null),[Q,pe]=(0,u.useState)(null),he=(0,u.useCallback)((e,t,n)=>{p(),fe({subagentId:e,params:t,...n}),pe(crypto.randomUUID())},[p]),ge=(0,u.useCallback)(()=>{let e=i.current;e&&e.onDismiss()},[]),_e=(0,u.useMemo)(()=>({scope:t,task:n,isOpen:a,openTask:c,closeTask:l,toggleOpen:f,pendingGoal:m,startOrchestrator:W,pageContext:B,pageContextCard:V,setPageContext:j,scopedSubagentId:U,pendingScopedSubagentId:D,componentAnchors:ee,anchoredUserMessages:z,registerComponentAnchor:I,openPanel:p,pendingExtraDestinations:g,pendingAttachments:v,pendingModel:b,orchestratorRunId:C,pendingCarryOver:T,commitEntityChat:G,resumeEntityChat:Y,pendingResume:K,resumeRunId:te,dismissForeignTask:ge,pendingManualEntry:ne,manualEntryRunId:X,startManualEntry:Z,pendingResumeWithAI:ae,resumeWithAIRunId:ce,resumeWithAI:ue,startSubagent:he,pendingStart:de,startRunId:Q}),[t,n,a,c,l,f,m,W,B,V,j,U,D,ee,z,I,p,g,v,b,C,T,G,Y,K,te,ge,ne,X,Z,ae,ce,ue,he,de,Q]);return(0,d.jsx)(Oe.Provider,{value:_e,children:e})}function Ae(){let e=(0,u.useContext)(Oe);if(!e)throw Error(`useAgentico must be used inside AgenticoProvider`);return e}function je(e){let t=e.search(/[{[]/);if(t===-1)return[{type:`text`,content:e}];let n=e[t],r=n===`{`?`}`:`]`,i=0,a=!1,o=!1,s=-1;for(let c=t;c<e.length;c++){let t=e[c];if(a){o?o=!1:t===`\\`?o=!0:t===`"`&&(a=!1);continue}if(t===`"`){a=!0;continue}if(t===n)i++;else if(t===r&&(i--,i===0)){s=c;break}}let c=s===-1?null:e.slice(t,s+1);if(!c||c.length<60)return[{type:`text`,content:e}];try{JSON.parse(c)}catch{return[{type:`text`,content:e}]}let l=[];t>0&&l.push({type:`text`,content:e.slice(0,t)}),l.push({type:`code`,content:c,language:`json`});let u=e.slice(s+1);return u.trim()&&l.push(...je(u)),l}function Me(e){let t=[],n=/```(\w+)?\n?([\s\S]*?)```/g,r=0,i;for(;i=n.exec(e);)i.index>r&&t.push(...je(e.slice(r,i.index))),t.push({type:`code`,content:i[2].replace(/\n$/,``),language:i[1]}),r=n.lastIndex;return r<e.length&&t.push(...je(e.slice(r))),t}function Ne({content:e,language:t}){let[n,r]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`relative cursor-pointer rounded-md ${n?`max-h-80 overflow-y-auto`:`max-h-28 overflow-hidden`}`,onClick:()=>r(e=>!e),title:n?`Clic per comprimere`:`Clic per espandere`,children:[(0,d.jsx)(l.Code,{language:t,showCopy:n,background:`transparent`,className:`!text-[11px]`,children:e}),!n&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-muted/30 to-transparent`})]})}function Pe({text:e,tone:t}){let n=Me(e);return(0,d.jsx)(d.Fragment,{children:n.map((e,n)=>e.type===`code`?(0,d.jsx)(Ne,{content:e.content,language:e.language},n):e.content.trim()&&(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:t,className:`break-words text-xs leading-relaxed`},n))})}function Fe({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 Ie(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 Le=96;function Re({entry:e,pinned:t=!0}){let n=(0,u.useRef)(null),[r,i]=(0,u.useState)(!1),[a,o]=(0,u.useState)(!1);(0,u.useLayoutEffect)(()=>{let e=n.current;e&&o(e.scrollHeight>97)},[e.detail,e.attachmentNames]);let s=a&&!r;return(0,d.jsx)(`div`,{className:`${t?`sticky top-0 z-20 border-b border-border/40`:``} flex justify-end bg-background py-1.5`,children:(0,d.jsxs)(`div`,{className:`max-w-[85%] rounded-lg bg-primary/10 text-xs text-foreground`,children:[(0,d.jsxs)(`div`,{ref:n,className:`space-y-1 px-2.5 pt-1.5 ${s?`overflow-hidden`:``}`,style:s?{maxHeight:Le}:void 0,children:[e.attachmentNames&&e.attachmentNames.length>0&&(0,d.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.attachmentNames.map((e,t)=>(0,d.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md bg-primary/15 px-1.5 py-0.5 text-[11px] text-foreground`,children:[(0,d.jsx)(l.Icon,{name:`paperclip`,size:10,className:`shrink-0`}),(0,d.jsx)(`span`,{className:`max-w-[160px] truncate`,children:e})]},t))}),(0,d.jsx)(Pe,{text:e.detail??``})]}),a&&(0,d.jsxs)(`button`,{type:`button`,onClick:()=>i(e=>!e),className:`relative flex w-full items-center justify-center rounded-b-lg py-1 text-muted-foreground hover:bg-primary/15`,title:r?`Comprimi`:`Espandi`,children:[s&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 -top-4 h-4 bg-gradient-to-t from-primary/10 to-transparent`}),(0,d.jsx)(l.Icon,{name:r?`chevron-up`:`chevron-down`,size:12})]})]})})}var ze={running:`loader-circle`,done:`check`,error:`x`,stopped:`circle-slash`};function Be({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:ze[e.status]}))}]})}function Ve({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:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[t.details&&(0,d.jsx)(l.ActionButton,{icon:`eye`,label:r.cardView,variant:`outline-secondary`,onClick:()=>a(!0)}),(t.actions??[]).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)(`span`,{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 He(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 Ue({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 We({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)(Be,{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)(Ve,{entry:e,part:r,questions:t},n.key):(0,d.jsx)(Ue,{entry:e,part:r,questions:t},n.key)})})}function Ge({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`&&e.parts.length===0;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[e.parts.length>0&&(0,d.jsx)(We,{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)(Fe,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:Ie(e,r)})]})]})}let i=e.kind===`thinking`&&e.detail?Me(e.detail):[],a=i.filter(e=>e.type===`code`),o=i.filter(e=>e.type===`text`&&e.content.trim()),s=e.kind===`thinking`?Ie(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)(Fe,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:s})]}),a.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-1`,children:a.map((e,t)=>(0,d.jsx)(Ne,{content:e.content,language:e.language},t))}),o.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-2`,children:o.map((e,t)=>(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:`muted`,className:`break-words text-xs leading-relaxed`},t))})]})}function Ke({activity:e,questions:t,docked:n,pinUserMessages:r=!0}){if(e.length===0)return null;let i=[];for(let t of e)t.kind===`user`||i.length===0?i.push(t.kind===`user`?{user:t,entries:[]}:{entries:[t]}):i[i.length-1].entries.push(t);return(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:i.map(e=>(0,d.jsxs)(`li`,{children:[e.user&&(0,d.jsx)(Re,{entry:e.user,pinned:r}),e.entries.length>0&&(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:e.entries.map(e=>(0,d.jsx)(Ge,{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 qe=420,Je=320,Ye=`60vw`,Xe=`agentico:panel-width`;function Ze(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 Qe(e,t,n){return Math.round(Math.min(Math.max(e,t),Math.max(t,n)))}function $e(){try{let e=window.localStorage.getItem(Xe),t=e===null?NaN:Number(e);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function et(e){try{e===null?window.localStorage.removeItem(Xe):window.localStorage.setItem(Xe,String(e))}catch{}}function tt(){return typeof window>`u`?1/0:window.innerWidth}function nt({defaultWidth:e=420,minWidth:t=320,maxWidth:n=Ye,onWidthChange:r}){let[i,a]=(0,u.useState)(tt),[o,s]=(0,u.useState)(()=>$e()??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,Ze(n,i)),d=Qe(o,c,l);return(0,u.useEffect)(()=>{r?.(d)},[d]),{width:d,min:c,max:l,set:(0,u.useCallback)(e=>s(Qe(e,c,l)),[c,l]),commit:(0,u.useCallback)(e=>et(Qe(e,c,l)),[c,l]),reset:(0,u.useCallback)(()=>{s(e),et(null)},[e])}}function rt({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 it({className:e=``}){let{isOpen:t,toggleOpen:n,task:r}=Ae(),i=$(),a=r?.agent.running??!1;return(0,d.jsx)(l.ActionButton,{icon:`bot`,ariaLabel:t?i.closePanel:i.openPanel,title:t?i.closePanel:i.openPanel,onClick:n,iconClassName:a?`animate-pulse`:void 0,className:`!h-9 !w-9 !p-0 rounded-md ${t?`bg-primary/10 text-primary hover:bg-primary/15`:`bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground`} ${e}`})}var at=`llmnative-cms.selectedAIModel`;function ot(){try{return localStorage.getItem(at)??``}catch{return``}}function st(e){try{e?localStorage.setItem(at,e):localStorage.removeItem(at)}catch{}}function ct(){let e=(0,l.useAIProviderRegistry)()?.registry??{},t=Object.keys(e).length>0,[n,r]=(0,u.useState)({}),[i,a]=(0,u.useState)(!1),[o,s]=(0,u.useState)(ot);return(0,u.useEffect)(()=>{if(!t){r({});return}let n=!1;return a(!0),(0,l.getAIModelCatalog)(e).then(e=>{if(n)return;r(e.modelsByProvider);let t=Object.values(e.modelsByProvider).flat();s(e=>t.some(t=>t.id===e)?e:(st(``),``))}).catch(e=>{console.error(`useAIModelCatalog: getAIModelCatalog failed`,e),n||r({})}).finally(()=>{n||a(!1)}),()=>{n=!0}},[t,JSON.stringify(Object.keys(e).sort())]),{hasProviders:t,modelsByProvider:n,modelsLoading:i,selectedModel:o,setSelectedModel:e=>{st(e),s(e)}}}var lt=`approval`;function ut(e,t){return typeof e.needsApproval==`function`?e.needsApproval(t):e.needsApproval===!0}function dt(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 ft=20,pt=26e4;function mt(e){return e.filter(e=>!l.PromptUtils.isTextAttachment(e.mimeType)||e.base64.length<=pt)}function ht(e,t={}){let{defaultEnabled:n=!1}=t,[r,i]=(0,u.useState)(n),{hasProviders:a,modelsByProvider:o,modelsLoading:s,selectedModel:c,setSelectedModel:d}=ct(),[p,_]=(0,u.useState)(!1),[v,y]=(0,u.useState)(null),[b,x]=(0,u.useState)(!1),[S,C]=(0,u.useState)([]),w=(0,u.useRef)([]),E=e=>{C(t=>{let n=typeof e==`function`?e(t):e;return w.current=n,n})},D=(0,u.useRef)(new Map),O=$(),k=(0,u.useRef)(O);k.current=O;let A=(0,u.useRef)(null),j=(0,u.useRef)(!1),N=(0,u.useRef)(null),P=()=>{N.current?.abort()},F=(0,l.useAIProviderRegistry)()?.registry??{},[I,ee]=(0,u.useState)(void 0),L=(0,u.useRef)(void 0),R=(e,t)=>{if(!t)return!1;if(!e)return!0;let n=(0,l.parseAIModelRef)(t);return!!n&&e.includes(n.provider)},z=(0,u.useMemo)(()=>I?Object.fromEntries(Object.entries(o).map(([e,t])=>[e,t.filter(e=>I.includes(e.provider))]).filter(([,e])=>e.length)):o,[I,o]),H=R(I,c)?c:Object.values(z).flat()[0]?.id??``,U=r&&H?(0,l.parseAIModelRef)(H):null,W=U?F[U.provider]:null,G=e.executor,K=!!G?.alongside,q=!!G&&!K,te=(0,u.useRef)([]),J=e=>!!e&&te.current.some(t=>t.value===e),Y=(0,u.useRef)(!1),[ne,re]=(0,u.useState)([]),[X,ie]=(0,u.useState)(``),Z=(0,u.useRef)(``),ae=e=>{Z.current=e,ie(e)},oe=e=>{let t=G?.models?.(e)??[];te.current=t,re(t);let n=G?.catalogProviders?.(e);L.current=n,ee(n);let r=K&&!R(n,c)?t[0]?.value:void 0;ae(G?.defaultModel?.(e)??r??``)},se=async(e,t,n,r)=>{let i=A.current;if(!i||!G)return y(k.current.noActiveSession),null;let a=new AbortController;N.current=a;let o=crypto.randomUUID();E(e=>[...e,{id:o,kind:`thinking`,label:k.current.thinking,status:`running`,parts:[]}]);let s=new Map,c=e=>Math.max(1,Math.round((Date.now()-(s.get(e)??Date.now()))/1e3)),l=e=>({...e,streaming:!1,duration:e.duration??c(e.id)}),u=(e,t)=>E(n=>n.map(n=>{if(n.id!==o)return n;let r=e(n.parts??[]),i=h(r);return{...n,parts:r,...t?{status:t}:{},...i?{detail:i}:{}}})),d=e=>u(t=>m(t,e,l)),p=!1,g=(e,t)=>{t?.id&&t.id!==`text`&&(p=!0),d({type:`text`,id:t?.id??`text`,text:e,streaming:!t?.done})},_=(e,t)=>{let n=t?.id??`reasoning`;s.has(n)||s.set(n,Date.now()),d({type:`reasoning`,id:n,text:e,streaming:!t?.done,...t?.duration===void 0?t?.done?{duration:c(n)}:{}:{duration:t.duration}})},v=e=>d({type:`tool`,id:e.id,label:e.label,status:e.status}),b=e=>d({...e,type:`card`}),x=new Set,S=0,C=()=>{for(let e of x){let t=D.current.get(e);D.current.delete(e),t?.reject(new DOMException(`The turn was stopped.`,`AbortError`))}x.clear()};a.signal.addEventListener(`abort`,C);let w=(e,t)=>{S+=1;let n=t?.id??`questions-${S}`;d({type:`questions`,id:n,questions:e});let r=`${o}:${n}`;return a.signal.aborted?Promise.reject(new DOMException(`The turn was stopped.`,`AbortError`)):(x.add(r),new Promise((e,t)=>{D.current.set(r,{resolve:e,reject:t})}))},T=(e,t)=>{u(n=>(t&&!p?m(n,{type:`text`,id:f,text:t,streaming:!1},l):n).map(t=>t.type===`reasoning`&&t.streaming?l(t):t.type===`text`&&t.streaming?{...t,streaming:!1}:t.type===`tool`&&t.status===`running`&&e!==`done`?{...t,status:`stopped`}:t),e),a.signal.removeEventListener(`abort`,C);for(let e of x)D.current.delete(e);x.clear()},O=e||r?.historyText||``;try{let o=await G.turn({params:i.params,context:i.context,text:e,first:t,signal:a.signal,...n||Z.current?{model:n||Z.current}:{},...r?{answers:{id:r.id,answers:r.answers}}:{},onText:g,onReasoning:_,onStep:v,onQuestions:w,onCard:b});return T(`done`,o.text),i.history=[...i.history,...O?[{role:`user`,content:O}]:[],{role:`assistant`,content:o.text}],o.result??null}catch(e){return i.history=[...i.history,...O?[{role:`user`,content:O}]:[]],a.signal.aborted?(T(`stopped`),null):(T(`error`),y(V(e)),null)}finally{N.current=null}},ce=async(t,n,r)=>{let i=w.current.find(e=>e.id===t)?.parts?.find(e=>e.type===`card`&&e.id===n),a=A.current;if(!i||!a||!e.onCardAction)return;let o;try{o=await e.onCardAction(a.params,i,r)}catch(e){o={status:`error`,text:V(e)}}o&&E(e=>e.map(e=>e.id===t?{...e,parts:e.parts?.map(e=>e.type===`card`&&e.id===n?{...e,outcome:o}:e)}:e))},le=async(e,t,n)=>{let r=w.current.find(t=>t.id===e)?.parts?.find(e=>e.type===`questions`&&e.id===t);if(!r||r.type!==`questions`)throw y(k.current.noActiveSession),Error(k.current.noActiveSession);let i=()=>E(r=>r.map(r=>r.id===e?{...r,parts:r.parts?.map(e=>e.type===`questions`&&e.id===t?{...e,answers:n}:e)}:r)),a=`${e}:${t}`,o=D.current.get(a);if(o)return D.current.delete(a),i(),o.resolve(n),null;if(j.current)throw y(k.current.requestInProgress),Error(k.current.requestInProgress);if(!q||!A.current)throw y(k.current.noActiveSession),Error(k.current.noActiveSession);j.current=!0,_(!0),y(null),i();try{return await se(``,!1,void 0,{id:t,answers:n,historyText:g(r.questions,n)})}finally{j.current=!1,_(!1)}},ue=async(t,n,r)=>{let i=L.current,a=Object.values(o).flat().find(e=>!i||i.includes(e.provider))?.id,s=r&&R(i,r)?r:R(i,H)?void 0:a,c=s?(0,l.parseAIModelRef)(s):U,u=c&&A.current?G?.catalogReasoning?.(A.current.params,c.provider):void 0,d=u?{reasoning:u}:{},f=A.current;if(!f)return y(k.current.noActiveSession),null;let p=s?(0,l.parseAIModelRef)(s):U,m=p?F[p.provider]:null;if(!m||!p)return y(k.current.noProviderAvailable),null;n?.length&&(f.attachmentsRef.current=[...f.attachmentsRef.current??[],...n]);let h=(n??[]).filter(e=>l.PromptUtils.isTextAttachment(e.mimeType)).map(e=>e.base64.length<=pt?`\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=mt(n??[]),_=f.tools.map(e=>({name:e.name,description:e.description,inputSchema:T(e.inputSchema)})),v=(e,t,n,r)=>{let i=k.current,a=`approval-${e}`,o=t.describeApproval?.(n)??t.describeInvocation?.(n)??t.name;E(e=>[...e,{id:a,kind:`thinking`,label:i.approvalHeader,status:`running`,parts:[{type:`questions`,id:lt,questions:[{header:i.approvalHeader,question:i.approveQuestion.replace(`{action}`,o),options:[{label:i.approve},{label:i.reject}],custom:!0}]}]}]);let s=`${a}:${lt}`;return new Promise((e,t)=>{let n=()=>{D.current.delete(s),S(a,`stopped`),t(new DOMException(`The turn was stopped.`,`AbortError`))};if(r.aborted){n();return}r.addEventListener(`abort`,n,{once:!0}),D.current.set(s,{resolve:t=>{r.removeEventListener(`abort`,n),S(a,`done`),e(dt(t,i.approve,i.reject))},reject:t})})},b=new Map(f.tools.map(e=>[e.name,e])),x=new AbortController;N.current=x;let S=(e,t,n,r)=>E(i=>i.map(i=>i.id===e?{...i,status:t,...n===void 0?{}:{detail:n},...r===void 0?{}:{toolNames:r}}:i));try{let n=f.history,r=t;for(let t=0;t<ft;t++){let i=crypto.randomUUID();E(e=>[...e,{id:i,kind:`thinking`,label:k.current.thinking,status:`running`}]);let a;try{a=await m.complete({prompt:r,model:p.model,...d,history:n,tools:_.length?_:void 0,signal:x.signal,attachments:t===0?g:void 0,logId:f.logId})}catch(t){return f.history=[...n,...r?[{role:`user`,content:r+h}]:[]],x.signal.aborted?(S(i,`stopped`),e.fallback(f.params,f.context)):(S(i,`error`),y(V(t)),null)}if(f.history=[...n,...r?[{role:`user`,content:r+h}]:[]],!a)return x.signal.aborted?(S(i,`stopped`),e.fallback(f.params,f.context)):(S(i,`error`),y(k.current.noProviderResponse),null);if(a.type===`text`)return S(i,`done`,a.text),e.conversational&&a.text.trim()&&E(e=>e.map(e=>e.id===i?{...e,parts:[{type:`text`,id:`text`,text:a.text}]}:e)),f.history=[...n,...r?[{role:`user`,content:r+h}]:[],{role:`assistant`,content:a.text}],e.parseResponse(a.text,f.params,f.context)||(console.error(`[useAgent] parseResponse ha restituito null — la risposta del modello non è nel formato atteso da questo subagent. Uso il fallback deterministico.`,{responseLength:a.text.length,responsePreview:a.text.length>2e3?`${a.text.slice(0,1e3)}\n…[troncato qui nel log, ${a.text.length} caratteri totali]…\n${a.text.slice(-1e3)}`:a.text,params:f.params}),y(k.current.invalidResponse),e.fallback(f.params,f.context));let o=a.toolCalls.map(e=>{let t=b.get(e.name);return t?.describeIntent??t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`});S(i,`done`,a.text||void 0,a.text?void 0:o);let s=new Map;for(let t of a.toolCalls){let n=b.get(t.name);if(n&&ut(n,t.input))try{s.set(t.id,await v(t.id,n,t.input,x.signal))}catch{return e.fallback(f.params,f.context)}}let c=await Promise.all(a.toolCalls.map(async e=>{let t=b.get(e.name),n=t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`,r=s.get(e.id);if(r&&!r.approved){E(t=>[...t,{id:e.id,kind:`tool`,label:n,status:`stopped`}]);let t=M().toolRejected.replace(`{reason}`,r.reason?` (${r.reason})`:``);return{toolCallId:e.id,name:e.name,output:t,isError:!0}}if(E(t=>[...t,{id:e.id,kind:`tool`,label:n,status:`running`}]),!t)return S(e.id,`error`),{toolCallId:e.id,name:e.name,output:`Tool sconosciuto: ${e.name}`,isError:!0};try{let n=await t.execute(e.input);S(e.id,`done`);let r=t.card?.(e.input,n);return r&&E(t=>[...t,{id:`card-${e.id}`,kind:`thinking`,label:``,status:`done`,parts:[{...r,type:`card`}]}]),{toolCallId:e.id,name:e.name,output:n}}catch(t){return S(e.id,`error`),{toolCallId:e.id,name:e.name,output:V(t),isError:!0}}}));n=[...n,...r?[{role:`user`,content:r+h}]:[],{role:`assistant`,content:a.text,toolCalls:a.toolCalls},{role:`tool_result`,results:c}],r=``}let i=crypto.randomUUID();E(e=>[...e,{id:i,kind:`thinking`,label:k.current.thinking,status:`running`}]);let a;try{a=await m.complete({...d,prompt:B(M().stopCallingTools,e.microPromptIds),model:p.model,history:n,signal:x.signal,logId:f.logId})}catch{a=null}if(a?.type===`text`){S(i,`done`,a.text),f.history=[...n,{role:`assistant`,content:a.text}];let t=e.parseResponse(a.text,f.params,f.context);if(t)return t}else S(i,x.signal.aborted?`stopped`:`error`),f.history=n;return x.signal.aborted||y(k.current.tooManyToolTurns),e.fallback(f.params,f.context)}finally{N.current=null}},de=async(t,n)=>{if(j.current)return y(k.current.requestInProgress),null;j.current=!0,y(null),E(n?.openingMessage?[{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:n.openingMessage,...n.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]:[]),_(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];if(A.current={params:t,context:i,tools:o,history:[],logId:crypto.randomUUID(),attachmentsRef:a},q)return x(!0),oe(t),await se(n?.openingMessage??``,!0);if(K){oe(t),Y.current=!1;let e=n?.model||Z.current;if(J(e))return x(!0),Y.current=!0,await se(n?.openingMessage??``,!0,e)}let s=n?.model||void 0,c=s?!!F[(0,l.parseAIModelRef)(s)?.provider??``]:!!W;if(!r||!c){x(!1);let n=e.fallback(t,i);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.aiDisabledFallback}]),n}x(!0);let u=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,d=B(e.buildPrompt(t,i),e.microPromptIds);return await ue(d,u,s)}catch(e){return y(V(e)),null}finally{j.current=!1,_(!1)}},fe=async(t,n)=>{if(j.current){y(k.current.requestInProgress);return}j.current=!0,y(null),E(n.activity),_(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];A.current={params:t,context:i,tools:o,history:n.history,logId:crypto.randomUUID(),attachmentsRef:a},(q||K)&&oe(t),Y.current=!1,x(q||K||r&&!!W)}catch(e){y(V(e))}finally{j.current=!1,_(!1)}},Q=async(t,n)=>{if(j.current)return y(k.current.requestInProgress),null;if(y(null),!t.trim())return y(`Messaggio vuoto.`),null;let r=A.current;if(!r)return y(k.current.noActiveSession),null;j.current=!0,_(!0),E(e=>[...e,{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:t,...n?.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{},...n?.retry?{retry:!0}:{}}]);try{if(q)return await se(t,!1,n?.model||void 0);let i=n?.model||(K?Z.current:``);if(K&&J(i)){let e=!Y.current;return Y.current=!0,await se(t,e,i)}let a=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,o=B(e.buildFollowUpPrompt(t,r.params,r.context),e.microPromptIds);return await ue(o,a,n?.model||void 0)}catch(e){return y(V(e)),null}finally{j.current=!1,_(!1)}},pe=()=>{let t=A.current;if(!t)return null;y(null);let n=e.fallback(t.params,t.context);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.continueWithoutAiFallback}]),n},me=()=>A.current?{history:A.current.history,activity:S}:null;return{enabled:r,setEnabled:i,hasProviders:a,selectedModel:q||K&&X?X:H,setSelectedModel:q?ae:K?e=>{J(e)?ae(e):(ae(``),d(e))}:d,modelsByProvider:z,modelsLoading:s,running:p,error:v,canContinue:b,remote:q,remoteModels:ne,alongside:K,...G?.catalogGroup?{catalogGroup:G.catalogGroup}:{},activity:S,run:de,resume:fe,sendMessage:Q,stop:P,runFallback:pe,snapshot:me,answerQuestions:le,cardAction:ce}}function gt(){let e=M();return[e.responseRulesHeading,...e.responseRules.map(e=>`- ${e}`)].join(`
17
- `)}function _t(e,t,n){let r=M(),i=n?`\n${r.pageContextHeading}\n${r.pageContextIntro}\n${n}\n`:``;return`${r.orchestratorIntro}
16
+ `);return`${M().multipleCandidates}\n\n${e}`},[R])??N?.text??null,V=R.length>0?null:N?.card??null,H=(0,u.useMemo)(()=>[...new Set(ee.map(e=>e.subagentId))],[ee]),U=H.length===1?H[0]:H.length===0?N?.card?.subagentId??null:null,W=(0,u.useCallback)((e,t)=>{p();let n=i.current;if(n?.id===`agentico-orchestrator`)return;let r=U&&n?.id.startsWith(`subagent-${U}-`)?n:void 0;E(r?{taskId:r.id,activity:[...r.precedingActivity??[],...r.agent.activity]}:null),h(e),_(t?.extraDestinations),y(t?.attachments),S(t?.model),O(t?.scopedSubagentId),w(crypto.randomUUID())},[p,U]),G=(0,u.useCallback)((e,t,n,a,o,s)=>{if(!n||!a)return;let c=i.current;if(!c||c.id!==n)return;let l=c.agent.snapshot();l&&(me({scopeId:a,subagentId:e,entityId:t,params:o,title:s,history:l.history,activity:[...c.precedingActivity??[],...l.activity]}),r(e=>e&&e.id===n?{...e,savedToDisk:!0}:e))},[]),[K,q]=(0,u.useState)(null),[te,J]=(0,u.useState)(null),Y=(0,u.useCallback)((e,t,n)=>{p(),q({subagentId:e,entityId:t,snapshot:n}),J(crypto.randomUUID())},[p]),[ne,re]=(0,u.useState)(null),[X,ie]=(0,u.useState)(null),Z=(0,u.useCallback)((e,t)=>{p(),l(De),re({subagentId:e,extraDestinations:t}),ie(crypto.randomUUID())},[p,l]),[ae,oe]=(0,u.useState)(null),[ce,le]=(0,u.useState)(null),ue=(0,u.useCallback)((e,t,n)=>{re(null),oe({subagentId:e,params:t,extraDestinations:n}),le(crypto.randomUUID())},[]),[de,fe]=(0,u.useState)(null),[Q,pe]=(0,u.useState)(null),he=(0,u.useCallback)((e,t,n)=>{p(),fe({subagentId:e,params:t,...n}),pe(crypto.randomUUID())},[p]),ge=(0,u.useCallback)(()=>{let e=i.current;e&&e.onDismiss()},[]),_e=(0,u.useMemo)(()=>({scope:t,task:n,isOpen:a,openTask:c,closeTask:l,toggleOpen:f,pendingGoal:m,startOrchestrator:W,pageContext:B,pageContextCard:V,setPageContext:j,scopedSubagentId:U,pendingScopedSubagentId:D,componentAnchors:ee,anchoredUserMessages:z,registerComponentAnchor:I,openPanel:p,pendingExtraDestinations:g,pendingAttachments:v,pendingModel:b,orchestratorRunId:C,pendingCarryOver:T,commitEntityChat:G,resumeEntityChat:Y,pendingResume:K,resumeRunId:te,dismissForeignTask:ge,pendingManualEntry:ne,manualEntryRunId:X,startManualEntry:Z,pendingResumeWithAI:ae,resumeWithAIRunId:ce,resumeWithAI:ue,startSubagent:he,pendingStart:de,startRunId:Q}),[t,n,a,c,l,f,m,W,B,V,j,U,D,ee,z,I,p,g,v,b,C,T,G,Y,K,te,ge,ne,X,Z,ae,ce,ue,he,de,Q]);return(0,d.jsx)(Oe.Provider,{value:_e,children:e})}function Ae(){let e=(0,u.useContext)(Oe);if(!e)throw Error(`useAgentico must be used inside AgenticoProvider`);return e}function je(e){let t=e.search(/[{[]/);if(t===-1)return[{type:`text`,content:e}];let n=e[t],r=n===`{`?`}`:`]`,i=0,a=!1,o=!1,s=-1;for(let c=t;c<e.length;c++){let t=e[c];if(a){o?o=!1:t===`\\`?o=!0:t===`"`&&(a=!1);continue}if(t===`"`){a=!0;continue}if(t===n)i++;else if(t===r&&(i--,i===0)){s=c;break}}let c=s===-1?null:e.slice(t,s+1);if(!c||c.length<60)return[{type:`text`,content:e}];try{JSON.parse(c)}catch{return[{type:`text`,content:e}]}let l=[];t>0&&l.push({type:`text`,content:e.slice(0,t)}),l.push({type:`code`,content:c,language:`json`});let u=e.slice(s+1);return u.trim()&&l.push(...je(u)),l}function Me(e){let t=[],n=/```(\w+)?\n?([\s\S]*?)```/g,r=0,i;for(;i=n.exec(e);)i.index>r&&t.push(...je(e.slice(r,i.index))),t.push({type:`code`,content:i[2].replace(/\n$/,``),language:i[1]}),r=n.lastIndex;return r<e.length&&t.push(...je(e.slice(r))),t}function Ne({content:e,language:t}){let[n,r]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`relative cursor-pointer rounded-md ${n?`max-h-80 overflow-y-auto`:`max-h-28 overflow-hidden`}`,onClick:()=>r(e=>!e),title:n?`Clic per comprimere`:`Clic per espandere`,children:[(0,d.jsx)(l.Code,{language:t,showCopy:n,background:`transparent`,className:`!text-[11px]`,children:e}),!n&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-muted/30 to-transparent`})]})}function Pe({text:e,tone:t}){let n=Me(e);return(0,d.jsx)(d.Fragment,{children:n.map((e,n)=>e.type===`code`?(0,d.jsx)(Ne,{content:e.content,language:e.language},n):e.content.trim()&&(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:t,className:`break-words text-xs leading-relaxed`},n))})}function Fe(){let[e]=(0,u.useState)(()=>Date.now()),[t,n]=(0,u.useState)(e);(0,u.useEffect)(()=>{let e=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(e)},[]);let r=Math.floor((t-e)/1e3);return r<10?null:(0,d.jsxs)(`span`,{className:`tabular-nums`,children:[` · `,Math.floor(r/60),`:`,String(r%60).padStart(2,`0`)]})}function Ie({status:e}){return e===`running`?(0,d.jsx)(`span`,{className:`inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-2 border-current border-t-transparent`}):e===`done`?(0,d.jsx)(l.Icon,{name:`check`,size:12,className:`shrink-0 text-green-600`}):e===`stopped`?(0,d.jsx)(l.Icon,{name:`circle-slash`,size:12,className:`shrink-0 text-muted-foreground`}):(0,d.jsx)(l.Icon,{name:`x`,size:12,className:`shrink-0 text-destructive`})}function Le(e,t){return e.status===`running`?t.thinking:e.status===`error`?t.modelRequestError:e.status===`stopped`?t.stopped:e.detail?t.responseReceived:e.toolNames&&e.toolNames.length>0?e.toolNames.join(` · `):t.toolRequest}var Re=96;function ze({entry:e,pinned:t=!0}){let n=(0,u.useRef)(null),[r,i]=(0,u.useState)(!1),[a,o]=(0,u.useState)(!1);(0,u.useLayoutEffect)(()=>{let e=n.current;e&&o(e.scrollHeight>97)},[e.detail,e.attachmentNames]);let s=a&&!r;return(0,d.jsx)(`div`,{className:`${t?`sticky top-0 z-20 border-b border-border/40`:``} flex justify-end bg-background py-1.5`,children:(0,d.jsxs)(`div`,{className:`max-w-[85%] rounded-lg bg-primary/10 text-xs text-foreground`,children:[(0,d.jsxs)(`div`,{ref:n,className:`space-y-1 px-2.5 pt-1.5 ${s?`overflow-hidden`:``}`,style:s?{maxHeight:Re}:void 0,children:[e.attachmentNames&&e.attachmentNames.length>0&&(0,d.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.attachmentNames.map((e,t)=>(0,d.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md bg-primary/15 px-1.5 py-0.5 text-[11px] text-foreground`,children:[(0,d.jsx)(l.Icon,{name:`paperclip`,size:10,className:`shrink-0`}),(0,d.jsx)(`span`,{className:`max-w-[160px] truncate`,children:e})]},t))}),(0,d.jsx)(Pe,{text:e.detail??``})]}),a&&(0,d.jsxs)(`button`,{type:`button`,onClick:()=>i(e=>!e),className:`relative flex w-full items-center justify-center rounded-b-lg py-1 text-muted-foreground hover:bg-primary/15`,title:r?`Comprimi`:`Espandi`,children:[s&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 -top-4 h-4 bg-gradient-to-t from-primary/10 to-transparent`}),(0,d.jsx)(l.Icon,{name:r?`chevron-up`:`chevron-down`,size:12})]})]})})}var Be={running:`loader-circle`,done:`check`,error:`x`,stopped:`circle-slash`};function Ve({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:Be[e.status]}))}]})}function He({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 Ue(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 We({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 Ge({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)(Ve,{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)(He,{entry:e,part:r,questions:t},n.key):(0,d.jsx)(We,{entry:e,part:r,questions:t},n.key)})})}function Ke({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)(Ge,{entry:e,questions:t,hiddenPartId:n}),i&&(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5 ${e.parts.length>0?`mt-1`:``}`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(Ie,{status:e.status})}),(0,d.jsxs)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:[Le(e,r),e.status===`running`&&(0,d.jsx)(Fe,{})]})]})]})}let i=e.kind===`thinking`&&e.detail?Me(e.detail):[],a=i.filter(e=>e.type===`code`),o=i.filter(e=>e.type===`text`&&e.content.trim()),s=e.kind===`thinking`?Le(e,r):e.label;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(Ie,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:s})]}),a.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-1`,children:a.map((e,t)=>(0,d.jsx)(Ne,{content:e.content,language:e.language},t))}),o.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-2`,children:o.map((e,t)=>(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:`muted`,className:`break-words text-xs leading-relaxed`},t))})]})}function qe({activity:e,questions:t,docked:n,pinUserMessages:r=!0}){if(e.length===0)return null;let i=[];for(let t of e)t.kind===`user`||i.length===0?i.push(t.kind===`user`?{user:t,entries:[]}:{entries:[t]}):i[i.length-1].entries.push(t);return(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:i.map(e=>(0,d.jsxs)(`li`,{children:[e.user&&(0,d.jsx)(ze,{entry:e.user,pinned:r}),e.entries.length>0&&(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:e.entries.map(e=>(0,d.jsx)(Ke,{entry:e,questions:t,hiddenPartId:n?.entry.id===e.id?n.part.id:void 0},e.id))})]},e.user?.id??e.entries[0]?.id))})}var Je=420,Ye=320,Xe=`60vw`,Ze=`agentico:panel-width`;function Qe(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 $e(e,t,n){return Math.round(Math.min(Math.max(e,t),Math.max(t,n)))}function et(){try{let e=window.localStorage.getItem(Ze),t=e===null?NaN:Number(e);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function tt(e){try{e===null?window.localStorage.removeItem(Ze):window.localStorage.setItem(Ze,String(e))}catch{}}function nt(){return typeof window>`u`?1/0:window.innerWidth}function rt({defaultWidth:e=420,minWidth:t=320,maxWidth:n=Xe,onWidthChange:r}){let[i,a]=(0,u.useState)(nt),[o,s]=(0,u.useState)(()=>et()??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,Qe(n,i)),d=$e(o,c,l);return(0,u.useEffect)(()=>{r?.(d)},[d]),{width:d,min:c,max:l,set:(0,u.useCallback)(e=>s($e(e,c,l)),[c,l]),commit:(0,u.useCallback)(e=>tt($e(e,c,l)),[c,l]),reset:(0,u.useCallback)(()=>{s(e),tt(null)},[e])}}function it({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 at({className:e=``}){let{isOpen:t,toggleOpen:n,task:r}=Ae(),i=$(),a=r?.agent.running??!1;return(0,d.jsx)(l.ActionButton,{icon:`bot`,ariaLabel:t?i.closePanel:i.openPanel,title:t?i.closePanel:i.openPanel,onClick:n,iconClassName:a?`animate-pulse`:void 0,className:`!h-9 !w-9 !p-0 rounded-md ${t?`bg-primary/10 text-primary hover:bg-primary/15`:`bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground`} ${e}`})}var ot=`llmnative-cms.selectedAIModel`;function st(){try{return localStorage.getItem(ot)??``}catch{return``}}function ct(e){try{e?localStorage.setItem(ot,e):localStorage.removeItem(ot)}catch{}}function lt(){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)(st);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:(ct(``),``))}).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=>{ct(e),s(e)}}}var ut=`approval`;function dt(e,t){return typeof e.needsApproval==`function`?e.needsApproval(t):e.needsApproval===!0}function ft(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 pt=20,mt=26e4;function ht(e){return e.filter(e=>!l.PromptUtils.isTextAttachment(e.mimeType)||e.base64.length<=mt)}function gt(e,t={}){let{defaultEnabled:n=!1}=t,[r,i]=(0,u.useState)(n),{hasProviders:a,modelsByProvider:o,modelsLoading:s,selectedModel:c,setSelectedModel:d}=lt(),[p,_]=(0,u.useState)(!1),[v,y]=(0,u.useState)(null),[b,x]=(0,u.useState)(!1),[S,C]=(0,u.useState)([]),w=(0,u.useRef)([]),E=e=>{C(t=>{let n=typeof e==`function`?e(t):e;return w.current=n,n})},D=(0,u.useRef)(new Map),O=$(),k=(0,u.useRef)(O);k.current=O;let A=(0,u.useRef)(null),j=(0,u.useRef)(!1),N=(0,u.useRef)(null),P=()=>{N.current?.abort()},F=(0,l.useAIProviderRegistry)()?.registry??{},[I,ee]=(0,u.useState)(void 0),L=(0,u.useRef)(void 0),R=(e,t)=>{if(!t)return!1;if(!e)return!0;let n=(0,l.parseAIModelRef)(t);return!!n&&e.includes(n.provider)},z=(0,u.useMemo)(()=>I?Object.fromEntries(Object.entries(o).map(([e,t])=>[e,t.filter(e=>I.includes(e.provider))]).filter(([,e])=>e.length)):o,[I,o]),H=R(I,c)?c:Object.values(z).flat()[0]?.id??``,U=r&&H?(0,l.parseAIModelRef)(H):null,W=U?F[U.provider]:null,G=e.executor,K=!!G?.alongside,q=!!G&&!K,te=(0,u.useRef)([]),J=e=>!!e&&te.current.some(t=>t.value===e),Y=(0,u.useRef)(!1),[ne,re]=(0,u.useState)([]),[X,ie]=(0,u.useState)(``),Z=(0,u.useRef)(``),ae=e=>{Z.current=e,ie(e)},oe=e=>{let t=G?.models?.(e)??[];te.current=t,re(t);let n=G?.catalogProviders?.(e);L.current=n,ee(n);let r=K&&!R(n,c)?t[0]?.value:void 0;ae(G?.defaultModel?.(e)??r??``)},se=async(e,t,n,r)=>{let i=A.current;if(!i||!G)return y(k.current.noActiveSession),null;let a=new AbortController;N.current=a;let o=crypto.randomUUID();E(e=>[...e,{id:o,kind:`thinking`,label:k.current.thinking,status:`running`,parts:[]}]);let s=new Map,c=e=>Math.max(1,Math.round((Date.now()-(s.get(e)??Date.now()))/1e3)),l=e=>({...e,streaming:!1,duration:e.duration??c(e.id)}),u=(e,t)=>E(n=>n.map(n=>{if(n.id!==o)return n;let r=e(n.parts??[]),i=h(r);return{...n,parts:r,...t?{status:t}:{},...i?{detail:i}:{}}})),d=e=>u(t=>m(t,e,l)),p=!1,g=(e,t)=>{t?.id&&t.id!==`text`&&(p=!0),d({type:`text`,id:t?.id??`text`,text:e,streaming:!t?.done})},_=(e,t)=>{let n=t?.id??`reasoning`;s.has(n)||s.set(n,Date.now()),d({type:`reasoning`,id:n,text:e,streaming:!t?.done,...t?.duration===void 0?t?.done?{duration:c(n)}:{}:{duration:t.duration}})},v=e=>d({type:`tool`,id:e.id,label:e.label,status:e.status}),b=e=>d({...e,type:`card`}),x=new Set,S=0,C=()=>{for(let e of x){let t=D.current.get(e);D.current.delete(e),t?.reject(new DOMException(`The turn was stopped.`,`AbortError`))}x.clear()};a.signal.addEventListener(`abort`,C);let w=(e,t)=>{S+=1;let n=t?.id??`questions-${S}`;d({type:`questions`,id:n,questions:e});let r=`${o}:${n}`;return a.signal.aborted?Promise.reject(new DOMException(`The turn was stopped.`,`AbortError`)):(x.add(r),new Promise((e,t)=>{D.current.set(r,{resolve:e,reject:t})}))},T=(e,t)=>{u(n=>(t&&!p?m(n,{type:`text`,id:f,text:t,streaming:!1},l):n).map(t=>t.type===`reasoning`&&t.streaming?l(t):t.type===`text`&&t.streaming?{...t,streaming:!1}:t.type===`tool`&&t.status===`running`&&e!==`done`?{...t,status:`stopped`}:t),e),a.signal.removeEventListener(`abort`,C);for(let e of x)D.current.delete(e);x.clear()},O=e||r?.historyText||``;try{let o=await G.turn({params:i.params,context:i.context,text:e,first:t,signal:a.signal,...n||Z.current?{model:n||Z.current}:{},...r?{answers:{id:r.id,answers:r.answers}}:{},onText:g,onReasoning:_,onStep:v,onQuestions:w,onCard:b});return T(`done`,o.text),i.history=[...i.history,...O?[{role:`user`,content:O}]:[],{role:`assistant`,content:o.text}],o.result??null}catch(e){return i.history=[...i.history,...O?[{role:`user`,content:O}]:[]],a.signal.aborted?(T(`stopped`),null):(T(`error`),y(V(e)),null)}finally{N.current=null}},ce=async(t,n,r)=>{let i=w.current.find(e=>e.id===t)?.parts?.find(e=>e.type===`card`&&e.id===n),a=A.current;if(!i||!a||!e.onCardAction)return;let o;try{o=await e.onCardAction(a.params,i,r)}catch(e){o={status:`error`,text:V(e)}}o&&E(e=>e.map(e=>e.id===t?{...e,parts:e.parts?.map(e=>e.type===`card`&&e.id===n?{...e,outcome:o}:e)}:e))},le=async(e,t,n)=>{let r=w.current.find(t=>t.id===e)?.parts?.find(e=>e.type===`questions`&&e.id===t);if(!r||r.type!==`questions`)throw y(k.current.noActiveSession),Error(k.current.noActiveSession);let i=()=>E(r=>r.map(r=>r.id===e?{...r,parts:r.parts?.map(e=>e.type===`questions`&&e.id===t?{...e,answers:n}:e)}:r)),a=`${e}:${t}`,o=D.current.get(a);if(o)return D.current.delete(a),i(),o.resolve(n),null;if(j.current)throw y(k.current.requestInProgress),Error(k.current.requestInProgress);if(!q||!A.current)throw y(k.current.noActiveSession),Error(k.current.noActiveSession);j.current=!0,_(!0),y(null),i();try{return await se(``,!1,void 0,{id:t,answers:n,historyText:g(r.questions,n)})}finally{j.current=!1,_(!1)}},ue=async(t,n,r)=>{let i=L.current,a=Object.values(o).flat().find(e=>!i||i.includes(e.provider))?.id,s=r&&R(i,r)?r:R(i,H)?void 0:a,c=s?(0,l.parseAIModelRef)(s):U,u=c&&A.current?G?.catalogReasoning?.(A.current.params,c.provider):void 0,d=u?{reasoning:u}:{},f=A.current;if(!f)return y(k.current.noActiveSession),null;let p=s?(0,l.parseAIModelRef)(s):U,m=p?F[p.provider]:null;if(!m||!p)return y(k.current.noProviderAvailable),null;n?.length&&(f.attachmentsRef.current=[...f.attachmentsRef.current??[],...n]);let h=(n??[]).filter(e=>l.PromptUtils.isTextAttachment(e.mimeType)).map(e=>e.base64.length<=mt?`\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=ht(n??[]),_=f.tools.map(e=>({name:e.name,description:e.description,inputSchema:T(e.inputSchema)})),v=(e,t,n,r)=>{let i=k.current,a=`approval-${e}`,o=t.describeApproval?.(n)??t.describeInvocation?.(n)??t.name;E(e=>[...e,{id:a,kind:`thinking`,label:i.approvalHeader,status:`running`,parts:[{type:`questions`,id:ut,questions:[{header:i.approvalHeader,question:i.approveQuestion.replace(`{action}`,o),options:[{label:i.approve},{label:i.reject}],custom:!0}]}]}]);let s=`${a}:${ut}`;return new Promise((e,t)=>{let n=()=>{D.current.delete(s),S(a,`stopped`),t(new DOMException(`The turn was stopped.`,`AbortError`))};if(r.aborted){n();return}r.addEventListener(`abort`,n,{once:!0}),D.current.set(s,{resolve:t=>{r.removeEventListener(`abort`,n),S(a,`done`),e(ft(t,i.approve,i.reject))},reject:t})})},b=new Map(f.tools.map(e=>[e.name,e])),x=new AbortController;N.current=x;let S=(e,t,n,r)=>E(i=>i.map(i=>i.id===e?{...i,status:t,...n===void 0?{}:{detail:n},...r===void 0?{}:{toolNames:r}}:i));try{let n=f.history,r=t;for(let t=0;t<pt;t++){let i=crypto.randomUUID();E(e=>[...e,{id:i,kind:`thinking`,label:k.current.thinking,status:`running`}]);let a;try{a=await m.complete({prompt:r,model:p.model,...d,history:n,tools:_.length?_:void 0,signal:x.signal,attachments:t===0?g:void 0,logId:f.logId})}catch(t){return f.history=[...n,...r?[{role:`user`,content:r+h}]:[]],x.signal.aborted?(S(i,`stopped`),e.fallback(f.params,f.context)):(S(i,`error`),y(V(t)),null)}if(f.history=[...n,...r?[{role:`user`,content:r+h}]:[]],!a)return x.signal.aborted?(S(i,`stopped`),e.fallback(f.params,f.context)):(S(i,`error`),y(k.current.noProviderResponse),null);if(a.type===`text`)return S(i,`done`,a.text),e.conversational&&a.text.trim()&&E(e=>e.map(e=>e.id===i?{...e,parts:[{type:`text`,id:`text`,text:a.text}]}:e)),f.history=[...n,...r?[{role:`user`,content:r+h}]:[],{role:`assistant`,content:a.text}],e.parseResponse(a.text,f.params,f.context)||(console.error(`[useAgent] parseResponse ha restituito null — la risposta del modello non è nel formato atteso da questo subagent. Uso il fallback deterministico.`,{responseLength:a.text.length,responsePreview:a.text.length>2e3?`${a.text.slice(0,1e3)}\n…[troncato qui nel log, ${a.text.length} caratteri totali]…\n${a.text.slice(-1e3)}`:a.text,params:f.params}),y(k.current.invalidResponse),e.fallback(f.params,f.context));let o=a.toolCalls.map(e=>{let t=b.get(e.name);return t?.describeIntent??t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`});S(i,`done`,a.text||void 0,a.text?void 0:o);let s=new Map;for(let t of a.toolCalls){let n=b.get(t.name);if(n&&dt(n,t.input))try{s.set(t.id,await v(t.id,n,t.input,x.signal))}catch{return e.fallback(f.params,f.context)}}let c=await Promise.all(a.toolCalls.map(async e=>{let t=b.get(e.name),n=t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`,r=s.get(e.id);if(r&&!r.approved){E(t=>[...t,{id:e.id,kind:`tool`,label:n,status:`stopped`}]);let t=M().toolRejected.replace(`{reason}`,r.reason?` (${r.reason})`:``);return{toolCallId:e.id,name:e.name,output:t,isError:!0}}if(E(t=>[...t,{id:e.id,kind:`tool`,label:n,status:`running`}]),!t)return S(e.id,`error`),{toolCallId:e.id,name:e.name,output:`Tool sconosciuto: ${e.name}`,isError:!0};try{let n=await t.execute(e.input);S(e.id,`done`);let r=t.card?.(e.input,n);return r&&E(t=>[...t,{id:`card-${e.id}`,kind:`thinking`,label:``,status:`done`,parts:[{...r,type:`card`}]}]),{toolCallId:e.id,name:e.name,output:n}}catch(t){return S(e.id,`error`),{toolCallId:e.id,name:e.name,output:V(t),isError:!0}}}));n=[...n,...r?[{role:`user`,content:r+h}]:[],{role:`assistant`,content:a.text,toolCalls:a.toolCalls},{role:`tool_result`,results:c}],r=``}let i=crypto.randomUUID();E(e=>[...e,{id:i,kind:`thinking`,label:k.current.thinking,status:`running`}]);let a;try{a=await m.complete({...d,prompt:B(M().stopCallingTools,e.microPromptIds),model:p.model,history:n,signal:x.signal,logId:f.logId})}catch{a=null}if(a?.type===`text`){S(i,`done`,a.text),f.history=[...n,{role:`assistant`,content:a.text}];let t=e.parseResponse(a.text,f.params,f.context);if(t)return t}else S(i,x.signal.aborted?`stopped`:`error`),f.history=n;return x.signal.aborted||y(k.current.tooManyToolTurns),e.fallback(f.params,f.context)}finally{N.current=null}},de=async(t,n)=>{if(j.current)return y(k.current.requestInProgress),null;j.current=!0,y(null),E(n?.openingMessage?[{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:n.openingMessage,...n.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]:[]),_(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];if(A.current={params:t,context:i,tools:o,history:[],logId:crypto.randomUUID(),attachmentsRef:a},q)return x(!0),oe(t),await se(n?.openingMessage??``,!0);if(K){oe(t),Y.current=!1;let e=n?.model||Z.current;if(J(e))return x(!0),Y.current=!0,await se(n?.openingMessage??``,!0,e)}let s=n?.model||void 0,c=s?!!F[(0,l.parseAIModelRef)(s)?.provider??``]:!!W;if(!r||!c){x(!1);let n=e.fallback(t,i);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.aiDisabledFallback}]),n}x(!0);let u=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,d=B(e.buildPrompt(t,i),e.microPromptIds);return await ue(d,u,s)}catch(e){return y(V(e)),null}finally{j.current=!1,_(!1)}},fe=async(t,n)=>{if(j.current){y(k.current.requestInProgress);return}j.current=!0,y(null),E(n.activity),_(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];A.current={params:t,context:i,tools:o,history:n.history,logId:crypto.randomUUID(),attachmentsRef:a},(q||K)&&oe(t),Y.current=!1,x(q||K||r&&!!W)}catch(e){y(V(e))}finally{j.current=!1,_(!1)}},Q=async(t,n)=>{if(j.current)return y(k.current.requestInProgress),null;if(y(null),!t.trim())return y(`Messaggio vuoto.`),null;let r=A.current;if(!r)return y(k.current.noActiveSession),null;j.current=!0,_(!0),E(e=>[...e,{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:t,...n?.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{},...n?.retry?{retry:!0}:{}}]);try{if(q)return await se(t,!1,n?.model||void 0);let i=n?.model||(K?Z.current:``);if(K&&J(i)){let e=!Y.current;return Y.current=!0,await se(t,e,i)}let a=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,o=B(e.buildFollowUpPrompt(t,r.params,r.context),e.microPromptIds);return await ue(o,a,n?.model||void 0)}catch(e){return y(V(e)),null}finally{j.current=!1,_(!1)}},pe=()=>{let t=A.current;if(!t)return null;y(null);let n=e.fallback(t.params,t.context);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.continueWithoutAiFallback}]),n},me=()=>A.current?{history:A.current.history,activity:S}:null;return{enabled:r,setEnabled:i,hasProviders:a,selectedModel:q||K&&X?X:H,setSelectedModel:q?ae:K?e=>{J(e)?ae(e):(ae(``),d(e))}:d,modelsByProvider:z,modelsLoading:s,running:p,error:v,canContinue:b,remote:q,remoteModels:ne,alongside:K,...G?.catalogGroup?{catalogGroup:G.catalogGroup}:{},activity:S,run:de,resume:fe,sendMessage:Q,stop:P,runFallback:pe,snapshot:me,answerQuestions:le,cardAction:ce}}function _t(){let e=M();return[e.responseRulesHeading,...e.responseRules.map(e=>`- ${e}`)].join(`
17
+ `)}function vt(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
- ${gt()}
22
+ ${_t()}
23
23
 
24
24
  ${r.userRequestHeading}
25
- ${e}`}function vt(e,t){return t?{kind:`handoff`,...t}:{kind:`chat`,message:e}}function yt(e){return b().filter(t=>!t.onlyWhenAnchored||e===t.id)}function bt(e){return{buildContext(e){return{cliCatalog:L(yt(e.scopedSubagentId)),handoff:{current:null},collected:{}}},buildPrompt({userGoal:e,pageContext:t},{cliCatalog:n}){return _t(e,n,t)},buildFollowUpPrompt(e,t,{cliCatalog:n}){return`${e}\n\n${gt()}\n\n${M().toolsHeading}\n${n}`},parseResponse(e,t,n){let r=n.handoff.current;return n.handoff.current=null,vt(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=yt(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 xt(e,t){return e.deriveHistoryTitle?.(t)??e.label}function St({manifest:e,result:t,meta:n,taskId:r,initiallyApplied:i,onApplied:a,extraDestinations:o}){let s=$(),c=Ae(),f=c.scope,p=(0,l.useProxy)(),[m,h]=(0,u.useState)(null),[g,_]=(0,u.useState)(new Set(i??[])),[v,y]=(0,u.useState)(null),b=te(),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(G.id,G);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,xt(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 Ct={};function wt(e){Object.assign(Ct,e)}function Tt(e){return Ct[e]}function Et({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 Dt(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 Ot={};function kt(e){Object.assign(Ot,e)}function At(e){return Ot[e]}function jt(e,t=6e3){let n=e.filter(e=>(e.kind===`user`||e.kind===`thinking`)&&e.detail?.trim()&&!be(e)).map(e=>`${e.kind===`user`?`Person`:`Agent`}: ${e.detail.trim()}`).join(`
25
+ ${e}`}function yt(e,t){return t?{kind:`handoff`,...t}:{kind:`chat`,message:e}}function bt(e){return b().filter(t=>!t.onlyWhenAnchored||e===t.id)}function xt(e){return{buildContext(e){return{cliCatalog:L(bt(e.scopedSubagentId)),handoff:{current:null},collected:{}}},buildPrompt({userGoal:e,pageContext:t},{cliCatalog:n}){return vt(e,n,t)},buildFollowUpPrompt(e,t,{cliCatalog:n}){return`${e}\n\n${_t()}\n\n${M().toolsHeading}\n${n}`},parseResponse(e,t,n){let r=n.handoff.current;return n.handoff.current=null,yt(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=bt(t.scopedSubagentId).flatMap(t=>t.commands.map(r=>({name:`${t.id}_${r.name}`,description:`${t.label}: ${r.summary}`,inputSchema:r.inputSchema,describeInvocation:()=>(0,l.interpolate)(e.preparing,{label:t.label}),describeIntent:(0,l.interpolate)(e.collecting,{label:t.label}),async execute(e){let i=t.withCollected?t.withCollected({...e},n.collected):e;return n.handoff.current={subagentId:t.id,command:r.name,params:i},{status:`queued`,note:(0,l.interpolate)(M().handoffQueued,{label:t.label})}}})));return[...o,...s]}}}function St(e,t){return e.deriveHistoryTitle?.(t)??e.label}function Ct({manifest:e,result:t,meta:n,taskId:r,initiallyApplied:i,onApplied:a,extraDestinations:o}){let s=$(),c=Ae(),f=c.scope,p=(0,l.useProxy)(),[m,h]=(0,u.useState)(null),[g,_]=(0,u.useState)(new Set(i??[])),[v,y]=(0,u.useState)(null),b=te(),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(G.id,G);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,St(e,n))}catch(e){y(e instanceof Error?e.message:String(e))}finally{h(null)}};return(0,d.jsxs)(`div`,{className:`space-y-2`,children:[(0,d.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:s.destinationPickerTitle}),(0,d.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:S.map(e=>(0,d.jsx)(`button`,{type:`button`,disabled:m!==null,onClick:()=>void C(e.id),className:`cursor-pointer rounded-md border border-input bg-background px-2.5 py-1.5 text-xs font-medium transition-colors hover:bg-accent hover:text-accent-foreground disabled:cursor-not-allowed disabled:opacity-60`,children:m===e.id?s.destinationApplying:`${g.has(e.id)?`✓ `:``}${e.id===`json-export`?s.exportJson:e.label}`},e.id))}),v&&(0,d.jsx)(`p`,{className:`text-xs text-destructive`,children:v})]})}var wt={};function Tt(e){Object.assign(wt,e)}function Et(e){return wt[e]}function Dt({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 Ot(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 kt={};function At(e){Object.assign(kt,e)}function jt(e){return kt[e]}function Mt(e,t=6e3){let n=e.filter(e=>(e.kind===`user`||e.kind===`thinking`)&&e.detail?.trim()&&!be(e)).map(e=>`${e.kind===`user`?`Person`:`Agent`}: ${e.detail.trim()}`).join(`
26
26
 
27
- `);return n.length>t?`${n.slice(0,t*.7)}\n\n[…]\n\n${n.slice(-t*.3)}`:n}function Mt(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 Nt(e,t){try{return e.definition.executor?.catalogProviders?.(e.toParams(t))}catch{return}}function Pt(e,t,n,r,i){let a=Nt(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 Ft(e){let t=(0,l.useAIProviderRegistry)()?.registry??{},{modelsByProvider:n,selectedModel:r}=ct(),i=(0,u.useRef)({registry:t,modelsByProvider:n,selectedModel:r});i.current={registry:t,modelsByProvider:n,selectedModel:r};let a=(0,u.useRef)(new Set),o=(0,u.useCallback)(async(t,n,r)=>{if(!e)return!1;let o=pe(e,t,n),s=x(t),c=`${e}:${t}:${n}`;if(!o||!s?.autoTitle||o.name||!ye(o)||a.current.has(c))return!1;let{registry:u,modelsByProvider:d,selectedModel:f}=i.current,p=Pt(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}`,jt(o.activity)),model:m.model,history:[]}),i=r&&r.type===`text`?Mt(r.text):``;return i?xe(e,t,n,i,`model`):!1}catch{return!1}finally{a.current.delete(c)}},[e]),s=Object.keys(n).length>0;return(0,u.useEffect)(()=>{e&&s&&!It.has(e)&&(It.add(e),(async()=>{for(let t of we(e)){let n=x(t.subagentId);if(n?.autoTitle){if(n.definition.conversational&&!ye(t)){Ce(e,t.subagentId,t.entityId);continue}t.name||await o(t.subagentId,t.entityId)}}})())},[e,s,o]),o}var It=new Set,Lt=()=>({});function Rt({manifest:e,params:t,extraDestinations:n,precedingActivity:r,taskId:i,resumeSeed:a,model:o,openingMessage:s}){let c=ht(e.definition,{defaultEnabled:!0}),f=Ae(),p=f.scope,m=(0,l.useProxy)(),h=(0,u.useRef)(i??`subagent-${e.id}-${crypto.randomUUID()}`).current,[g,_]=(0,u.useState)(null),v=t=>{e.definition.conversational||_(t)},[y,b]=(0,u.useState)([]),[x,S]=(0,u.useState)(null),C=Tt(e.id),w=C?.kind===`selection`?C:null,[T,E]=(0,u.useState)(null),D=(0,u.useRef)(!1),O=(0,u.useRef)(0),k=(0,u.useRef)(null);g&&g!==k.current&&(k.current=g,O.current=(r?.length??0)+c.activity.length);let A=(0,u.useRef)(!1),j=c.remote||!c.hasProviders||c.selectedModel!==``;(0,u.useEffect)(()=>{!D.current&&j&&(D.current=!0,a?(B.current=!0,c.resume(e.toParams(t),a)):(o&&c.setSelectedModel(o),c.run(e.toParams(t),{model:o,openingMessage:s}).then(e=>{e&&v(e)})))},[j]),(0,u.useEffect)(()=>{if(!g||!p)return;let n=e.autoApplyDestinationIds??[],r=f.componentAnchors.find(t=>t.subagentId===e.id&&t.pinnedEntityId)?.pinnedEntityId,i=te();n.forEach(n=>{let a=i[n];a&&(S(null),a.apply(g,{scopeId:p.id,dataProvider:p.dataProvider,storageProvider:p.storageProvider,proxyFetch:m},{...t,pinnedEntityId:r}).then(n=>{n?.id&&f.commitEntityChat(e.id,n.id,h,p.id,t,xt(e,t))}).catch(e=>S(e instanceof Error?e.message:String(e))))})},[g,c.activity,p]),(0,u.useEffect)(()=>{g&&w&&E(w.defaultSelection(g))},[g,w]);let M=(e,t)=>{E(n=>n&&{...n,[e]:t})},N=e=>v(e),P=(0,u.useMemo)(()=>g&&w&&T?w.applySelection(g,T):g,[g,w,T]),F=(0,u.useMemo)(()=>f.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[f.componentAnchors,e.id]),I=(0,u.useMemo)(()=>Dt(F,t,h),[F,t,h]),ee=(0,u.useMemo)(()=>I?[I,...n??[]]:n,[I,n]),L=e.chatEntityId?.(t),R=Ft(p?.id),z=(0,u.useRef)(!1),B=(0,u.useRef)(!1);(0,u.useEffect)(()=>{let n=!z.current&&c.running,i=z.current&&!c.running;if(z.current=c.running,!n&&!i||!L||!p)return;if(B.current){i&&(B.current=!1);return}let a=c.snapshot();if(!a)return;let o=[...r??[],...a.activity];e.autoTitle&&e.definition.conversational&&!ye({activity:o})||(me({scopeId:p.id,subagentId:e.id,entityId:L,params:t,title:xt(e,t),history:a.history,activity:o}),i&&e.autoTitle&&R(e.id,L,c.selectedModel))},[c.running]);let V=()=>{A.current=!0,c.running&&c.stop(),f.closeTask(h)},H=(0,u.useRef)(At(e.id)??Lt).current,U=H({params:t,taskId:h,running:c.running,close:V}),W=e=>{b(t=>t.includes(e)?t:[...t,e])};return(0,u.useEffect)(()=>{A.current||f.openTask({id:h,title:xt(e,t),icon:e.icon,agent:c,onApplied:e=>v(e),precedingActivity:r,panelExtraAnchorIndex:O.current,onDismiss:V,...L?{savedToDisk:!0}:{},panelActions:U.content,composerActions:U.actions,composerCommands:U.commands,panelExtra:g?(0,d.jsxs)(d.Fragment,{children:[w&&T?(0,d.jsx)(w.Report,{result:g,selection:T,onChange:M}):C?.kind===`editable`?(0,d.jsx)(C.Report,{result:g,onResultChange:N}):(0,d.jsx)(Et,{result:P}),x&&(0,d.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Salvataggio automatico non riuscito: `,x]}),(0,d.jsx)(St,{manifest:e,result:P,meta:t,taskId:h,initiallyApplied:y,onApplied:W,extraDestinations:ee})]}):void 0})},[c.activity,c.running,c.error,c.canContinue,c.selectedModel,c.modelsByProvider,c.hasProviders,c.remoteModels,f.openTask,f.componentAnchors,h,e,t,g,P,T,y,n,r,x,U.content,U.actions,U.commands]),(0,u.useEffect)(()=>()=>{f.closeTask(h)},[f.closeTask,h]),null}function zt({userGoal:e}){let t=$(),n=ht((0,u.useMemo)(()=>bt({unavailable:t.orchestratorUnavailable,continueWithoutAi:t.orchestratorContinueWithoutAi,preparing:t.orchestratorPreparing,collecting:t.orchestratorCollecting}),[]),{defaultEnabled:!0}),r=Ae(),[i,a]=(0,u.useState)(null),o=(0,u.useRef)(!1),s=!n.hasProviders||n.selectedModel!==``,c=(0,u.useRef)(r.pendingExtraDestinations),l=(0,u.useRef)(r.pendingAttachments),f=(0,u.useRef)(r.pendingModel),p=(0,u.useRef)(r.pendingScopedSubagentId??r.scopedSubagentId??void 0),m=(0,u.useRef)(r.pendingCarryOver),h=(0,u.useRef)(!1),g=e=>{e&&typeof e==`object`&&e.kind===`handoff`&&(a(e),r.closeTask(De))};(0,u.useEffect)(()=>{!o.current&&s&&(o.current=!0,f.current&&n.setSelectedModel(f.current),n.run({userGoal:e,pageContext:r.pageContext,scopedSubagentId:p.current??null},{attachments:l.current,model:f.current,openingMessage:e}).then(e=>{e&&g(e)}))},[s]),(0,u.useEffect)(()=>{h.current||r.openTask({id:De,title:`Agentico`,icon:`bot`,agent:n,onApplied:g,scopedSubagentId:p.current,precedingActivity:m.current?.activity,onDismiss:()=>{h.current=!0,n.running&&n.stop(),r.closeTask(De)}})},[n.activity,n.running,n.error,n.canContinue,n.selectedModel,n.modelsByProvider,n.hasProviders,r.openTask]),(0,u.useEffect)(()=>()=>{r.closeTask(De)},[r.closeTask]);let _=(0,u.useMemo)(()=>[...m.current?.activity??[],...n.activity],[n.activity]);if(!i)return null;let v=x(i.subagentId);return v?(0,d.jsx)(Rt,{manifest:v,params:i.params,extraDestinations:c.current,model:f.current||void 0,taskId:m.current?.taskId,precedingActivity:_}):null}function Bt({manifest:e,extraDestinations:t}){let n=ht(e.definition,{defaultEnabled:!1}),r=$(),i=Ae(),a=(0,u.useRef)(`manual-${e.id}-${crypto.randomUUID()}`).current,[o,s]=(0,u.useState)(null),[c,f]=(0,u.useState)([]),p=Tt(e.id),m=p?.kind===`selection`?p:null,[h,g]=(0,u.useState)(null),[_,v]=(0,u.useState)(null),y=(0,u.useRef)(!1),b=t=>{if(!e.manualEntry)return;let r;try{r=e.manualEntry.fromRawText(t)}catch(e){console.error(`[ManualEntryRunner] manualEntry.fromRawText ha rifiutato il testo:`,e);return}v(r),f([]),n.run(r,{openingMessage:t}).then(e=>{e&&s(e)})};(0,u.useEffect)(()=>{o&&m&&g(m.defaultSelection(o))},[o,m]);let x=(e,t)=>{g(n=>n&&{...n,[e]:t})},S=e=>s(e),C=(0,u.useMemo)(()=>o&&m&&h?m.applySelection(o,h):o,[o,m,h]),w=e=>{f(t=>t.includes(e)?t:[...t,e])},T=(0,u.useMemo)(()=>i.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[i.componentAnchors,e.id]),E=(0,u.useMemo)(()=>_?Dt(T,_,a):null,[T,_,a]),D=(0,u.useMemo)(()=>E?[E,...t??[]]:t,[E,t]);return(0,u.useEffect)(()=>{y.current||i.openTask({id:a,title:e.label,icon:e.icon,agent:n,onApplied:e=>s(e),manualEntry:e.manualEntry?{prompt:e.manualEntry.prompt,onSubmit:b}:void 0,onDismiss:()=>{y.current=!0,n.running&&n.stop(),i.closeTask(a)},panelExtra:o?(0,d.jsxs)(`div`,{className:`space-y-2`,children:[m&&h?(0,d.jsx)(m.Report,{result:o,selection:h,onChange:x}):p?.kind===`editable`?(0,d.jsx)(p.Report,{result:o,onResultChange:S}):(0,d.jsx)(Et,{result:C}),(0,d.jsx)(St,{manifest:e,result:C,meta:_??{},taskId:a,initiallyApplied:c,onApplied:w,extraDestinations:D}),n.hasProviders&&(0,d.jsx)(l.ActionButton,{label:r.resumeWithAi,variant:`outline-secondary`,className:`text-xs`,onClick:()=>{_&&i.resumeWithAI(e.id,_,t)}})]}):void 0})},[n.activity,n.running,n.error,n.hasProviders,i.componentAnchors,o,C,h,c,_]),(0,u.useEffect)(()=>()=>{i.closeTask(a)},[]),null}function Vt(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 Ht({task:e}){let t=$(),[n,r]=(0,u.useState)(``),{agent:i,onApplied:a,manualEntry:o}=e,s=i.running,c=e=>{if(r(``),o){o.onSubmit(e.text);return}i.sendMessage(e.text,{attachments:e.files,model:e.model}).then(e=>{e&&a(e)})},f=!!o||i.remote&&i.remoteModels.length===0,p=i.alongside&&i.remoteModels.some(e=>e.value===i.selectedModel),m=!f&&!i.remote&&!p&&i.hasProviders&&!i.selectedModel,h=f?[]:i.remote?i.remoteModels:i.alongside?[...i.remoteModels,...Vt(i.modelsByProvider,i.catalogGroup)]:Vt(i.modelsByProvider);return(0,d.jsx)(l.Chatbot,{value:n,onChange:r,placeholder:o?.prompt??t.messagePlaceholder,running:s,onStop:i.stop,disabled:!n.trim()||m,onSubmit:c,attachments:!o&&!i.remote&&!p,models:h,selectedModel:f?``:i.selectedModel,actions:e.composerActions,commands:e.composerCommands,onModelChange:i.setSelectedModel,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function Ut(){let{startOrchestrator:e}=Ae(),t=$(),[n,r]=(0,u.useState)(``),{hasProviders:i,modelsByProvider:a,selectedModel:o,setSelectedModel:s}=ct(),c=t=>{t.text.trim()&&(e(t.text.trim(),{attachments:t.files.length>0?t.files:void 0,model:t.model||void 0}),r(``))},f=i&&!o;return(0,d.jsx)(l.Chatbot,{value:n,onChange:r,placeholder:t.orchestratorStarterPlaceholder,disabled:!n.trim()||f,onSubmit:c,attachments:!0,models:Vt(a),selectedModel:o,onModelChange:s,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function Wt({chat:e,onClose:t}){let n=$(),r=(0,l.useFormController)();return(0,d.jsx)(l.Modal,{title:n.renameChat,size:`sm`,onClose:t,onSave:()=>(xe(e.scopeId,e.subagentId,e.entityId,String(r.record?.title??ve(e)),`person`),t(),Promise.resolve(!0)),children:(0,d.jsxs)(l.Form,{appearance:`empty`,controller:r,defaultValues:{title:ve(e)},footer:!1,children:[(0,d.jsx)(l.Input,{name:`title`,label:n.chatTitleLabel,placeholder:e.title}),(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:n.chatTitleHint})]})})}function Gt(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 Kt({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 qt({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 Jt({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)(()=>de(()=>h(e=>e+1)),[]);let g=(0,u.useMemo)(()=>n?we(e):[],[e,n,m]),[_,v]=(0,u.useState)(null),y=async n=>{let r=x(n.subagentId),i=await r?.confirmArchive?.(n.entityId,n.params);if(!i||window.confirm(i)){try{await r?.onArchive?.(n.entityId,n.params)}catch{return}Ce(e,n.subagentId,n.entityId),t===Te(n.subagentId,n.entityId)&&o(),h(e=>e+1)}},b=(0,u.useMemo)(()=>{let e=f.trim().toLowerCase();return e?g.filter(t=>{let n=x(t.subagentId)?.label??t.subagentId;return ve(t).toLowerCase().includes(e)||n.toLowerCase().includes(e)}):g},[g,f]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(l.Dropdown,{trigger:{icon:`history`,title:s.chatHistory},triggerClassName:`!h-9 !w-9 !p-0 rounded-md bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground`,open:n,onOpenChange:r,position:`end`,strategy:`absolute`,menuClassName:`w-[380px] max-h-[70vh] overflow-y-auto`,header:(0,d.jsxs)(`div`,{className:`flex items-center gap-2 px-1 pb-1.5`,children:[(0,d.jsx)(l.Icon,{name:`search`,size:14,className:`shrink-0 text-muted-foreground`}),(0,d.jsx)(`input`,{autoFocus:!0,value:f,onChange:e=>p(e.target.value),placeholder:s.searchChats,className:`min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),(0,d.jsx)(l.ActionButton,{icon:`square-pen`,ariaLabel:s.newChat,title:s.newChat,variant:`link`,className:`shrink-0`,onClick:a})]}),children:b.length===0?(0,d.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground`,children:g.length===0?s.noSavedChats:s.noResults}):b.map(e=>{let n=x(e.subagentId),a=t===Te(e.subagentId,e.entityId);return(0,d.jsx)(l.DropdownItem,{icon:a?`check`:n?.icon??`bot`,className:a?`bg-accent font-semibold text-primary`:void 0,actions:[{icon:`pencil`,label:s.renameChat,onClick:()=>{r(!1),v(e)}},{icon:`archive`,label:s.archiveChat,onClick:()=>void y(e)}],onClick:()=>i(e.subagentId,e.entityId,e),children:(0,d.jsxs)(`span`,{className:`flex min-w-0 flex-1 items-center justify-between gap-2`,children:[(0,d.jsx)(`span`,{className:`min-w-0 truncate`,title:`${n?.label??e.subagentId} · ${ve(e)}`,children:ve(e)}),(0,d.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,title:`${s.chatStarted.replace(`{at}`,new Date(Se(e)).toLocaleString(c))} · ${s.chatLastMessage.replace(`{at}`,new Date(e.savedAt).toLocaleString(c))}`,children:Gt(Se(e),c)})]})},`${e.subagentId}:${e.entityId}`)})}),_&&(0,d.jsx)(Wt,{chat:_,onClose:()=>v(null)})]})}function Yt({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}={}){let{task:i,isOpen:a,pendingGoal:o,orchestratorRunId:s,pageContext:c,pageContextCard:f,anchoredUserMessages:p,pendingResume:m,resumeRunId:h,dismissForeignTask:g,resumeEntityChat:_,pendingManualEntry:v,manualEntryRunId:y,startManualEntry:b,pendingExtraDestinations:S,pendingResumeWithAI:C,resumeWithAIRunId:w,pendingStart:T,startRunId:E,scope:D}=Ae(),O=$(),k=(0,u.useRef)(null),[A,j]=(0,u.useState)(!1);Ft(D?.id);let M=nt({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}),N=()=>{(!i||i.agent.running||i.savedToDisk||window.confirm(O.unsavedConversationConfirm))&&(g(),j(!1))},P=i?[...i.precedingActivity??[],...i.agent.activity]:[],F=P.length,I=Math.max(0,Math.min(i?.panelExtraAnchorIndex??F,F)),ee=P.slice(0,I),L=P.slice(I),R=!!(i&&!i.agent.running&&i.agent.error),z=new Set(i?.agent.activity.map(e=>e.id)??[]),B=i?{canAnswer:e=>z.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,V=B?He(P,B.canAnswer):null,H=i?.id===`agentico-orchestrator`&&i.scopedSubagentId?x(i.scopedSubagentId):void 0,U=H?.manualEntry?H:null,W=(0,u.useRef)(!0);(0,u.useEffect)(()=>{let e=k.current;if(!e)return;let t=()=>{W.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&&(W.current=!0,e.scrollTop=e.scrollHeight)},[i?.id]);let G=P.at(-1)?.detail?.length??0;(0,u.useEffect)(()=>{let e=k.current;e&&W.current&&(e.scrollTop=e.scrollHeight)},[F,R,G]);let K=(0,u.useRef)(null);(0,u.useEffect)(()=>{let e=k.current,t=K.current;if(!e||!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>{W.current&&(e.scrollTop=e.scrollHeight)});return n.observe(t),()=>n.disconnect()},[i?.id,a]);let q=o?(0,d.jsx)(zt,{userGoal:o},s):null,te=m?x(m.subagentId):void 0,J=m&&te?(0,d.jsx)(Rt,{manifest:te,params:m.snapshot.params,taskId:Te(m.subagentId,m.entityId),resumeSeed:{history:m.snapshot.history,activity:m.snapshot.activity}},h):null,Y=v?x(v.subagentId):void 0,ne=v&&Y?(0,d.jsx)(Bt,{manifest:Y,extraDestinations:v.extraDestinations},y):null,re=C?x(C.subagentId):void 0,X=C&&re?(0,d.jsx)(Rt,{manifest:re,params:C.params,extraDestinations:C.extraDestinations},w):null,ie=T?x(T.subagentId):void 0,Z=T&&ie?(0,d.jsx)(Rt,{manifest:ie,params:T.params,taskId:T.taskId,openingMessage:T.openingMessage},E):null;return a?(0,d.jsxs)(d.Fragment,{children:[q,J,ne,X,Z,(0,d.jsxs)(`div`,{style:{width:M.width},className:`relative flex h-full shrink-0 flex-col border-l border-border bg-background`,children:[(0,d.jsx)(rt,{width:M.width,min:M.min,max:M.max,onResize:M.set,onCommit:M.commit,onReset:M.reset}),(0,d.jsxs)(`div`,{className:`flex min-h-[60px] items-center gap-1 border-b border-border/60 px-4 py-3`,children:[(0,d.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-lg font-semibold leading-tight`,children:i?i.title:`Agentico`}),D&&(0,d.jsx)(Jt,{scopeId:D.id,currentTaskId:i?.id??null,open:A,onOpenChange:j,onNewChat:N,onSelect:(e,t,n)=>_(e,t,n),onArchivedCurrent:g}),(0,d.jsx)(it,{})]}),(0,d.jsx)(`div`,{ref:k,className:`flex-1 overflow-y-auto px-3 pb-2 ${V?`min-h-24`:`min-h-0`}`,children:(0,d.jsx)(`div`,{ref:K,className:`pt-2`,children:i?(0,d.jsxs)(d.Fragment,{children:[i.manualEntry&&P.length===0&&(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i.manualEntry.prompt}),(0,d.jsx)(Ke,{activity:ee,questions:B,docked:V,pinUserMessages:!V}),i.panelExtra&&(0,d.jsx)(`div`,{className:`mt-3`,children:i.panelExtra}),L.length>0&&(0,d.jsx)(Ke,{activity:L,questions:B,docked:V,pinUserMessages:!V}),!i.agent.running&&i.agent.error&&(0,d.jsxs)(`div`,{className:`mt-2 flex items-center gap-2`,children:[(0,d.jsx)(`p`,{className:`flex-1 text-xs text-destructive`,children:i.agent.error}),(0,d.jsx)(l.ActionButton,{label:O.retry,variant:`secondary`,className:`shrink-0`,onClick:()=>{i.agent.sendMessage(O.retryMessage,{retry:!0}).then(e=>{e&&i.onApplied(e)})}}),!i.agent.remote&&(0,d.jsx)(l.ActionButton,{label:O.continueWithoutAi,variant:`secondary`,className:`shrink-0`,onClick:()=>{if(U){b(U.id,S);return}let e=i.agent.runFallback();e&&i.onApplied(e)}})]})]}):p.length>0?(0,d.jsx)(qt,{messages:p}):f?(0,d.jsx)(Kt,{card:f}):(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c??O.orchestratorStarterHint})})}),i&&V?(0,d.jsxs)(`section`,{"aria-label":O.pendingQuestions,className:`flex min-h-0 shrink flex-col border-t border-border/60`,children:[i.panelActions&&(0,d.jsx)(`div`,{className:`shrink-0 px-4 pt-3`,children:i.panelActions}),(0,d.jsx)(`div`,{className:`min-h-0 overflow-y-auto px-4 py-3`,children:(0,d.jsx)(Ue,{entry:V.entry,part:V.part,questions:B,autoFocus:!0},`${V.entry.id}:${V.part.id}`)}),i.agent.running&&(0,d.jsx)(`div`,{className:`flex shrink-0 justify-end px-4 pb-3`,children:(0,d.jsx)(l.ActionButton,{icon:`square`,label:O.stop,variant:`secondary`,onClick:i.agent.stop})})]}):(0,d.jsxs)(`div`,{className:`border-t border-border/60 px-4 py-3`,children:[i?.panelActions&&(0,d.jsx)(`div`,{className:`mb-2`,children:i.panelActions}),i?(0,d.jsx)(Ht,{task:i},i.id):(0,d.jsx)(Ut,{})]})]})]}):(0,d.jsxs)(d.Fragment,{children:[q,J,ne,X,Z]})}function Xt(e,t){let{setPageContext:n}=Ae(),r=(0,u.useRef)(crypto.randomUUID()).current;(0,u.useEffect)(()=>(n(r,e,t??null),()=>n(r,null)),[e,t])}function Zt(e,t,n,r,i=!0,a){let{registerComponentAnchor:o}=Ae(),s=(0,u.useRef)(crypto.randomUUID()).current,c=(0,u.useRef)(n);c.current=n,(0,u.useEffect)(()=>{if(i)return o(s,{subagentId:e,componentKey:t,contextInfo:r,pinnedEntityId:a,onResult:(e,t,n)=>c.current?.(e,t,n)}),()=>o(s,null)},[e,t,r,i,a])}exports.AGENTICO_MAX_WIDTH=Ye,exports.AGENTICO_MIN_WIDTH=Je,exports.AGENTICO_WIDTH=qe,exports.AGENTICO_WIDTH_STORAGE_KEY=Xe,exports.Agentico=Yt,exports.AgenticoProvider=ke,exports.AgenticoToggle=it,exports.DEFAULT_REASONING_PART_ID=p,exports.DEFAULT_TEXT_PART_ID=f,exports.JSON_EXPORT_DESTINATION_ID=W,exports.MICRO_PROMPT_REGISTRY=z,exports.ORCHESTRATOR_TASK_ID=De,exports.SUMMARY_MICRO_PROMPT=R,exports.agenticoDe=ne,exports.agenticoEn=J,exports.agenticoIt=Y,exports.agenticoPromptsEn=O,exports.agenticoPromptsIt=k,exports.agenticoTranslations=Ee,exports.applyMicroPrompts=B,exports.chatHasPersonMessage=ye,exports.chatStartedAt=Se,exports.chatTitle=ve,exports.configureAgenticoPrompts=j,exports.configureEntityChatStore=ie,exports.createCrossAgentTools=w,exports.defineSubagent=_,exports.entityChatTaskId=Te,exports.extractErrorMessage=V,exports.extractJsonBlock=H,exports.findSubagentManifest=x,exports.formatQuestionAnswers=g,exports.getAgenticoPrompts=M,exports.getDestinationRegistry=te,exports.getEntityChat=pe,exports.getSubagentControls=At,exports.getSubagentRegistry=b,exports.getSubagentReport=Tt,exports.hasEntityChatBackend=Z,exports.jsonExportDestination=G,exports.listEntityChats=we,exports.messagePartsText=h,exports.onEntityChatsChange=de,exports.registerCrossAgentTools=C,exports.registerDestinations=q,exports.registerSubagentControls=kt,exports.registerSubagentReports=wt,exports.registerSubagents=y,exports.removeEntityChat=Ce,exports.renameEntityChat=xe,exports.renderRegistryCli=L,exports.renderSubagentCli=ee,exports.resetAgenticoPrompts=N,exports.saveEntityChat=me,exports.syncEntityChats=se,exports.toJsonSchema=T,exports.toMcpTool=E,exports.upsertMessagePart=m,exports.useAgent=ht,exports.useAgentico=Ae,exports.useAgenticoI18n=$,exports.useAgenticoPageContext=Xt,exports.useSubagentComponentContext=Zt;
27
+ `);return n.length>t?`${n.slice(0,t*.7)}\n\n[…]\n\n${n.slice(-t*.3)}`:n}function Nt(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 Pt(e,t){try{return e.definition.executor?.catalogProviders?.(e.toParams(t))}catch{return}}function Ft(e,t,n,r,i){let a=Pt(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 It(e){let t=(0,l.useAIProviderRegistry)()?.registry??{},{modelsByProvider:n,selectedModel:r}=lt(),i=(0,u.useRef)({registry:t,modelsByProvider:n,selectedModel:r});i.current={registry:t,modelsByProvider:n,selectedModel:r};let a=(0,u.useRef)(new Set),o=(0,u.useCallback)(async(t,n,r)=>{if(!e)return!1;let o=pe(e,t,n),s=x(t),c=`${e}:${t}:${n}`;if(!o||!s?.autoTitle||o.name||!ye(o)||a.current.has(c))return!1;let{registry:u,modelsByProvider:d,selectedModel:f}=i.current,p=Ft(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}`,Mt(o.activity)),model:m.model,history:[]}),i=r&&r.type===`text`?Nt(r.text):``;return i?xe(e,t,n,i,`model`):!1}catch{return!1}finally{a.current.delete(c)}},[e]),s=Object.keys(n).length>0;return(0,u.useEffect)(()=>{e&&s&&!Lt.has(e)&&(Lt.add(e),(async()=>{for(let t of we(e)){let n=x(t.subagentId);if(n?.autoTitle){if(n.definition.conversational&&!ye(t)){Ce(e,t.subagentId,t.entityId);continue}t.name||await o(t.subagentId,t.entityId)}}})())},[e,s,o]),o}var Lt=new Set,Rt=()=>({});function zt({manifest:e,params:t,extraDestinations:n,precedingActivity:r,taskId:i,resumeSeed:a,model:o,openingMessage:s}){let c=gt(e.definition,{defaultEnabled:!0}),f=Ae(),p=f.scope,m=(0,l.useProxy)(),h=(0,u.useRef)(i??`subagent-${e.id}-${crypto.randomUUID()}`).current,[g,_]=(0,u.useState)(null),v=t=>{e.definition.conversational||_(t)},[y,b]=(0,u.useState)([]),[x,S]=(0,u.useState)(null),C=Et(e.id),w=C?.kind===`selection`?C:null,[T,E]=(0,u.useState)(null),D=(0,u.useRef)(!1),O=(0,u.useRef)(0),k=(0,u.useRef)(null);g&&g!==k.current&&(k.current=g,O.current=(r?.length??0)+c.activity.length);let A=(0,u.useRef)(!1),j=c.remote||!c.hasProviders||c.selectedModel!==``;(0,u.useEffect)(()=>{!D.current&&j&&(D.current=!0,a?(B.current=!0,c.resume(e.toParams(t),a)):(o&&c.setSelectedModel(o),c.run(e.toParams(t),{model:o,openingMessage:s}).then(e=>{e&&v(e)})))},[j]),(0,u.useEffect)(()=>{if(!g||!p)return;let n=e.autoApplyDestinationIds??[],r=f.componentAnchors.find(t=>t.subagentId===e.id&&t.pinnedEntityId)?.pinnedEntityId,i=te();n.forEach(n=>{let a=i[n];a&&(S(null),a.apply(g,{scopeId:p.id,dataProvider:p.dataProvider,storageProvider:p.storageProvider,proxyFetch:m},{...t,pinnedEntityId:r}).then(n=>{n?.id&&f.commitEntityChat(e.id,n.id,h,p.id,t,St(e,t))}).catch(e=>S(e instanceof Error?e.message:String(e))))})},[g,c.activity,p]),(0,u.useEffect)(()=>{g&&w&&E(w.defaultSelection(g))},[g,w]);let M=(e,t)=>{E(n=>n&&{...n,[e]:t})},N=e=>v(e),P=(0,u.useMemo)(()=>g&&w&&T?w.applySelection(g,T):g,[g,w,T]),F=(0,u.useMemo)(()=>f.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[f.componentAnchors,e.id]),I=(0,u.useMemo)(()=>Ot(F,t,h),[F,t,h]),ee=(0,u.useMemo)(()=>I?[I,...n??[]]:n,[I,n]),L=e.chatEntityId?.(t),R=It(p?.id),z=(0,u.useRef)(!1),B=(0,u.useRef)(!1);(0,u.useEffect)(()=>{let n=!z.current&&c.running,i=z.current&&!c.running;if(z.current=c.running,!n&&!i||!L||!p)return;if(B.current){i&&(B.current=!1);return}let a=c.snapshot();if(!a)return;let o=[...r??[],...a.activity];e.autoTitle&&e.definition.conversational&&!ye({activity:o})||(me({scopeId:p.id,subagentId:e.id,entityId:L,params:t,title:St(e,t),history:a.history,activity:o}),i&&e.autoTitle&&R(e.id,L,c.selectedModel))},[c.running]);let V=()=>{A.current=!0,c.running&&c.stop(),f.closeTask(h)},H=(0,u.useRef)(jt(e.id)??Rt).current,U=H({params:t,taskId:h,running:c.running,close:V}),W=e=>{b(t=>t.includes(e)?t:[...t,e])};return(0,u.useEffect)(()=>{A.current||f.openTask({id:h,title:St(e,t),icon:e.icon,agent:c,onApplied:e=>v(e),precedingActivity:r,panelExtraAnchorIndex:O.current,onDismiss:V,...L?{savedToDisk:!0}:{},panelActions:U.content,composerActions:U.actions,composerCommands:U.commands,panelExtra:g?(0,d.jsxs)(d.Fragment,{children:[w&&T?(0,d.jsx)(w.Report,{result:g,selection:T,onChange:M}):C?.kind===`editable`?(0,d.jsx)(C.Report,{result:g,onResultChange:N}):(0,d.jsx)(Dt,{result:P}),x&&(0,d.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Salvataggio automatico non riuscito: `,x]}),(0,d.jsx)(Ct,{manifest:e,result:P,meta:t,taskId:h,initiallyApplied:y,onApplied:W,extraDestinations:ee})]}):void 0})},[c.activity,c.running,c.error,c.canContinue,c.selectedModel,c.modelsByProvider,c.hasProviders,c.remoteModels,f.openTask,f.componentAnchors,h,e,t,g,P,T,y,n,r,x,U.content,U.actions,U.commands]),(0,u.useEffect)(()=>()=>{f.closeTask(h)},[f.closeTask,h]),null}function Bt({userGoal:e}){let t=$(),n=gt((0,u.useMemo)(()=>xt({unavailable:t.orchestratorUnavailable,continueWithoutAi:t.orchestratorContinueWithoutAi,preparing:t.orchestratorPreparing,collecting:t.orchestratorCollecting}),[]),{defaultEnabled:!0}),r=Ae(),[i,a]=(0,u.useState)(null),o=(0,u.useRef)(!1),s=!n.hasProviders||n.selectedModel!==``,c=(0,u.useRef)(r.pendingExtraDestinations),l=(0,u.useRef)(r.pendingAttachments),f=(0,u.useRef)(r.pendingModel),p=(0,u.useRef)(r.pendingScopedSubagentId??r.scopedSubagentId??void 0),m=(0,u.useRef)(r.pendingCarryOver),h=(0,u.useRef)(!1),g=e=>{e&&typeof e==`object`&&e.kind===`handoff`&&(a(e),r.closeTask(De))};(0,u.useEffect)(()=>{!o.current&&s&&(o.current=!0,f.current&&n.setSelectedModel(f.current),n.run({userGoal:e,pageContext:r.pageContext,scopedSubagentId:p.current??null},{attachments:l.current,model:f.current,openingMessage:e}).then(e=>{e&&g(e)}))},[s]),(0,u.useEffect)(()=>{h.current||r.openTask({id:De,title:`Agentico`,icon:`bot`,agent:n,onApplied:g,scopedSubagentId:p.current,precedingActivity:m.current?.activity,onDismiss:()=>{h.current=!0,n.running&&n.stop(),r.closeTask(De)}})},[n.activity,n.running,n.error,n.canContinue,n.selectedModel,n.modelsByProvider,n.hasProviders,r.openTask]),(0,u.useEffect)(()=>()=>{r.closeTask(De)},[r.closeTask]);let _=(0,u.useMemo)(()=>[...m.current?.activity??[],...n.activity],[n.activity]);if(!i)return null;let v=x(i.subagentId);return v?(0,d.jsx)(zt,{manifest:v,params:i.params,extraDestinations:c.current,model:f.current||void 0,taskId:m.current?.taskId,precedingActivity:_}):null}function Vt({manifest:e,extraDestinations:t}){let n=gt(e.definition,{defaultEnabled:!1}),r=$(),i=Ae(),a=(0,u.useRef)(`manual-${e.id}-${crypto.randomUUID()}`).current,[o,s]=(0,u.useState)(null),[c,f]=(0,u.useState)([]),p=Et(e.id),m=p?.kind===`selection`?p:null,[h,g]=(0,u.useState)(null),[_,v]=(0,u.useState)(null),y=(0,u.useRef)(!1),b=t=>{if(!e.manualEntry)return;let r;try{r=e.manualEntry.fromRawText(t)}catch(e){console.error(`[ManualEntryRunner] manualEntry.fromRawText ha rifiutato il testo:`,e);return}v(r),f([]),n.run(r,{openingMessage:t}).then(e=>{e&&s(e)})};(0,u.useEffect)(()=>{o&&m&&g(m.defaultSelection(o))},[o,m]);let x=(e,t)=>{g(n=>n&&{...n,[e]:t})},S=e=>s(e),C=(0,u.useMemo)(()=>o&&m&&h?m.applySelection(o,h):o,[o,m,h]),w=e=>{f(t=>t.includes(e)?t:[...t,e])},T=(0,u.useMemo)(()=>i.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[i.componentAnchors,e.id]),E=(0,u.useMemo)(()=>_?Ot(T,_,a):null,[T,_,a]),D=(0,u.useMemo)(()=>E?[E,...t??[]]:t,[E,t]);return(0,u.useEffect)(()=>{y.current||i.openTask({id:a,title:e.label,icon:e.icon,agent:n,onApplied:e=>s(e),manualEntry:e.manualEntry?{prompt:e.manualEntry.prompt,onSubmit:b}:void 0,onDismiss:()=>{y.current=!0,n.running&&n.stop(),i.closeTask(a)},panelExtra:o?(0,d.jsxs)(`div`,{className:`space-y-2`,children:[m&&h?(0,d.jsx)(m.Report,{result:o,selection:h,onChange:x}):p?.kind===`editable`?(0,d.jsx)(p.Report,{result:o,onResultChange:S}):(0,d.jsx)(Dt,{result:C}),(0,d.jsx)(Ct,{manifest:e,result:C,meta:_??{},taskId:a,initiallyApplied:c,onApplied:w,extraDestinations:D}),n.hasProviders&&(0,d.jsx)(l.ActionButton,{label:r.resumeWithAi,variant:`outline-secondary`,className:`text-xs`,onClick:()=>{_&&i.resumeWithAI(e.id,_,t)}})]}):void 0})},[n.activity,n.running,n.error,n.hasProviders,i.componentAnchors,o,C,h,c,_]),(0,u.useEffect)(()=>()=>{i.closeTask(a)},[]),null}function Ht(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 Ut({task:e}){let t=$(),[n,r]=(0,u.useState)(``),{agent:i,onApplied:a,manualEntry:o}=e,s=i.running,c=e=>{if(r(``),o){o.onSubmit(e.text);return}i.sendMessage(e.text,{attachments:e.files,model:e.model}).then(e=>{e&&a(e)})},f=!!o||i.remote&&i.remoteModels.length===0,p=i.alongside&&i.remoteModels.some(e=>e.value===i.selectedModel),m=!f&&!i.remote&&!p&&i.hasProviders&&!i.selectedModel,h=f?[]:i.remote?i.remoteModels:i.alongside?[...i.remoteModels,...Ht(i.modelsByProvider,i.catalogGroup)]:Ht(i.modelsByProvider);return(0,d.jsx)(l.Chatbot,{value:n,onChange:r,placeholder:o?.prompt??t.messagePlaceholder,running:s,onStop:i.stop,disabled:!n.trim()||m,onSubmit:c,attachments:!o&&!i.remote&&!p,models:h,selectedModel:f?``:i.selectedModel,actions:e.composerActions,commands:e.composerCommands,onModelChange:i.setSelectedModel,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function Wt(){let{startOrchestrator:e}=Ae(),t=$(),[n,r]=(0,u.useState)(``),{hasProviders:i,modelsByProvider:a,selectedModel:o,setSelectedModel:s}=lt(),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:Ht(a),selectedModel:o,onModelChange:s,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function Gt({chat:e,onClose:t}){let n=$(),r=(0,l.useFormController)();return(0,d.jsx)(l.Modal,{title:n.renameChat,size:`sm`,onClose:t,onSave:()=>(xe(e.scopeId,e.subagentId,e.entityId,String(r.record?.title??ve(e)),`person`),t(),Promise.resolve(!0)),children:(0,d.jsxs)(l.Form,{appearance:`empty`,controller:r,defaultValues:{title:ve(e)},footer:!1,children:[(0,d.jsx)(l.Input,{name:`title`,label:n.chatTitleLabel,placeholder:e.title}),(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:n.chatTitleHint})]})})}function Kt(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 qt({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 Jt({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 Yt({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)(()=>de(()=>h(e=>e+1)),[]);let g=(0,u.useMemo)(()=>n?we(e):[],[e,n,m]),[_,v]=(0,u.useState)(null),y=async n=>{let r=x(n.subagentId),i=await r?.confirmArchive?.(n.entityId,n.params);if(!i||window.confirm(i)){try{await r?.onArchive?.(n.entityId,n.params)}catch{return}Ce(e,n.subagentId,n.entityId),t===Te(n.subagentId,n.entityId)&&o(),h(e=>e+1)}},b=(0,u.useMemo)(()=>{let e=f.trim().toLowerCase();return e?g.filter(t=>{let n=x(t.subagentId)?.label??t.subagentId;return ve(t).toLowerCase().includes(e)||n.toLowerCase().includes(e)}):g},[g,f]);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(l.Dropdown,{trigger:{icon:`history`,title:s.chatHistory},triggerClassName:`!h-9 !w-9 !p-0 rounded-md bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground`,open:n,onOpenChange:r,position:`end`,strategy:`absolute`,menuClassName:`w-[380px] max-h-[70vh] overflow-y-auto`,header:(0,d.jsxs)(`div`,{className:`flex items-center gap-2 px-1 pb-1.5`,children:[(0,d.jsx)(l.Icon,{name:`search`,size:14,className:`shrink-0 text-muted-foreground`}),(0,d.jsx)(`input`,{autoFocus:!0,value:f,onChange:e=>p(e.target.value),placeholder:s.searchChats,className:`min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),(0,d.jsx)(l.ActionButton,{icon:`square-pen`,ariaLabel:s.newChat,title:s.newChat,variant:`link`,className:`shrink-0`,onClick:a})]}),children:b.length===0?(0,d.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground`,children:g.length===0?s.noSavedChats:s.noResults}):b.map(e=>{let n=x(e.subagentId),a=t===Te(e.subagentId,e.entityId);return(0,d.jsx)(l.DropdownItem,{icon:a?`check`:n?.icon??`bot`,className:a?`bg-accent font-semibold text-primary`:void 0,actions:[{icon:`pencil`,label:s.renameChat,onClick:()=>{r(!1),v(e)}},{icon:`archive`,label:s.archiveChat,onClick:()=>void y(e)}],onClick:()=>i(e.subagentId,e.entityId,e),children:(0,d.jsxs)(`span`,{className:`flex min-w-0 flex-1 items-center justify-between gap-2`,children:[(0,d.jsx)(`span`,{className:`min-w-0 truncate`,title:`${n?.label??e.subagentId} · ${ve(e)}`,children:ve(e)}),(0,d.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,title:`${s.chatStarted.replace(`{at}`,new Date(Se(e)).toLocaleString(c))} · ${s.chatLastMessage.replace(`{at}`,new Date(e.savedAt).toLocaleString(c))}`,children:Kt(Se(e),c)})]})},`${e.subagentId}:${e.entityId}`)})}),_&&(0,d.jsx)(Gt,{chat:_,onClose:()=>v(null)})]})}function Xt({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}={}){let{task:i,isOpen:a,pendingGoal:o,orchestratorRunId:s,pageContext:c,pageContextCard:f,anchoredUserMessages:p,pendingResume:m,resumeRunId:h,dismissForeignTask:g,resumeEntityChat:_,pendingManualEntry:v,manualEntryRunId:y,startManualEntry:b,pendingExtraDestinations:S,pendingResumeWithAI:C,resumeWithAIRunId:w,pendingStart:T,startRunId:E,scope:D}=Ae(),O=$(),k=(0,u.useRef)(null),[A,j]=(0,u.useState)(!1);It(D?.id);let M=rt({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}),N=()=>{(!i||i.agent.running||i.savedToDisk||window.confirm(O.unsavedConversationConfirm))&&(g(),j(!1))},P=i?[...i.precedingActivity??[],...i.agent.activity]:[],F=P.length,I=Math.max(0,Math.min(i?.panelExtraAnchorIndex??F,F)),ee=P.slice(0,I),L=P.slice(I),R=!!(i&&!i.agent.running&&i.agent.error),z=new Set(i?.agent.activity.map(e=>e.id)??[]),B=i?{canAnswer:e=>z.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,V=B?Ue(P,B.canAnswer):null,H=i?.id===`agentico-orchestrator`&&i.scopedSubagentId?x(i.scopedSubagentId):void 0,U=H?.manualEntry?H:null,W=(0,u.useRef)(!0);(0,u.useEffect)(()=>{let e=k.current;if(!e)return;let t=()=>{W.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&&(W.current=!0,e.scrollTop=e.scrollHeight)},[i?.id]);let G=P.at(-1)?.detail?.length??0;(0,u.useEffect)(()=>{let e=k.current;e&&W.current&&(e.scrollTop=e.scrollHeight)},[F,R,G]);let K=(0,u.useRef)(null);(0,u.useEffect)(()=>{let e=k.current,t=K.current;if(!e||!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>{W.current&&(e.scrollTop=e.scrollHeight)});return n.observe(t),()=>n.disconnect()},[i?.id,a]);let q=o?(0,d.jsx)(Bt,{userGoal:o},s):null,te=m?x(m.subagentId):void 0,J=m&&te?(0,d.jsx)(zt,{manifest:te,params:m.snapshot.params,taskId:Te(m.subagentId,m.entityId),resumeSeed:{history:m.snapshot.history,activity:m.snapshot.activity}},h):null,Y=v?x(v.subagentId):void 0,ne=v&&Y?(0,d.jsx)(Vt,{manifest:Y,extraDestinations:v.extraDestinations},y):null,re=C?x(C.subagentId):void 0,X=C&&re?(0,d.jsx)(zt,{manifest:re,params:C.params,extraDestinations:C.extraDestinations},w):null,ie=T?x(T.subagentId):void 0,Z=T&&ie?(0,d.jsx)(zt,{manifest:ie,params:T.params,taskId:T.taskId,openingMessage:T.openingMessage},E):null;return a?(0,d.jsxs)(d.Fragment,{children:[q,J,ne,X,Z,(0,d.jsxs)(`div`,{style:{width:M.width},className:`relative flex h-full shrink-0 flex-col border-l border-border bg-background`,children:[(0,d.jsx)(it,{width:M.width,min:M.min,max:M.max,onResize:M.set,onCommit:M.commit,onReset:M.reset}),(0,d.jsxs)(`div`,{className:`flex min-h-[60px] items-center gap-1 border-b border-border/60 px-4 py-3`,children:[(0,d.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-lg font-semibold leading-tight`,children:i?i.title:`Agentico`}),D&&(0,d.jsx)(Yt,{scopeId:D.id,currentTaskId:i?.id??null,open:A,onOpenChange:j,onNewChat:N,onSelect:(e,t,n)=>_(e,t,n),onArchivedCurrent:g}),(0,d.jsx)(at,{})]}),(0,d.jsx)(`div`,{ref:k,className:`flex-1 overflow-y-auto px-3 pb-2 ${V?`min-h-24`:`min-h-0`}`,children:(0,d.jsx)(`div`,{ref:K,className:`pt-2`,children:i?(0,d.jsxs)(d.Fragment,{children:[i.manualEntry&&P.length===0&&(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i.manualEntry.prompt}),(0,d.jsx)(qe,{activity:ee,questions:B,docked:V,pinUserMessages:!V}),i.panelExtra&&(0,d.jsx)(`div`,{className:`mt-3`,children:i.panelExtra}),L.length>0&&(0,d.jsx)(qe,{activity:L,questions:B,docked:V,pinUserMessages:!V}),!i.agent.running&&i.agent.error&&(0,d.jsxs)(`div`,{className:`mt-2 flex items-center gap-2`,children:[(0,d.jsx)(`p`,{className:`flex-1 text-xs text-destructive`,children:i.agent.error}),(0,d.jsx)(l.ActionButton,{label:O.retry,variant:`secondary`,className:`shrink-0`,onClick:()=>{i.agent.sendMessage(O.retryMessage,{retry:!0}).then(e=>{e&&i.onApplied(e)})}}),!i.agent.remote&&(0,d.jsx)(l.ActionButton,{label:O.continueWithoutAi,variant:`secondary`,className:`shrink-0`,onClick:()=>{if(U){b(U.id,S);return}let e=i.agent.runFallback();e&&i.onApplied(e)}})]})]}):p.length>0?(0,d.jsx)(Jt,{messages:p}):f?(0,d.jsx)(qt,{card:f}):(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c??O.orchestratorStarterHint})})}),i&&V?(0,d.jsxs)(`section`,{"aria-label":O.pendingQuestions,className:`flex min-h-0 shrink flex-col border-t border-border/60`,children:[i.panelActions&&(0,d.jsx)(`div`,{className:`shrink-0 px-4 pt-3`,children:i.panelActions}),(0,d.jsx)(`div`,{className:`min-h-0 overflow-y-auto px-4 py-3`,children:(0,d.jsx)(We,{entry:V.entry,part:V.part,questions:B,autoFocus:!0},`${V.entry.id}:${V.part.id}`)}),i.agent.running&&(0,d.jsx)(`div`,{className:`flex shrink-0 justify-end px-4 pb-3`,children:(0,d.jsx)(l.ActionButton,{icon:`square`,label:O.stop,variant:`secondary`,onClick:i.agent.stop})})]}):(0,d.jsxs)(`div`,{className:`border-t border-border/60 px-4 py-3`,children:[i?.panelActions&&(0,d.jsx)(`div`,{className:`mb-2`,children:i.panelActions}),i?(0,d.jsx)(Ut,{task:i},i.id):(0,d.jsx)(Wt,{})]})]})]}):(0,d.jsxs)(d.Fragment,{children:[q,J,ne,X,Z]})}function Zt(e,t){let{setPageContext:n}=Ae(),r=(0,u.useRef)(crypto.randomUUID()).current;(0,u.useEffect)(()=>(n(r,e,t??null),()=>n(r,null)),[e,t])}function Qt(e,t,n,r,i=!0,a){let{registerComponentAnchor:o}=Ae(),s=(0,u.useRef)(crypto.randomUUID()).current,c=(0,u.useRef)(n);c.current=n,(0,u.useEffect)(()=>{if(i)return o(s,{subagentId:e,componentKey:t,contextInfo:r,pinnedEntityId:a,onResult:(e,t,n)=>c.current?.(e,t,n)}),()=>o(s,null)},[e,t,r,i,a])}exports.AGENTICO_MAX_WIDTH=Xe,exports.AGENTICO_MIN_WIDTH=Ye,exports.AGENTICO_WIDTH=Je,exports.AGENTICO_WIDTH_STORAGE_KEY=Ze,exports.Agentico=Xt,exports.AgenticoProvider=ke,exports.AgenticoToggle=at,exports.DEFAULT_REASONING_PART_ID=p,exports.DEFAULT_TEXT_PART_ID=f,exports.JSON_EXPORT_DESTINATION_ID=W,exports.MICRO_PROMPT_REGISTRY=z,exports.ORCHESTRATOR_TASK_ID=De,exports.SUMMARY_MICRO_PROMPT=R,exports.agenticoDe=ne,exports.agenticoEn=J,exports.agenticoIt=Y,exports.agenticoPromptsEn=O,exports.agenticoPromptsIt=k,exports.agenticoTranslations=Ee,exports.applyMicroPrompts=B,exports.chatHasPersonMessage=ye,exports.chatStartedAt=Se,exports.chatTitle=ve,exports.configureAgenticoPrompts=j,exports.configureEntityChatStore=ie,exports.createCrossAgentTools=w,exports.defineSubagent=_,exports.entityChatTaskId=Te,exports.extractErrorMessage=V,exports.extractJsonBlock=H,exports.findSubagentManifest=x,exports.formatQuestionAnswers=g,exports.getAgenticoPrompts=M,exports.getDestinationRegistry=te,exports.getEntityChat=pe,exports.getSubagentControls=jt,exports.getSubagentRegistry=b,exports.getSubagentReport=Et,exports.hasEntityChatBackend=Z,exports.jsonExportDestination=G,exports.listEntityChats=we,exports.messagePartsText=h,exports.onEntityChatsChange=de,exports.registerCrossAgentTools=C,exports.registerDestinations=q,exports.registerSubagentControls=At,exports.registerSubagentReports=Tt,exports.registerSubagents=y,exports.removeEntityChat=Ce,exports.renameEntityChat=xe,exports.renderRegistryCli=L,exports.renderSubagentCli=ee,exports.resetAgenticoPrompts=N,exports.saveEntityChat=me,exports.syncEntityChats=se,exports.toJsonSchema=T,exports.toMcpTool=E,exports.upsertMessagePart=m,exports.useAgent=gt,exports.useAgentico=Ae,exports.useAgenticoI18n=$,exports.useAgenticoPageContext=Zt,exports.useSubagentComponentContext=Qt;
29
29
  //# sourceMappingURL=index.js.map