@llmnative/agentico 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +108 -99
- package/dist/index.mjs.map +1 -1
- package/dist/types/domain/agentDefinition.d.ts +5 -0
- package/llms.txt +3 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -59,6 +59,7 @@ configureAgenticoPrompts({ // optional: langu
|
|
|
59
59
|
| **Scope** — the host's current tenant/company: id + data and storage providers | `<AgenticoProvider scope>` |
|
|
60
60
|
| **Page context** — what the user is looking at, for the orchestrator prompt | `useAgenticoPageContext`, `useSubagentComponentContext` |
|
|
61
61
|
| **Saved chats** — one chat per saved entity, resumable | `configureEntityChatStore`, `getEntityChat`, `listEntityChats` |
|
|
62
|
+
| **Conversational subagents** — a chat with the model and its tools, nothing to apply at the end: each reply a message of the chat, no result preview or destinations | `AgentDefinition.conversational` |
|
|
62
63
|
| **Remote subagents** — turns answered by the host (a remote agent with its own memory, e.g. an opencode session), streamed with its steps; its own models in the composer, no fallback | `AgentDefinition.executor` (`AgentExecutor`, `models`, `defaultModel`) |
|
|
63
64
|
| **Message parts** — a remote reply in parts, as in the Vercel AI SDK / AG-UI: Markdown text (tables, lists, code; repaired while it streams), the reasoning of the model (closed, "Reasoned for 12 s"), the steps grouped and collapsible, questions answered with a click. Answers go back structured: to the waiting turn (`onQuestions` resolves) or as a new turn with `answers`. Parts are saved with the chat; chats saved with text only still load | `AgentExecutorTurn.onText(text, { id?, done? })`, `onReasoning(text, { id?, done?, duration? })`, `onStep`, `onQuestions(questions, { id? })`, `AgentExecutorTurn.answers`, `AgentMessagePart`, `useAgent().answerQuestions` |
|
|
64
65
|
| **Panel** — a column beside the page, resizable by dragging its inner edge (or with the arrow keys on it; double click resets), the width kept per browser (`localStorage`, key `agentico:panel-width`). Questions waiting in the latest message of the agent are docked at the bottom in place of the composer, until answered or stopped | `<Agentico defaultWidth minWidth maxWidth onWidthChange>`, `AGENTICO_WIDTH`, `AGENTICO_MIN_WIDTH`, `AGENTICO_MAX_WIDTH` |
|
package/dist/index.js
CHANGED
|
@@ -6,9 +6,9 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
6
6
|
`).map(e=>e&&n+e).join(`
|
|
7
7
|
`)}function L(e){return[`NAME`,` ${e.id} — ${e.label}`,``,`DESCRIPTION`,I(e.description,2),``,...e.commands.map(t=>F(e.id,t))].join(`
|
|
8
8
|
`)}function R(e){return e.length===0?M().noToolsAvailable:e.map(e=>`${e.id} [${e.commands.map(e=>e.name).join(`|`)}] — ${e.label}: ${e.commands.map(e=>e.summary).join(` / `)}`).join(`
|
|
9
|
-
`)}var z={id:`closing-summary`,get text(){return M().closingSummary}},
|
|
10
|
-
`)}`}function V(e){if(e instanceof Error)return e.message;if(typeof e==`object`&&e){let t=e;if(typeof t.error==`string`)return t.error;if(t.error&&typeof t.error==`object`){let e=t.error;if(typeof e.message==`string`)return e.message}if(typeof t.message==`string`)return t.message;if(typeof t.status==`number`)return`HTTP ${t.status}`;try{return JSON.stringify(e)}catch{}}return String(e)}function H(e){let t=e.match(/```(?:json)?\s*\n?([\s\S]*?)```/i);if(t)return t[1].trim();let n=e.replace(/^```json\s*/i,``).replace(/^```\s*/i,``).replace(/```\s*$/,``).trim();return te(n)??n}function te(e){let t=e.search(/[{[]/);if(t===-1)return null;let n=e[t],r=n===`{`?`}`:`]`,i=0,a=!1,o=!1;for(let s=t;s<e.length;s++){let c=e[s];if(a){o?o=!1:c===`\\`?o=!0:c===`"`&&(a=!1);continue}if(c===`"`){a=!0;continue}if(c===n)i++;else if(c===r&&(i--,i===0))return e.slice(t,s+1)}return null}var U=`json-export`,W={id:U,label:`Export as JSON`,async apply(e){let t=new Blob([JSON.stringify(e,null,2)],{type:`application/json`}),n=URL.createObjectURL(t);try{let e=document.createElement(`a`);e.href=n,e.download=`tool-result-${Date.now()}.json`,e.click()}finally{URL.revokeObjectURL(n)}}},G={};function K(e){G=e}function q(){return{[W.id]:W,...G}}var J=`llmnative.agentico.entityChat`;function Y(e){J=e.storageKey}function ne(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.entityId!=`string`)return null;let n=t.scopeId??t.tenantId;if(typeof n!=`string`)return null;let{tenantId:r,...i}=t;return{...i,scopeId:n}}function X(){try{let e=localStorage.getItem(J);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(ne).filter(e=>e!==null):[]}catch{return[]}}function re(e){try{localStorage.setItem(J,JSON.stringify(e))}catch{}}var Z=(e,t,n)=>`${e}:${t}:${n}`;function ie(e,t,n){let r=Z(e,t,n);return X().find(e=>Z(e.scopeId,e.subagentId,e.entityId)===r)??null}function ae(e){let t=Z(e.scopeId,e.subagentId,e.entityId),n=X().filter(e=>Z(e.scopeId,e.subagentId,e.entityId)!==t);n.push({...e,savedAt:Date.now()}),re(n)}function oe(e,t,n){let r=Z(e,t,n);re(X().filter(e=>Z(e.scopeId,e.subagentId,e.entityId)!==r))}function se(e){return X().filter(t=>t.scopeId===e).sort((e,t)=>t.savedAt-e.savedAt)}var ce=(e,t)=>`entitychat-${e}-${t}`,le={modelLabel:`Modell`,modelsLoading:`Wird geladen…`,noModelsAvailable:`Keine Modelle verfügbar`,noProviderConnected:`Kein AI-Provider verbunden`,selectModelPlaceholder:`Modell wählen…`,orchestratorStarterHint:`Sag Agentico, was du erreichen willst — es wählt das passende Werkzeug und fragt nach den nötigen Angaben.`,orchestratorStarterPlaceholder:`Beschreibe, was du tun möchtest…`,destinationPickerTitle:`Ergebnis speichern in…`,destinationApplying:`Wird gespeichert…`,destinationNoScope:`Kein Ziel ausgewählt — vor dem Speichern eines auswählen.`,unknownDestination:`Unbekanntes Ziel: {id}`,exportJson:`Als JSON exportieren`,orchestratorUnavailable:`AI nicht verfügbar — öffne das benötigte Werkzeug direkt auf seiner Seite.`,orchestratorContinueWithoutAi:`Weiter ohne AI.`,orchestratorPreparing:`{label} wird vorbereitet…`,orchestratorCollecting:`Parameter für {label} werden gesammelt…`,thinking:`Denke nach…`,stopped:`Vom Benutzer abgebrochen.`,toolRequest:`Werkzeugausführung angefordert`,modelRequestError:`Fehler bei der Anfrage an das Modell`,noProviderResponse:`Keine Antwort vom AI-Provider.`,noActiveSession:`Keine aktive Sitzung — zuerst run() aufrufen.`,requestInProgress:`Eine andere Anfrage läuft bereits.`,invalidResponse:`Ungültige AI-Antwort.`,responseReceived:`Antwort erhalten`,noProviderAvailable:`Kein AI-Provider verfügbar.`,tooManyToolTurns:`Zu viele aufeinanderfolgende Werkzeugaufrufe — das bisher gesammelte deterministische Ergebnis wird verwendet.`,aiDisabledFallback:`AI deaktiviert — das deterministische Ergebnis wird verwendet.`,continueWithoutAiFallback:`Weiter ohne AI — das deterministische Ergebnis wird verwendet.`,oneStep:`1 Schritt`,steps:`{count} Schritte`,stepsLabel:`Schritte des Agenten`,newInstance:`Neue Instanz von "{label}"`,chatHistory:`Chatverlauf`,newChat:`Neuer Chat`,searchChats:`Chats durchsuchen…`,messagePlaceholder:`Nachricht schreiben…`,unsavedConversationConfirm:`Diese Unterhaltung wurde nicht gespeichert und geht verloren. Fortfahren?`,noSavedChats:`Noch keine gespeicherten Chats.`,archiveChat:`Archivieren`,noResults:`Keine Ergebnisse.`,retry:`Erneut versuchen`,retryMessage:`Erneut versuchen.`,continueWithoutAi:`Ohne AI fortfahren`,resumeWithAi:`Mit AI fortsetzen`,openPanel:`Agentenbereich öffnen`,closePanel:`Agentenbereich schließen`,resizePanel:`Agent-Bereich in der Größe ändern`,resizePanelHint:`Ziehen zum Ändern der Größe, Doppelklick zum Zurücksetzen`,pendingQuestions:`Fragen des Agenten`,stop:`Stoppen`},ue={modelLabel:`Model`,modelsLoading:`Loading…`,noModelsAvailable:`No models available`,noProviderConnected:`No AI provider connected`,selectModelPlaceholder:`Choose a model…`,orchestratorStarterHint:`Tell Agentico what you want to do — it will pick the right tool and ask for what it needs.`,orchestratorStarterPlaceholder:`Describe what you want to do…`,destinationPickerTitle:`Save result to…`,destinationApplying:`Saving…`,destinationNoScope:`Nothing selected to save into — select one before saving.`,unknownDestination:`Unknown destination: {id}`,exportJson:`Export as JSON`,orchestratorUnavailable:`AI not available — open the tool you need directly from its page.`,orchestratorContinueWithoutAi:`Continuing without AI.`,orchestratorPreparing:`Preparing {label}…`,orchestratorCollecting:`Collecting the parameters for {label}…`,thinking:`Thinking…`,stopped:`Stopped by the user.`,toolRequest:`Requested to run some tools`,modelRequestError:`Error in the request to the model`,noProviderResponse:`No response from the AI provider.`,noActiveSession:`No active session — call run() first.`,requestInProgress:`Another request is already running.`,invalidResponse:`Invalid AI response.`,responseReceived:`Response received`,noProviderAvailable:`No AI provider available.`,tooManyToolTurns:`Too many consecutive tool-calling turns — using the deterministic result collected so far.`,aiDisabledFallback:`AI disabled — using the deterministic result.`,continueWithoutAiFallback:`Continuing without AI — using the deterministic result.`,oneStep:`1 step`,steps:`{count} steps`,stepsLabel:`Steps of the agent`,newInstance:`New "{label}" instance`,chatHistory:`Chat history`,newChat:`New chat`,searchChats:`Search chats…`,messagePlaceholder:`Write a message…`,unsavedConversationConfirm:`This conversation has not been saved and will be lost. Continue?`,noSavedChats:`No saved chats yet.`,archiveChat:`Archive`,noResults:`No results.`,retry:`Retry`,retryMessage:`Retry.`,continueWithoutAi:`Continue without AI`,resumeWithAi:`Resume with AI`,openPanel:`Open agent panel`,closePanel:`Close agent panel`,resizePanel:`Resize the agent panel`,resizePanelHint:`Drag to resize, double-click to reset`,pendingQuestions:`Questions of the agent`,stop:`Stop`},de={modelLabel:`Modello`,modelsLoading:`Caricamento…`,noModelsAvailable:`Nessun modello disponibile`,noProviderConnected:`Nessun provider AI connesso`,selectModelPlaceholder:`Scegli un modello…`,orchestratorStarterHint:`Dì ad Agentico cosa vuoi fare — sceglierà lo strumento giusto e ti chiederà cosa serve.`,orchestratorStarterPlaceholder:`Descrivi cosa vuoi fare…`,destinationPickerTitle:`Salva risultato in…`,destinationApplying:`Salvataggio…`,destinationNoScope:`Nessuna destinazione selezionata — selezionane una prima di salvare.`,unknownDestination:`Destinazione sconosciuta: {id}`,exportJson:`Esporta come JSON`,orchestratorUnavailable:`AI non disponibile — apri il tool che ti serve direttamente dalla sua pagina.`,orchestratorContinueWithoutAi:`Continuo senza AI.`,orchestratorPreparing:`Preparo {label}…`,orchestratorCollecting:`Sto raccogliendo i parametri per {label}…`,thinking:`Sto pensando…`,stopped:`Interrotto dall'utente.`,toolRequest:`Richiesta di eseguire dei tool`,modelRequestError:`Errore nella richiesta al modello`,noProviderResponse:`Nessuna risposta dal provider AI.`,noActiveSession:`Nessuna sessione attiva — chiama prima run().`,requestInProgress:`Un'altra richiesta è già in corso.`,invalidResponse:`Risposta AI non valida.`,responseReceived:`Risposta ricevuta`,noProviderAvailable:`Nessun provider AI disponibile.`,tooManyToolTurns:`Troppi turni di tool-calling consecutivi — uso il risultato deterministico raccolto finora.`,aiDisabledFallback:`AI disabilitata — uso il risultato deterministico.`,continueWithoutAiFallback:`Continuo senza AI — uso il risultato deterministico.`,oneStep:`1 passo`,steps:`{count} passi`,stepsLabel:`Passi dell'agente`,newInstance:`Nuova istanza di "{label}"`,chatHistory:`Storico chat`,newChat:`Nuova chat`,searchChats:`Cerca nelle chat…`,messagePlaceholder:`Scrivi un messaggio…`,unsavedConversationConfirm:`Questa conversazione non è stata salvata e andrà persa. Continuare?`,noSavedChats:`Nessuna chat salvata ancora.`,archiveChat:`Archivia`,noResults:`Nessun risultato.`,retry:`Riprova`,retryMessage:`Riprova.`,continueWithoutAi:`Continua senza AI`,resumeWithAi:`Riprendi con AI`,openPanel:`Apri pannello agente`,closePanel:`Chiudi pannello agente`,resizePanel:`Ridimensiona il pannello dell'agente`,resizePanelHint:`Trascina per ridimensionare, doppio clic per ripristinare`,pendingQuestions:`Domande dell'agente`,stop:`Ferma`},fe={en:{agentico:ue},it:{agentico:de},de:{agentico:le}};function Q(){let{dict:e}=(0,l.useI18n)(),t=e.agentico;return t?{...ue,...t}:ue}var pe=`agentico-orchestrator`,me=(0,u.createContext)(null);function he({children:e,scope:t=null}){let[n,r]=(0,u.useState)(null),i=(0,u.useRef)(null);(0,u.useEffect)(()=>{i.current=n},[n]);let[a,o]=(0,u.useState)(!1),s=(0,u.useCallback)(e=>{let t=i.current;t&&t.id!==e.id&&t.onDismiss();let n=t&&t.id===e.id&&t.savedToDisk&&e.savedToDisk===void 0?{...e,savedToDisk:!0}:e;r(n)},[]),c=(0,u.useCallback)(e=>{r(t=>t&&t.id===e?null:t)},[]),l=(0,u.useCallback)(()=>o(e=>!e),[]),f=(0,u.useCallback)(()=>o(!0),[]),[p,m]=(0,u.useState)(null),[h,g]=(0,u.useState)(void 0),[_,v]=(0,u.useState)(void 0),[y,b]=(0,u.useState)(void 0),[S,C]=(0,u.useState)(null),[w,T]=(0,u.useState)(null),[E,D]=(0,u.useState)(void 0),[O,k]=(0,u.useState)([]),A=(0,u.useCallback)((e,t,n=null)=>{k(r=>{let i=r.filter(t=>t.id!==e);return t?[...i,{id:e,text:t,card:n}]:i})},[]),j=O.length>0?O[O.length-1]:null,[N,P]=(0,u.useState)([]),F=(0,u.useCallback)((e,t)=>{P(n=>{let r=n.filter(t=>t.id!==e);return t?[...r,{id:e,...t}]:r})},[]),I=(0,u.useMemo)(()=>N.map(e=>({subagentId:e.subagentId,componentKey:e.componentKey,onResult:e.onResult,pinnedEntityId:e.pinnedEntityId})),[N]),L=(0,u.useMemo)(()=>{let e=new Map;for(let t of N)e.set(t.subagentId,{subagentId:t.subagentId,componentKey:t.componentKey,onResult:t.onResult,contextInfo:t.contextInfo});return[...e.values()]},[N]),R=(0,u.useMemo)(()=>L.map(e=>{let t=x(e.subagentId)?.componentContexts?.[e.componentKey];if(!t)return null;let n=e.contextInfo?`${t.agenticoHint}\n${e.contextInfo}`:t.agenticoHint;return{subagentId:e.subagentId,agenticoHint:n,userMessage:t.userMessage}}).filter(e=>e!==null),[L]),z=(0,u.useMemo)(()=>R.map(e=>e.userMessage),[R]),ee=(0,u.useMemo)(()=>{if(R.length===0)return null;if(R.length===1)return R[0].agenticoHint;let e=R.map((e,t)=>`${t+1}. ${e.agenticoHint}`).join(`
|
|
11
|
-
`);return`${M().multipleCandidates}\n\n${e}`},[R])??j?.text??null,B=R.length>0?null:j?.card??null,V=(0,u.useMemo)(()=>[...new Set(I.map(e=>e.subagentId))],[I]),H=V.length===1?V[0]:V.length===0?j?.card?.subagentId??null:null,te=(0,u.useCallback)((e,t)=>{f();let n=i.current;if(n?.id===`agentico-orchestrator`)return;let r=H&&n?.id.startsWith(`subagent-${H}-`)?n:void 0;T(r?{taskId:r.id,activity:[...r.precedingActivity??[],...r.agent.activity]}:null),m(e),g(t?.extraDestinations),v(t?.attachments),b(t?.model),D(t?.scopedSubagentId),C(crypto.randomUUID())},[f,H]),U=(0,u.useCallback)((e,t,n,a,o,s)=>{if(!n||!a)return;let c=i.current;if(!c||c.id!==n)return;let l=c.agent.snapshot();l&&(ae({scopeId:a,subagentId:e,entityId:t,params:o,title:s,history:l.history,activity:[...c.precedingActivity??[],...l.activity]}),r(e=>e&&e.id===n?{...e,savedToDisk:!0}:e))},[]),[W,G]=(0,u.useState)(null),[K,q]=(0,u.useState)(null),J=(0,u.useCallback)((e,t,n)=>{f(),G({subagentId:e,entityId:t,snapshot:n}),q(crypto.randomUUID())},[f]),[Y,ne]=(0,u.useState)(null),[X,re]=(0,u.useState)(null),Z=(0,u.useCallback)((e,t)=>{f(),c(pe),ne({subagentId:e,extraDestinations:t}),re(crypto.randomUUID())},[f,c]),[ie,oe]=(0,u.useState)(null),[se,ce]=(0,u.useState)(null),le=(0,u.useCallback)((e,t,n)=>{ne(null),oe({subagentId:e,params:t,extraDestinations:n}),ce(crypto.randomUUID())},[]),[ue,de]=(0,u.useState)(null),[fe,Q]=(0,u.useState)(null),he=(0,u.useCallback)((e,t,n)=>{f(),de({subagentId:e,params:t,...n}),Q(crypto.randomUUID())},[f]),$=(0,u.useCallback)(()=>{let e=i.current;e&&e.onDismiss()},[]),ge=(0,u.useMemo)(()=>({scope:t,task:n,isOpen:a,openTask:s,closeTask:c,toggleOpen:l,pendingGoal:p,startOrchestrator:te,pageContext:ee,pageContextCard:B,setPageContext:A,scopedSubagentId:H,pendingScopedSubagentId:E,componentAnchors:I,anchoredUserMessages:z,registerComponentAnchor:F,openPanel:f,pendingExtraDestinations:h,pendingAttachments:_,pendingModel:y,orchestratorRunId:S,pendingCarryOver:w,commitEntityChat:U,resumeEntityChat:J,pendingResume:W,resumeRunId:K,dismissForeignTask:$,pendingManualEntry:Y,manualEntryRunId:X,startManualEntry:Z,pendingResumeWithAI:ie,resumeWithAIRunId:se,resumeWithAI:le,startSubagent:he,pendingStart:ue,startRunId:fe}),[t,n,a,s,c,l,p,te,ee,B,A,H,E,I,z,F,f,h,_,y,S,w,U,J,W,K,$,Y,X,Z,ie,se,le,he,ue,fe]);return(0,d.jsx)(me.Provider,{value:ge,children:e})}function $(){let e=(0,u.useContext)(me);if(!e)throw Error(`useAgentico must be used inside AgenticoProvider`);return e}function ge(e){let t=e.search(/[{[]/);if(t===-1)return[{type:`text`,content:e}];let n=e[t],r=n===`{`?`}`:`]`,i=0,a=!1,o=!1,s=-1;for(let c=t;c<e.length;c++){let t=e[c];if(a){o?o=!1:t===`\\`?o=!0:t===`"`&&(a=!1);continue}if(t===`"`){a=!0;continue}if(t===n)i++;else if(t===r&&(i--,i===0)){s=c;break}}let c=s===-1?null:e.slice(t,s+1);if(!c||c.length<60)return[{type:`text`,content:e}];try{JSON.parse(c)}catch{return[{type:`text`,content:e}]}let l=[];t>0&&l.push({type:`text`,content:e.slice(0,t)}),l.push({type:`code`,content:c,language:`json`});let u=e.slice(s+1);return u.trim()&&l.push(...ge(u)),l}function _e(e){let t=[],n=/```(\w+)?\n?([\s\S]*?)```/g,r=0,i;for(;i=n.exec(e);)i.index>r&&t.push(...ge(e.slice(r,i.index))),t.push({type:`code`,content:i[2].replace(/\n$/,``),language:i[1]}),r=n.lastIndex;return r<e.length&&t.push(...ge(e.slice(r))),t}function ve({content:e,language:t}){let[n,r]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`relative cursor-pointer rounded-md ${n?`max-h-80 overflow-y-auto`:`max-h-28 overflow-hidden`}`,onClick:()=>r(e=>!e),title:n?`Clic per comprimere`:`Clic per espandere`,children:[(0,d.jsx)(l.Code,{language:t,showCopy:n,background:`transparent`,className:`!text-[11px]`,children:e}),!n&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-muted/30 to-transparent`})]})}function ye({text:e,tone:t}){let n=_e(e);return(0,d.jsx)(d.Fragment,{children:n.map((e,n)=>e.type===`code`?(0,d.jsx)(ve,{content:e.content,language:e.language},n):e.content.trim()&&(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:t,className:`break-words text-xs leading-relaxed`},n))})}function be({status:e}){return e===`running`?(0,d.jsx)(`span`,{className:`inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-2 border-current border-t-transparent`}):e===`done`?(0,d.jsx)(l.Icon,{name:`check`,size:12,className:`shrink-0 text-green-600`}):e===`stopped`?(0,d.jsx)(l.Icon,{name:`circle-slash`,size:12,className:`shrink-0 text-muted-foreground`}):(0,d.jsx)(l.Icon,{name:`x`,size:12,className:`shrink-0 text-destructive`})}function xe(e,t){return e.status===`running`?t.thinking:e.status===`error`?t.modelRequestError:e.status===`stopped`?t.stopped:e.detail?t.responseReceived:e.toolNames&&e.toolNames.length>0?e.toolNames.join(` · `):t.toolRequest}var Se=96;function Ce({entry:e,pinned:t=!0}){let n=(0,u.useRef)(null),[r,i]=(0,u.useState)(!1),[a,o]=(0,u.useState)(!1);(0,u.useLayoutEffect)(()=>{let e=n.current;e&&o(e.scrollHeight>97)},[e.detail,e.attachmentNames]);let s=a&&!r;return(0,d.jsx)(`div`,{className:`${t?`sticky top-0 z-20 border-b border-border/40`:``} flex justify-end bg-background py-1.5`,children:(0,d.jsxs)(`div`,{className:`max-w-[85%] rounded-lg bg-primary/10 text-xs text-foreground`,children:[(0,d.jsxs)(`div`,{ref:n,className:`space-y-1 px-2.5 pt-1.5 ${s?`overflow-hidden`:``}`,style:s?{maxHeight:Se}:void 0,children:[e.attachmentNames&&e.attachmentNames.length>0&&(0,d.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.attachmentNames.map((e,t)=>(0,d.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md bg-primary/15 px-1.5 py-0.5 text-[11px] text-foreground`,children:[(0,d.jsx)(l.Icon,{name:`paperclip`,size:10,className:`shrink-0`}),(0,d.jsx)(`span`,{className:`max-w-[160px] truncate`,children:e})]},t))}),(0,d.jsx)(ye,{text:e.detail??``})]}),a&&(0,d.jsxs)(`button`,{type:`button`,onClick:()=>i(e=>!e),className:`relative flex w-full items-center justify-center rounded-b-lg py-1 text-muted-foreground hover:bg-primary/15`,title:r?`Comprimi`:`Espandi`,children:[s&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 -top-4 h-4 bg-gradient-to-t from-primary/10 to-transparent`}),(0,d.jsx)(l.Icon,{name:r?`chevron-up`:`chevron-down`,size:12})]})]})})}var we={running:`loader-circle`,done:`check`,error:`x`,stopped:`circle-slash`};function Te({steps:e}){let t=Q(),n=e.filter(e=>e.status===`running`).at(-1),r=e.some(e=>e.status===`error`),i=n?.label??(e.length===1?t.oneStep:(0,l.interpolate)(t.steps,{count:e.length}));return(0,d.jsx)(l.Tree,{ariaLabel:t.stepsLabel,selectedId:null,itemClassName:`py-0.5 text-xs text-muted-foreground`,nodes:[{id:`steps-${e[0]?.id??``}`,label:i,icon:n?`loader-circle`:r?`circle-alert`:`list-checks`,children:e.map(e=>({id:e.id,label:(0,d.jsx)(`span`,{className:e.status===`error`?`text-destructive`:void 0,children:e.label}),icon:we[e.status]}))}]})}function Ee(e,t){let n=e.at(-1);if(!n||n.kind!==`thinking`||!n.parts||n.status===`stopped`||n.status===`error`)return null;let r=[...n.parts].reverse().find(e=>e.type===`questions`);return!r||r.answers||!t(n.id)?null:{entry:n,part:r}}function De({entry:e,part:t,questions:n,autoFocus:r,className:i}){let a=!!n?.canAnswer(e.id);return(0,d.jsx)(l.ChatQuestions,{questions:t.questions,...t.answers?{answers:t.answers}:{},disabled:!t.answers&&!a,onSubmit:n&&a?r=>n.onAnswer(e.id,t.id,r):void 0,autoFocus:r,className:i??`text-xs`})}function Oe({entry:e,questions:t,hiddenPartId:n}){let r=(e.parts??[]).filter(e=>e.type!==`questions`||e.id!==n),i=[];for(let e of r){let t=i.at(-1);e.type===`tool`?t&&`steps`in t?t.steps.push(e):i.push({key:`tool-${e.id}`,steps:[e]}):i.push({key:`${e.type}-${e.id}`,part:e})}return(0,d.jsx)(`div`,{className:`space-y-2`,children:i.map(n=>{if(`steps`in n)return(0,d.jsx)(Te,{steps:n.steps},n.key);let{part:r}=n;return r.type===`text`?r.text.trim()?(0,d.jsx)(l.ChatMarkdown,{content:r.text,streaming:r.streaming,className:`break-words text-xs leading-relaxed text-foreground`},n.key):null:r.type===`reasoning`?(0,d.jsx)(l.ChatReasoning,{content:r.text,streaming:r.streaming,duration:r.duration,className:`my-0`},n.key):(0,d.jsx)(De,{entry:e,part:r,questions:t},n.key)})})}function ke({entry:e,questions:t,hiddenPartId:n}){let r=Q();if(e.kind===`thinking`&&e.parts){let i=e.status===`error`||e.status===`stopped`||e.status===`running`&&e.parts.length===0;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[e.parts.length>0&&(0,d.jsx)(Oe,{entry:e,questions:t,hiddenPartId:n}),i&&(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5 ${e.parts.length>0?`mt-1`:``}`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(be,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:xe(e,r)})]})]})}let i=e.kind===`thinking`&&e.detail?_e(e.detail):[],a=i.filter(e=>e.type===`code`),o=i.filter(e=>e.type===`text`&&e.content.trim()),s=e.kind===`thinking`?xe(e,r):e.label;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(be,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:s})]}),a.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-1`,children:a.map((e,t)=>(0,d.jsx)(ve,{content:e.content,language:e.language},t))}),o.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-2`,children:o.map((e,t)=>(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:`muted`,className:`break-words text-xs leading-relaxed`},t))})]})}function Ae({activity:e,questions:t,docked:n,pinUserMessages:r=!0}){if(e.length===0)return null;let i=[];for(let t of e)t.kind===`user`||i.length===0?i.push(t.kind===`user`?{user:t,entries:[]}:{entries:[t]}):i[i.length-1].entries.push(t);return(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:i.map(e=>(0,d.jsxs)(`li`,{children:[e.user&&(0,d.jsx)(Ce,{entry:e.user,pinned:r}),e.entries.length>0&&(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:e.entries.map(e=>(0,d.jsx)(ke,{entry:e,questions:t,hiddenPartId:n?.entry.id===e.id?n.part.id:void 0},e.id))})]},e.user?.id??e.entries[0]?.id))})}var je=420,Me=320,Ne=`60vw`,Pe=`agentico:panel-width`;function Fe(e,t){if(typeof e==`number`)return e;let n=Number.parseFloat(e);return Number.isFinite(n)?Math.round(n/100*t):1/0}function Ie(e,t,n){return Math.round(Math.min(Math.max(e,t),Math.max(t,n)))}function Le(){try{let e=window.localStorage.getItem(Pe),t=e===null?NaN:Number(e);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function Re(e){try{e===null?window.localStorage.removeItem(Pe):window.localStorage.setItem(Pe,String(e))}catch{}}function ze(){return typeof window>`u`?1/0:window.innerWidth}function Be({defaultWidth:e=420,minWidth:t=320,maxWidth:n=Ne,onWidthChange:r}){let[i,a]=(0,u.useState)(ze),[o,s]=(0,u.useState)(()=>Le()??e);(0,u.useEffect)(()=>{if(typeof window>`u`)return;let e=()=>a(window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let c=t,l=Math.max(c,Fe(n,i)),d=Ie(o,c,l);return(0,u.useEffect)(()=>{r?.(d)},[d]),{width:d,min:c,max:l,set:(0,u.useCallback)(e=>s(Ie(e,c,l)),[c,l]),commit:(0,u.useCallback)(e=>Re(Ie(e,c,l)),[c,l]),reset:(0,u.useCallback)(()=>{s(e),Re(null)},[e])}}function Ve({width:e,min:t,max:n,onResize:r,onCommit:i,onReset:a}){let o=Q(),s=(0,u.useRef)(null),[c,l]=(0,u.useState)(!1),f=e=>Math.round(Math.min(Math.max(e,t),Math.max(t,n))),p=e=>{let t=s.current;if(t&&t.pointerId===e.pointerId){s.current=null,l(!1),document.body.style.removeProperty(`cursor`),document.body.style.removeProperty(`user-select`);try{e.currentTarget.releasePointerCapture(e.pointerId)}catch{}i(t.last)}};return(0,d.jsx)(`div`,{role:`separator`,"aria-orientation":`vertical`,"aria-label":o.resizePanel,"aria-valuenow":e,"aria-valuemin":t,"aria-valuemax":n,tabIndex:0,title:o.resizePanelHint,"data-dragging":c||void 0,className:`group absolute inset-y-0 -left-1 z-30 flex w-2 cursor-col-resize touch-none select-none justify-center outline-none`,onPointerDown:t=>{if(t.button===0){t.preventDefault(),s.current={pointerId:t.pointerId,startX:t.clientX,startWidth:e,last:e},l(!0),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`;try{t.currentTarget.setPointerCapture(t.pointerId)}catch{}}},onPointerMove:e=>{let t=s.current;t&&t.pointerId===e.pointerId&&(t.last=f(t.startWidth+(t.startX-e.clientX)),r(t.last))},onPointerUp:p,onPointerCancel:p,onLostPointerCapture:p,onDoubleClick:a,onKeyDown:a=>{let o=a.shiftKey?64:16,s=null;if(a.key===`ArrowLeft`?s=e+o:a.key===`ArrowRight`?s=e-o:a.key===`Home`?s=t:a.key===`End`&&(s=n),s===null)return;a.preventDefault();let c=f(s);r(c),i(c)},children:(0,d.jsx)(`span`,{"aria-hidden":!0,className:`h-full w-0.5 transition-colors ${c?`bg-primary`:`bg-transparent group-hover:bg-primary/50 group-focus-visible:bg-primary`}`})})}function He({className:e=``}){let{isOpen:t,toggleOpen:n,task:r}=$(),i=Q(),a=r?.agent.running??!1;return(0,d.jsx)(l.ActionButton,{icon:`bot`,ariaLabel:t?i.closePanel:i.openPanel,title:t?i.closePanel:i.openPanel,onClick:n,iconClassName:a?`animate-pulse`:void 0,className:`!h-9 !w-9 !p-0 rounded-md ${t?`bg-primary/10 text-primary hover:bg-primary/15`:`bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground`} ${e}`})}var Ue=`llmnative-cms.selectedAIModel`;function We(){try{return localStorage.getItem(Ue)??``}catch{return``}}function Ge(e){try{e?localStorage.setItem(Ue,e):localStorage.removeItem(Ue)}catch{}}function Ke(){let e=(0,l.useAIProviderRegistry)()?.registry??{},t=Object.keys(e).length>0,[n,r]=(0,u.useState)({}),[i,a]=(0,u.useState)(!1),[o,s]=(0,u.useState)(We);return(0,u.useEffect)(()=>{if(!t){r({});return}let n=!1;return a(!0),(0,l.getAIModelCatalog)(e).then(e=>{if(n)return;r(e.modelsByProvider);let t=Object.values(e.modelsByProvider).flat();s(e=>t.some(t=>t.id===e)?e:(Ge(``),``))}).catch(e=>{console.error(`useAIModelCatalog: getAIModelCatalog failed`,e),n||r({})}).finally(()=>{n||a(!1)}),()=>{n=!0}},[t,JSON.stringify(Object.keys(e).sort())]),{hasProviders:t,modelsByProvider:n,modelsLoading:i,selectedModel:o,setSelectedModel:e=>{Ge(e),s(e)}}}var qe=20,Je=26e4;function Ye(e){return e.filter(e=>!l.PromptUtils.isTextAttachment(e.mimeType)||e.base64.length<=Je)}function Xe(e,t={}){let{defaultEnabled:n=!1}=t,[r,i]=(0,u.useState)(n),{hasProviders:a,modelsByProvider:o,modelsLoading:s,selectedModel:c,setSelectedModel:d}=Ke(),[p,_]=(0,u.useState)(!1),[v,y]=(0,u.useState)(null),[b,x]=(0,u.useState)(!1),[S,C]=(0,u.useState)([]),w=(0,u.useRef)([]),E=e=>{C(t=>{let n=typeof e==`function`?e(t):e;return w.current=n,n})},D=(0,u.useRef)(new Map),O=Q(),k=(0,u.useRef)(O);k.current=O;let A=(0,u.useRef)(null),j=(0,u.useRef)(!1),N=(0,u.useRef)(null),P=()=>{N.current?.abort()},F=(0,l.useAIProviderRegistry)()?.registry??{},I=r&&c?(0,l.parseAIModelRef)(c):null,L=I?F[I.provider]:null,R=e.executor,z=!!R,[ee,H]=(0,u.useState)([]),[te,U]=(0,u.useState)(``),W=(0,u.useRef)(``),G=e=>{W.current=e,U(e)},K=e=>{H(R?.models?.(e)??[]),G(R?.defaultModel?.(e)??``)},q=async(e,t,n,r)=>{let i=A.current;if(!i||!R)return y(k.current.noActiveSession),null;let a=new AbortController;N.current=a;let o=crypto.randomUUID();E(e=>[...e,{id:o,kind:`thinking`,label:k.current.thinking,status:`running`,parts:[]}]);let s=new Map,c=e=>Math.max(1,Math.round((Date.now()-(s.get(e)??Date.now()))/1e3)),l=e=>({...e,streaming:!1,duration:e.duration??c(e.id)}),u=(e,t)=>E(n=>n.map(n=>{if(n.id!==o)return n;let r=e(n.parts??[]),i=h(r);return{...n,parts:r,...t?{status:t}:{},...i?{detail:i}:{}}})),d=e=>u(t=>m(t,e,l)),p=!1,g=(e,t)=>{t?.id&&t.id!==`text`&&(p=!0),d({type:`text`,id:t?.id??`text`,text:e,streaming:!t?.done})},_=(e,t)=>{let n=t?.id??`reasoning`;s.has(n)||s.set(n,Date.now()),d({type:`reasoning`,id:n,text:e,streaming:!t?.done,...t?.duration===void 0?t?.done?{duration:c(n)}:{}:{duration:t.duration}})},v=e=>d({type:`tool`,id:e.id,label:e.label,status:e.status}),b=new Set,x=0,S=()=>{for(let e of b){let t=D.current.get(e);D.current.delete(e),t?.reject(new DOMException(`The turn was stopped.`,`AbortError`))}b.clear()};a.signal.addEventListener(`abort`,S);let C=(e,t)=>{x+=1;let n=t?.id??`questions-${x}`;d({type:`questions`,id:n,questions:e});let r=`${o}:${n}`;return a.signal.aborted?Promise.reject(new DOMException(`The turn was stopped.`,`AbortError`)):(b.add(r),new Promise((e,t)=>{D.current.set(r,{resolve:e,reject:t})}))},w=(e,t)=>{u(n=>(t&&!p?m(n,{type:`text`,id:f,text:t,streaming:!1},l):n).map(t=>t.type===`reasoning`&&t.streaming?l(t):t.type===`text`&&t.streaming?{...t,streaming:!1}:t.type===`tool`&&t.status===`running`&&e!==`done`?{...t,status:`stopped`}:t),e),a.signal.removeEventListener(`abort`,S);for(let e of b)D.current.delete(e);b.clear()},T=e||r?.historyText||``;try{let o=await R.turn({params:i.params,context:i.context,text:e,first:t,signal:a.signal,...n||W.current?{model:n||W.current}:{},...r?{answers:{id:r.id,answers:r.answers}}:{},onText:g,onReasoning:_,onStep:v,onQuestions:C});return w(`done`,o.text),i.history=[...i.history,...T?[{role:`user`,content:T}]:[],{role:`assistant`,content:o.text}],o.result??null}catch(e){return i.history=[...i.history,...T?[{role:`user`,content:T}]:[]],a.signal.aborted?(w(`stopped`),null):(w(`error`),y(V(e)),null)}finally{N.current=null}},J=async(e,t,n)=>{let r=w.current.find(t=>t.id===e)?.parts?.find(e=>e.type===`questions`&&e.id===t);if(!r||r.type!==`questions`)throw y(k.current.noActiveSession),Error(k.current.noActiveSession);let i=()=>E(r=>r.map(r=>r.id===e?{...r,parts:r.parts?.map(e=>e.type===`questions`&&e.id===t?{...e,answers:n}:e)}:r)),a=`${e}:${t}`,o=D.current.get(a);if(o)return D.current.delete(a),i(),o.resolve(n),null;if(j.current)throw y(k.current.requestInProgress),Error(k.current.requestInProgress);if(!z||!A.current)throw y(k.current.noActiveSession),Error(k.current.noActiveSession);j.current=!0,_(!0),y(null),i();try{return await q(``,!1,void 0,{id:t,answers:n,historyText:g(r.questions,n)})}finally{j.current=!1,_(!1)}},Y=async(t,n,r)=>{let i=A.current;if(!i)return y(k.current.noActiveSession),null;let a=r?(0,l.parseAIModelRef)(r):I,o=a?F[a.provider]:null;if(!o||!a)return y(k.current.noProviderAvailable),null;n?.length&&(i.attachmentsRef.current=[...i.attachmentsRef.current??[],...n]);let s=(n??[]).filter(e=>l.PromptUtils.isTextAttachment(e.mimeType)).map(e=>e.base64.length<=Je?`\n\n[File allegato: ${e.name}]\n${l.PromptUtils.decodeBase64Text(e.base64)}`:`\n\n[File allegato: ${e.name} — troppo grande per essere incollato qui. Usa uno dei tool di lettura file disponibili (es. list_csv_columns/extract_csv_column) per leggerne il contenuto prima di chiedere altro all'utente.]`).join(``),c=Ye(n??[]),u=i.tools.map(e=>({name:e.name,description:e.description,inputSchema:T(e.inputSchema)})),d=new Map(i.tools.map(e=>[e.name,e])),f=new AbortController;N.current=f;let p=(e,t,n,r)=>E(i=>i.map(i=>i.id===e?{...i,status:t,...n===void 0?{}:{detail:n},...r===void 0?{}:{toolNames:r}}:i));try{let n=i.history,r=t;for(let t=0;t<qe;t++){let l=crypto.randomUUID();E(e=>[...e,{id:l,kind:`thinking`,label:k.current.thinking,status:`running`}]);let m;try{m=await o.complete({prompt:r,model:a.model,history:n,tools:u.length?u:void 0,signal:f.signal,attachments:t===0?c:void 0,logId:i.logId})}catch(t){return i.history=[...n,...r?[{role:`user`,content:r+s}]:[]],f.signal.aborted?(p(l,`stopped`),e.fallback(i.params,i.context)):(p(l,`error`),y(V(t)),null)}if(i.history=[...n,...r?[{role:`user`,content:r+s}]:[]],!m)return f.signal.aborted?(p(l,`stopped`),e.fallback(i.params,i.context)):(p(l,`error`),y(k.current.noProviderResponse),null);if(m.type===`text`)return p(l,`done`,m.text),i.history=[...n,...r?[{role:`user`,content:r+s}]:[],{role:`assistant`,content:m.text}],e.parseResponse(m.text,i.params,i.context)||(console.error(`[useAgent] parseResponse ha restituito null — la risposta del modello non è nel formato atteso da questo subagent. Uso il fallback deterministico.`,{responseLength:m.text.length,responsePreview:m.text.length>2e3?`${m.text.slice(0,1e3)}\n…[troncato qui nel log, ${m.text.length} caratteri totali]…\n${m.text.slice(-1e3)}`:m.text,params:i.params}),y(k.current.invalidResponse),e.fallback(i.params,i.context));let h=m.toolCalls.map(e=>{let t=d.get(e.name);return t?.describeIntent??t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`});p(l,`done`,m.text||void 0,m.text?void 0:h);let g=await Promise.all(m.toolCalls.map(async e=>{let t=d.get(e.name),n=t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`;if(E(t=>[...t,{id:e.id,kind:`tool`,label:n,status:`running`}]),!t)return p(e.id,`error`),{toolCallId:e.id,name:e.name,output:`Tool sconosciuto: ${e.name}`,isError:!0};try{let n=await t.execute(e.input);return p(e.id,`done`),{toolCallId:e.id,name:e.name,output:n}}catch(t){return p(e.id,`error`),{toolCallId:e.id,name:e.name,output:V(t),isError:!0}}}));n=[...n,...r?[{role:`user`,content:r+s}]:[],{role:`assistant`,content:m.text,toolCalls:m.toolCalls},{role:`tool_result`,results:g}],r=``}let l=crypto.randomUUID();E(e=>[...e,{id:l,kind:`thinking`,label:k.current.thinking,status:`running`}]);let m;try{m=await o.complete({prompt:B(M().stopCallingTools,e.microPromptIds),model:a.model,history:n,signal:f.signal,logId:i.logId})}catch{m=null}if(m?.type===`text`){p(l,`done`,m.text),i.history=[...n,{role:`assistant`,content:m.text}];let t=e.parseResponse(m.text,i.params,i.context);if(t)return t}else p(l,f.signal.aborted?`stopped`:`error`),i.history=n;return f.signal.aborted||y(k.current.tooManyToolTurns),e.fallback(i.params,i.context)}finally{N.current=null}};return{enabled:r,setEnabled:i,hasProviders:a,selectedModel:z?te:c,setSelectedModel:z?G:d,modelsByProvider:o,modelsLoading:s,running:p,error:v,canContinue:b,remote:z,remoteModels:ee,activity:S,run:async(t,n)=>{if(j.current)return y(k.current.requestInProgress),null;j.current=!0,y(null),E(n?.openingMessage?[{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:n.openingMessage,...n.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]:[]),_(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];if(A.current={params:t,context:i,tools:o,history:[],logId:crypto.randomUUID(),attachmentsRef:a},z)return x(!0),K(t),await q(n?.openingMessage??``,!0);let s=n?.model||void 0,c=s?!!F[(0,l.parseAIModelRef)(s)?.provider??``]:!!L;if(!r||!c){x(!1);let n=e.fallback(t,i);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.aiDisabledFallback}]),n}x(!0);let u=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,d=B(e.buildPrompt(t,i),e.microPromptIds);return await Y(d,u,s)}catch(e){return y(V(e)),null}finally{j.current=!1,_(!1)}},resume:async(t,n)=>{if(j.current){y(k.current.requestInProgress);return}j.current=!0,y(null),E(n.activity),_(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];A.current={params:t,context:i,tools:o,history:n.history,logId:crypto.randomUUID(),attachmentsRef:a},z&&K(t),x(z||r&&!!L)}catch(e){y(V(e))}finally{j.current=!1,_(!1)}},sendMessage:async(t,n)=>{if(j.current)return y(k.current.requestInProgress),null;if(y(null),!t.trim())return y(`Messaggio vuoto.`),null;let r=A.current;if(!r)return y(k.current.noActiveSession),null;j.current=!0,_(!0),E(e=>[...e,{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:t,...n?.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]);try{if(z)return await q(t,!1,n?.model||void 0);let i=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,a=B(e.buildFollowUpPrompt(t,r.params,r.context),e.microPromptIds);return await Y(a,i,n?.model||void 0)}catch(e){return y(V(e)),null}finally{j.current=!1,_(!1)}},stop:P,runFallback:()=>{let t=A.current;if(!t)return null;y(null);let n=e.fallback(t.params,t.context);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.continueWithoutAiFallback}]),n},snapshot:()=>A.current?{history:A.current.history,activity:S}:null,answerQuestions:J}}function Ze(){let e=M();return[e.responseRulesHeading,...e.responseRules.map(e=>`- ${e}`)].join(`
|
|
9
|
+
`)}var z={id:`closing-summary`,get text(){return M().closingSummary}},B={[z.id]:z};function V(e,t){if(!t||t.length===0)return e;let n=t.map(e=>B[e]?.text).filter(e=>!!e);return n.length===0?e:`${e}\n\n${n.join(`
|
|
10
|
+
`)}`}function H(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 U(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 ee(n)??n}function ee(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 J(){return{[G.id]:G,...K}}var Y=`llmnative.agentico.entityChat`;function te(e){Y=e.storageKey}function ne(e){if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.entityId!=`string`)return null;let n=t.scopeId??t.tenantId;if(typeof n!=`string`)return null;let{tenantId:r,...i}=t;return{...i,scopeId:n}}function X(){try{let e=localStorage.getItem(Y);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.map(ne).filter(e=>e!==null):[]}catch{return[]}}function re(e){try{localStorage.setItem(Y,JSON.stringify(e))}catch{}}var Z=(e,t,n)=>`${e}:${t}:${n}`;function ie(e,t,n){let r=Z(e,t,n);return X().find(e=>Z(e.scopeId,e.subagentId,e.entityId)===r)??null}function ae(e){let t=Z(e.scopeId,e.subagentId,e.entityId),n=X().filter(e=>Z(e.scopeId,e.subagentId,e.entityId)!==t);n.push({...e,savedAt:Date.now()}),re(n)}function oe(e,t,n){let r=Z(e,t,n);re(X().filter(e=>Z(e.scopeId,e.subagentId,e.entityId)!==r))}function se(e){return X().filter(t=>t.scopeId===e).sort((e,t)=>t.savedAt-e.savedAt)}var ce=(e,t)=>`entitychat-${e}-${t}`,le={modelLabel:`Modell`,modelsLoading:`Wird geladen…`,noModelsAvailable:`Keine Modelle verfügbar`,noProviderConnected:`Kein AI-Provider verbunden`,selectModelPlaceholder:`Modell wählen…`,orchestratorStarterHint:`Sag Agentico, was du erreichen willst — es wählt das passende Werkzeug und fragt nach den nötigen Angaben.`,orchestratorStarterPlaceholder:`Beschreibe, was du tun möchtest…`,destinationPickerTitle:`Ergebnis speichern in…`,destinationApplying:`Wird gespeichert…`,destinationNoScope:`Kein Ziel ausgewählt — vor dem Speichern eines auswählen.`,unknownDestination:`Unbekanntes Ziel: {id}`,exportJson:`Als JSON exportieren`,orchestratorUnavailable:`AI nicht verfügbar — öffne das benötigte Werkzeug direkt auf seiner Seite.`,orchestratorContinueWithoutAi:`Weiter ohne AI.`,orchestratorPreparing:`{label} wird vorbereitet…`,orchestratorCollecting:`Parameter für {label} werden gesammelt…`,thinking:`Denke nach…`,stopped:`Vom Benutzer abgebrochen.`,toolRequest:`Werkzeugausführung angefordert`,modelRequestError:`Fehler bei der Anfrage an das Modell`,noProviderResponse:`Keine Antwort vom AI-Provider.`,noActiveSession:`Keine aktive Sitzung — zuerst run() aufrufen.`,requestInProgress:`Eine andere Anfrage läuft bereits.`,invalidResponse:`Ungültige AI-Antwort.`,responseReceived:`Antwort erhalten`,noProviderAvailable:`Kein AI-Provider verfügbar.`,tooManyToolTurns:`Zu viele aufeinanderfolgende Werkzeugaufrufe — das bisher gesammelte deterministische Ergebnis wird verwendet.`,aiDisabledFallback:`AI deaktiviert — das deterministische Ergebnis wird verwendet.`,continueWithoutAiFallback:`Weiter ohne AI — das deterministische Ergebnis wird verwendet.`,oneStep:`1 Schritt`,steps:`{count} Schritte`,stepsLabel:`Schritte des Agenten`,newInstance:`Neue Instanz von "{label}"`,chatHistory:`Chatverlauf`,newChat:`Neuer Chat`,searchChats:`Chats durchsuchen…`,messagePlaceholder:`Nachricht schreiben…`,unsavedConversationConfirm:`Diese Unterhaltung wurde nicht gespeichert und geht verloren. Fortfahren?`,noSavedChats:`Noch keine gespeicherten Chats.`,archiveChat:`Archivieren`,noResults:`Keine Ergebnisse.`,retry:`Erneut versuchen`,retryMessage:`Erneut versuchen.`,continueWithoutAi:`Ohne AI fortfahren`,resumeWithAi:`Mit AI fortsetzen`,openPanel:`Agentenbereich öffnen`,closePanel:`Agentenbereich schließen`,resizePanel:`Agent-Bereich in der Größe ändern`,resizePanelHint:`Ziehen zum Ändern der Größe, Doppelklick zum Zurücksetzen`,pendingQuestions:`Fragen des Agenten`,stop:`Stoppen`},ue={modelLabel:`Model`,modelsLoading:`Loading…`,noModelsAvailable:`No models available`,noProviderConnected:`No AI provider connected`,selectModelPlaceholder:`Choose a model…`,orchestratorStarterHint:`Tell Agentico what you want to do — it will pick the right tool and ask for what it needs.`,orchestratorStarterPlaceholder:`Describe what you want to do…`,destinationPickerTitle:`Save result to…`,destinationApplying:`Saving…`,destinationNoScope:`Nothing selected to save into — select one before saving.`,unknownDestination:`Unknown destination: {id}`,exportJson:`Export as JSON`,orchestratorUnavailable:`AI not available — open the tool you need directly from its page.`,orchestratorContinueWithoutAi:`Continuing without AI.`,orchestratorPreparing:`Preparing {label}…`,orchestratorCollecting:`Collecting the parameters for {label}…`,thinking:`Thinking…`,stopped:`Stopped by the user.`,toolRequest:`Requested to run some tools`,modelRequestError:`Error in the request to the model`,noProviderResponse:`No response from the AI provider.`,noActiveSession:`No active session — call run() first.`,requestInProgress:`Another request is already running.`,invalidResponse:`Invalid AI response.`,responseReceived:`Response received`,noProviderAvailable:`No AI provider available.`,tooManyToolTurns:`Too many consecutive tool-calling turns — using the deterministic result collected so far.`,aiDisabledFallback:`AI disabled — using the deterministic result.`,continueWithoutAiFallback:`Continuing without AI — using the deterministic result.`,oneStep:`1 step`,steps:`{count} steps`,stepsLabel:`Steps of the agent`,newInstance:`New "{label}" instance`,chatHistory:`Chat history`,newChat:`New chat`,searchChats:`Search chats…`,messagePlaceholder:`Write a message…`,unsavedConversationConfirm:`This conversation has not been saved and will be lost. Continue?`,noSavedChats:`No saved chats yet.`,archiveChat:`Archive`,noResults:`No results.`,retry:`Retry`,retryMessage:`Retry.`,continueWithoutAi:`Continue without AI`,resumeWithAi:`Resume with AI`,openPanel:`Open agent panel`,closePanel:`Close agent panel`,resizePanel:`Resize the agent panel`,resizePanelHint:`Drag to resize, double-click to reset`,pendingQuestions:`Questions of the agent`,stop:`Stop`},de={modelLabel:`Modello`,modelsLoading:`Caricamento…`,noModelsAvailable:`Nessun modello disponibile`,noProviderConnected:`Nessun provider AI connesso`,selectModelPlaceholder:`Scegli un modello…`,orchestratorStarterHint:`Dì ad Agentico cosa vuoi fare — sceglierà lo strumento giusto e ti chiederà cosa serve.`,orchestratorStarterPlaceholder:`Descrivi cosa vuoi fare…`,destinationPickerTitle:`Salva risultato in…`,destinationApplying:`Salvataggio…`,destinationNoScope:`Nessuna destinazione selezionata — selezionane una prima di salvare.`,unknownDestination:`Destinazione sconosciuta: {id}`,exportJson:`Esporta come JSON`,orchestratorUnavailable:`AI non disponibile — apri il tool che ti serve direttamente dalla sua pagina.`,orchestratorContinueWithoutAi:`Continuo senza AI.`,orchestratorPreparing:`Preparo {label}…`,orchestratorCollecting:`Sto raccogliendo i parametri per {label}…`,thinking:`Sto pensando…`,stopped:`Interrotto dall'utente.`,toolRequest:`Richiesta di eseguire dei tool`,modelRequestError:`Errore nella richiesta al modello`,noProviderResponse:`Nessuna risposta dal provider AI.`,noActiveSession:`Nessuna sessione attiva — chiama prima run().`,requestInProgress:`Un'altra richiesta è già in corso.`,invalidResponse:`Risposta AI non valida.`,responseReceived:`Risposta ricevuta`,noProviderAvailable:`Nessun provider AI disponibile.`,tooManyToolTurns:`Troppi turni di tool-calling consecutivi — uso il risultato deterministico raccolto finora.`,aiDisabledFallback:`AI disabilitata — uso il risultato deterministico.`,continueWithoutAiFallback:`Continuo senza AI — uso il risultato deterministico.`,oneStep:`1 passo`,steps:`{count} passi`,stepsLabel:`Passi dell'agente`,newInstance:`Nuova istanza di "{label}"`,chatHistory:`Storico chat`,newChat:`Nuova chat`,searchChats:`Cerca nelle chat…`,messagePlaceholder:`Scrivi un messaggio…`,unsavedConversationConfirm:`Questa conversazione non è stata salvata e andrà persa. Continuare?`,noSavedChats:`Nessuna chat salvata ancora.`,archiveChat:`Archivia`,noResults:`Nessun risultato.`,retry:`Riprova`,retryMessage:`Riprova.`,continueWithoutAi:`Continua senza AI`,resumeWithAi:`Riprendi con AI`,openPanel:`Apri pannello agente`,closePanel:`Chiudi pannello agente`,resizePanel:`Ridimensiona il pannello dell'agente`,resizePanelHint:`Trascina per ridimensionare, doppio clic per ripristinare`,pendingQuestions:`Domande dell'agente`,stop:`Ferma`},fe={en:{agentico:ue},it:{agentico:de},de:{agentico:le}};function Q(){let{dict:e}=(0,l.useI18n)(),t=e.agentico;return t?{...ue,...t}:ue}var pe=`agentico-orchestrator`,me=(0,u.createContext)(null);function he({children:e,scope:t=null}){let[n,r]=(0,u.useState)(null),i=(0,u.useRef)(null);(0,u.useEffect)(()=>{i.current=n},[n]);let[a,o]=(0,u.useState)(!1),s=(0,u.useCallback)(e=>{let t=i.current;t&&t.id!==e.id&&t.onDismiss();let n=t&&t.id===e.id&&t.savedToDisk&&e.savedToDisk===void 0?{...e,savedToDisk:!0}:e;r(n)},[]),c=(0,u.useCallback)(e=>{r(t=>t&&t.id===e?null:t)},[]),l=(0,u.useCallback)(()=>o(e=>!e),[]),f=(0,u.useCallback)(()=>o(!0),[]),[p,m]=(0,u.useState)(null),[h,g]=(0,u.useState)(void 0),[_,v]=(0,u.useState)(void 0),[y,b]=(0,u.useState)(void 0),[S,C]=(0,u.useState)(null),[w,T]=(0,u.useState)(null),[E,D]=(0,u.useState)(void 0),[O,k]=(0,u.useState)([]),A=(0,u.useCallback)((e,t,n=null)=>{k(r=>{let i=r.filter(t=>t.id!==e);return t?[...i,{id:e,text:t,card:n}]:i})},[]),j=O.length>0?O[O.length-1]:null,[N,P]=(0,u.useState)([]),F=(0,u.useCallback)((e,t)=>{P(n=>{let r=n.filter(t=>t.id!==e);return t?[...r,{id:e,...t}]:r})},[]),I=(0,u.useMemo)(()=>N.map(e=>({subagentId:e.subagentId,componentKey:e.componentKey,onResult:e.onResult,pinnedEntityId:e.pinnedEntityId})),[N]),L=(0,u.useMemo)(()=>{let e=new Map;for(let t of N)e.set(t.subagentId,{subagentId:t.subagentId,componentKey:t.componentKey,onResult:t.onResult,contextInfo:t.contextInfo});return[...e.values()]},[N]),R=(0,u.useMemo)(()=>L.map(e=>{let t=x(e.subagentId)?.componentContexts?.[e.componentKey];if(!t)return null;let n=e.contextInfo?`${t.agenticoHint}\n${e.contextInfo}`:t.agenticoHint;return{subagentId:e.subagentId,agenticoHint:n,userMessage:t.userMessage}}).filter(e=>e!==null),[L]),z=(0,u.useMemo)(()=>R.map(e=>e.userMessage),[R]),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(`
|
|
11
|
+
`);return`${M().multipleCandidates}\n\n${e}`},[R])??j?.text??null,V=R.length>0?null:j?.card??null,H=(0,u.useMemo)(()=>[...new Set(I.map(e=>e.subagentId))],[I]),U=H.length===1?H[0]:H.length===0?j?.card?.subagentId??null:null,ee=(0,u.useCallback)((e,t)=>{f();let n=i.current;if(n?.id===`agentico-orchestrator`)return;let r=U&&n?.id.startsWith(`subagent-${U}-`)?n:void 0;T(r?{taskId:r.id,activity:[...r.precedingActivity??[],...r.agent.activity]}:null),m(e),g(t?.extraDestinations),v(t?.attachments),b(t?.model),D(t?.scopedSubagentId),C(crypto.randomUUID())},[f,U]),W=(0,u.useCallback)((e,t,n,a,o,s)=>{if(!n||!a)return;let c=i.current;if(!c||c.id!==n)return;let l=c.agent.snapshot();l&&(ae({scopeId:a,subagentId:e,entityId:t,params:o,title:s,history:l.history,activity:[...c.precedingActivity??[],...l.activity]}),r(e=>e&&e.id===n?{...e,savedToDisk:!0}:e))},[]),[G,K]=(0,u.useState)(null),[q,J]=(0,u.useState)(null),Y=(0,u.useCallback)((e,t,n)=>{f(),K({subagentId:e,entityId:t,snapshot:n}),J(crypto.randomUUID())},[f]),[te,ne]=(0,u.useState)(null),[X,re]=(0,u.useState)(null),Z=(0,u.useCallback)((e,t)=>{f(),c(pe),ne({subagentId:e,extraDestinations:t}),re(crypto.randomUUID())},[f,c]),[ie,oe]=(0,u.useState)(null),[se,ce]=(0,u.useState)(null),le=(0,u.useCallback)((e,t,n)=>{ne(null),oe({subagentId:e,params:t,extraDestinations:n}),ce(crypto.randomUUID())},[]),[ue,de]=(0,u.useState)(null),[fe,Q]=(0,u.useState)(null),he=(0,u.useCallback)((e,t,n)=>{f(),de({subagentId:e,params:t,...n}),Q(crypto.randomUUID())},[f]),$=(0,u.useCallback)(()=>{let e=i.current;e&&e.onDismiss()},[]),ge=(0,u.useMemo)(()=>({scope:t,task:n,isOpen:a,openTask:s,closeTask:c,toggleOpen:l,pendingGoal:p,startOrchestrator:ee,pageContext:B,pageContextCard:V,setPageContext:A,scopedSubagentId:U,pendingScopedSubagentId:E,componentAnchors:I,anchoredUserMessages:z,registerComponentAnchor:F,openPanel:f,pendingExtraDestinations:h,pendingAttachments:_,pendingModel:y,orchestratorRunId:S,pendingCarryOver:w,commitEntityChat:W,resumeEntityChat:Y,pendingResume:G,resumeRunId:q,dismissForeignTask:$,pendingManualEntry:te,manualEntryRunId:X,startManualEntry:Z,pendingResumeWithAI:ie,resumeWithAIRunId:se,resumeWithAI:le,startSubagent:he,pendingStart:ue,startRunId:fe}),[t,n,a,s,c,l,p,ee,B,V,A,U,E,I,z,F,f,h,_,y,S,w,W,Y,G,q,$,te,X,Z,ie,se,le,he,ue,fe]);return(0,d.jsx)(me.Provider,{value:ge,children:e})}function $(){let e=(0,u.useContext)(me);if(!e)throw Error(`useAgentico must be used inside AgenticoProvider`);return e}function ge(e){let t=e.search(/[{[]/);if(t===-1)return[{type:`text`,content:e}];let n=e[t],r=n===`{`?`}`:`]`,i=0,a=!1,o=!1,s=-1;for(let c=t;c<e.length;c++){let t=e[c];if(a){o?o=!1:t===`\\`?o=!0:t===`"`&&(a=!1);continue}if(t===`"`){a=!0;continue}if(t===n)i++;else if(t===r&&(i--,i===0)){s=c;break}}let c=s===-1?null:e.slice(t,s+1);if(!c||c.length<60)return[{type:`text`,content:e}];try{JSON.parse(c)}catch{return[{type:`text`,content:e}]}let l=[];t>0&&l.push({type:`text`,content:e.slice(0,t)}),l.push({type:`code`,content:c,language:`json`});let u=e.slice(s+1);return u.trim()&&l.push(...ge(u)),l}function _e(e){let t=[],n=/```(\w+)?\n?([\s\S]*?)```/g,r=0,i;for(;i=n.exec(e);)i.index>r&&t.push(...ge(e.slice(r,i.index))),t.push({type:`code`,content:i[2].replace(/\n$/,``),language:i[1]}),r=n.lastIndex;return r<e.length&&t.push(...ge(e.slice(r))),t}function ve({content:e,language:t}){let[n,r]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`relative cursor-pointer rounded-md ${n?`max-h-80 overflow-y-auto`:`max-h-28 overflow-hidden`}`,onClick:()=>r(e=>!e),title:n?`Clic per comprimere`:`Clic per espandere`,children:[(0,d.jsx)(l.Code,{language:t,showCopy:n,background:`transparent`,className:`!text-[11px]`,children:e}),!n&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-muted/30 to-transparent`})]})}function ye({text:e,tone:t}){let n=_e(e);return(0,d.jsx)(d.Fragment,{children:n.map((e,n)=>e.type===`code`?(0,d.jsx)(ve,{content:e.content,language:e.language},n):e.content.trim()&&(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:t,className:`break-words text-xs leading-relaxed`},n))})}function be({status:e}){return e===`running`?(0,d.jsx)(`span`,{className:`inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-2 border-current border-t-transparent`}):e===`done`?(0,d.jsx)(l.Icon,{name:`check`,size:12,className:`shrink-0 text-green-600`}):e===`stopped`?(0,d.jsx)(l.Icon,{name:`circle-slash`,size:12,className:`shrink-0 text-muted-foreground`}):(0,d.jsx)(l.Icon,{name:`x`,size:12,className:`shrink-0 text-destructive`})}function xe(e,t){return e.status===`running`?t.thinking:e.status===`error`?t.modelRequestError:e.status===`stopped`?t.stopped:e.detail?t.responseReceived:e.toolNames&&e.toolNames.length>0?e.toolNames.join(` · `):t.toolRequest}var Se=96;function Ce({entry:e,pinned:t=!0}){let n=(0,u.useRef)(null),[r,i]=(0,u.useState)(!1),[a,o]=(0,u.useState)(!1);(0,u.useLayoutEffect)(()=>{let e=n.current;e&&o(e.scrollHeight>97)},[e.detail,e.attachmentNames]);let s=a&&!r;return(0,d.jsx)(`div`,{className:`${t?`sticky top-0 z-20 border-b border-border/40`:``} flex justify-end bg-background py-1.5`,children:(0,d.jsxs)(`div`,{className:`max-w-[85%] rounded-lg bg-primary/10 text-xs text-foreground`,children:[(0,d.jsxs)(`div`,{ref:n,className:`space-y-1 px-2.5 pt-1.5 ${s?`overflow-hidden`:``}`,style:s?{maxHeight:Se}:void 0,children:[e.attachmentNames&&e.attachmentNames.length>0&&(0,d.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.attachmentNames.map((e,t)=>(0,d.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md bg-primary/15 px-1.5 py-0.5 text-[11px] text-foreground`,children:[(0,d.jsx)(l.Icon,{name:`paperclip`,size:10,className:`shrink-0`}),(0,d.jsx)(`span`,{className:`max-w-[160px] truncate`,children:e})]},t))}),(0,d.jsx)(ye,{text:e.detail??``})]}),a&&(0,d.jsxs)(`button`,{type:`button`,onClick:()=>i(e=>!e),className:`relative flex w-full items-center justify-center rounded-b-lg py-1 text-muted-foreground hover:bg-primary/15`,title:r?`Comprimi`:`Espandi`,children:[s&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 -top-4 h-4 bg-gradient-to-t from-primary/10 to-transparent`}),(0,d.jsx)(l.Icon,{name:r?`chevron-up`:`chevron-down`,size:12})]})]})})}var we={running:`loader-circle`,done:`check`,error:`x`,stopped:`circle-slash`};function Te({steps:e}){let t=Q(),n=e.filter(e=>e.status===`running`).at(-1),r=e.some(e=>e.status===`error`),i=n?.label??(e.length===1?t.oneStep:(0,l.interpolate)(t.steps,{count:e.length}));return(0,d.jsx)(l.Tree,{ariaLabel:t.stepsLabel,selectedId:null,itemClassName:`py-0.5 text-xs text-muted-foreground`,nodes:[{id:`steps-${e[0]?.id??``}`,label:i,icon:n?`loader-circle`:r?`circle-alert`:`list-checks`,children:e.map(e=>({id:e.id,label:(0,d.jsx)(`span`,{className:e.status===`error`?`text-destructive`:void 0,children:e.label}),icon:we[e.status]}))}]})}function Ee(e,t){let n=e.at(-1);if(!n||n.kind!==`thinking`||!n.parts||n.status===`stopped`||n.status===`error`)return null;let r=[...n.parts].reverse().find(e=>e.type===`questions`);return!r||r.answers||!t(n.id)?null:{entry:n,part:r}}function De({entry:e,part:t,questions:n,autoFocus:r,className:i}){let a=!!n?.canAnswer(e.id);return(0,d.jsx)(l.ChatQuestions,{questions:t.questions,...t.answers?{answers:t.answers}:{},disabled:!t.answers&&!a,onSubmit:n&&a?r=>n.onAnswer(e.id,t.id,r):void 0,autoFocus:r,className:i??`text-xs`})}function Oe({entry:e,questions:t,hiddenPartId:n}){let r=(e.parts??[]).filter(e=>e.type!==`questions`||e.id!==n),i=[];for(let e of r){let t=i.at(-1);e.type===`tool`?t&&`steps`in t?t.steps.push(e):i.push({key:`tool-${e.id}`,steps:[e]}):i.push({key:`${e.type}-${e.id}`,part:e})}return(0,d.jsx)(`div`,{className:`space-y-2`,children:i.map(n=>{if(`steps`in n)return(0,d.jsx)(Te,{steps:n.steps},n.key);let{part:r}=n;return r.type===`text`?r.text.trim()?(0,d.jsx)(l.ChatMarkdown,{content:r.text,streaming:r.streaming,className:`break-words text-xs leading-relaxed text-foreground`},n.key):null:r.type===`reasoning`?(0,d.jsx)(l.ChatReasoning,{content:r.text,streaming:r.streaming,duration:r.duration,className:`my-0`},n.key):(0,d.jsx)(De,{entry:e,part:r,questions:t},n.key)})})}function ke({entry:e,questions:t,hiddenPartId:n}){let r=Q();if(e.kind===`thinking`&&e.parts){let i=e.status===`error`||e.status===`stopped`||e.status===`running`&&e.parts.length===0;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[e.parts.length>0&&(0,d.jsx)(Oe,{entry:e,questions:t,hiddenPartId:n}),i&&(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5 ${e.parts.length>0?`mt-1`:``}`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(be,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:xe(e,r)})]})]})}let i=e.kind===`thinking`&&e.detail?_e(e.detail):[],a=i.filter(e=>e.type===`code`),o=i.filter(e=>e.type===`text`&&e.content.trim()),s=e.kind===`thinking`?xe(e,r):e.label;return(0,d.jsxs)(`li`,{className:`text-xs text-muted-foreground`,children:[(0,d.jsxs)(`div`,{className:`flex items-start gap-1.5`,children:[(0,d.jsx)(`span`,{className:`pt-px`,children:(0,d.jsx)(be,{status:e.status})}),(0,d.jsx)(`span`,{className:`min-w-0 flex-1 whitespace-pre-wrap break-words`,children:s})]}),a.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-1`,children:a.map((e,t)=>(0,d.jsx)(ve,{content:e.content,language:e.language},t))}),o.length>0&&(0,d.jsx)(`div`,{className:`mt-1 ml-[18px] space-y-2`,children:o.map((e,t)=>(0,d.jsx)(l.ChatMarkdown,{content:e.content.trim(),tone:`muted`,className:`break-words text-xs leading-relaxed`},t))})]})}function Ae({activity:e,questions:t,docked:n,pinUserMessages:r=!0}){if(e.length===0)return null;let i=[];for(let t of e)t.kind===`user`||i.length===0?i.push(t.kind===`user`?{user:t,entries:[]}:{entries:[t]}):i[i.length-1].entries.push(t);return(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:i.map(e=>(0,d.jsxs)(`li`,{children:[e.user&&(0,d.jsx)(Ce,{entry:e.user,pinned:r}),e.entries.length>0&&(0,d.jsx)(`ul`,{className:`space-y-0.5`,children:e.entries.map(e=>(0,d.jsx)(ke,{entry:e,questions:t,hiddenPartId:n?.entry.id===e.id?n.part.id:void 0},e.id))})]},e.user?.id??e.entries[0]?.id))})}var je=420,Me=320,Ne=`60vw`,Pe=`agentico:panel-width`;function Fe(e,t){if(typeof e==`number`)return e;let n=Number.parseFloat(e);return Number.isFinite(n)?Math.round(n/100*t):1/0}function Ie(e,t,n){return Math.round(Math.min(Math.max(e,t),Math.max(t,n)))}function Le(){try{let e=window.localStorage.getItem(Pe),t=e===null?NaN:Number(e);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function Re(e){try{e===null?window.localStorage.removeItem(Pe):window.localStorage.setItem(Pe,String(e))}catch{}}function ze(){return typeof window>`u`?1/0:window.innerWidth}function Be({defaultWidth:e=420,minWidth:t=320,maxWidth:n=Ne,onWidthChange:r}){let[i,a]=(0,u.useState)(ze),[o,s]=(0,u.useState)(()=>Le()??e);(0,u.useEffect)(()=>{if(typeof window>`u`)return;let e=()=>a(window.innerWidth);return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let c=t,l=Math.max(c,Fe(n,i)),d=Ie(o,c,l);return(0,u.useEffect)(()=>{r?.(d)},[d]),{width:d,min:c,max:l,set:(0,u.useCallback)(e=>s(Ie(e,c,l)),[c,l]),commit:(0,u.useCallback)(e=>Re(Ie(e,c,l)),[c,l]),reset:(0,u.useCallback)(()=>{s(e),Re(null)},[e])}}function Ve({width:e,min:t,max:n,onResize:r,onCommit:i,onReset:a}){let o=Q(),s=(0,u.useRef)(null),[c,l]=(0,u.useState)(!1),f=e=>Math.round(Math.min(Math.max(e,t),Math.max(t,n))),p=e=>{let t=s.current;if(t&&t.pointerId===e.pointerId){s.current=null,l(!1),document.body.style.removeProperty(`cursor`),document.body.style.removeProperty(`user-select`);try{e.currentTarget.releasePointerCapture(e.pointerId)}catch{}i(t.last)}};return(0,d.jsx)(`div`,{role:`separator`,"aria-orientation":`vertical`,"aria-label":o.resizePanel,"aria-valuenow":e,"aria-valuemin":t,"aria-valuemax":n,tabIndex:0,title:o.resizePanelHint,"data-dragging":c||void 0,className:`group absolute inset-y-0 -left-1 z-30 flex w-2 cursor-col-resize touch-none select-none justify-center outline-none`,onPointerDown:t=>{if(t.button===0){t.preventDefault(),s.current={pointerId:t.pointerId,startX:t.clientX,startWidth:e,last:e},l(!0),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`;try{t.currentTarget.setPointerCapture(t.pointerId)}catch{}}},onPointerMove:e=>{let t=s.current;t&&t.pointerId===e.pointerId&&(t.last=f(t.startWidth+(t.startX-e.clientX)),r(t.last))},onPointerUp:p,onPointerCancel:p,onLostPointerCapture:p,onDoubleClick:a,onKeyDown:a=>{let o=a.shiftKey?64:16,s=null;if(a.key===`ArrowLeft`?s=e+o:a.key===`ArrowRight`?s=e-o:a.key===`Home`?s=t:a.key===`End`&&(s=n),s===null)return;a.preventDefault();let c=f(s);r(c),i(c)},children:(0,d.jsx)(`span`,{"aria-hidden":!0,className:`h-full w-0.5 transition-colors ${c?`bg-primary`:`bg-transparent group-hover:bg-primary/50 group-focus-visible:bg-primary`}`})})}function He({className:e=``}){let{isOpen:t,toggleOpen:n,task:r}=$(),i=Q(),a=r?.agent.running??!1;return(0,d.jsx)(l.ActionButton,{icon:`bot`,ariaLabel:t?i.closePanel:i.openPanel,title:t?i.closePanel:i.openPanel,onClick:n,iconClassName:a?`animate-pulse`:void 0,className:`!h-9 !w-9 !p-0 rounded-md ${t?`bg-primary/10 text-primary hover:bg-primary/15`:`bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground`} ${e}`})}var Ue=`llmnative-cms.selectedAIModel`;function We(){try{return localStorage.getItem(Ue)??``}catch{return``}}function Ge(e){try{e?localStorage.setItem(Ue,e):localStorage.removeItem(Ue)}catch{}}function Ke(){let e=(0,l.useAIProviderRegistry)()?.registry??{},t=Object.keys(e).length>0,[n,r]=(0,u.useState)({}),[i,a]=(0,u.useState)(!1),[o,s]=(0,u.useState)(We);return(0,u.useEffect)(()=>{if(!t){r({});return}let n=!1;return a(!0),(0,l.getAIModelCatalog)(e).then(e=>{if(n)return;r(e.modelsByProvider);let t=Object.values(e.modelsByProvider).flat();s(e=>t.some(t=>t.id===e)?e:(Ge(``),``))}).catch(e=>{console.error(`useAIModelCatalog: getAIModelCatalog failed`,e),n||r({})}).finally(()=>{n||a(!1)}),()=>{n=!0}},[t,JSON.stringify(Object.keys(e).sort())]),{hasProviders:t,modelsByProvider:n,modelsLoading:i,selectedModel:o,setSelectedModel:e=>{Ge(e),s(e)}}}var qe=20,Je=26e4;function Ye(e){return e.filter(e=>!l.PromptUtils.isTextAttachment(e.mimeType)||e.base64.length<=Je)}function Xe(e,t={}){let{defaultEnabled:n=!1}=t,[r,i]=(0,u.useState)(n),{hasProviders:a,modelsByProvider:o,modelsLoading:s,selectedModel:c,setSelectedModel:d}=Ke(),[p,_]=(0,u.useState)(!1),[v,y]=(0,u.useState)(null),[b,x]=(0,u.useState)(!1),[S,C]=(0,u.useState)([]),w=(0,u.useRef)([]),E=e=>{C(t=>{let n=typeof e==`function`?e(t):e;return w.current=n,n})},D=(0,u.useRef)(new Map),O=Q(),k=(0,u.useRef)(O);k.current=O;let A=(0,u.useRef)(null),j=(0,u.useRef)(!1),N=(0,u.useRef)(null),P=()=>{N.current?.abort()},F=(0,l.useAIProviderRegistry)()?.registry??{},I=r&&c?(0,l.parseAIModelRef)(c):null,L=I?F[I.provider]:null,R=e.executor,z=!!R,[B,U]=(0,u.useState)([]),[ee,W]=(0,u.useState)(``),G=(0,u.useRef)(``),K=e=>{G.current=e,W(e)},q=e=>{U(R?.models?.(e)??[]),K(R?.defaultModel?.(e)??``)},J=async(e,t,n,r)=>{let i=A.current;if(!i||!R)return y(k.current.noActiveSession),null;let a=new AbortController;N.current=a;let o=crypto.randomUUID();E(e=>[...e,{id:o,kind:`thinking`,label:k.current.thinking,status:`running`,parts:[]}]);let s=new Map,c=e=>Math.max(1,Math.round((Date.now()-(s.get(e)??Date.now()))/1e3)),l=e=>({...e,streaming:!1,duration:e.duration??c(e.id)}),u=(e,t)=>E(n=>n.map(n=>{if(n.id!==o)return n;let r=e(n.parts??[]),i=h(r);return{...n,parts:r,...t?{status:t}:{},...i?{detail:i}:{}}})),d=e=>u(t=>m(t,e,l)),p=!1,g=(e,t)=>{t?.id&&t.id!==`text`&&(p=!0),d({type:`text`,id:t?.id??`text`,text:e,streaming:!t?.done})},_=(e,t)=>{let n=t?.id??`reasoning`;s.has(n)||s.set(n,Date.now()),d({type:`reasoning`,id:n,text:e,streaming:!t?.done,...t?.duration===void 0?t?.done?{duration:c(n)}:{}:{duration:t.duration}})},v=e=>d({type:`tool`,id:e.id,label:e.label,status:e.status}),b=new Set,x=0,S=()=>{for(let e of b){let t=D.current.get(e);D.current.delete(e),t?.reject(new DOMException(`The turn was stopped.`,`AbortError`))}b.clear()};a.signal.addEventListener(`abort`,S);let C=(e,t)=>{x+=1;let n=t?.id??`questions-${x}`;d({type:`questions`,id:n,questions:e});let r=`${o}:${n}`;return a.signal.aborted?Promise.reject(new DOMException(`The turn was stopped.`,`AbortError`)):(b.add(r),new Promise((e,t)=>{D.current.set(r,{resolve:e,reject:t})}))},w=(e,t)=>{u(n=>(t&&!p?m(n,{type:`text`,id:f,text:t,streaming:!1},l):n).map(t=>t.type===`reasoning`&&t.streaming?l(t):t.type===`text`&&t.streaming?{...t,streaming:!1}:t.type===`tool`&&t.status===`running`&&e!==`done`?{...t,status:`stopped`}:t),e),a.signal.removeEventListener(`abort`,S);for(let e of b)D.current.delete(e);b.clear()},T=e||r?.historyText||``;try{let o=await R.turn({params:i.params,context:i.context,text:e,first:t,signal:a.signal,...n||G.current?{model:n||G.current}:{},...r?{answers:{id:r.id,answers:r.answers}}:{},onText:g,onReasoning:_,onStep:v,onQuestions:C});return w(`done`,o.text),i.history=[...i.history,...T?[{role:`user`,content:T}]:[],{role:`assistant`,content:o.text}],o.result??null}catch(e){return i.history=[...i.history,...T?[{role:`user`,content:T}]:[]],a.signal.aborted?(w(`stopped`),null):(w(`error`),y(H(e)),null)}finally{N.current=null}},Y=async(e,t,n)=>{let r=w.current.find(t=>t.id===e)?.parts?.find(e=>e.type===`questions`&&e.id===t);if(!r||r.type!==`questions`)throw y(k.current.noActiveSession),Error(k.current.noActiveSession);let i=()=>E(r=>r.map(r=>r.id===e?{...r,parts:r.parts?.map(e=>e.type===`questions`&&e.id===t?{...e,answers:n}:e)}:r)),a=`${e}:${t}`,o=D.current.get(a);if(o)return D.current.delete(a),i(),o.resolve(n),null;if(j.current)throw y(k.current.requestInProgress),Error(k.current.requestInProgress);if(!z||!A.current)throw y(k.current.noActiveSession),Error(k.current.noActiveSession);j.current=!0,_(!0),y(null),i();try{return await J(``,!1,void 0,{id:t,answers:n,historyText:g(r.questions,n)})}finally{j.current=!1,_(!1)}},te=async(t,n,r)=>{let i=A.current;if(!i)return y(k.current.noActiveSession),null;let a=r?(0,l.parseAIModelRef)(r):I,o=a?F[a.provider]:null;if(!o||!a)return y(k.current.noProviderAvailable),null;n?.length&&(i.attachmentsRef.current=[...i.attachmentsRef.current??[],...n]);let s=(n??[]).filter(e=>l.PromptUtils.isTextAttachment(e.mimeType)).map(e=>e.base64.length<=Je?`\n\n[File allegato: ${e.name}]\n${l.PromptUtils.decodeBase64Text(e.base64)}`:`\n\n[File allegato: ${e.name} — troppo grande per essere incollato qui. Usa uno dei tool di lettura file disponibili (es. list_csv_columns/extract_csv_column) per leggerne il contenuto prima di chiedere altro all'utente.]`).join(``),c=Ye(n??[]),u=i.tools.map(e=>({name:e.name,description:e.description,inputSchema:T(e.inputSchema)})),d=new Map(i.tools.map(e=>[e.name,e])),f=new AbortController;N.current=f;let p=(e,t,n,r)=>E(i=>i.map(i=>i.id===e?{...i,status:t,...n===void 0?{}:{detail:n},...r===void 0?{}:{toolNames:r}}:i));try{let n=i.history,r=t;for(let t=0;t<qe;t++){let l=crypto.randomUUID();E(e=>[...e,{id:l,kind:`thinking`,label:k.current.thinking,status:`running`}]);let m;try{m=await o.complete({prompt:r,model:a.model,history:n,tools:u.length?u:void 0,signal:f.signal,attachments:t===0?c:void 0,logId:i.logId})}catch(t){return i.history=[...n,...r?[{role:`user`,content:r+s}]:[]],f.signal.aborted?(p(l,`stopped`),e.fallback(i.params,i.context)):(p(l,`error`),y(H(t)),null)}if(i.history=[...n,...r?[{role:`user`,content:r+s}]:[]],!m)return f.signal.aborted?(p(l,`stopped`),e.fallback(i.params,i.context)):(p(l,`error`),y(k.current.noProviderResponse),null);if(m.type===`text`)return p(l,`done`,m.text),e.conversational&&m.text.trim()&&E(e=>e.map(e=>e.id===l?{...e,parts:[{type:`text`,id:`text`,text:m.text}]}:e)),i.history=[...n,...r?[{role:`user`,content:r+s}]:[],{role:`assistant`,content:m.text}],e.parseResponse(m.text,i.params,i.context)||(console.error(`[useAgent] parseResponse ha restituito null — la risposta del modello non è nel formato atteso da questo subagent. Uso il fallback deterministico.`,{responseLength:m.text.length,responsePreview:m.text.length>2e3?`${m.text.slice(0,1e3)}\n…[troncato qui nel log, ${m.text.length} caratteri totali]…\n${m.text.slice(-1e3)}`:m.text,params:i.params}),y(k.current.invalidResponse),e.fallback(i.params,i.context));let h=m.toolCalls.map(e=>{let t=d.get(e.name);return t?.describeIntent??t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`});p(l,`done`,m.text||void 0,m.text?void 0:h);let g=await Promise.all(m.toolCalls.map(async e=>{let t=d.get(e.name),n=t?.describeInvocation?.(e.input)??`Chiamata: ${e.name}`;if(E(t=>[...t,{id:e.id,kind:`tool`,label:n,status:`running`}]),!t)return p(e.id,`error`),{toolCallId:e.id,name:e.name,output:`Tool sconosciuto: ${e.name}`,isError:!0};try{let n=await t.execute(e.input);return p(e.id,`done`),{toolCallId:e.id,name:e.name,output:n}}catch(t){return p(e.id,`error`),{toolCallId:e.id,name:e.name,output:H(t),isError:!0}}}));n=[...n,...r?[{role:`user`,content:r+s}]:[],{role:`assistant`,content:m.text,toolCalls:m.toolCalls},{role:`tool_result`,results:g}],r=``}let l=crypto.randomUUID();E(e=>[...e,{id:l,kind:`thinking`,label:k.current.thinking,status:`running`}]);let m;try{m=await o.complete({prompt:V(M().stopCallingTools,e.microPromptIds),model:a.model,history:n,signal:f.signal,logId:i.logId})}catch{m=null}if(m?.type===`text`){p(l,`done`,m.text),i.history=[...n,{role:`assistant`,content:m.text}];let t=e.parseResponse(m.text,i.params,i.context);if(t)return t}else p(l,f.signal.aborted?`stopped`:`error`),i.history=n;return f.signal.aborted||y(k.current.tooManyToolTurns),e.fallback(i.params,i.context)}finally{N.current=null}};return{enabled:r,setEnabled:i,hasProviders:a,selectedModel:z?ee:c,setSelectedModel:z?K:d,modelsByProvider:o,modelsLoading:s,running:p,error:v,canContinue:b,remote:z,remoteModels:B,activity:S,run:async(t,n)=>{if(j.current)return y(k.current.requestInProgress),null;j.current=!0,y(null),E(n?.openingMessage?[{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:n.openingMessage,...n.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]:[]),_(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];if(A.current={params:t,context:i,tools:o,history:[],logId:crypto.randomUUID(),attachmentsRef:a},z)return x(!0),q(t),await J(n?.openingMessage??``,!0);let s=n?.model||void 0,c=s?!!F[(0,l.parseAIModelRef)(s)?.provider??``]:!!L;if(!r||!c){x(!1);let n=e.fallback(t,i);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.aiDisabledFallback}]),n}x(!0);let u=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,d=V(e.buildPrompt(t,i),e.microPromptIds);return await te(d,u,s)}catch(e){return y(H(e)),null}finally{j.current=!1,_(!1)}},resume:async(t,n)=>{if(j.current){y(k.current.requestInProgress);return}j.current=!0,y(null),E(n.activity),_(!0);try{let i=await e.buildContext(t),a={current:void 0},o=e.getTools?.(t,i,a)??[];A.current={params:t,context:i,tools:o,history:n.history,logId:crypto.randomUUID(),attachmentsRef:a},z&&q(t),x(z||r&&!!L)}catch(e){y(H(e))}finally{j.current=!1,_(!1)}},sendMessage:async(t,n)=>{if(j.current)return y(k.current.requestInProgress),null;if(y(null),!t.trim())return y(`Messaggio vuoto.`),null;let r=A.current;if(!r)return y(k.current.noActiveSession),null;j.current=!0,_(!0),E(e=>[...e,{id:crypto.randomUUID(),kind:`user`,label:`Tu`,status:`done`,detail:t,...n?.attachments?.length?{attachmentNames:n.attachments.map(e=>e.name)}:{}}]);try{if(z)return await J(t,!1,n?.model||void 0);let i=n?.attachments?.length?await Promise.all(n.attachments.map(e=>l.PromptUtils.fileToAttachment(e))):void 0,a=V(e.buildFollowUpPrompt(t,r.params,r.context),e.microPromptIds);return await te(a,i,n?.model||void 0)}catch(e){return y(H(e)),null}finally{j.current=!1,_(!1)}},stop:P,runFallback:()=>{let t=A.current;if(!t)return null;y(null);let n=e.fallback(t.params,t.context);return E(t=>[...t,{id:crypto.randomUUID(),kind:`tool`,status:`done`,label:e.describeFallback?.(n)??k.current.continueWithoutAiFallback}]),n},snapshot:()=>A.current?{history:A.current.history,activity:S}:null,answerQuestions:Y}}function Ze(){let e=M();return[e.responseRulesHeading,...e.responseRules.map(e=>`- ${e}`)].join(`
|
|
12
12
|
`)}function Qe(e,t,n){let r=M(),i=n?`\n${r.pageContextHeading}\n${r.pageContextIntro}\n${n}\n`:``;return`${r.orchestratorIntro}
|
|
13
13
|
|
|
14
14
|
${r.toolsHeading}
|
|
@@ -17,5 +17,5 @@ ${i}
|
|
|
17
17
|
${Ze()}
|
|
18
18
|
|
|
19
19
|
${r.userRequestHeading}
|
|
20
|
-
${e}`}function $e(e,t){return t?{kind:`handoff`,...t}:{kind:`chat`,message:e}}function et(e){return b().filter(t=>!t.onlyWhenAnchored||e===t.id)}function tt(e){return{buildContext(e){return{cliCatalog:R(et(e.scopedSubagentId)),handoff:{current:null},collected:{}}},buildPrompt({userGoal:e,pageContext:t},{cliCatalog:n}){return Qe(e,n,t)},buildFollowUpPrompt(e,t,{cliCatalog:n}){return`${e}\n\n${Ze()}\n\n${M().toolsHeading}\n${n}`},parseResponse(e,t,n){let r=n.handoff.current;return n.handoff.current=null,$e(e,r)},fallback(){return{kind:`chat`,message:e.unavailable}},describeFallback(t){return t.kind===`chat`?t.message:e.continueWithoutAi},getTools(t,n,r){let i=w({attachmentsRef:r,collected:n.collected,proxyFetch:l.proxyFetch}),a=t.scopedSubagentId?x(t.scopedSubagentId):null,o=a?i.filter(e=>(a.crossAgentToolIds??[]).includes(e.name)):i,s=et(t.scopedSubagentId).flatMap(t=>t.commands.map(r=>({name:`${t.id}_${r.name}`,description:`${t.label}: ${r.summary}`,inputSchema:r.inputSchema,describeInvocation:()=>(0,l.interpolate)(e.preparing,{label:t.label}),describeIntent:(0,l.interpolate)(e.collecting,{label:t.label}),async execute(e){let i=t.withCollected?t.withCollected({...e},n.collected):e;return n.handoff.current={subagentId:t.id,command:r.name,params:i},{status:`queued`,note:(0,l.interpolate)(M().handoffQueued,{label:t.label})}}})));return[...o,...s]}}}function nt(e,t){return e.deriveHistoryTitle?.(t)??e.label}function rt({manifest:e,result:t,meta:n,taskId:r,initiallyApplied:i,onApplied:a,extraDestinations:o}){let s=Q(),c=$(),f=c.scope,p=(0,l.useProxy)(),[m,h]=(0,u.useState)(null),[g,_]=(0,u.useState)(new Set(i??[])),[v,y]=(0,u.useState)(null),b=q(),x=new Map;e.destinationIds.forEach(e=>{let t=b[e];t&&x.set(e,t)}),(o??[]).forEach(e=>x.set(e.id,e)),x.set(W.id,W);let S=Array.from(x.values()),C=async i=>{h(i),y(null);try{let o=x.get(i);if(!o)throw Error((0,l.interpolate)(s.unknownDestination,{id:i}));if(i!==`json-export`&&!f)throw Error(s.destinationNoScope);let u=await o.apply(t,{scopeId:f?.id??``,dataProvider:f?.dataProvider,storageProvider:f?.storageProvider??null,proxyFetch:p},n);_(e=>new Set(e).add(i)),a?.(i),u?.id&&c.commitEntityChat(e.id,u.id,r,f?.id,n,nt(e,n))}catch(e){y(e instanceof Error?e.message:String(e))}finally{h(null)}};return(0,d.jsxs)(`div`,{className:`space-y-2`,children:[(0,d.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:s.destinationPickerTitle}),(0,d.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:S.map(e=>(0,d.jsx)(`button`,{type:`button`,disabled:m!==null,onClick:()=>void C(e.id),className:`cursor-pointer rounded-md border border-input bg-background px-2.5 py-1.5 text-xs font-medium transition-colors hover:bg-accent hover:text-accent-foreground disabled:cursor-not-allowed disabled:opacity-60`,children:m===e.id?s.destinationApplying:`${g.has(e.id)?`✓ `:``}${e.id===`json-export`?s.exportJson:e.label}`},e.id))}),v&&(0,d.jsx)(`p`,{className:`text-xs text-destructive`,children:v})]})}var it={};function at(e){Object.assign(it,e)}function ot(e){return it[e]}function st({result:e}){let[t,n]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`relative cursor-pointer rounded-md border border-border/60 ${t?`max-h-80 overflow-y-auto`:`max-h-28 overflow-hidden`}`,onClick:()=>n(e=>!e),title:t?`Clic per comprimere`:`Clic per espandere`,children:[(0,d.jsx)(l.Code,{language:`json`,showCopy:t,background:`transparent`,className:`!text-[11px]`,children:JSON.stringify(e,null,2)}),!t&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-muted/30 to-transparent`})]})}function ct(e,t,n){return e.length===0?null:{id:`live-component`,label:`Applica al componente aperto`,async apply(r){e.forEach(e=>e.onResult?.(r,t,n))}}}var lt={};function ut(e){Object.assign(lt,e)}function dt(e){return lt[e]}var ft=()=>({});function pt({manifest:e,params:t,extraDestinations:n,precedingActivity:r,taskId:i,resumeSeed:a,model:o,openingMessage:s}){let c=Xe(e.definition,{defaultEnabled:!0}),f=$(),p=f.scope,m=(0,l.useProxy)(),h=(0,u.useRef)(i??`subagent-${e.id}-${crypto.randomUUID()}`).current,[g,_]=(0,u.useState)(null),[v,y]=(0,u.useState)([]),[b,x]=(0,u.useState)(null),S=ot(e.id),C=S?.kind===`selection`?S:null,[w,T]=(0,u.useState)(null),E=(0,u.useRef)(!1),D=(0,u.useRef)(0),O=(0,u.useRef)(null);g&&g!==O.current&&(O.current=g,D.current=(r?.length??0)+c.activity.length);let k=(0,u.useRef)(!1),A=c.remote||!c.hasProviders||c.selectedModel!==``;(0,u.useEffect)(()=>{!E.current&&A&&(E.current=!0,a?c.resume(e.toParams(t),a):(o&&c.setSelectedModel(o),c.run(e.toParams(t),{model:o,openingMessage:s}).then(e=>{e&&_(e)})))},[A]),(0,u.useEffect)(()=>{if(!g||!p)return;let n=e.autoApplyDestinationIds??[],r=f.componentAnchors.find(t=>t.subagentId===e.id&&t.pinnedEntityId)?.pinnedEntityId,i=q();n.forEach(n=>{let a=i[n];a&&(x(null),a.apply(g,{scopeId:p.id,dataProvider:p.dataProvider,storageProvider:p.storageProvider,proxyFetch:m},{...t,pinnedEntityId:r}).then(n=>{n?.id&&f.commitEntityChat(e.id,n.id,h,p.id,t,nt(e,t))}).catch(e=>x(e instanceof Error?e.message:String(e))))})},[g,c.activity,p]),(0,u.useEffect)(()=>{g&&C&&T(C.defaultSelection(g))},[g,C]);let j=(e,t)=>{T(n=>n&&{...n,[e]:t})},M=e=>_(e),N=(0,u.useMemo)(()=>g&&C&&w?C.applySelection(g,w):g,[g,C,w]),P=(0,u.useMemo)(()=>f.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[f.componentAnchors,e.id]),F=(0,u.useMemo)(()=>ct(P,t,h),[P,t,h]),I=(0,u.useMemo)(()=>F?[F,...n??[]]:n,[F,n]),L=e.chatEntityId?.(t),R=(0,u.useRef)(!1);(0,u.useEffect)(()=>{let n=R.current&&!c.running;if(R.current=c.running,!n||!L||!p)return;let i=c.snapshot();i&&ae({scopeId:p.id,subagentId:e.id,entityId:L,params:t,title:nt(e,t),history:i.history,activity:[...r??[],...i.activity]})},[c.running]);let z=()=>{k.current=!0,c.running&&c.stop(),f.closeTask(h)},ee=(0,u.useRef)(dt(e.id)??ft).current,B=ee({params:t,taskId:h,running:c.running,close:z}),V=e=>{y(t=>t.includes(e)?t:[...t,e])};return(0,u.useEffect)(()=>{k.current||f.openTask({id:h,title:nt(e,t),icon:e.icon,agent:c,onApplied:e=>_(e),precedingActivity:r,panelExtraAnchorIndex:D.current,onDismiss:z,...L?{savedToDisk:!0}:{},panelActions:B.content,composerActions:B.actions,composerCommands:B.commands,panelExtra:g?(0,d.jsxs)(d.Fragment,{children:[C&&w?(0,d.jsx)(C.Report,{result:g,selection:w,onChange:j}):S?.kind===`editable`?(0,d.jsx)(S.Report,{result:g,onResultChange:M}):(0,d.jsx)(st,{result:N}),b&&(0,d.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Salvataggio automatico non riuscito: `,b]}),(0,d.jsx)(rt,{manifest:e,result:N,meta:t,taskId:h,initiallyApplied:v,onApplied:V,extraDestinations:I})]}):void 0})},[c.activity,c.running,c.error,c.canContinue,c.selectedModel,c.modelsByProvider,c.hasProviders,c.remoteModels,f.openTask,f.componentAnchors,h,e,t,g,N,w,v,n,r,b,B.content,B.actions,B.commands]),(0,u.useEffect)(()=>()=>{f.closeTask(h)},[f.closeTask,h]),null}function mt({userGoal:e}){let t=Q(),n=Xe((0,u.useMemo)(()=>tt({unavailable:t.orchestratorUnavailable,continueWithoutAi:t.orchestratorContinueWithoutAi,preparing:t.orchestratorPreparing,collecting:t.orchestratorCollecting}),[]),{defaultEnabled:!0}),r=$(),[i,a]=(0,u.useState)(null),o=(0,u.useRef)(!1),s=!n.hasProviders||n.selectedModel!==``,c=(0,u.useRef)(r.pendingExtraDestinations),l=(0,u.useRef)(r.pendingAttachments),f=(0,u.useRef)(r.pendingModel),p=(0,u.useRef)(r.pendingScopedSubagentId??r.scopedSubagentId??void 0),m=(0,u.useRef)(r.pendingCarryOver),h=(0,u.useRef)(!1),g=e=>{e&&typeof e==`object`&&e.kind===`handoff`&&(a(e),r.closeTask(pe))};(0,u.useEffect)(()=>{!o.current&&s&&(o.current=!0,f.current&&n.setSelectedModel(f.current),n.run({userGoal:e,pageContext:r.pageContext,scopedSubagentId:p.current??null},{attachments:l.current,model:f.current,openingMessage:e}).then(e=>{e&&g(e)}))},[s]),(0,u.useEffect)(()=>{h.current||r.openTask({id:pe,title:`Agentico`,icon:`bot`,agent:n,onApplied:g,scopedSubagentId:p.current,precedingActivity:m.current?.activity,onDismiss:()=>{h.current=!0,n.running&&n.stop(),r.closeTask(pe)}})},[n.activity,n.running,n.error,n.canContinue,n.selectedModel,n.modelsByProvider,n.hasProviders,r.openTask]),(0,u.useEffect)(()=>()=>{r.closeTask(pe)},[r.closeTask]);let _=(0,u.useMemo)(()=>[...m.current?.activity??[],...n.activity],[n.activity]);if(!i)return null;let v=x(i.subagentId);return v?(0,d.jsx)(pt,{manifest:v,params:i.params,extraDestinations:c.current,model:f.current||void 0,taskId:m.current?.taskId,precedingActivity:_}):null}function ht({manifest:e,extraDestinations:t}){let n=Xe(e.definition,{defaultEnabled:!1}),r=Q(),i=$(),a=(0,u.useRef)(`manual-${e.id}-${crypto.randomUUID()}`).current,[o,s]=(0,u.useState)(null),[c,f]=(0,u.useState)([]),p=ot(e.id),m=p?.kind===`selection`?p:null,[h,g]=(0,u.useState)(null),[_,v]=(0,u.useState)(null),y=(0,u.useRef)(!1),b=t=>{if(!e.manualEntry)return;let r;try{r=e.manualEntry.fromRawText(t)}catch(e){console.error(`[ManualEntryRunner] manualEntry.fromRawText ha rifiutato il testo:`,e);return}v(r),f([]),n.run(r,{openingMessage:t}).then(e=>{e&&s(e)})};(0,u.useEffect)(()=>{o&&m&&g(m.defaultSelection(o))},[o,m]);let x=(e,t)=>{g(n=>n&&{...n,[e]:t})},S=e=>s(e),C=(0,u.useMemo)(()=>o&&m&&h?m.applySelection(o,h):o,[o,m,h]),w=e=>{f(t=>t.includes(e)?t:[...t,e])},T=(0,u.useMemo)(()=>i.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[i.componentAnchors,e.id]),E=(0,u.useMemo)(()=>_?ct(T,_,a):null,[T,_,a]),D=(0,u.useMemo)(()=>E?[E,...t??[]]:t,[E,t]);return(0,u.useEffect)(()=>{y.current||i.openTask({id:a,title:e.label,icon:e.icon,agent:n,onApplied:e=>s(e),manualEntry:e.manualEntry?{prompt:e.manualEntry.prompt,onSubmit:b}:void 0,onDismiss:()=>{y.current=!0,n.running&&n.stop(),i.closeTask(a)},panelExtra:o?(0,d.jsxs)(`div`,{className:`space-y-2`,children:[m&&h?(0,d.jsx)(m.Report,{result:o,selection:h,onChange:x}):p?.kind===`editable`?(0,d.jsx)(p.Report,{result:o,onResultChange:S}):(0,d.jsx)(st,{result:C}),(0,d.jsx)(rt,{manifest:e,result:C,meta:_??{},taskId:a,initiallyApplied:c,onApplied:w,extraDestinations:D}),n.hasProviders&&(0,d.jsx)(l.ActionButton,{label:r.resumeWithAi,variant:`outline-secondary`,className:`text-xs`,onClick:()=>{_&&i.resumeWithAI(e.id,_,t)}})]}):void 0})},[n.activity,n.running,n.error,n.hasProviders,i.componentAnchors,o,C,h,c,_]),(0,u.useEffect)(()=>()=>{i.closeTask(a)},[]),null}function gt(e){return Object.values(e).flat().map(e=>({label:e.model,value:e.id,pricing:e.pricing??null,group:e.providerLabel??e.provider}))}function _t({task:e}){let t=Q(),[n,r]=(0,u.useState)(``),{agent:i,onApplied:a,manualEntry:o}=e,s=i.running,c=e=>{if(r(``),o){o.onSubmit(e.text);return}i.sendMessage(e.text,{attachments:e.files,model:e.model}).then(e=>{e&&a(e)})},f=!!o||i.remote&&i.remoteModels.length===0,p=!f&&!i.remote&&i.hasProviders&&!i.selectedModel,m=f?[]:i.remote?i.remoteModels:gt(i.modelsByProvider);return(0,d.jsx)(l.Chatbot,{value:n,onChange:r,placeholder:o?.prompt??t.messagePlaceholder,running:s,onStop:i.stop,disabled:!n.trim()||p,onSubmit:c,attachments:!o&&!i.remote,models:m,selectedModel:f?``:i.selectedModel,actions:e.composerActions,commands:e.composerCommands,onModelChange:i.setSelectedModel,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function vt(){let{startOrchestrator:e}=$(),t=Q(),[n,r]=(0,u.useState)(``),{hasProviders:i,modelsByProvider:a,selectedModel:o,setSelectedModel:s}=Ke(),c=t=>{t.text.trim()&&(e(t.text.trim(),{attachments:t.files.length>0?t.files:void 0,model:t.model||void 0}),r(``))},f=i&&!o;return(0,d.jsx)(l.Chatbot,{value:n,onChange:r,placeholder:t.orchestratorStarterPlaceholder,disabled:!n.trim()||f,onSubmit:c,attachments:!0,models:gt(a),selectedModel:o,onModelChange:s,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function yt(e,t,n=Date.now()){let r=Math.round((e-n)/1e3),i=new Intl.RelativeTimeFormat(t,{numeric:`auto`,style:`short`});for(let[e,t]of[[`day`,86400],[`hour`,3600],[`minute`,60]])if(Math.abs(r)>=t)return i.format(Math.round(r/t),e);return i.format(0,`minute`)}function bt({card:e}){let t=Q();return e.humanSummaryOnly?(0,d.jsxs)(`div`,{className:`space-y-2 rounded-lg border border-border/60 p-3`,children:[(0,d.jsxs)(`p`,{className:`text-xs font-medium text-foreground`,children:[`"`,e.label,`"`]}),(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.humanSummary})]}):(0,d.jsxs)(`div`,{className:`space-y-2 rounded-lg border border-border/60 p-3`,children:[(0,d.jsx)(`p`,{className:`text-xs font-medium text-foreground`,children:(0,l.interpolate)(t.newInstance,{label:e.label})}),(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.humanSummary}),e.fields.length>0&&(0,d.jsx)(`ul`,{className:`space-y-1`,children:e.fields.map(e=>(0,d.jsxs)(`li`,{className:`flex items-start gap-1.5 text-xs`,children:[(0,d.jsx)(l.Badge,{variant:e.required?`primary`:`secondary`,className:`mt-px shrink-0`,children:e.required?`richiesto`:`opzionale`}),(0,d.jsxs)(`span`,{className:`min-w-0`,children:[(0,d.jsx)(`span`,{className:`font-mono text-foreground`,children:e.key}),e.humanDescription?(0,d.jsxs)(`span`,{className:`text-muted-foreground`,children:[` — `,e.humanDescription]}):null]})]},e.key))}),e.example&&(0,d.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Esempio: `,(0,d.jsx)(`span`,{className:`font-mono`,children:e.example})]})]})}function xt({messages:e}){return(0,d.jsx)(`div`,{className:`space-y-2 rounded-lg border border-border/60 p-3`,children:e.map((e,t)=>(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e},t))})}function St({scopeId:e,currentTaskId:t,open:n,onOpenChange:r,onSelect:i,onNewChat:a,onArchivedCurrent:o}){let s=Q(),{locale:c}=(0,l.useI18n)(),[f,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(0),g=(0,u.useMemo)(()=>n?se(e):[],[e,n,m]),_=async n=>{let r=x(n.subagentId),i=await r?.confirmArchive?.(n.entityId,n.params);if(!i||window.confirm(i)){try{await r?.onArchive?.(n.entityId,n.params)}catch{return}oe(e,n.subagentId,n.entityId),t===ce(n.subagentId,n.entityId)&&o(),h(e=>e+1)}},v=(0,u.useMemo)(()=>{let e=f.trim().toLowerCase();return e?g.filter(t=>{let n=x(t.subagentId)?.label??t.subagentId;return t.title.toLowerCase().includes(e)||n.toLowerCase().includes(e)}):g},[g,f]);return(0,d.jsx)(l.Dropdown,{trigger:{icon:`history`,title:s.chatHistory},triggerClassName:`!h-9 !w-9 !p-0 rounded-md bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground`,open:n,onOpenChange:r,position:`end`,strategy:`absolute`,menuClassName:`w-[380px] max-h-[70vh] overflow-y-auto`,header:(0,d.jsxs)(`div`,{className:`flex items-center gap-2 px-1 pb-1.5`,children:[(0,d.jsx)(l.Icon,{name:`search`,size:14,className:`shrink-0 text-muted-foreground`}),(0,d.jsx)(`input`,{autoFocus:!0,value:f,onChange:e=>p(e.target.value),placeholder:s.searchChats,className:`min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),(0,d.jsx)(l.ActionButton,{icon:`square-pen`,ariaLabel:s.newChat,title:s.newChat,variant:`link`,className:`shrink-0`,onClick:a})]}),children:v.length===0?(0,d.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground`,children:g.length===0?s.noSavedChats:s.noResults}):v.map(e=>{let n=x(e.subagentId),r=t===ce(e.subagentId,e.entityId);return(0,d.jsx)(l.DropdownItem,{icon:r?`check`:n?.icon??`bot`,className:r?`bg-accent font-medium`:void 0,actions:[{icon:`archive`,label:s.archiveChat,onClick:()=>void _(e)}],onClick:()=>i(e.subagentId,e.entityId,e),children:(0,d.jsxs)(`span`,{className:`flex min-w-0 flex-1 items-center justify-between gap-2`,children:[(0,d.jsxs)(`span`,{className:`min-w-0 truncate`,children:[(0,d.jsx)(`span`,{className:`text-muted-foreground`,children:n?.label??e.subagentId}),` · `,e.title||e.entityId]}),(0,d.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,title:new Date(e.savedAt).toLocaleString(c),children:yt(e.savedAt,c)})]})},`${e.subagentId}:${e.entityId}`)})})}function Ct({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}={}){let{task:i,isOpen:a,pendingGoal:o,orchestratorRunId:s,pageContext:c,pageContextCard:f,anchoredUserMessages:p,pendingResume:m,resumeRunId:h,dismissForeignTask:g,resumeEntityChat:_,pendingManualEntry:v,manualEntryRunId:y,startManualEntry:b,pendingExtraDestinations:S,pendingResumeWithAI:C,resumeWithAIRunId:w,pendingStart:T,startRunId:E,scope:D}=$(),O=Q(),k=(0,u.useRef)(null),[A,j]=(0,u.useState)(!1),M=Be({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}),N=()=>{(!i||i.agent.running||i.savedToDisk||window.confirm(O.unsavedConversationConfirm))&&(g(),j(!1))},P=i?[...i.precedingActivity??[],...i.agent.activity]:[],F=P.length,I=Math.max(0,Math.min(i?.panelExtraAnchorIndex??F,F)),L=P.slice(0,I),R=P.slice(I),z=!!(i&&!i.agent.running&&i.agent.error),ee=new Set(i?.agent.activity.map(e=>e.id)??[]),B=i?{canAnswer:e=>ee.has(e),onAnswer:(e,t,n)=>i.agent.answerQuestions(e,t,n).then(e=>{e&&i.onApplied(e)})}:void 0,V=B?Ee(P,B.canAnswer):null,H=i?.id===`agentico-orchestrator`&&i.scopedSubagentId?x(i.scopedSubagentId):void 0,te=H?.manualEntry?H:null,U=(0,u.useRef)(!0);(0,u.useEffect)(()=>{let e=k.current;if(!e)return;let t=()=>{U.current=e.scrollHeight-e.scrollTop-e.clientHeight<80};return e.addEventListener(`scroll`,t),()=>e.removeEventListener(`scroll`,t)},[i?.id]),(0,u.useEffect)(()=>{let e=k.current;e&&(U.current=!0,e.scrollTop=e.scrollHeight)},[i?.id]);let W=P.at(-1)?.detail?.length??0;(0,u.useEffect)(()=>{let e=k.current;e&&U.current&&(e.scrollTop=e.scrollHeight)},[F,z,W]);let G=(0,u.useRef)(null);(0,u.useEffect)(()=>{let e=k.current,t=G.current;if(!e||!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>{U.current&&(e.scrollTop=e.scrollHeight)});return n.observe(t),()=>n.disconnect()},[i?.id,a]);let K=o?(0,d.jsx)(mt,{userGoal:o},s):null,q=m?x(m.subagentId):void 0,J=m&&q?(0,d.jsx)(pt,{manifest:q,params:m.snapshot.params,taskId:ce(m.subagentId,m.entityId),resumeSeed:{history:m.snapshot.history,activity:m.snapshot.activity}},h):null,Y=v?x(v.subagentId):void 0,ne=v&&Y?(0,d.jsx)(ht,{manifest:Y,extraDestinations:v.extraDestinations},y):null,X=C?x(C.subagentId):void 0,re=C&&X?(0,d.jsx)(pt,{manifest:X,params:C.params,extraDestinations:C.extraDestinations},w):null,Z=T?x(T.subagentId):void 0,ie=T&&Z?(0,d.jsx)(pt,{manifest:Z,params:T.params,taskId:T.taskId,openingMessage:T.openingMessage},E):null;return a?(0,d.jsxs)(d.Fragment,{children:[K,J,ne,re,ie,(0,d.jsxs)(`div`,{style:{width:M.width},className:`relative flex h-full shrink-0 flex-col border-l border-border bg-background`,children:[(0,d.jsx)(Ve,{width:M.width,min:M.min,max:M.max,onResize:M.set,onCommit:M.commit,onReset:M.reset}),(0,d.jsxs)(`div`,{className:`flex min-h-[60px] items-center gap-1 border-b border-border/60 px-4 py-3`,children:[(0,d.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-lg font-semibold leading-tight`,children:i?i.title:`Agentico`}),D&&(0,d.jsx)(St,{scopeId:D.id,currentTaskId:i?.id??null,open:A,onOpenChange:j,onNewChat:N,onSelect:(e,t,n)=>_(e,t,n),onArchivedCurrent:g}),(0,d.jsx)(He,{})]}),(0,d.jsx)(`div`,{ref:k,className:`flex-1 overflow-y-auto px-3 pb-2 ${V?`min-h-24`:`min-h-0`}`,children:(0,d.jsx)(`div`,{ref:G,className:`pt-2`,children:i?(0,d.jsxs)(d.Fragment,{children:[i.manualEntry&&P.length===0&&(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:i.manualEntry.prompt}),(0,d.jsx)(Ae,{activity:L,questions:B,docked:V,pinUserMessages:!V}),i.panelExtra&&(0,d.jsx)(`div`,{className:`mt-3`,children:i.panelExtra}),R.length>0&&(0,d.jsx)(Ae,{activity:R,questions:B,docked:V,pinUserMessages:!V}),!i.agent.running&&i.agent.error&&(0,d.jsxs)(`div`,{className:`mt-2 flex items-center gap-2`,children:[(0,d.jsx)(`p`,{className:`flex-1 text-xs text-destructive`,children:i.agent.error}),(0,d.jsx)(l.ActionButton,{label:O.retry,variant:`secondary`,className:`shrink-0`,onClick:()=>{i.agent.sendMessage(O.retryMessage).then(e=>{e&&i.onApplied(e)})}}),!i.agent.remote&&(0,d.jsx)(l.ActionButton,{label:O.continueWithoutAi,variant:`secondary`,className:`shrink-0`,onClick:()=>{if(te){b(te.id,S);return}let e=i.agent.runFallback();e&&i.onApplied(e)}})]})]}):p.length>0?(0,d.jsx)(xt,{messages:p}):f?(0,d.jsx)(bt,{card:f}):(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c??O.orchestratorStarterHint})})}),i&&V?(0,d.jsxs)(`section`,{"aria-label":O.pendingQuestions,className:`flex min-h-0 shrink flex-col border-t border-border/60`,children:[i.panelActions&&(0,d.jsx)(`div`,{className:`shrink-0 px-4 pt-3`,children:i.panelActions}),(0,d.jsx)(`div`,{className:`min-h-0 overflow-y-auto px-4 py-3`,children:(0,d.jsx)(De,{entry:V.entry,part:V.part,questions:B,autoFocus:!0},`${V.entry.id}:${V.part.id}`)}),i.agent.running&&(0,d.jsx)(`div`,{className:`flex shrink-0 justify-end px-4 pb-3`,children:(0,d.jsx)(l.ActionButton,{icon:`square`,label:O.stop,variant:`secondary`,onClick:i.agent.stop})})]}):(0,d.jsxs)(`div`,{className:`border-t border-border/60 px-4 py-3`,children:[i?.panelActions&&(0,d.jsx)(`div`,{className:`mb-2`,children:i.panelActions}),i?(0,d.jsx)(_t,{task:i},i.id):(0,d.jsx)(vt,{})]})]})]}):(0,d.jsxs)(d.Fragment,{children:[K,J,ne,re,ie]})}function wt(e,t){let{setPageContext:n}=$(),r=(0,u.useRef)(crypto.randomUUID()).current;(0,u.useEffect)(()=>(n(r,e,t??null),()=>n(r,null)),[e,t])}function Tt(e,t,n,r,i=!0,a){let{registerComponentAnchor:o}=$(),s=(0,u.useRef)(crypto.randomUUID()).current,c=(0,u.useRef)(n);c.current=n,(0,u.useEffect)(()=>{if(i)return o(s,{subagentId:e,componentKey:t,contextInfo:r,pinnedEntityId:a,onResult:(e,t,n)=>c.current?.(e,t,n)}),()=>o(s,null)},[e,t,r,i,a])}exports.AGENTICO_MAX_WIDTH=Ne,exports.AGENTICO_MIN_WIDTH=Me,exports.AGENTICO_WIDTH=je,exports.AGENTICO_WIDTH_STORAGE_KEY=Pe,exports.Agentico=Ct,exports.AgenticoProvider=he,exports.AgenticoToggle=He,exports.DEFAULT_REASONING_PART_ID=p,exports.DEFAULT_TEXT_PART_ID=f,exports.JSON_EXPORT_DESTINATION_ID=U,exports.MICRO_PROMPT_REGISTRY=ee,exports.ORCHESTRATOR_TASK_ID=pe,exports.SUMMARY_MICRO_PROMPT=z,exports.agenticoDe=le,exports.agenticoEn=ue,exports.agenticoIt=de,exports.agenticoPromptsEn=O,exports.agenticoPromptsIt=k,exports.agenticoTranslations=fe,exports.applyMicroPrompts=B,exports.configureAgenticoPrompts=j,exports.configureEntityChatStore=Y,exports.createCrossAgentTools=w,exports.defineSubagent=_,exports.entityChatTaskId=ce,exports.extractErrorMessage=V,exports.extractJsonBlock=H,exports.findSubagentManifest=x,exports.formatQuestionAnswers=g,exports.getAgenticoPrompts=M,exports.getDestinationRegistry=q,exports.getEntityChat=ie,exports.getSubagentControls=dt,exports.getSubagentRegistry=b,exports.getSubagentReport=ot,exports.jsonExportDestination=W,exports.listEntityChats=se,exports.messagePartsText=h,exports.registerCrossAgentTools=C,exports.registerDestinations=K,exports.registerSubagentControls=ut,exports.registerSubagentReports=at,exports.registerSubagents=y,exports.removeEntityChat=oe,exports.renderRegistryCli=R,exports.renderSubagentCli=L,exports.resetAgenticoPrompts=N,exports.saveEntityChat=ae,exports.toJsonSchema=T,exports.toMcpTool=E,exports.upsertMessagePart=m,exports.useAgent=Xe,exports.useAgentico=$,exports.useAgenticoI18n=Q,exports.useAgenticoPageContext=wt,exports.useSubagentComponentContext=Tt;
|
|
20
|
+
${e}`}function $e(e,t){return t?{kind:`handoff`,...t}:{kind:`chat`,message:e}}function et(e){return b().filter(t=>!t.onlyWhenAnchored||e===t.id)}function tt(e){return{buildContext(e){return{cliCatalog:R(et(e.scopedSubagentId)),handoff:{current:null},collected:{}}},buildPrompt({userGoal:e,pageContext:t},{cliCatalog:n}){return Qe(e,n,t)},buildFollowUpPrompt(e,t,{cliCatalog:n}){return`${e}\n\n${Ze()}\n\n${M().toolsHeading}\n${n}`},parseResponse(e,t,n){let r=n.handoff.current;return n.handoff.current=null,$e(e,r)},fallback(){return{kind:`chat`,message:e.unavailable}},describeFallback(t){return t.kind===`chat`?t.message:e.continueWithoutAi},getTools(t,n,r){let i=w({attachmentsRef:r,collected:n.collected,proxyFetch:l.proxyFetch}),a=t.scopedSubagentId?x(t.scopedSubagentId):null,o=a?i.filter(e=>(a.crossAgentToolIds??[]).includes(e.name)):i,s=et(t.scopedSubagentId).flatMap(t=>t.commands.map(r=>({name:`${t.id}_${r.name}`,description:`${t.label}: ${r.summary}`,inputSchema:r.inputSchema,describeInvocation:()=>(0,l.interpolate)(e.preparing,{label:t.label}),describeIntent:(0,l.interpolate)(e.collecting,{label:t.label}),async execute(e){let i=t.withCollected?t.withCollected({...e},n.collected):e;return n.handoff.current={subagentId:t.id,command:r.name,params:i},{status:`queued`,note:(0,l.interpolate)(M().handoffQueued,{label:t.label})}}})));return[...o,...s]}}}function nt(e,t){return e.deriveHistoryTitle?.(t)??e.label}function rt({manifest:e,result:t,meta:n,taskId:r,initiallyApplied:i,onApplied:a,extraDestinations:o}){let s=Q(),c=$(),f=c.scope,p=(0,l.useProxy)(),[m,h]=(0,u.useState)(null),[g,_]=(0,u.useState)(new Set(i??[])),[v,y]=(0,u.useState)(null),b=J(),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,nt(e,n))}catch(e){y(e instanceof Error?e.message:String(e))}finally{h(null)}};return(0,d.jsxs)(`div`,{className:`space-y-2`,children:[(0,d.jsx)(`p`,{className:`text-xs font-medium text-muted-foreground`,children:s.destinationPickerTitle}),(0,d.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:S.map(e=>(0,d.jsx)(`button`,{type:`button`,disabled:m!==null,onClick:()=>void C(e.id),className:`cursor-pointer rounded-md border border-input bg-background px-2.5 py-1.5 text-xs font-medium transition-colors hover:bg-accent hover:text-accent-foreground disabled:cursor-not-allowed disabled:opacity-60`,children:m===e.id?s.destinationApplying:`${g.has(e.id)?`✓ `:``}${e.id===`json-export`?s.exportJson:e.label}`},e.id))}),v&&(0,d.jsx)(`p`,{className:`text-xs text-destructive`,children:v})]})}var it={};function at(e){Object.assign(it,e)}function ot(e){return it[e]}function st({result:e}){let[t,n]=(0,u.useState)(!1);return(0,d.jsxs)(`div`,{className:`relative cursor-pointer rounded-md border border-border/60 ${t?`max-h-80 overflow-y-auto`:`max-h-28 overflow-hidden`}`,onClick:()=>n(e=>!e),title:t?`Clic per comprimere`:`Clic per espandere`,children:[(0,d.jsx)(l.Code,{language:`json`,showCopy:t,background:`transparent`,className:`!text-[11px]`,children:JSON.stringify(e,null,2)}),!t&&(0,d.jsx)(`div`,{className:`pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-muted/30 to-transparent`})]})}function ct(e,t,n){return e.length===0?null:{id:`live-component`,label:`Applica al componente aperto`,async apply(r){e.forEach(e=>e.onResult?.(r,t,n))}}}var lt={};function ut(e){Object.assign(lt,e)}function dt(e){return lt[e]}var ft=()=>({});function pt({manifest:e,params:t,extraDestinations:n,precedingActivity:r,taskId:i,resumeSeed:a,model:o,openingMessage:s}){let c=Xe(e.definition,{defaultEnabled:!0}),f=$(),p=f.scope,m=(0,l.useProxy)(),h=(0,u.useRef)(i??`subagent-${e.id}-${crypto.randomUUID()}`).current,[g,_]=(0,u.useState)(null),v=t=>{e.definition.conversational||_(t)},[y,b]=(0,u.useState)([]),[x,S]=(0,u.useState)(null),C=ot(e.id),w=C?.kind===`selection`?C:null,[T,E]=(0,u.useState)(null),D=(0,u.useRef)(!1),O=(0,u.useRef)(0),k=(0,u.useRef)(null);g&&g!==k.current&&(k.current=g,O.current=(r?.length??0)+c.activity.length);let A=(0,u.useRef)(!1),j=c.remote||!c.hasProviders||c.selectedModel!==``;(0,u.useEffect)(()=>{!D.current&&j&&(D.current=!0,a?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=J();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,nt(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)(()=>ct(F,t,h),[F,t,h]),L=(0,u.useMemo)(()=>I?[I,...n??[]]:n,[I,n]),R=e.chatEntityId?.(t),z=(0,u.useRef)(!1);(0,u.useEffect)(()=>{let n=z.current&&!c.running;if(z.current=c.running,!n||!R||!p)return;let i=c.snapshot();i&&ae({scopeId:p.id,subagentId:e.id,entityId:R,params:t,title:nt(e,t),history:i.history,activity:[...r??[],...i.activity]})},[c.running]);let B=()=>{A.current=!0,c.running&&c.stop(),f.closeTask(h)},V=(0,u.useRef)(dt(e.id)??ft).current,H=V({params:t,taskId:h,running:c.running,close:B}),U=e=>{b(t=>t.includes(e)?t:[...t,e])};return(0,u.useEffect)(()=>{A.current||f.openTask({id:h,title:nt(e,t),icon:e.icon,agent:c,onApplied:e=>v(e),precedingActivity:r,panelExtraAnchorIndex:O.current,onDismiss:B,...R?{savedToDisk:!0}:{},panelActions:H.content,composerActions:H.actions,composerCommands:H.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)(st,{result:P}),x&&(0,d.jsxs)(`p`,{className:`text-xs text-destructive`,children:[`Salvataggio automatico non riuscito: `,x]}),(0,d.jsx)(rt,{manifest:e,result:P,meta:t,taskId:h,initiallyApplied:y,onApplied:U,extraDestinations:L})]}):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,H.content,H.actions,H.commands]),(0,u.useEffect)(()=>()=>{f.closeTask(h)},[f.closeTask,h]),null}function mt({userGoal:e}){let t=Q(),n=Xe((0,u.useMemo)(()=>tt({unavailable:t.orchestratorUnavailable,continueWithoutAi:t.orchestratorContinueWithoutAi,preparing:t.orchestratorPreparing,collecting:t.orchestratorCollecting}),[]),{defaultEnabled:!0}),r=$(),[i,a]=(0,u.useState)(null),o=(0,u.useRef)(!1),s=!n.hasProviders||n.selectedModel!==``,c=(0,u.useRef)(r.pendingExtraDestinations),l=(0,u.useRef)(r.pendingAttachments),f=(0,u.useRef)(r.pendingModel),p=(0,u.useRef)(r.pendingScopedSubagentId??r.scopedSubagentId??void 0),m=(0,u.useRef)(r.pendingCarryOver),h=(0,u.useRef)(!1),g=e=>{e&&typeof e==`object`&&e.kind===`handoff`&&(a(e),r.closeTask(pe))};(0,u.useEffect)(()=>{!o.current&&s&&(o.current=!0,f.current&&n.setSelectedModel(f.current),n.run({userGoal:e,pageContext:r.pageContext,scopedSubagentId:p.current??null},{attachments:l.current,model:f.current,openingMessage:e}).then(e=>{e&&g(e)}))},[s]),(0,u.useEffect)(()=>{h.current||r.openTask({id:pe,title:`Agentico`,icon:`bot`,agent:n,onApplied:g,scopedSubagentId:p.current,precedingActivity:m.current?.activity,onDismiss:()=>{h.current=!0,n.running&&n.stop(),r.closeTask(pe)}})},[n.activity,n.running,n.error,n.canContinue,n.selectedModel,n.modelsByProvider,n.hasProviders,r.openTask]),(0,u.useEffect)(()=>()=>{r.closeTask(pe)},[r.closeTask]);let _=(0,u.useMemo)(()=>[...m.current?.activity??[],...n.activity],[n.activity]);if(!i)return null;let v=x(i.subagentId);return v?(0,d.jsx)(pt,{manifest:v,params:i.params,extraDestinations:c.current,model:f.current||void 0,taskId:m.current?.taskId,precedingActivity:_}):null}function ht({manifest:e,extraDestinations:t}){let n=Xe(e.definition,{defaultEnabled:!1}),r=Q(),i=$(),a=(0,u.useRef)(`manual-${e.id}-${crypto.randomUUID()}`).current,[o,s]=(0,u.useState)(null),[c,f]=(0,u.useState)([]),p=ot(e.id),m=p?.kind===`selection`?p:null,[h,g]=(0,u.useState)(null),[_,v]=(0,u.useState)(null),y=(0,u.useRef)(!1),b=t=>{if(!e.manualEntry)return;let r;try{r=e.manualEntry.fromRawText(t)}catch(e){console.error(`[ManualEntryRunner] manualEntry.fromRawText ha rifiutato il testo:`,e);return}v(r),f([]),n.run(r,{openingMessage:t}).then(e=>{e&&s(e)})};(0,u.useEffect)(()=>{o&&m&&g(m.defaultSelection(o))},[o,m]);let x=(e,t)=>{g(n=>n&&{...n,[e]:t})},S=e=>s(e),C=(0,u.useMemo)(()=>o&&m&&h?m.applySelection(o,h):o,[o,m,h]),w=e=>{f(t=>t.includes(e)?t:[...t,e])},T=(0,u.useMemo)(()=>i.componentAnchors.filter(t=>t.subagentId===e.id&&t.onResult),[i.componentAnchors,e.id]),E=(0,u.useMemo)(()=>_?ct(T,_,a):null,[T,_,a]),D=(0,u.useMemo)(()=>E?[E,...t??[]]:t,[E,t]);return(0,u.useEffect)(()=>{y.current||i.openTask({id:a,title:e.label,icon:e.icon,agent:n,onApplied:e=>s(e),manualEntry:e.manualEntry?{prompt:e.manualEntry.prompt,onSubmit:b}:void 0,onDismiss:()=>{y.current=!0,n.running&&n.stop(),i.closeTask(a)},panelExtra:o?(0,d.jsxs)(`div`,{className:`space-y-2`,children:[m&&h?(0,d.jsx)(m.Report,{result:o,selection:h,onChange:x}):p?.kind===`editable`?(0,d.jsx)(p.Report,{result:o,onResultChange:S}):(0,d.jsx)(st,{result:C}),(0,d.jsx)(rt,{manifest:e,result:C,meta:_??{},taskId:a,initiallyApplied:c,onApplied:w,extraDestinations:D}),n.hasProviders&&(0,d.jsx)(l.ActionButton,{label:r.resumeWithAi,variant:`outline-secondary`,className:`text-xs`,onClick:()=>{_&&i.resumeWithAI(e.id,_,t)}})]}):void 0})},[n.activity,n.running,n.error,n.hasProviders,i.componentAnchors,o,C,h,c,_]),(0,u.useEffect)(()=>()=>{i.closeTask(a)},[]),null}function gt(e){return Object.values(e).flat().map(e=>({label:e.model,value:e.id,pricing:e.pricing??null,group:e.providerLabel??e.provider}))}function _t({task:e}){let t=Q(),[n,r]=(0,u.useState)(``),{agent:i,onApplied:a,manualEntry:o}=e,s=i.running,c=e=>{if(r(``),o){o.onSubmit(e.text);return}i.sendMessage(e.text,{attachments:e.files,model:e.model}).then(e=>{e&&a(e)})},f=!!o||i.remote&&i.remoteModels.length===0,p=!f&&!i.remote&&i.hasProviders&&!i.selectedModel,m=f?[]:i.remote?i.remoteModels:gt(i.modelsByProvider);return(0,d.jsx)(l.Chatbot,{value:n,onChange:r,placeholder:o?.prompt??t.messagePlaceholder,running:s,onStop:i.stop,disabled:!n.trim()||p,onSubmit:c,attachments:!o&&!i.remote,models:m,selectedModel:f?``:i.selectedModel,actions:e.composerActions,commands:e.composerCommands,onModelChange:i.setSelectedModel,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function vt(){let{startOrchestrator:e}=$(),t=Q(),[n,r]=(0,u.useState)(``),{hasProviders:i,modelsByProvider:a,selectedModel:o,setSelectedModel:s}=Ke(),c=t=>{t.text.trim()&&(e(t.text.trim(),{attachments:t.files.length>0?t.files:void 0,model:t.model||void 0}),r(``))},f=i&&!o;return(0,d.jsx)(l.Chatbot,{value:n,onChange:r,placeholder:t.orchestratorStarterPlaceholder,disabled:!n.trim()||f,onSubmit:c,attachments:!0,models:gt(a),selectedModel:o,onModelChange:s,modelPlaceholder:t.selectModelPlaceholder,minHeight:44,maxHeight:220})}function yt(e,t,n=Date.now()){let r=Math.round((e-n)/1e3),i=new Intl.RelativeTimeFormat(t,{numeric:`auto`,style:`short`});for(let[e,t]of[[`day`,86400],[`hour`,3600],[`minute`,60]])if(Math.abs(r)>=t)return i.format(Math.round(r/t),e);return i.format(0,`minute`)}function bt({card:e}){let t=Q();return e.humanSummaryOnly?(0,d.jsxs)(`div`,{className:`space-y-2 rounded-lg border border-border/60 p-3`,children:[(0,d.jsxs)(`p`,{className:`text-xs font-medium text-foreground`,children:[`"`,e.label,`"`]}),(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.humanSummary})]}):(0,d.jsxs)(`div`,{className:`space-y-2 rounded-lg border border-border/60 p-3`,children:[(0,d.jsx)(`p`,{className:`text-xs font-medium text-foreground`,children:(0,l.interpolate)(t.newInstance,{label:e.label})}),(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.humanSummary}),e.fields.length>0&&(0,d.jsx)(`ul`,{className:`space-y-1`,children:e.fields.map(e=>(0,d.jsxs)(`li`,{className:`flex items-start gap-1.5 text-xs`,children:[(0,d.jsx)(l.Badge,{variant:e.required?`primary`:`secondary`,className:`mt-px shrink-0`,children:e.required?`richiesto`:`opzionale`}),(0,d.jsxs)(`span`,{className:`min-w-0`,children:[(0,d.jsx)(`span`,{className:`font-mono text-foreground`,children:e.key}),e.humanDescription?(0,d.jsxs)(`span`,{className:`text-muted-foreground`,children:[` — `,e.humanDescription]}):null]})]},e.key))}),e.example&&(0,d.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Esempio: `,(0,d.jsx)(`span`,{className:`font-mono`,children:e.example})]})]})}function xt({messages:e}){return(0,d.jsx)(`div`,{className:`space-y-2 rounded-lg border border-border/60 p-3`,children:e.map((e,t)=>(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e},t))})}function St({scopeId:e,currentTaskId:t,open:n,onOpenChange:r,onSelect:i,onNewChat:a,onArchivedCurrent:o}){let s=Q(),{locale:c}=(0,l.useI18n)(),[f,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(0),g=(0,u.useMemo)(()=>n?se(e):[],[e,n,m]),_=async n=>{let r=x(n.subagentId),i=await r?.confirmArchive?.(n.entityId,n.params);if(!i||window.confirm(i)){try{await r?.onArchive?.(n.entityId,n.params)}catch{return}oe(e,n.subagentId,n.entityId),t===ce(n.subagentId,n.entityId)&&o(),h(e=>e+1)}},v=(0,u.useMemo)(()=>{let e=f.trim().toLowerCase();return e?g.filter(t=>{let n=x(t.subagentId)?.label??t.subagentId;return t.title.toLowerCase().includes(e)||n.toLowerCase().includes(e)}):g},[g,f]);return(0,d.jsx)(l.Dropdown,{trigger:{icon:`history`,title:s.chatHistory},triggerClassName:`!h-9 !w-9 !p-0 rounded-md bg-transparent text-muted-foreground hover:bg-accent hover:text-foreground`,open:n,onOpenChange:r,position:`end`,strategy:`absolute`,menuClassName:`w-[380px] max-h-[70vh] overflow-y-auto`,header:(0,d.jsxs)(`div`,{className:`flex items-center gap-2 px-1 pb-1.5`,children:[(0,d.jsx)(l.Icon,{name:`search`,size:14,className:`shrink-0 text-muted-foreground`}),(0,d.jsx)(`input`,{autoFocus:!0,value:f,onChange:e=>p(e.target.value),placeholder:s.searchChats,className:`min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground`}),(0,d.jsx)(l.ActionButton,{icon:`square-pen`,ariaLabel:s.newChat,title:s.newChat,variant:`link`,className:`shrink-0`,onClick:a})]}),children:v.length===0?(0,d.jsx)(`p`,{className:`px-2 py-3 text-center text-xs text-muted-foreground`,children:g.length===0?s.noSavedChats:s.noResults}):v.map(e=>{let n=x(e.subagentId),r=t===ce(e.subagentId,e.entityId);return(0,d.jsx)(l.DropdownItem,{icon:r?`check`:n?.icon??`bot`,className:r?`bg-accent font-medium`:void 0,actions:[{icon:`archive`,label:s.archiveChat,onClick:()=>void _(e)}],onClick:()=>i(e.subagentId,e.entityId,e),children:(0,d.jsxs)(`span`,{className:`flex min-w-0 flex-1 items-center justify-between gap-2`,children:[(0,d.jsxs)(`span`,{className:`min-w-0 truncate`,children:[(0,d.jsx)(`span`,{className:`text-muted-foreground`,children:n?.label??e.subagentId}),` · `,e.title||e.entityId]}),(0,d.jsx)(`span`,{className:`shrink-0 text-xs text-muted-foreground`,title:new Date(e.savedAt).toLocaleString(c),children:yt(e.savedAt,c)})]})},`${e.subagentId}:${e.entityId}`)})})}function Ct({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}={}){let{task:i,isOpen:a,pendingGoal:o,orchestratorRunId:s,pageContext:c,pageContextCard:f,anchoredUserMessages:p,pendingResume:m,resumeRunId:h,dismissForeignTask:g,resumeEntityChat:_,pendingManualEntry:v,manualEntryRunId:y,startManualEntry:b,pendingExtraDestinations:S,pendingResumeWithAI:C,resumeWithAIRunId:w,pendingStart:T,startRunId:E,scope:D}=$(),O=Q(),k=(0,u.useRef)(null),[A,j]=(0,u.useState)(!1),M=Be({defaultWidth:e,minWidth:t,maxWidth:n,onWidthChange:r}),N=()=>{(!i||i.agent.running||i.savedToDisk||window.confirm(O.unsavedConversationConfirm))&&(g(),j(!1))},P=i?[...i.precedingActivity??[],...i.agent.activity]:[],F=P.length,I=Math.max(0,Math.min(i?.panelExtraAnchorIndex??F,F)),L=P.slice(0,I),R=P.slice(I),z=!!(i&&!i.agent.running&&i.agent.error),B=new Set(i?.agent.activity.map(e=>e.id)??[]),V=i?{canAnswer:e=>B.has(e),onAnswer:(e,t,n)=>i.agent.answerQuestions(e,t,n).then(e=>{e&&i.onApplied(e)})}:void 0,H=V?Ee(P,V.canAnswer):null,U=i?.id===`agentico-orchestrator`&&i.scopedSubagentId?x(i.scopedSubagentId):void 0,ee=U?.manualEntry?U: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,z,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)(mt,{userGoal:o},s):null,J=m?x(m.subagentId):void 0,Y=m&&J?(0,d.jsx)(pt,{manifest:J,params:m.snapshot.params,taskId:ce(m.subagentId,m.entityId),resumeSeed:{history:m.snapshot.history,activity:m.snapshot.activity}},h):null,te=v?x(v.subagentId):void 0,ne=v&&te?(0,d.jsx)(ht,{manifest:te,extraDestinations:v.extraDestinations},y):null,X=C?x(C.subagentId):void 0,re=C&&X?(0,d.jsx)(pt,{manifest:X,params:C.params,extraDestinations:C.extraDestinations},w):null,Z=T?x(T.subagentId):void 0,ie=T&&Z?(0,d.jsx)(pt,{manifest:Z,params:T.params,taskId:T.taskId,openingMessage:T.openingMessage},E):null;return a?(0,d.jsxs)(d.Fragment,{children:[q,Y,ne,re,ie,(0,d.jsxs)(`div`,{style:{width:M.width},className:`relative flex h-full shrink-0 flex-col border-l border-border bg-background`,children:[(0,d.jsx)(Ve,{width:M.width,min:M.min,max:M.max,onResize:M.set,onCommit:M.commit,onReset:M.reset}),(0,d.jsxs)(`div`,{className:`flex min-h-[60px] items-center gap-1 border-b border-border/60 px-4 py-3`,children:[(0,d.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-lg font-semibold leading-tight`,children:i?i.title:`Agentico`}),D&&(0,d.jsx)(St,{scopeId:D.id,currentTaskId:i?.id??null,open:A,onOpenChange:j,onNewChat:N,onSelect:(e,t,n)=>_(e,t,n),onArchivedCurrent:g}),(0,d.jsx)(He,{})]}),(0,d.jsx)(`div`,{ref:k,className:`flex-1 overflow-y-auto px-3 pb-2 ${H?`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)(Ae,{activity:L,questions:V,docked:H,pinUserMessages:!H}),i.panelExtra&&(0,d.jsx)(`div`,{className:`mt-3`,children:i.panelExtra}),R.length>0&&(0,d.jsx)(Ae,{activity:R,questions:V,docked:H,pinUserMessages:!H}),!i.agent.running&&i.agent.error&&(0,d.jsxs)(`div`,{className:`mt-2 flex items-center gap-2`,children:[(0,d.jsx)(`p`,{className:`flex-1 text-xs text-destructive`,children:i.agent.error}),(0,d.jsx)(l.ActionButton,{label:O.retry,variant:`secondary`,className:`shrink-0`,onClick:()=>{i.agent.sendMessage(O.retryMessage).then(e=>{e&&i.onApplied(e)})}}),!i.agent.remote&&(0,d.jsx)(l.ActionButton,{label:O.continueWithoutAi,variant:`secondary`,className:`shrink-0`,onClick:()=>{if(ee){b(ee.id,S);return}let e=i.agent.runFallback();e&&i.onApplied(e)}})]})]}):p.length>0?(0,d.jsx)(xt,{messages:p}):f?(0,d.jsx)(bt,{card:f}):(0,d.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:c??O.orchestratorStarterHint})})}),i&&H?(0,d.jsxs)(`section`,{"aria-label":O.pendingQuestions,className:`flex min-h-0 shrink flex-col border-t border-border/60`,children:[i.panelActions&&(0,d.jsx)(`div`,{className:`shrink-0 px-4 pt-3`,children:i.panelActions}),(0,d.jsx)(`div`,{className:`min-h-0 overflow-y-auto px-4 py-3`,children:(0,d.jsx)(De,{entry:H.entry,part:H.part,questions:V,autoFocus:!0},`${H.entry.id}:${H.part.id}`)}),i.agent.running&&(0,d.jsx)(`div`,{className:`flex shrink-0 justify-end px-4 pb-3`,children:(0,d.jsx)(l.ActionButton,{icon:`square`,label:O.stop,variant:`secondary`,onClick:i.agent.stop})})]}):(0,d.jsxs)(`div`,{className:`border-t border-border/60 px-4 py-3`,children:[i?.panelActions&&(0,d.jsx)(`div`,{className:`mb-2`,children:i.panelActions}),i?(0,d.jsx)(_t,{task:i},i.id):(0,d.jsx)(vt,{})]})]})]}):(0,d.jsxs)(d.Fragment,{children:[q,Y,ne,re,ie]})}function wt(e,t){let{setPageContext:n}=$(),r=(0,u.useRef)(crypto.randomUUID()).current;(0,u.useEffect)(()=>(n(r,e,t??null),()=>n(r,null)),[e,t])}function Tt(e,t,n,r,i=!0,a){let{registerComponentAnchor:o}=$(),s=(0,u.useRef)(crypto.randomUUID()).current,c=(0,u.useRef)(n);c.current=n,(0,u.useEffect)(()=>{if(i)return o(s,{subagentId:e,componentKey:t,contextInfo:r,pinnedEntityId:a,onResult:(e,t,n)=>c.current?.(e,t,n)}),()=>o(s,null)},[e,t,r,i,a])}exports.AGENTICO_MAX_WIDTH=Ne,exports.AGENTICO_MIN_WIDTH=Me,exports.AGENTICO_WIDTH=je,exports.AGENTICO_WIDTH_STORAGE_KEY=Pe,exports.Agentico=Ct,exports.AgenticoProvider=he,exports.AgenticoToggle=He,exports.DEFAULT_REASONING_PART_ID=p,exports.DEFAULT_TEXT_PART_ID=f,exports.JSON_EXPORT_DESTINATION_ID=W,exports.MICRO_PROMPT_REGISTRY=B,exports.ORCHESTRATOR_TASK_ID=pe,exports.SUMMARY_MICRO_PROMPT=z,exports.agenticoDe=le,exports.agenticoEn=ue,exports.agenticoIt=de,exports.agenticoPromptsEn=O,exports.agenticoPromptsIt=k,exports.agenticoTranslations=fe,exports.applyMicroPrompts=V,exports.configureAgenticoPrompts=j,exports.configureEntityChatStore=te,exports.createCrossAgentTools=w,exports.defineSubagent=_,exports.entityChatTaskId=ce,exports.extractErrorMessage=H,exports.extractJsonBlock=U,exports.findSubagentManifest=x,exports.formatQuestionAnswers=g,exports.getAgenticoPrompts=M,exports.getDestinationRegistry=J,exports.getEntityChat=ie,exports.getSubagentControls=dt,exports.getSubagentRegistry=b,exports.getSubagentReport=ot,exports.jsonExportDestination=G,exports.listEntityChats=se,exports.messagePartsText=h,exports.registerCrossAgentTools=C,exports.registerDestinations=q,exports.registerSubagentControls=ut,exports.registerSubagentReports=at,exports.registerSubagents=y,exports.removeEntityChat=oe,exports.renderRegistryCli=R,exports.renderSubagentCli=L,exports.resetAgenticoPrompts=N,exports.saveEntityChat=ae,exports.toJsonSchema=T,exports.toMcpTool=E,exports.upsertMessagePart=m,exports.useAgent=Xe,exports.useAgentico=$,exports.useAgenticoI18n=Q,exports.useAgenticoPageContext=wt,exports.useSubagentComponentContext=Tt;
|
|
21
21
|
//# sourceMappingURL=index.js.map
|