@collective-intelligence/ai 0.7.1 → 0.9.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 +7 -1
- package/dist/api/chat-api.d.ts +1 -0
- package/dist/api/chat-surface-api.d.ts +1 -0
- package/dist/api/transcript.d.ts +5 -0
- package/dist/api.js +1 -1
- package/dist/domain/data-parts.d.ts +2 -0
- package/dist/domain/display-part-evidence.d.ts +19 -0
- package/dist/domain/index.d.ts +2 -0
- package/dist/domain-54qeg701.js +3 -0
- package/dist/domain-8rwbw2ah.js +2 -0
- package/dist/domain-tg4azwc2.js +1 -0
- package/dist/domain.d.ts +2 -0
- package/dist/domain.js +1 -1
- package/dist/headless/chat-surface.d.ts +1 -0
- package/dist/headless/transcript-messages.d.ts +1 -1
- package/dist/headless.js +1 -1
- package/dist/views.js +2 -2
- package/docs/guide/ai/index.md +4 -2
- package/docs/guide/ai/studio.md +1 -1
- package/docs/guide/data/documents.md +1 -1
- package/package.json +6 -6
- package/dist/domain-g97xs965.js +0 -2
- package/dist/domain-hk3yw2m7.js +0 -1
- package/dist/domain-s07s1ry1.js +0 -2
- /package/dist/{domain-qyts6dgz.js → domain-mzqq5ky3.js} +0 -0
package/dist/views.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{useIntentsScope2,useIntentResult2,makeChatSessionRuntime,toSessionFailure,callChatSurface,useChatSession2,useCiChat2,ChatSessionProvider2,useIntentDispatch2,useIntents2,useLaunch2,useHasLaunchTarget2,useChatLaunchTarget2,useTrailEntries2}from"./domain-hk3yw2m7.js";import{ChatSurfaceApi2}from"./domain-g97xs965.js";import{InvocationId2,AgentId2}from"./domain-5fpd4fte.js";import{ciDataPartSchemas2}from"./domain-50vzrrp9.js";import{ciAskUserToolName2,ciAskUserSchemas2,hasNumberRuntimeKind2,hasNullRuntimeKind2,hasObjectRuntimeKind2,hasStringRuntimeKind2}from"./domain-s07s1ry1.js";import{AiFailureError2}from"./domain-9wzbv87n.js";import{cn as cn16}from"@collective-intelligence/ui-react";import{ChevronRight as ChevronRight2,History,Trash2 as Trash24}from"@collective-intelligence/ui-react/icons";import{Button as Button17}from"@collective-intelligence/ui-react/ui";import{createContext as createContext2,useContext as useContext2}from"react";import{cn as cn15}from"@collective-intelligence/ui-react";import{Sheet,SheetContent,SheetDescription,SheetHeader,SheetTitle}from"@collective-intelligence/ui-react/ui";import{useId as useId5,useState as useState21}from"react";import{cn}from"@collective-intelligence/ui-react";import{MessageSquare}from"@collective-intelligence/ui-react/icons";import{Button,Empty,EmptyContent,EmptyDescription,EmptyHeader,EmptyMedia,EmptyTitle}from"@collective-intelligence/ui-react/ui";import{jsx,jsxs}from"react/jsx-runtime";var blockedLabels={app_not_available:["appNotAvailable","appNotAvailableDescription"],chat_not_available:["chatNotAvailable","chatNotAvailableDescription"],service_not_available:["serviceNotAvailable","serviceNotAvailableDescription"],sign_in_to_chat:["signInToChat","signInToChatDescription"]};var ChatBlockedState=({blocked,className,labels})=>{const{retry}=useChatSession2();const[title,description]=blockedLabels[blocked.kind];return jsxs(Empty,{className:cn("flex-1",className),"data-kind":blocked.kind,"data-part":"chat-blocked-state",role:"alert",children:[jsxs(EmptyHeader,{children:[jsx(EmptyMedia,{variant:"icon",children:jsx(MessageSquare,{})}),jsx(EmptyTitle,{children:labels[title]}),jsx(EmptyDescription,{children:labels[description]})]}),blocked.kind==="service_not_available"?jsx(EmptyContent,{children:jsx(Button,{onClick:retry,type:"button",variant:"outline",children:labels.retry})}):null]})};import{cn as cn2}from"@collective-intelligence/ui-react";import{PortalContainerProvider}from"@collective-intelligence/ui-react/ui";import{useState}from"react";import{jsx as jsx2}from"react/jsx-runtime";var ChatRoot=({children,className})=>{const[container,setContainer]=useState(null);return jsx2("div",{className:cn2("ci-root size-full",className),"data-ci-root":"",ref:setContainer,children:jsx2(PortalContainerProvider,{container,children})})};import{cn as cn5}from"@collective-intelligence/ui-react";import{PromptInput,PromptInputBody,PromptInputFooter,PromptInputSubmit,PromptInputTextarea,PromptInputTools}from"@collective-intelligence/ui-react/ai-elements";import{useState as useState7}from"react";import{useState as useState4}from"react";import{Bot,Sparkles,Wrench}from"@collective-intelligence/ui-react/icons";import{Badge}from"@collective-intelligence/ui-react/ui";import{IconTile as IconTile2}from"@collective-intelligence/ui-react/ui-extensions";import{useState as useState2,useSyncExternalStore,useTransition}from"react";var offSnapshot={isLoading:false,result:null};var makeReadStore=(read,enabled)=>{let snapshot=enabled?{isLoading:true,result:null}:offSnapshot;let started=false;let latest=0;const listeners=new Set;const publish=(next)=>{snapshot=next;for(const listener of listeners){listener()}};const load=async()=>{latest+=1;const own=latest;if(!snapshot.isLoading){publish({...snapshot,isLoading:true})}const result=await read();if(own===latest){publish({isLoading:false,result})}};return{getSnapshot:()=>snapshot,reload:()=>{if(enabled){load()}},subscribe:(listener)=>{listeners.add(listener);if(enabled&&!started){started=true;load()}return()=>{listeners.delete(listener)}}}};var useChatRead=(operation,enabled=true)=>{const{call}=useChatSession2();const[store]=useState2(()=>makeReadStore(()=>call(operation),enabled));const snapshot=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return{...snapshot,reload:store.reload}};var useChatAction=()=>{const{call}=useChatSession2();const[isPending,startTransition]=useTransition();const[failure,setFailure]=useState2(null);return{failure,isPending,reset:()=>{setFailure(null)},run:(operation,onDone)=>{setFailure(null);startTransition(async()=>{const result=await call(operation);startTransition(()=>{if(result.ok){onDone?.(result.value)}else{setFailure(result.error)}})})}}};var failureText=(failure,labels)=>{if(failure.code==="conflict"&&failure.reason==="intent_turn_busy"){return labels.launchIntoBusyConversation}if(failure.code==="conflict"&&failure.reason==="intent_turn_agent"){return labels.launchIntoAgentConversation}return failure.code==="rate_limited"||failure.code==="unavailable"&&!failure.retryable?failure.message:labels.actionFailed};import{cn as cn3}from"@collective-intelligence/ui-react";import{Check,X}from"@collective-intelligence/ui-react/icons";import{Button as Button2,Command,CommandEmpty,CommandGroup,CommandInput,CommandItem,CommandList,Popover,PopoverContent,PopoverTrigger}from"@collective-intelligence/ui-react/ui";import{IconTile}from"@collective-intelligence/ui-react/ui-extensions";import{useState as useState3}from"react";var en={actionFailed:"This action failed. Try again.",addProjectFiles:"Add files",agent:"Agent",agentConversationNoProjectContext:"This Agent conversation does not receive the project context.",agentRefreshFailed:"Could not refresh the reply.",agentTurnBlocked:"This agent cannot run this message under its current policy.",agentTurnBlockedWithReason:"This agent cannot run this message: {reason}.",agentTurnCancelled:"This request was cancelled.",agentTurnFailed:"The agent could not complete this request.",agentTurnNoReply:"The agent finished without a reply.",agentTurnPaused:"This agent is paused. Your message is queued and will run after it resumes.",agentTurnWorking:"The agent is working on this…",allListedPlaces:"All listed places",appNotAvailable:"App not available",appNotAvailableDescription:"This app cannot use the chat now.",approvalApprove:"Approve",approvalApproving:"Approving…",approvalComment:"Comment (optional)",approvalCommentPlaceholder:"Add a comment",approvalConfirmReject:"Confirm rejection",approvalDecideHint:"Review the approval details and record your decision.",approvalDecision:"{actor} · {decision} · {date}",approvalDecisionApproved:"approved",approvalDecisionRejected:"rejected",approvalDecisions:"Accepted decisions",approvalEligibleDirect:"Eligible through direct assignment",approvalEligibleGroup:"Eligible through group membership",approvalExpires:"Expires {date}",approvalLoadFailed:"The approval details could not load.",approvalModeAll:"All steps",approvalModeAny:"Any step",approvalOutcomeAlreadyApproved:"Already approved",approvalOutcomeAlreadyDecided:"Already decided",approvalOutcomeContinuationFailed:"The run could not continue",approvalOutcomeContinuationInProgress:"The run is continuing",approvalOutcomeReconciliationRequired:"The run needs a check before it continues",approvalOutcomeRecorded:"Decision recorded",approvalReadOnly:"Read only",approvalReadOnlyHint:"Review the recorded approval details.",approvalReject:"Reject",approvalRejectReason:"Reason for rejecting",approvalRejectReasonPlaceholder:"Tell the requester why",approvalResolution:"Resolution: {reason}",approvalStatusApproved:"Approved",approvalStatusCancelled:"Cancelled",approvalStatusExpired:"Expired",approvalStatusPending:"Pending",approvalStatusRejected:"Rejected",approvalStepProgress:"{approved} of {required} approved",approvalSteps:"Approval steps",approvalTitle:"Approval request",artifactCurrent:"Processing {filename}",artifactFailed:"{count} failed",artifactFiles:"Files: {summary}",artifactLeased:"{count} processing",artifactPending:"{count} pending",artifactProcessed:"{count} processed",artifactSkipped:"{count} skipped",assistant:"Assistant",assistantSidebarCollapse:"Collapse",assistantSidebarDelete:"Delete this conversation",assistantSidebarDeleteTitle:"Delete this conversation?",assistantSidebarToggle:"Assistant",attach:"Attach files",attachmentDownload:"Download",attachmentDownloadFile:"Download {name}",attachmentDownloading:"Downloading",attachmentNotAttached:"The file {name} was not attached.",attachmentOversized:"Each file can be 10 MB at most.",attachmentPreview:"Preview {name}",attachmentPreviewDescription:"Preview of the attached image.",attachmentRemove:"Remove {name}",attachmentTooManyFiles:"You can attach 10 files at most to one message.",attachmentUnsupported:"This file type is not supported.",attachmentsNotAttached:"The files were not attached.",cancel:"Cancel",chatNotAvailable:"Chat not available",chatNotAvailableDescription:"Your account cannot use the chat here.",clearAgent:"Clear agent",clearSearch:"Clear search",clearSkills:"Clear selected skills",clearTools:"Clear selected tools",compact:"Compact",compacted:"Compacted",compactedContext:"Compacted context",compactedContextDescription:"The assistant uses this summary for older chat history.",compactionCoveredMessages:"Covered messages",compactionCoveredRuns:"Covered runs",compactionFailed:"The conversation was not compacted. Try again.",compactionMarker:"Older context compacted",compactionMessages:"{count} messages",compactionNotChanged:"The compacted context was not changed. Try again.",compactionRuns:"{count} runs",compactionStatus:"Status",composerDrop:"Drop files to attach them",composerInput:"Message",composerPlaceholder:"Ask anything...",contextUsage:"Context usage",conversationActions:"Manage conversation {title}",conversationNotMoved:"The conversation was not moved. Try again.",conversationTitle:"Conversation title",conversations:"Conversations",conversationsDescription:"Open or manage your conversations.",conversationsNotLoaded:"The conversations were not loaded.",createProject:"Create project",delete:"Delete",deleteConversation:"Delete conversation?",deleteConversationDescription:'This removes "{title}" from your conversations.',deleteProject:"Delete project",deleteProjectDescription:"Its conversations are deleted with it, also those started in other places.",deleteProjectFile:"Delete file {name}",deleteProjectTitle:'Delete project "{name}"?',downloadProjectFile:"Download file {name}",draft:"Draft",earlier:"Earlier",editQueuedMessage:"Edit queued message {content}",emptyDescription:"Ask a question to start a conversation.",emptyTitle:"New chat",evidenceContradiction:"Contradiction: {status}",evidenceEmpty:"No content",evidenceLinks:"Links",evidenceOmitted:"{count} more evidence items were omitted.",evidenceOpen:"Open",evidenceOpenSource:"Open {title}",evidenceOpening:"Checking…",evidenceRelevance:"{percent}% relevant",evidenceShowMore:"Show {count} more",evidenceSources:"Sources",evidenceUnavailable:"This source is not available.",evidenceWarnings:"Warnings",feedbackGroup:"Answer feedback",feedbackNegative:"Rate answer not helpful",feedbackNote:"Note (required)",feedbackNoteDescription:"Tell reviewers what went wrong. A note is required.",feedbackNoteTitle:"Add a note",feedbackPositive:"Rate answer helpful",feedbackSaving:"Saving…",feedbackSubmit:"Submit feedback",fileDownload:"Download {name}",fileOpen:"Open {name}",filePreview:"Preview {name}",filePreviewDescription:"Preview this file or download a copy.",historyFilter:"Conversations to show",imageActualCost:"Actual cost",imageAspectRatio:"Aspect ratio",imageBackground:"Background",imageCost:"Cost",imageCostSource:"Cost source",imageCostUnavailable:"Cost unavailable",imageCount:"Images",imageDeployment:"Deployment",imageDetailsUnavailable:"Image generation details unavailable",imageEstimatedCost:"Estimated cost",imageFormat:"Format",imageModel:"Model",imageModelVersion:"Model version",imageProvider:"Provider",imageProviderConfigured:"Configured provider",imageProviderModel:"Provider model",imageQuality:"Quality",imageReferenceImages:"Reference images",imageResolution:"Resolution",imageStatusAttentionRequired:"Image generation needs attention",imageStatusCancelled:"Image generation cancelled",imageStatusCompleted:"Image generation complete",imageStatusFailed:"Image generation failed",imageStatusPartial:"Some images could not be generated",imageStatusPending:"Image generation pending",imageStatusRunning:"Generating images…",imageTitle:"Image generation",intentApprovalInputs:"Inputs",intentApprovalTitle:"Allow assistant to run the Intent {name}?",intentCardCompleted:"Completed",intentCardEnded:"Result no longer available",intentCardFailed:"Failed",intentCardTitle:"Intent {name}",intentCardWorking:"Working",launchIntoAgentConversation:"This conversation belongs to an Agent. Start a new chat to run this action.",launchIntoBusyConversation:"This conversation is busy. Wait for the answer, then try again.",loading:"Loading...",memoryCreated:"Created",memoryDisabled:"Disabled",memoryMerged:"Merged",memoryNotChanged:"The memory setting was not changed. Try again.",memoryOff:"Memory off",memoryOn:"Memory on",memoryRetrieved:"Retrieved",memorySaved:"{count} saved",memorySelected:"Selected",memorySkipped:"Skipped",memorySuggested:"Suggested",memorySuperseded:"Superseded",memoryTitle:"Memory evidence",memoryUsed:"{count} used",memoryUsedEvent:"Used",moveToProject:"Move to project",multipleSkills:"{count} skills",multipleTools:"{count} tools",newChat:"New chat",newProject:"New project",noAgents:"No agents available.",noChat:"No chat is available",noCompactionSummary:"No active compaction summary is available.",noConversations:"No conversations yet",noConversationsDescription:"Start a new chat to see it listed here.",noProjectFiles:"No files in this project yet",noProjectFilesDescription:"Add a file to give its text to each conversation of this project.",noProjects:"No projects yet",noSearchResults:"No conversations match the search",noSkills:"No skills match.",noTools:"No tools match.",openConversation:"Open conversation {title}",openConversationList:"Open conversations",openProject:"Open project {name}",optionsError:"The list could not load.",permissionAllowAlways:"Allow always",permissionAllowThisConversation:"Allow for this conversation only",permissionDeny:"Do not allow",permissionDescription:"Allow it for this chat, or remember this exact item for later.",permissionRegion:"Permission request for {name}",permissionSkill:"the skill",permissionTitle:"Allow assistant to use {name}?",permissionTool:"the tool",personalAgent:"Personal",pickAgent:"Pick an agent to start a chat.",previousSevenDays:"Previous 7 days",projectActions:"Manage project {name}",projectConversations:"Conversations",projectConversationsToggle:"Show or hide the conversations of {name}",projectDescription:"A project groups the conversations about one subject.",projectFileFailed:"Failed",projectFileFailedHelp:"No text could be read from this file. It is not used.",projectFileInContext:"In context",projectFileNotAdded:"The file was not added. Try again.",projectFileNotDeleted:"The file was not deleted. Try again.",projectFileNotDownloaded:"The file was not downloaded. Try again.",projectFileNotInContext:"Not in context",projectFileNotInContextHelp:"This file does not fit in the {max} characters of file text. It is not used.",projectFileRejectedMalformed:"The file could not be read. It can be damaged.",projectFileRejectedOversized:"The file has more than 10 MB.",projectFileRejectedTooManyFiles:"The project already has 20 files. Delete a file to add another.",projectFileRejectedUnsupported:"This file type is not accepted. Use a docx, pdf, txt or md file.",projectFileTruncated:"Truncated",projectFileTruncatedHelp:"Only the first 12,000 characters of this file are used.",projectFiles:"Project files",projectFilesFull:"This project has 20 files, the most that it can have. Delete a file to add another.",projectFilesHelp:"Each conversation of this project receives the text of these files, except Agent conversations. You can add docx, pdf, txt and md files of 10 MB at most, 20 for each project.",projectFilesNotAdded:"Files not added",projectFilesNotLoaded:"The project files were not loaded.",projectFilesUsage:"File text in context",projectFilesUsageValue:"{used} of {max} characters",projectInstructions:"Project instructions",projectInstructionsHelp:"Each conversation of this project receives these instructions, except Agent conversations. To remove them, save an empty text.",projectInstructionsNotSaved:"The project instructions were not saved. Try again.",projectInstructionsTooLong:"Project instructions can have 8,000 characters at most. Make the text shorter to save it.",projectName:"Project name",projectNameHelp:"Use 1 to 200 characters.",projectNoConversations:"No conversations in this project yet",projectNoConversationsDescription:"Send a message to start the first one.",projectNotDeleted:"The project was not deleted. Try again.",projectNotSaved:"The project was not saved. Try again.",projects:"Projects",projectsNotLoaded:"The projects were not loaded.",questionAnswer:"Answer",questionApprovalCompleted:"Approval resolved",questionApprove:"Approve",questionCancelled:"Cancelled",questionCompleted:"Answer received",questionConfirmHint:"This confirms the current operation only and does not change organization approval status.",questionConfirmTitle:"Direct confirmation",questionContinue:"Continue",questionFailed:"Response failed",questionOtherAnswer:"Other answer",questionOtherOption:"Tell me what to do",questionPreview:"Preview",questionResponding:"Applying…",questionRevise:"Revise",questionReviseLabel:"Tell me what to do differently",questionTextAnswer:"Your answer",questionTextPlaceholder:"Write your answer…",questionTool:"Tool: {name}",queuedMessageNotRemoved:"The queued message was not removed. Try again.",queuedMessages:"Queued messages",readAloud:"Read aloud",readAloudFailed:"The answer was not read aloud. Try again.",readAloudStop:"Stop reading aloud",reasoning:"Reasoning",refreshConversation:"Refresh conversation",regenerate:"Regenerate",removeFromProject:"Remove from project",removeQueuedMessage:"Remove queued message {content}",rename:"Rename",renameConversation:"Rename conversation",renameConversationDescription:"Use a short title that makes this chat easy to find later.",renameProject:"Rename project",reset:"Reset",retry:"Try again",runApprovalNeeded:"Your approval is needed",runCardDetail:"Run {id}",runCardStatus:"Status:",runCardTitle:"Assistant run",runCardTraceLink:"View trace",runInputNeeded:"Your input is needed",runOutputPending:"Finishing the response",runPermissionNeeded:"Your permission is needed",runProcessedCount:"Processed {completed} of {expected}",runProgressLost:"Live progress is not available. Try again to see the latest answer.",runRequestsWaiting:"{count} more requests waiting",runReserved:"Preparing {expected} items",runStatusActive:"Active",runStatusAnswerReceived:"Answer received",runStatusCompleted:"Completed",runStatusFailed:"Failed",runStatusNeedsInput:"Needs your input",runStatusResponseFailed:"Response failed",runStatusStopped:"Stopped",runStatusWaitingForApproval:"Waiting for approval",runTerminal:"Finalizing {completed} processed items",save:"Save",searchAgents:"Search agents...",searchConversations:"Search conversations",searchSkills:"Search skills...",searchTools:"Search tools...",selectAgent:"Select agent",selectSkills:"Select skills",selectTools:"Select tools",selectedSkills:"{count} skills",send:"Send",sendAfterThisAnswer:"Send after this answer",sendFailed:"The message was not sent. Try again.",sendOptions:"More send options",serviceNotAvailable:"Service not available",serviceNotAvailableDescription:"The chat cannot reach the service now. Try again later.",signInToChat:"Sign in to chat",signInToChatDescription:"Sign in to see your conversations and to chat.",skillOwnModeNotice:"A selected skill reads all Organization data in its own mode: every Knowledge schema and document, whatever your access.",skills:"Skills",steeringMessageSent:"Sent while answering",stepAccepted:"Prepared request",stepApproval:"Waiting for approval",stepCommand:"Ran {name}",stepCommandFallback:"command",stepCompacted:"Compacted older context",stepCompacting:"Compacting older context",stepCompactionFailed:"Context compaction failed",stepCompactionReused:"Using compacted context",stepDone:"Done",stepDuration:"{ms} ms",stepFile:"Read {name}",stepFileFallback:"file",stepInput:"Waiting for your input",stepModel:"Queried model",stepPermission:"Waiting for permission",stepRun:"Ran assistant workflow",stepRunFailed:"Assistant run failed",stepSkill:"Skill: {name}",stepSkillFallback:"Skill",stepTool:"Tool: {name}",stepToolFallback:"Tool",stepUpdated:"Assistant step updated",stepsSummary:"Processing steps ({count})",stepsSummaryFailed:"Processing steps ({count}), failed",stop:"Stop",stopFailed:"The answer was not stopped. Try again.",submitting:"Sending",thisPlace:"This place",today:"Today",tools:"Tools",trailChips:"Context Trail",trailEvent:"Event",trailNotice:"The assistant can see the pages you open in this app.",trailPage:"Page",trailRemove:"Remove {chip}",trailSent:"Context Trail of this message",transcriptError:"The conversation could not load.",transcriptErrorDescription:"Something went wrong while loading this conversation. Try again after checking your connection.",unknownPlace:"Unknown place",voiceInput:"Dictate a message",voiceInputFailed:"Voice input did not work. Try again.",voiceInputStop:"Stop and transcribe",voiceInputTimeLimit:"Recording stopped at the time limit.",voiceInputTooLong:"The recording is too long. Record a shorter message.",voiceInputTranscribing:"Transcribing…",working:"Working on it",yesterday:"Yesterday",you:"You"};var it={actionFailed:"Questa azione non è riuscita. Riprova.",addProjectFiles:"Aggiungi file",agent:"Agent",agentConversationNoProjectContext:"Questa conversazione con un agent non riceve il contesto del progetto.",agentRefreshFailed:"Impossibile aggiornare la risposta.",agentTurnBlocked:"Questo agent non può eseguire il messaggio con i criteri attuali.",agentTurnBlockedWithReason:"Questo agent non può eseguire il messaggio: {reason}.",agentTurnCancelled:"Questa richiesta è stata annullata.",agentTurnFailed:"L'agent non è riuscito a completare questa richiesta.",agentTurnNoReply:"L'agent ha terminato senza una risposta.",agentTurnPaused:"Questo agent è in pausa. Il tuo messaggio è in coda e partirà alla ripresa.",agentTurnWorking:"L'agent ci sta lavorando…",allListedPlaces:"Tutti i luoghi elencati",appNotAvailable:"App non disponibile",appNotAvailableDescription:"Questa app non può usare la chat ora.",approvalApprove:"Approva",approvalApproving:"Approvazione in corso…",approvalComment:"Commento (facoltativo)",approvalCommentPlaceholder:"Aggiungi un commento",approvalConfirmReject:"Conferma il rifiuto",approvalDecideHint:"Controlla i dettagli dell'approvazione e registra la tua decisione.",approvalDecision:"{actor} · {decision} · {date}",approvalDecisionApproved:"approvata",approvalDecisionRejected:"rifiutata",approvalDecisions:"Decisioni registrate",approvalEligibleDirect:"Idoneo per assegnazione diretta",approvalEligibleGroup:"Idoneo come membro di un gruppo",approvalExpires:"Scade il {date}",approvalLoadFailed:"Impossibile caricare i dettagli dell'approvazione.",approvalModeAll:"Tutti i passaggi",approvalModeAny:"Un passaggio qualsiasi",approvalOutcomeAlreadyApproved:"Già approvata",approvalOutcomeAlreadyDecided:"Già decisa",approvalOutcomeContinuationFailed:"L'esecuzione non è potuta proseguire",approvalOutcomeContinuationInProgress:"L'esecuzione sta proseguendo",approvalOutcomeReconciliationRequired:"L'esecuzione richiede una verifica prima di proseguire",approvalOutcomeRecorded:"Decisione registrata",approvalReadOnly:"Sola lettura",approvalReadOnlyHint:"Controlla i dettagli registrati dell'approvazione.",approvalReject:"Rifiuta",approvalRejectReason:"Motivo del rifiuto",approvalRejectReasonPlaceholder:"Spiega il motivo a chi ha fatto la richiesta",approvalResolution:"Esito: {reason}",approvalStatusApproved:"Approvata",approvalStatusCancelled:"Annullata",approvalStatusExpired:"Scaduta",approvalStatusPending:"In attesa",approvalStatusRejected:"Rifiutata",approvalStepProgress:"{approved} di {required} approvate",approvalSteps:"Passaggi di approvazione",approvalTitle:"Richiesta di approvazione",artifactCurrent:"Elaborazione di {filename}",artifactFailed:"{count} non riusciti",artifactFiles:"File: {summary}",artifactLeased:"{count} in elaborazione",artifactPending:"{count} in attesa",artifactProcessed:"{count} elaborati",artifactSkipped:"{count} saltati",assistant:"Assistente",assistantSidebarCollapse:"Comprimi",assistantSidebarDelete:"Elimina questa conversazione",assistantSidebarDeleteTitle:"Eliminare questa conversazione?",assistantSidebarToggle:"Assistente",attach:"Allega file",attachmentDownload:"Scarica",attachmentDownloadFile:"Scarica {name}",attachmentDownloading:"Download in corso",attachmentNotAttached:"Il file {name} non è stato allegato.",attachmentOversized:"Ogni file può avere al massimo 10 MB.",attachmentPreview:"Anteprima di {name}",attachmentPreviewDescription:"Anteprima dell'immagine allegata.",attachmentRemove:"Rimuovi {name}",attachmentTooManyFiles:"Puoi allegare al massimo 10 file a un messaggio.",attachmentUnsupported:"Questo tipo di file non è supportato.",attachmentsNotAttached:"I file non sono stati allegati.",cancel:"Annulla",chatNotAvailable:"Chat non disponibile",chatNotAvailableDescription:"Il tuo account non può usare la chat qui.",clearAgent:"Rimuovi agent",clearSearch:"Cancella ricerca",clearSkills:"Rimuovi le skill selezionate",clearTools:"Rimuovi gli strumenti selezionati",compact:"Compatta",compacted:"Compattata",compactedContext:"Contesto compattato",compactedContextDescription:"L'assistente usa questo riepilogo per la cronologia meno recente della chat.",compactionCoveredMessages:"Messaggi inclusi",compactionCoveredRuns:"Esecuzioni incluse",compactionFailed:"La conversazione non è stata compattata. Riprova.",compactionMarker:"Contesto precedente compattato",compactionMessages:"{count} messaggi",compactionNotChanged:"Il contesto compattato non è stato modificato. Riprova.",compactionRuns:"{count} esecuzioni",compactionStatus:"Stato",composerDrop:"Rilascia i file per allegarli",composerInput:"Messaggio",composerPlaceholder:"Chiedi qualsiasi cosa...",contextUsage:"Uso del contesto",conversationActions:"Gestisci la conversazione {title}",conversationNotMoved:"La conversazione non è stata spostata. Riprova.",conversationTitle:"Titolo della conversazione",conversations:"Conversazioni",conversationsDescription:"Apri o gestisci le tue conversazioni.",conversationsNotLoaded:"Le conversazioni non sono state caricate.",createProject:"Crea progetto",delete:"Elimina",deleteConversation:"Eliminare la conversazione?",deleteConversationDescription:'Questa azione rimuove "{title}" dalle tue conversazioni.',deleteProject:"Elimina progetto",deleteProjectDescription:"Le sue conversazioni vengono eliminate insieme al progetto, anche quelle avviate in altri luoghi.",deleteProjectFile:"Elimina il file {name}",deleteProjectTitle:'Eliminare il progetto "{name}"?',downloadProjectFile:"Scarica il file {name}",draft:"Bozza",earlier:"Precedenti",editQueuedMessage:"Modifica il messaggio in coda {content}",emptyDescription:"Fai una domanda per iniziare una conversazione.",emptyTitle:"Nuova chat",evidenceContradiction:"Contraddizione: {status}",evidenceEmpty:"Nessun contenuto",evidenceLinks:"Link",evidenceOmitted:"Altri {count} elementi di evidenza sono stati omessi.",evidenceOpen:"Apri",evidenceOpenSource:"Apri {title}",evidenceOpening:"Verifica in corso…",evidenceRelevance:"Pertinenza {percent}%",evidenceShowMore:"Mostra altri {count}",evidenceSources:"Fonti",evidenceUnavailable:"Questa fonte non è disponibile.",evidenceWarnings:"Avvisi",feedbackGroup:"Valutazione della risposta",feedbackNegative:"Valuta la risposta come non utile",feedbackNote:"Nota (obbligatoria)",feedbackNoteDescription:"Spiega cosa non ha funzionato. La nota è obbligatoria.",feedbackNoteTitle:"Aggiungi una nota",feedbackPositive:"Valuta la risposta come utile",feedbackSaving:"Salvataggio…",feedbackSubmit:"Invia la valutazione",fileDownload:"Scarica {name}",fileOpen:"Apri {name}",filePreview:"Anteprima di {name}",filePreviewDescription:"Visualizza l'anteprima del file o scaricane una copia.",historyFilter:"Conversazioni da mostrare",imageActualCost:"Costo effettivo",imageAspectRatio:"Proporzioni",imageBackground:"Sfondo",imageCost:"Costo",imageCostSource:"Origine del costo",imageCostUnavailable:"Costo non disponibile",imageCount:"Immagini",imageDeployment:"Deployment",imageDetailsUnavailable:"Dettagli della generazione non disponibili",imageEstimatedCost:"Costo stimato",imageFormat:"Formato",imageModel:"Modello",imageModelVersion:"Versione del modello",imageProvider:"Provider",imageProviderConfigured:"Provider configurato",imageProviderModel:"Modello del provider",imageQuality:"Qualità",imageReferenceImages:"Immagini di riferimento",imageResolution:"Risoluzione",imageStatusAttentionRequired:"La generazione delle immagini richiede attenzione",imageStatusCancelled:"Generazione delle immagini annullata",imageStatusCompleted:"Generazione delle immagini completata",imageStatusFailed:"Generazione delle immagini non riuscita",imageStatusPartial:"Alcune immagini non sono state generate",imageStatusPending:"Generazione delle immagini in attesa",imageStatusRunning:"Generazione delle immagini…",imageTitle:"Generazione di immagini",intentApprovalInputs:"Input",intentApprovalTitle:"Consentire all'assistente di eseguire l'Intent {name}?",intentCardCompleted:"Completato",intentCardEnded:"Risultato non più disponibile",intentCardFailed:"Non riuscito",intentCardTitle:"Intent {name}",intentCardWorking:"In corso",launchIntoAgentConversation:"Questa conversazione appartiene a un Agente. Avvia una nuova chat per eseguire questa azione.",launchIntoBusyConversation:"Questa conversazione è occupata. Attendi la risposta, poi riprova.",loading:"Caricamento...",memoryCreated:"Creata",memoryDisabled:"Disattivata",memoryMerged:"Unita",memoryNotChanged:"L'impostazione della memoria non è stata modificata. Riprova.",memoryOff:"Memoria disattivata",memoryOn:"Memoria attiva",memoryRetrieved:"Recuperata",memorySaved:"{count} salvate",memorySelected:"Selezionata",memorySkipped:"Saltata",memorySuggested:"Suggerita",memorySuperseded:"Sostituita",memoryTitle:"Memoria usata",memoryUsed:"{count} usate",memoryUsedEvent:"Usata",moveToProject:"Sposta nel progetto",multipleSkills:"{count} skill",multipleTools:"{count} strumenti",newChat:"Nuova chat",newProject:"Nuovo progetto",noAgents:"Nessun agent disponibile.",noChat:"Nessuna chat disponibile",noCompactionSummary:"Nessun riepilogo di compattazione attivo.",noConversations:"Ancora nessuna conversazione",noConversationsDescription:"Avvia una nuova chat per visualizzarla qui.",noProjectFiles:"Ancora nessun file in questo progetto",noProjectFilesDescription:"Aggiungi un file per fornire il suo testo a ogni conversazione del progetto.",noProjects:"Ancora nessun progetto",noSearchResults:"Nessuna conversazione corrisponde alla ricerca",noSkills:"Nessuna skill corrisponde.",noTools:"Nessuno strumento corrisponde.",openConversation:"Apri la conversazione {title}",openConversationList:"Apri le conversazioni",openProject:"Apri progetto {name}",optionsError:"Impossibile caricare l'elenco.",permissionAllowAlways:"Consenti sempre",permissionAllowThisConversation:"Consenti solo per questa conversazione",permissionDeny:"Non consentire",permissionDescription:"Consentilo per questa chat, o ricorda questo elemento per le prossime volte.",permissionRegion:"Richiesta di autorizzazione per {name}",permissionSkill:"la skill",permissionTitle:"Consentire all'assistente di usare {name}?",permissionTool:"lo strumento",personalAgent:"Personale",pickAgent:"Scegli un agent per iniziare una chat.",previousSevenDays:"Ultimi 7 giorni",projectActions:"Gestisci progetto {name}",projectConversations:"Conversazioni",projectConversationsToggle:"Mostra o nascondi le conversazioni di {name}",projectDescription:"Un progetto raggruppa le conversazioni su un argomento.",projectFileFailed:"Lettura non riuscita",projectFileFailedHelp:"Non è stato possibile leggere il testo di questo file. Non viene usato.",projectFileInContext:"Nel contesto",projectFileNotAdded:"Il file non è stato aggiunto. Riprova.",projectFileNotDeleted:"Il file non è stato eliminato. Riprova.",projectFileNotDownloaded:"Il file non è stato scaricato. Riprova.",projectFileNotInContext:"Fuori dal contesto",projectFileNotInContextHelp:"Questo file non rientra nei {max} caratteri di testo dei file. Non viene usato.",projectFileRejectedMalformed:"Non è stato possibile leggere il file. Potrebbe essere danneggiato.",projectFileRejectedOversized:"Il file supera i 10 MB.",projectFileRejectedTooManyFiles:"Il progetto ha già 20 file. Elimina un file per aggiungerne un altro.",projectFileRejectedUnsupported:"Questo tipo di file non è accettato. Usa un file docx, pdf, txt o md.",projectFileTruncated:"Troncato",projectFileTruncatedHelp:"Vengono usati solo i primi 12.000 caratteri di questo file.",projectFiles:"File del progetto",projectFilesFull:"Questo progetto ha 20 file, il numero massimo. Elimina un file per aggiungerne un altro.",projectFilesHelp:"Ogni conversazione del progetto riceve il testo di questi file, tranne le conversazioni con un agent. Puoi aggiungere file docx, pdf, txt e md di 10 MB al massimo, fino a 20 per progetto.",projectFilesNotAdded:"File non aggiunti",projectFilesNotLoaded:"I file del progetto non sono stati caricati.",projectFilesUsage:"Testo dei file nel contesto",projectFilesUsageValue:"{used} di {max} caratteri",projectInstructions:"Istruzioni del progetto",projectInstructionsHelp:"Ogni conversazione del progetto riceve queste istruzioni, tranne le conversazioni con un agent. Per rimuoverle, salva un testo vuoto.",projectInstructionsNotSaved:"Le istruzioni del progetto non sono state salvate. Riprova.",projectInstructionsTooLong:"Le istruzioni del progetto possono avere al massimo 8.000 caratteri. Accorcia il testo per salvarlo.",projectName:"Nome del progetto",projectNameHelp:"Usa da 1 a 200 caratteri.",projectNoConversations:"Ancora nessuna conversazione in questo progetto",projectNoConversationsDescription:"Invia un messaggio per avviare la prima.",projectNotDeleted:"Il progetto non è stato eliminato. Riprova.",projectNotSaved:"Il progetto non è stato salvato. Riprova.",projects:"Progetti",projectsNotLoaded:"I progetti non sono stati caricati.",questionAnswer:"Rispondi",questionApprovalCompleted:"Approvazione risolta",questionApprove:"Approva",questionCancelled:"Annullata",questionCompleted:"Risposta ricevuta",questionConfirmHint:"Conferma solo l'operazione corrente e non cambia lo stato di approvazione dell'organizzazione.",questionConfirmTitle:"Conferma diretta",questionContinue:"Continua",questionFailed:"Risposta non riuscita",questionOtherAnswer:"Altra risposta",questionOtherOption:"Dimmi cosa fare",questionPreview:"Anteprima",questionResponding:"Applicazione in corso…",questionRevise:"Modifica",questionReviseLabel:"Dimmi cosa fare in modo diverso",questionTextAnswer:"La tua risposta",questionTextPlaceholder:"Scrivi la tua risposta…",questionTool:"Strumento: {name}",queuedMessageNotRemoved:"Il messaggio in coda non è stato rimosso. Riprova.",queuedMessages:"Messaggi in coda",readAloud:"Leggi ad alta voce",readAloudFailed:"Non è stato possibile leggere la risposta ad alta voce. Riprova.",readAloudStop:"Interrompi la lettura",reasoning:"Ragionamento",refreshConversation:"Aggiorna conversazione",regenerate:"Rigenera",removeFromProject:"Rimuovi dal progetto",removeQueuedMessage:"Rimuovi il messaggio in coda {content}",rename:"Rinomina",renameConversation:"Rinomina la conversazione",renameConversationDescription:"Usa un titolo breve, per ritrovare facilmente questa chat.",renameProject:"Rinomina progetto",reset:"Reimposta",retry:"Riprova",runApprovalNeeded:"Serve la tua approvazione",runCardDetail:"Esecuzione {id}",runCardStatus:"Stato:",runCardTitle:"Esecuzione dell'assistente",runCardTraceLink:"Vedi traccia",runInputNeeded:"Serve una tua risposta",runOutputPending:"Completamento della risposta",runPermissionNeeded:"Serve la tua autorizzazione",runProcessedCount:"Elaborati {completed} di {expected}",runProgressLost:"L'avanzamento in tempo reale non è disponibile. Riprova per vedere l'ultima risposta.",runRequestsWaiting:"Altre {count} richieste in attesa",runReserved:"Preparazione di {expected} elementi",runStatusActive:"Attiva",runStatusAnswerReceived:"Risposta ricevuta",runStatusCompleted:"Completata",runStatusFailed:"Non riuscita",runStatusNeedsInput:"Serve una tua risposta",runStatusResponseFailed:"Risposta non riuscita",runStatusStopped:"Interrotta",runStatusWaitingForApproval:"In attesa di approvazione",runTerminal:"Finalizzazione di {completed} elementi elaborati",save:"Salva",searchAgents:"Cerca agent...",searchConversations:"Cerca conversazioni",searchSkills:"Cerca skill...",searchTools:"Cerca strumenti...",selectAgent:"Seleziona agent",selectSkills:"Seleziona skill",selectTools:"Seleziona strumenti",selectedSkills:"{count} skill",send:"Invia",sendAfterThisAnswer:"Invia dopo questa risposta",sendFailed:"Il messaggio non è stato inviato. Riprova.",sendOptions:"Altre opzioni di invio",serviceNotAvailable:"Servizio non disponibile",serviceNotAvailableDescription:"La chat non raggiunge il servizio ora. Riprova più tardi.",signInToChat:"Accedi per chattare",signInToChatDescription:"Accedi per vedere le tue conversazioni e chattare.",skillOwnModeNotice:"Una skill selezionata legge tutti i dati dell’organizzazione nella propria modalità: ogni schema Knowledge e ogni documento, qualunque sia il tuo accesso.",skills:"Skill",steeringMessageSent:"Inviato durante la risposta",stepAccepted:"Richiesta preparata",stepApproval:"In attesa di approvazione",stepCommand:"Eseguito {name}",stepCommandFallback:"comando",stepCompacted:"Contesto precedente compattato",stepCompacting:"Compattazione del contesto precedente",stepCompactionFailed:"Compattazione del contesto non riuscita",stepCompactionReused:"Uso del contesto compattato",stepDone:"Fatto",stepDuration:"{ms} ms",stepFile:"Letto {name}",stepFileFallback:"file",stepInput:"In attesa di una tua risposta",stepModel:"Modello interrogato",stepPermission:"In attesa di autorizzazione",stepRun:"Flusso dell'assistente eseguito",stepRunFailed:"Esecuzione dell'assistente non riuscita",stepSkill:"Skill: {name}",stepSkillFallback:"Skill",stepTool:"Strumento: {name}",stepToolFallback:"Strumento",stepUpdated:"Passaggio dell'assistente aggiornato",stepsSummary:"Passaggi di elaborazione ({count})",stepsSummaryFailed:"Passaggi di elaborazione ({count}), non riuscito",stop:"Interrompi",stopFailed:"La risposta non è stata interrotta. Riprova.",submitting:"Invio in corso",thisPlace:"Questo luogo",today:"Oggi",tools:"Strumenti",trailChips:"Contesto di navigazione",trailEvent:"Evento",trailNotice:"L'assistente può vedere le pagine che apri in questa app.",trailPage:"Pagina",trailRemove:"Rimuovi {chip}",trailSent:"Contesto di navigazione di questo messaggio",transcriptError:"Impossibile caricare la conversazione.",transcriptErrorDescription:"Si è verificato un errore durante il caricamento della conversazione. Controlla la connessione e riprova.",unknownPlace:"Luogo sconosciuto",voiceInput:"Detta un messaggio",voiceInputFailed:"L'input vocale non ha funzionato. Riprova.",voiceInputStop:"Interrompi e trascrivi",voiceInputTimeLimit:"Registrazione interrotta al limite di tempo.",voiceInputTooLong:"La registrazione è troppo lunga. Registra un messaggio più breve.",voiceInputTranscribing:"Trascrizione in corso…",working:"Al lavoro",yesterday:"Ieri",you:"Tu"};var chatLabels={en,it};var labelsOf=(locale,overrides)=>overrides===undefined?chatLabels[locale]:{...chatLabels[locale],...overrides};var fillLabel=(label,values)=>label.replaceAll(/\{(?<name>\w+)\}/gu,(placeholder,name)=>values[name]??placeholder);import{jsx as jsx3,jsxs as jsxs2}from"react/jsx-runtime";var triggerText=(chosen,labels)=>{const[first]=chosen;if(first===undefined){return labels.none}return chosen.length===1?first.name:fillLabel(labels.multiple,{count:String(chosen.length)})};var ChatPicker=({chosen,dataPart,disabled=false,failed,icon,labels,onClear,onToggle,options,single=false})=>{const[open,setOpen]=useState3(false);const chosenIds=new Set(chosen.map(({id})=>id));return jsxs2("div",{className:cn3("flex max-w-48 min-w-0 items-center overflow-hidden rounded-md",chosen.length>0&&"bg-muted"),"data-part":dataPart,children:[jsxs2(Popover,{onOpenChange:setOpen,open,children:[jsxs2(PopoverTrigger,{render:jsx3(Button2,{"aria-label":labels.select,className:"h-8 min-w-0 flex-1 gap-1.5 px-3",disabled,size:"sm",title:chosen.map(({name})=>name).join(", ")||undefined,type:"button",variant:"ghost"}),children:[icon,jsx3("span",{className:"truncate",children:triggerText(chosen,labels)})]}),jsx3(PopoverContent,{align:"start",className:"w-96 p-0",children:jsxs2(Command,{children:[jsx3(CommandInput,{placeholder:labels.search}),jsxs2(CommandList,{children:[jsx3(CommandEmpty,{children:failed?labels.error:labels.empty}),jsx3(CommandGroup,{children:(options??[]).map((option)=>jsxs2(CommandItem,{className:"items-center gap-2.5 px-2 py-2",keywords:[option.name,...option.keywords],onSelect:()=>{onToggle(option);if(single){setOpen(false)}},value:option.id,children:[option.icon??jsx3(IconTile,{initial:option.name,size:"sm"}),jsxs2("span",{className:"min-w-0 flex-1",children:[jsx3("span",{className:"block truncate text-sm font-medium",children:option.name}),option.description===null||option.description.trim()===""?null:jsx3("span",{className:"block truncate text-xs text-muted-foreground",children:option.description})]}),option.end,jsx3(Check,{className:cn3("size-4 shrink-0",chosenIds.has(option.id)?"opacity-100":"opacity-0")})]},option.id))})]})]})})]}),onClear===undefined||chosen.length===0?null:jsx3(Button2,{"aria-label":labels.clear,className:"size-8 shrink-0 rounded-none border-l border-border/70 text-muted-foreground hover:text-foreground",disabled,onClick:onClear,size:"icon",type:"button",variant:"ghost",children:jsx3(X,{className:"size-3.5"})})]})};var capabilityChoice=(capabilities,setCapabilities,kind)=>{const chosen=capabilities.filter((capability)=>capability.kind===kind);const others=capabilities.filter((capability)=>capability.kind!==kind);return{chosen,onClear:()=>{setCapabilities(others)},onToggle:({id,name})=>{setCapabilities(chosen.some((capability)=>capability.id===id)?capabilities.filter((capability)=>capability.id!==id):[...capabilities,{id,kind,name}])}}};import{jsx as jsx4,jsxs as jsxs3,Fragment}from"react/jsx-runtime";var listOf=(read)=>({failed:read.result?.ok===false,items:read.result?.ok===true?read.result.value.data:undefined});var useChatSkills=()=>listOf(useChatRead((client)=>client.chatCatalog.listSkills()));var skillOption=(skill)=>({description:skill.description,id:skill.id,keywords:[skill.slug,`/${skill.slug}`],name:skill.name});var toolOption=(tool)=>({description:tool.description,id:tool.id,keywords:[tool.fqn],name:tool.displayName});var pickerLabels=(labels,kind)=>kind==="skill"?{clear:labels.clearSkills,empty:labels.noSkills,error:labels.optionsError,multiple:labels.multipleSkills,none:labels.skills,search:labels.searchSkills,select:labels.selectSkills}:{clear:labels.clearTools,empty:labels.noTools,error:labels.optionsError,multiple:labels.multipleTools,none:labels.tools,search:labels.searchTools,select:labels.selectTools};var ToolPicker=({capabilities,disabled,labels,setCapabilities})=>{const tools=listOf(useChatRead((client)=>client.chatCatalog.listTools({query:{usageScope:"chat"}})));return jsx4(ChatPicker,{...capabilityChoice(capabilities,setCapabilities,"tool"),dataPart:"tool-picker",disabled,failed:tools.failed,icon:jsx4(Wrench,{className:"size-3.5"}),labels:pickerLabels(labels,"tool"),options:tools.items?.map(toolOption)})};var ChatCapabilityPickers=({capabilities,disabled,labels,setCapabilities,skills})=>jsxs3(Fragment,{children:[jsx4(ChatPicker,{...capabilityChoice(capabilities,setCapabilities,"skill"),dataPart:"skill-picker",disabled,failed:skills.failed,icon:jsx4(Sparkles,{className:"size-3.5"}),labels:pickerLabels(labels,"skill"),options:skills.items?.map(skillOption)}),jsx4(ToolPicker,{capabilities,disabled,labels,setCapabilities})]});var ChatAgentPicker=({agentId,clearable,disabled,labels,onChange})=>{const agents=listOf(useChatRead((client)=>client.chatCatalog.listAgents()));const picked=agents.items?.find(({id})=>id===agentId);return jsx4(ChatPicker,{chosen:agentId===null?[]:[{id:agentId,name:picked?.displayName??labels.agent}],dataPart:"agent-picker",disabled,failed:agents.failed,icon:jsx4(Bot,{className:"size-3.5 shrink-0"}),labels:{clear:labels.clearAgent,empty:labels.noAgents,error:labels.optionsError,multiple:labels.agent,none:labels.agent,search:labels.searchAgents,select:labels.selectAgent},onClear:clearable?()=>{onChange(null)}:undefined,onToggle:({id})=>{const agent=agents.items?.find((item)=>item.id===id);if(agent!==undefined){onChange(agent.id)}},options:agents.items?.map((agent)=>({description:agent.responsibility,...agent.agentType==="personal"&&{end:jsx4(Badge,{className:"text-muted-foreground",variant:"outline",children:labels.personalAgent})},icon:jsx4(IconTile2,{size:"sm",tone:"accent",children:jsx4(Bot,{})}),id:agent.id,keywords:[agent.displayName,agent.responsibility],name:agent.displayName})),single:true})};var skillSources=["datasets","documents","knowledge"];var picksOwnModeSkill=(skills,capabilities)=>skills.some(({dataAccess,id})=>capabilities.some((capability)=>capability.kind==="skill"&&capability.id===id)&&skillSources.some((source)=>dataAccess?.[source]!=="user"));import{Button as Button3}from"@collective-intelligence/ui-react/ui";import{IconTile as IconTile3}from"@collective-intelligence/ui-react/ui-extensions";import{jsx as jsx5,jsxs as jsxs4}from"react/jsx-runtime";var maxSuggestions=5;var slashWord=/(?:^|\s)\/(?<word>[a-z0-9_-]*)$/iu;var slashMatches=(draft,skills,capabilities)=>{const word=slashWord.exec(draft)?.groups?.word?.toLowerCase();if(word===undefined){return[]}return skills.filter(({id})=>!capabilities.some((capability)=>capability.id===id)).filter(({name,slug})=>slug.toLowerCase().startsWith(word)||name.toLowerCase().includes(word)).slice(0,maxSuggestions)};var withoutSlashWord=(draft)=>draft.replace(slashWord,"").trimStart();var choosingKeys=new Set(["Enter","Tab"," "]);var useSlashSkills=(session,skills,enabled)=>{const matches=enabled?slashMatches(session.draft,skills,session.capabilities):[];const handleChoose=({id,name})=>{session.setCapabilities([...session.capabilities,{id,kind:"skill",name}]);session.setDraft(withoutSlashWord(session.draft))};const handleKeyDown=(event)=>{const[first]=matches;if(first!==undefined&&choosingKeys.has(event.key)){event.preventDefault();handleChoose(first)}};return{handleChoose,handleKeyDown,matches}};var SlashSuggestions=({matches,onChoose})=>matches.length===0?null:jsx5("div",{className:"flex w-[min(400px,100%)] flex-col overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md","data-part":"slash-suggestions",children:matches.map((skill)=>jsxs4(Button3,{className:"h-auto justify-start gap-2.5 px-2 py-1.5 text-left",onClick:()=>{onChoose(skill)},type:"button",variant:"ghost",children:[jsx5(IconTile3,{initial:skill.name,size:"sm"}),jsxs4("span",{className:"min-w-0 flex-1",children:[jsx5("span",{className:"block truncate font-medium",children:skill.name}),skill.description===null||skill.description.trim()===""?null:jsx5("span",{className:"block truncate text-xs font-normal text-muted-foreground",children:skill.description})]}),jsxs4("span",{className:"shrink-0 text-xs font-normal text-muted-foreground",children:["/",skill.slug]})]},skill.id))});import{jsx as jsx6,jsxs as jsxs5,Fragment as Fragment2}from"react/jsx-runtime";var modelAnswers=({conversationId,conversations},agentChoice,pickedAgentId)=>conversationId===null?agentChoice==="optional"&&pickedAgentId===null:conversations.some(({agentId,id})=>id===conversationId&&agentId===null);var useComposerPicks=({agentChoice,composerParts,disabled,labels,onAgentPicked,running,session})=>{const[agentId,setAgentId]=useState4(null);const skills=useChatSkills();const newChat=session.conversationId===null;const takesCapabilities=modelAnswers(session,agentChoice,agentId);const slash=useSlashSkills(session,skills.items??[],takesCapabilities);const AgentPicker=composerParts?.AgentPicker??ChatAgentPicker;const CapabilityPickers=composerParts?.CapabilityPickers??ChatCapabilityPickers;const pickAgent=(next)=>{setAgentId(next);session.setCapabilities([]);onAgentPicked()};const ownModeSkill=takesCapabilities&&picksOwnModeSkill(skills.items??[],session.capabilities);return{agentId:newChat?agentId:null,handleKeyDown:slash.handleKeyDown,notice:ownModeSkill?jsx6("output",{className:"block text-sm text-muted-foreground","data-part":"own-mode-notice",children:labels.skillOwnModeNotice}):null,pickers:jsxs5(Fragment2,{children:[takesCapabilities?jsx6(CapabilityPickers,{capabilities:session.capabilities,disabled,labels,setCapabilities:session.setCapabilities,skills}):null,newChat&&agentChoice!=="pinned"?jsx6(AgentPicker,{agentId,clearable:agentChoice==="optional",disabled:disabled||running,labels,onChange:pickAgent}):null]}),suggestions:jsx6(SlashSuggestions,{matches:slash.matches,onChoose:slash.handleChoose}),takesCapabilities}};import{X as X2}from"@collective-intelligence/ui-react/icons";import{Badge as Badge2}from"@collective-intelligence/ui-react/ui";import{jsx as jsx7,jsxs as jsxs6}from"react/jsx-runtime";var chipText=(entry,labels)=>{if("event"in entry){return`${labels.trailEvent}: ${entry.event}`}if("source"in entry){const{"@type":type,name}=entry.data;return hasStringRuntimeKind2(name)?`${type}: ${name}`:type}return`${labels.trailPage}: ${entry.title}`};var entryKeys=new WeakMap;var lastKey=0;var keyOf=(entry)=>{const known=entryKeys.get(entry);if(known!==undefined){return known}lastKey+=1;entryKeys.set(entry,lastKey);return lastKey};var TrailChips=({entries,labels,onRemove,region})=>{if(entries.length===0){return null}return jsx7("ul",{"aria-label":region,className:"flex flex-wrap gap-1.5","data-part":"trail-chips",children:entries.map((entry)=>{const text=chipText(entry,labels);return jsx7("li",{children:jsxs6(Badge2,{variant:"outline",children:[text,onRemove===undefined?null:jsx7("button",{"aria-label":fillLabel(labels.trailRemove,{chip:text}),className:"rounded-sm text-muted-foreground hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",onClick:()=>{onRemove(entry)},type:"button",children:jsx7(X2,{className:"size-3.5"})})]})},keyOf(entry))})})};import{jsx as jsx8}from"react/jsx-runtime";var useTrailSwitches=()=>{const{placeContext}=useChatSession2();return{enabled:placeContext?.contextTrailEnabled===true,visible:placeContext?.contextTrailVisible===true}};var ComposerTrailChips=({labels})=>{const{enabled,visible}=useTrailSwitches();const{trail}=useChatSession2().controls;const entries=useTrailEntries2(trail);if(!enabled||!visible||trail===undefined){return null}return jsx8(TrailChips,{entries,labels,onRemove:(entry)=>{trail.remove(entry)},region:labels.trailChips})};var ComposerTrailNotice=({labels})=>{const{enabled,visible}=useTrailSwitches();if(!enabled||visible){return null}return jsx8("p",{className:"text-xs text-muted-foreground","data-part":"trail-notice",children:labels.trailNotice})};import{Attachment,AttachmentInfo,AttachmentPreview,AttachmentRemove,Attachments,PromptInputButton,PromptInputHeader,usePromptInputAttachments}from"@collective-intelligence/ui-react/ai-elements";import{Paperclip}from"@collective-intelligence/ui-react/icons";import{jsx as jsx9,jsxs as jsxs7}from"react/jsx-runtime";var maxDraftFiles=10;var maxDraftFileBytes=10*1024*1024;var rejectionText=(rejection,takesFiles,labels)=>{if(!takesFiles){return labels.attachmentsNotAttached}const reasons={accept:labels.attachmentUnsupported,max_file_size:labels.attachmentOversized,max_files:labels.attachmentTooManyFiles};return`${labels.attachmentsNotAttached} ${reasons[rejection]}`};var useDraftFileTypes=()=>{const capabilities=useChatRead((client)=>client.chatCatalog.getAttachmentCapabilities());return capabilities.result?.ok===true?capabilities.result.value.fileTypes.flatMap(({extension,mediaTypes})=>[extension,...mediaTypes]).join(","):undefined};var bytesOf=(dataUrl)=>{const comma=dataUrl.indexOf(",");const payload=dataUrl.slice(comma+1);if(!dataUrl.slice(0,comma).endsWith(";base64")){return new TextEncoder().encode(decodeURIComponent(payload))}const binary=atob(payload);return Uint8Array.from(binary,(char)=>char.codePointAt(0)??0)};var filesOf=(parts)=>parts.map(({filename,mediaType,url})=>new File([bytesOf(url)],filename??"file",{type:mediaType}));var AttachButton=({labels})=>{const attachments=usePromptInputAttachments();return jsx9(PromptInputButton,{"aria-label":labels.attach,"data-part":"attach",onClick:()=>{attachments.openFileDialog()},children:jsx9(Paperclip,{})})};var DraftAttachments=({labels})=>{const attachments=usePromptInputAttachments();if(attachments.files.length===0){return null}return jsx9(PromptInputHeader,{"data-part":"draft-attachments",children:jsx9(Attachments,{variant:"inline",children:attachments.files.map((file)=>jsxs7(Attachment,{data:file,onRemove:()=>{attachments.remove(file.id)},children:[jsx9(AttachmentPreview,{}),jsx9(AttachmentInfo,{}),jsx9(AttachmentRemove,{label:fillLabel(labels.attachmentRemove,{name:file.filename??""})})]},file.id))})})};import{Pencil,X as X3}from"@collective-intelligence/ui-react/icons";import{Button as Button4,Input}from"@collective-intelligence/ui-react/ui";import{useId,useState as useState5}from"react";import{jsx as jsx10,jsxs as jsxs8,Fragment as Fragment3}from"react/jsx-runtime";var QueuedMessageEdit=({labels,message,onDone})=>{const session=useChatSession2();const[content,setContent]=useState5(message.content);const label=fillLabel(labels.editQueuedMessage,{content:message.content});return jsxs8("form",{className:"flex min-w-0 flex-1 items-center gap-1",onSubmit:(event)=>{event.preventDefault();session.updateQueuedMessage(message.id,content.trim(),message.revision);onDone()},children:[jsx10(Input,{"aria-label":label,autoFocus:true,className:"h-7 min-w-0 flex-1",onChange:(event)=>{setContent(event.target.value)},value:content}),jsx10(Button4,{disabled:content.trim()==="",size:"sm",type:"submit",children:labels.save}),jsx10(Button4,{onClick:onDone,size:"sm",type:"button",variant:"ghost",children:labels.cancel})]})};var QueuedMessages=({labels})=>{const session=useChatSession2();const headingId=useId();const[editing,setEditing]=useState5(null);const waiting=session.queuedMessages.filter(({status})=>status==="waiting");if(waiting.length===0){return null}return jsxs8("section",{className:"rounded-none border border-border bg-muted/30 px-3 py-2","data-part":"queued-messages",children:[jsx10("h3",{className:"text-xs font-medium text-muted-foreground",id:headingId,children:labels.queuedMessages}),jsx10("ul",{"aria-labelledby":headingId,className:"mt-1 flex flex-col gap-1",children:waiting.map((message)=>jsx10("li",{className:"flex min-w-0 items-center gap-1",children:editing===message.id?jsx10(QueuedMessageEdit,{labels,message,onDone:()=>{setEditing(null)}}):jsxs8(Fragment3,{children:[jsx10("p",{className:"min-w-0 flex-1 truncate text-sm text-foreground",children:message.content}),jsx10(Button4,{"aria-label":fillLabel(labels.editQueuedMessage,{content:message.content}),onClick:()=>{setEditing(message.id)},size:"icon-sm",type:"button",variant:"ghost",children:jsx10(Pencil,{})}),jsx10(Button4,{"aria-label":fillLabel(labels.removeQueuedMessage,{content:message.content}),onClick:()=>{session.removeQueuedMessage(message.id,message.revision)},size:"icon-sm",type:"button",variant:"ghost",children:jsx10(X3,{})})]})},message.id))})]})};import{PromptInputActionMenu,PromptInputActionMenuContent,PromptInputActionMenuItem,PromptInputActionMenuTrigger}from"@collective-intelligence/ui-react/ai-elements";import{ChevronDown}from"@collective-intelligence/ui-react/icons";import{DropdownMenuGroup}from"@collective-intelligence/ui-react/ui";import{jsx as jsx11,jsxs as jsxs9}from"react/jsx-runtime";var SendMenu=({disabled,labels,onQueue})=>jsxs9(PromptInputActionMenu,{children:[jsx11(PromptInputActionMenuTrigger,{"aria-label":labels.sendOptions,"data-part":"send-options",children:jsx11(ChevronDown,{})}),jsx11(PromptInputActionMenuContent,{align:"end",children:jsx11(DropdownMenuGroup,{children:jsx11(PromptInputActionMenuItem,{disabled,onClick:onQueue,children:labels.sendAfterThisAnswer})})})]});import{cn as cn4}from"@collective-intelligence/ui-react";import{PromptInputButton as PromptInputButton2}from"@collective-intelligence/ui-react/ai-elements";import{Loader2,Mic}from"@collective-intelligence/ui-react/icons";var noMicrophone={code:"forbidden",message:"The microphone is not available.",retryable:false};var recorderFailed={code:"unavailable",message:"The recording could not start.",retryable:true};var preferredTypes=["audio/webm;codecs=opus","audio/webm","audio/mp4"];var chunksOf=(recorder)=>new ReadableStream({start:(controller)=>{recorder.addEventListener("dataavailable",(event)=>{if(event.data.size>0){controller.enqueue(event.data)}});recorder.addEventListener("stop",()=>{controller.close()},{once:true})}});var readAll=async(reader,chunks=[])=>{const{done,value}=await reader.read();return done?chunks:await readAll(reader,[...chunks,value])};var captureMicrophone=async()=>{if(!("mediaDevices"in navigator)||!("MediaRecorder"in globalThis)){return{error:noMicrophone,ok:false}}let stream;try{stream=await navigator.mediaDevices.getUserMedia({audio:true})}catch{return{error:noMicrophone,ok:false}}const release=()=>{for(const track of stream.getTracks()){track.stop()}};try{const mimeType=preferredTypes.find((type)=>MediaRecorder.isTypeSupported(type));const recorder=new MediaRecorder(stream,mimeType===undefined?{}:{mimeType});const chunks=chunksOf(recorder).getReader();recorder.start();return{ok:true,value:{cancel:()=>{recorder.stop();release()},stop:async()=>{recorder.stop();const audio=await readAll(chunks);release();return new Blob([...audio],{type:recorder.mimeType})}}}}catch{release();return{error:recorderFailed,ok:false}}};var uploadFailed={code:"unavailable",message:"The voice clip could not be uploaded.",retryable:true};var fallbackContentType="audio/webm";var maxClipBytes=25*1024*1024;var clipTooLarge={code:"invalid_request",message:"The voice clip is larger than 25 MiB.",retryable:false};var putClip=async(audio,{headers,method,url})=>{try{const upload=await fetch(url,{body:audio,headers,method});return upload.ok}catch{return false}};var transcribeRecording=async(call,audio)=>{if(audio.size>maxClipBytes){return{error:clipTooLarge,ok:false}}const clip=await call((client)=>client.chatSpeech.createSpeechClip({payload:{contentType:audio.type===""?fallbackContentType:audio.type,size:audio.size}}));if(!clip.ok){return clip}if(!await putClip(audio,clip.value)){return{error:uploadFailed,ok:false}}const transcription=await call((client)=>client.chatSpeech.transcribeSpeechClip({payload:{clipId:clip.value.clipId}}));return transcription.ok?{ok:true,value:transcription.value.text}:transcription};import{useEffect,useRef,useState as useState6}from"react";var maxRecordingMs=30000;var idle={status:"idle",stoppedAtLimit:false};var withDictation=(draft,text)=>{const dictated=text.trim();const kept=draft.trimEnd();if(dictated.length===0){return draft}return kept.length===0?dictated:`${kept}
|
|
3
|
-
${dictated}`};var useVoiceInput=(port,draft)=>{const[state,setState]=useState6(idle);const recording=useRef(null);const timeLimit=useRef(undefined);const mounted=useRef(false);const latestDraft=useRef(draft);useEffect(()=>{latestDraft.current=draft});useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;globalThis.clearTimeout(timeLimit.current);recording.current?.cancel()}},[]);const finish=async(current,stoppedAtLimit)=>{if(recording.current!==current){return}globalThis.clearTimeout(timeLimit.current);recording.current=null;setState({status:"transcribing",stoppedAtLimit});try{const text=await current.finish();if(!text.ok){setState({status:"failed",tooLong:text.error.code==="invalid_request"});return}const{setValue,value}=latestDraft.current;setValue(withDictation(value,text.value));setState({status:"idle",stoppedAtLimit})}catch{setState({status:"failed",tooLong:false})}};const start=async()=>{setState({status:"starting"});try{const started=await port.record();if(!mounted.current){if(started.ok){started.value.cancel()}return}if(!started.ok){setState({status:"failed",tooLong:false});return}recording.current=started.value;timeLimit.current=globalThis.setTimeout(()=>{finish(started.value,true)},maxRecordingMs);setState({status:"recording"})}catch{setState({status:"failed",tooLong:false})}};const toggle=()=>{const{current}=recording;current===null?start():finish(current,false)};return{state,toggle}};import{jsx as jsx12,jsxs as jsxs10,Fragment as Fragment4}from"react/jsx-runtime";var buttonLabel=({status},labels)=>{if(status==="recording"){return labels.voiceInputStop}return status==="transcribing"?labels.voiceInputTranscribing:labels.voiceInput};var noticeOf=(state,labels)=>{if(state.status==="failed"){return state.tooLong?labels.voiceInputTooLong:labels.voiceInputFailed}return(state.status==="idle"||state.status==="transcribing")&&state.stoppedAtLimit?labels.voiceInputTimeLimit:undefined};var ButtonIcon=({status})=>status==="starting"||status==="transcribing"?jsx12(Loader2,{className:"animate-spin"}):jsx12(Mic,{className:cn4(status==="recording"&&"animate-pulse text-destructive")});var useRemoteSpeechInput=()=>{const{call}=useChatSession2();return{record:async()=>{const capture=await captureMicrophone();if(!capture.ok){return capture}const{cancel,stop}=capture.value;return{ok:true,value:{cancel,finish:async()=>await transcribeRecording(call,await stop())}}}}};var VoiceButton=({draft,labels})=>{const port=useRemoteSpeechInput();const{state,toggle}=useVoiceInput(port,draft);const notice=noticeOf(state,labels);return jsxs10(Fragment4,{children:[jsx12(PromptInputButton2,{"aria-label":buttonLabel(state,labels),"aria-pressed":state.status==="recording",className:cn4(state.status==="failed"&&"text-destructive"),"data-part":"voice-input",disabled:draft.disabled||state.status==="starting"||state.status==="transcribing",onClick:toggle,title:notice,children:jsx12(ButtonIcon,{...state})}),jsx12("output",{"aria-live":"polite",className:"sr-only",children:notice??""})]})};var ChatVoiceInput=({draft,labels})=>{const{controls}=useChatSession2();const availability=useChatRead((client)=>client.chatSpeech.getSpeechAvailability(),controls.voiceInput===undefined);const available=availability.result?.ok===true&&availability.result.value.remoteTranscription;return available?jsx12(VoiceButton,{draft,labels}):null};import{jsx as jsx13,jsxs as jsxs11,Fragment as Fragment5}from"react/jsx-runtime";var accessoryFor=(slot,draft)=>typeof slot==="function"?slot(draft):slot;var ChatComposer=({agentChoice,className,composerParts,labels,send,slots})=>{const session=useChatSession2();const[refusal,setRefusal]=useState7(null);const[rejection,setRejection]=useState7(null);const disabled=session.status!=="ready";const cannotSend=disabled||session.busy||session.draft.trim()==="";const running=session.sendMode==="running";const picks=useComposerPicks({agentChoice,composerParts,disabled,labels,onAgentPicked:()=>{setRefusal(null)},running,session});const canAttach=!disabled&&!running&&picks.takesCapabilities;const accept=useDraftFileTypes();const draft={disabled,setValue:session.setDraft,value:session.draft};const notices=[refusal?.message,rejection===null?undefined:rejectionText(rejection,canAttach,labels)].filter((notice)=>notice!==undefined);return jsxs11("div",{className:cn5("mx-auto flex w-full max-w-[900px] flex-col gap-2 px-6 pb-6",className),"data-part":"chat-composer",children:[notices.map((notice)=>jsx13("p",{className:"text-sm text-destructive",role:"alert",children:notice},notice)),picks.notice,jsx13(QueuedMessages,{labels}),jsx13(ComposerTrailChips,{labels}),picks.suggestions,jsxs11(PromptInput,{...accept!==undefined&&{accept},maxFileSize:maxDraftFileBytes,maxFiles:canAttach?maxDraftFiles:0,multiple:true,onError:({code})=>{setRejection(code)},onSubmit:({files,text})=>{if(disabled||session.busy||text.trim()===""){return}const sent=send({text,...picks.agentId!==null&&{agentId:picks.agentId},...files.length>0&&{files:filesOf(files)}});setRefusal(sent.ok?null:sent.error);setRejection(null)},children:[jsx13(DraftAttachments,{labels}),jsx13(PromptInputBody,{children:jsx13(PromptInputTextarea,{"aria-label":labels.composerInput,disabled,onChange:(event)=>{session.setDraft(event.target.value)},onKeyDown:picks.handleKeyDown,placeholder:labels.composerPlaceholder,value:session.draft})}),jsxs11(PromptInputFooter,{children:[jsxs11(PromptInputTools,{children:[canAttach?jsx13(AttachButton,{labels}):null,jsx13(ChatVoiceInput,{draft,labels}),slots.composerAccessory===undefined?null:accessoryFor(slots.composerAccessory,draft),picks.pickers]}),jsxs11(PromptInputTools,{children:[running?jsxs11(Fragment5,{children:[jsx13(SendMenu,{disabled:cannotSend,labels,onQueue:()=>{session.queue(session.draft.trim())}}),jsx13(PromptInputSubmit,{"aria-label":labels.stop,"data-part":"stop",onStop:()=>{session.stop()},status:"streaming",variant:"outline"})]}):null,jsx13(PromptInputSubmit,{"aria-label":labels.send,"data-part":"send",disabled:cannotSend})]})]})]}),jsx13(ComposerTrailNotice,{labels})]})};import{cn as cn7}from"@collective-intelligence/ui-react";import{Bot as Bot2,PanelLeftIcon,RefreshCw as RefreshCw2}from"@collective-intelligence/ui-react/icons";import{Badge as Badge3,Button as Button7}from"@collective-intelligence/ui-react/ui";import{RefreshCw,RotateCcw}from"@collective-intelligence/ui-react/icons";import{Button as Button5,Dialog,DialogBody,DialogContent,DialogDescription,DialogFooter,DialogHeader,DialogTitle,Spinner}from"@collective-intelligence/ui-react/ui";import{useState as useState8}from"react";import{jsx as jsx14,jsxs as jsxs12,Fragment as Fragment6}from"react/jsx-runtime";var Meta=({label,value})=>value===undefined||value===""?null:jsxs12("div",{children:[jsx14("dt",{className:"text-xs text-muted-foreground uppercase",children:label}),jsx14("dd",{className:"font-medium text-foreground",children:value})]});var CompactionControls=({conversationId,labels,write})=>{const params={conversationId};const read=useChatRead((client)=>client.chat.getCompaction({params}));const[isSummaryOpen,setIsSummaryOpen]=useState8(false);if(read.result?.ok!==true){return null}const{compaction}=read.result.value;const summary=compaction.activeSummary;const operate=(operation,onDone)=>{write.run((client)=>{switch(operation){case"compact":{return client.chat.compact({params})}case"regenerateCompaction":{return client.chat.regenerateCompaction({params})}default:{return client.chat.resetCompaction({params})}}},()=>{read.reload();onDone?.()})};if(!compaction.active){return jsx14(Button5,{disabled:write.isPending,onClick:()=>{operate("compact")},type:"button",variant:"outline",children:labels.compact})}return jsxs12(Fragment6,{children:[jsx14(Button5,{onClick:()=>{setIsSummaryOpen(true)},type:"button",variant:"outline",children:labels.compacted}),jsx14(Dialog,{onOpenChange:setIsSummaryOpen,open:isSummaryOpen,children:jsxs12(DialogContent,{size:"lg",children:[jsxs12(DialogHeader,{children:[jsx14(DialogTitle,{children:labels.compactedContext}),jsx14(DialogDescription,{children:labels.compactedContextDescription})]}),jsx14(DialogBody,{children:summary===null?jsx14("p",{className:"text-sm text-muted-foreground",children:labels.noCompactionSummary}):jsxs12("div",{className:"flex flex-col gap-4",children:[jsx14("div",{className:"rounded-md border border-border bg-muted p-4 text-sm leading-6 whitespace-pre-wrap text-foreground",children:summary.summary}),jsxs12("dl",{className:"grid gap-2 text-sm text-muted-foreground sm:grid-cols-2",children:[jsx14(Meta,{label:labels.compactionCoveredMessages,value:compaction.boundary?.coveredMessageCount}),jsx14(Meta,{label:labels.compactionCoveredRuns,value:compaction.boundary?.coveredInvocationCount}),jsx14(Meta,{label:labels.compactionStatus,value:summary.status})]})]})}),jsxs12(DialogFooter,{children:[jsxs12(Button5,{disabled:summary===null||write.isPending,onClick:()=>{operate("regenerateCompaction")},type:"button",variant:"outline",children:[write.isPending?jsx14(Spinner,{"data-icon":"inline-start"}):jsx14(RefreshCw,{"data-icon":"inline-start"}),labels.regenerate]}),jsxs12(Button5,{disabled:summary===null||write.isPending,onClick:()=>{operate("resetCompaction",()=>{setIsSummaryOpen(false)})},type:"button",variant:"secondary",children:[jsx14(RotateCcw,{"data-icon":"inline-start"}),labels.reset]})]})]})})]})};import{cn as cn6}from"@collective-intelligence/ui-react";import{Button as Button6}from"@collective-intelligence/ui-react/ui";import{jsx as jsx15,jsxs as jsxs13}from"react/jsx-runtime";var MemorySwitch=({conversation,labels,write})=>{const session=useChatSession2();const{memoryEnabled}=conversation;return jsxs13(Button6,{"aria-pressed":memoryEnabled,disabled:write.isPending,onClick:()=>{write.run((client)=>client.chat.updateConversation({params:{conversationId:conversation.id},payload:{memoryEnabled:!memoryEnabled}}),session.reloadConversations)},type:"button",variant:memoryEnabled?"outline":"secondary",children:[jsx15("span",{"aria-hidden":"true",className:cn6("size-2 rounded-full",memoryEnabled?"bg-primary":"bg-muted-foreground"),"data-icon":"inline-start"}),memoryEnabled?labels.memoryOn:labels.memoryOff]})};import{jsx as jsx16,jsxs as jsxs14}from"react/jsx-runtime";var AgentBadge=({agentId,labels})=>{const read=useChatRead((client)=>client.chatCatalog.listAgents());const agent=read.result?.ok===true?read.result.value.data.find(({id})=>id===agentId):undefined;return jsxs14(Badge3,{"data-part":"chat-header-agent",variant:"secondary",children:[jsx16(Bot2,{"data-icon":"inline-start"}),agent?.displayName??labels.agent]})};var headerNotices=({compaction,isAgentInProject,labels,memory})=>[isAgentInProject&&{alert:false,text:labels.agentConversationNoProjectContext},memory.failure!==null&&{alert:true,text:labels.memoryNotChanged},compaction.failure!==null&&{alert:true,text:labels.compactionFailed}].filter((notice)=>notice!==false);var ChatHeader=({className,labels,openConversations,slots})=>{const session=useChatSession2();const memory=useChatAction();const compaction=useChatAction();const{conversationId}=session;const listed=session.conversations.find(({id})=>id===conversationId);const agentId=listed?.agentId??null;const title=conversationId===null?labels.newChat:listed?.title??"";const notices=headerNotices({compaction,isAgentInProject:session.controls.projects&&agentId!==null&&(listed?.projectId??null)!==null,labels,memory});return jsxs14("header",{className:cn7("flex flex-col border-b border-border bg-background",className),"data-part":"chat-header",children:[jsxs14("div",{className:"flex min-h-16 items-center justify-between gap-3 px-6",children:[jsxs14("div",{className:"flex min-w-0 items-center gap-2",children:[jsx16(Button7,{"aria-haspopup":"dialog","aria-label":labels.openConversationList,className:"@3xl/chat:hidden",onClick:openConversations,size:"icon",variant:"outline",children:jsx16(PanelLeftIcon,{})}),jsx16("h1",{className:"truncate text-lg font-semibold text-foreground",children:title}),agentId===null?null:jsx16(AgentBadge,{agentId,labels},agentId)]}),jsxs14("div",{className:"flex shrink-0 items-center gap-2",children:[listed===undefined||agentId!==null||!session.controls.memory?null:jsx16(MemorySwitch,{conversation:listed,labels,write:memory}),conversationId===null||agentId!==null?null:jsx16(CompactionControls,{conversationId,labels,write:compaction},conversationId),conversationId===null?null:jsx16(Button7,{"aria-label":labels.refreshConversation,onClick:()=>{session.retry()},size:"icon",variant:"outline",children:jsx16(RefreshCw2,{})}),slots.headerActions]})]}),notices.map(({alert,text})=>jsx16("p",{className:cn7("border-t border-border px-6 py-2 text-sm",alert?"text-destructive":"text-muted-foreground"),role:alert?"alert":undefined,children:text},text)),session.failure===null?null:jsxs14("div",{className:"flex items-center justify-between gap-3 border-t border-border px-6 py-2 text-sm text-destructive",role:"alert",children:[jsx16("span",{children:failureText(session.failure,labels)}),jsx16(Button7,{onClick:()=>{session.retry()},size:"sm",type:"button",variant:"outline",children:labels.retry})]})]})};import{cn as cn10}from"@collective-intelligence/ui-react";import{Plus,Search}from"@collective-intelligence/ui-react/icons";import{Button as Button12,Empty as Empty2,EmptyDescription as EmptyDescription2,EmptyHeader as EmptyHeader2,EmptyTitle as EmptyTitle2,InputGroup,InputGroupAddon,InputGroupInput,ScrollArea}from"@collective-intelligence/ui-react/ui";import{useState as useState13}from"react";import{AlertDialog,AlertDialogCancel,AlertDialogContent,AlertDialogDescription,AlertDialogFooter,AlertDialogHeader,AlertDialogTitle,Button as Button8,Dialog as Dialog2,DialogContent as DialogContent2,DialogDescription as DialogDescription2,DialogFooter as DialogFooter2,DialogHeader as DialogHeader2,DialogTitle as DialogTitle2,Input as Input2}from"@collective-intelligence/ui-react/ui";import{useState as useState9}from"react";import{jsx as jsx17,jsxs as jsxs15,Fragment as Fragment7}from"react/jsx-runtime";var useConversationDialogs=({onDeletedOpen,onSelect,projects})=>{const session=useChatSession2();const[dialog,setDialog]=useState9();const write=useChatAction();const close=()=>{write.reset();setDialog(undefined)};const actions={onDelete:(conversation)=>{write.reset();setDialog({conversation,kind:"delete"})},onMove:({id},projectId)=>{write.run((client)=>client.chat.updateConversation({params:{conversationId:id},payload:{projectId}}),session.reloadConversations)},onRename:(conversation)=>{write.reset();setDialog({conversation,kind:"rename"})},onSelect,projects};const remove=({id})=>{write.run((client)=>client.chat.deleteConversation({params:{conversationId:id}}),()=>{setDialog(undefined);if(id===session.conversationId){onDeletedOpen()}session.reloadConversations()})};return{actions,close,dialog,remove,write}};var RenameForm=({conversation,labels,onClose,write})=>{const session=useChatSession2();const[title,setTitle]=useState9(conversation.title);const trimmed=title.trim();return jsxs15("form",{className:"flex flex-col gap-4",onSubmit:(event)=>{event.preventDefault();if(trimmed===""){return}write.run((client)=>client.chat.updateConversation({params:{conversationId:conversation.id},payload:{title:trimmed}}),()=>{session.reloadConversations();onClose()})},children:[jsxs15(DialogHeader2,{children:[jsx17(DialogTitle2,{children:labels.renameConversation}),jsx17(DialogDescription2,{children:labels.renameConversationDescription})]}),jsx17(Input2,{"aria-label":labels.conversationTitle,onChange:(event)=>{setTitle(event.target.value)},value:title}),write.failure===null?null:jsx17("p",{className:"text-sm text-destructive",role:"alert",children:labels.actionFailed}),jsxs15(DialogFooter2,{children:[jsx17(Button8,{onClick:onClose,type:"button",variant:"outline",children:labels.cancel}),jsx17(Button8,{disabled:trimmed===""||write.isPending,type:"submit",children:labels.save})]})]})};var ConversationDialogs=({dialogs:{close,dialog,remove,write},labels})=>{const closeWhenShut=(open)=>{if(!open){close()}};return jsxs15(Fragment7,{children:[jsx17(Dialog2,{onOpenChange:closeWhenShut,open:dialog?.kind==="rename",children:jsx17(DialogContent2,{children:dialog?.kind==="rename"?jsx17(RenameForm,{conversation:dialog.conversation,labels,onClose:close,write},dialog.conversation.id):null})}),jsx17(AlertDialog,{onOpenChange:closeWhenShut,open:dialog?.kind==="delete",children:jsxs15(AlertDialogContent,{children:[jsxs15(AlertDialogHeader,{children:[jsx17(AlertDialogTitle,{children:labels.deleteConversation}),jsx17(AlertDialogDescription,{children:fillLabel(labels.deleteConversationDescription,{title:dialog?.conversation.title??""})})]}),write.failure===null?null:jsx17("p",{className:"text-sm text-destructive",role:"alert",children:labels.actionFailed}),jsxs15(AlertDialogFooter,{children:[jsx17(AlertDialogCancel,{children:labels.cancel}),jsx17(Button8,{disabled:write.isPending,onClick:()=>{if(dialog!==undefined){remove(dialog.conversation)}},variant:"destructive",children:labels.delete})]})]})})]})};import{cn as cn8}from"@collective-intelligence/ui-react";import{FolderInput,MoreHorizontal,Pencil as Pencil2,Trash2,X as X4}from"@collective-intelligence/ui-react/icons";import{Button as Button9,DropdownMenu,DropdownMenuContent,DropdownMenuGroup as DropdownMenuGroup2,DropdownMenuItem,DropdownMenuSub,DropdownMenuSubContent,DropdownMenuSubTrigger,DropdownMenuTrigger}from"@collective-intelligence/ui-react/ui";import{useId as useId2}from"react";import{jsx as jsx18,jsxs as jsxs16,Fragment as Fragment8}from"react/jsx-runtime";var ProjectItems=({actions,conversation,labels,projects})=>{const targets=projects.filter(({id})=>id!==conversation.projectId);return jsxs16(Fragment8,{children:[jsxs16(DropdownMenuSub,{children:[jsxs16(DropdownMenuSubTrigger,{disabled:targets.length===0,children:[jsx18(FolderInput,{}),labels.moveToProject]}),jsx18(DropdownMenuSubContent,{children:jsx18(DropdownMenuGroup2,{children:targets.map((project)=>jsx18(DropdownMenuItem,{onClick:()=>{actions.onMove(conversation,project.id)},children:project.name},project.id))})})]}),conversation.projectId===null?null:jsxs16(DropdownMenuItem,{onClick:()=>{actions.onMove(conversation,null)},children:[jsx18(X4,{}),labels.removeFromProject]})]})};var ConversationRow=({actions,active,conversation,labels,placeName})=>{const placeholders={title:conversation.title};const placeNameId=useId2();return jsxs16("div",{className:cn8("relative flex items-center gap-2 rounded-md border px-2.5 py-2 transition-colors",active?"border-transparent bg-accent text-accent-foreground":"border-border bg-background text-muted-foreground hover:text-foreground"),"data-active":active?"":undefined,"data-part":"conversation-row",children:[jsx18("button",{"aria-current":active?"true":undefined,"aria-describedby":placeName===undefined?undefined:placeNameId,"aria-label":fillLabel(labels.openConversation,placeholders),className:"absolute inset-0 rounded-md focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",onClick:()=>{actions.onSelect(conversation.id)},type:"button"}),jsxs16("span",{className:"pointer-events-none flex min-w-0 flex-1 flex-col",children:[jsx18("span",{className:"truncate text-sm font-semibold text-foreground",children:conversation.title}),placeName===undefined?null:jsx18("span",{className:"truncate text-xs text-muted-foreground",id:placeNameId,children:placeName})]}),jsx18("div",{className:"relative z-10",children:jsxs16(DropdownMenu,{children:[jsx18(DropdownMenuTrigger,{render:jsx18(Button9,{"aria-label":fillLabel(labels.conversationActions,placeholders),size:"icon-sm",variant:"ghost"}),children:jsx18(MoreHorizontal,{})}),jsx18(DropdownMenuContent,{align:"end",children:jsxs16(DropdownMenuGroup2,{children:[jsxs16(DropdownMenuItem,{onClick:()=>{actions.onRename(conversation)},children:[jsx18(Pencil2,{}),labels.rename]}),actions.projects===undefined?null:jsx18(ProjectItems,{actions,conversation,labels,projects:actions.projects}),jsxs16(DropdownMenuItem,{onClick:()=>{actions.onDelete(conversation)},variant:"destructive",children:[jsx18(Trash2,{}),labels.delete]})]})})]})})]})};var groupOrder=["today","yesterday","previous_seven_days","earlier"];var dayMs=86400000;var startOfDay=(value)=>new Date(value.getFullYear(),value.getMonth(),value.getDate()).getTime();var activityOf=({createdAt,lastActivityAt,updatedAt})=>lastActivityAt??updatedAt??createdAt;var groupOf=(conversation,now)=>{const activity=activityOf(conversation);if(activity===null){return"earlier"}const days=Math.round((startOfDay(now)-startOfDay(activity))/dayMs);if(days<=0){return"today"}if(days===1){return"yesterday"}return days<7?"previous_seven_days":"earlier"};var groupByActivity=(conversations,now)=>groupOrder.map((group)=>({conversations:conversations.filter((conversation)=>groupOf(conversation,now)===group),group})).filter(({conversations:rows})=>rows.length>0);var matchesSearch=(title,search)=>title.toLowerCase().includes(search.trim().toLowerCase());import{ToggleGroup,ToggleGroupItem}from"@collective-intelligence/ui-react/ui";import{useState as useState10}from"react";import{jsx as jsx19}from"react/jsx-runtime";var keyOf2=({id,kind})=>`${kind}:${id}`;var useChatHistory=({historyScope,labels,place,placeContext})=>{const[value,setValue]=useState10("this_place");const own=keyOf2(place);const developerScope=historyScope===undefined?undefined:new Set([own,...historyScope.map(keyOf2)]);const inScope=(origin)=>developerScope===undefined||developerScope.has(keyOf2(origin));const others=(placeContext?.places??[]).filter((entry)=>keyOf2(entry)!==own&&inScope(entry));const names=new Map((placeContext?.places??[]).map((entry)=>[keyOf2(entry),entry.name]));return{filter:{options:[{label:labels.thisPlace,value:"this_place"},{label:labels.allListedPlaces,value:"all_listed"}],setValue,value,visible:others.length>0},listed:(conversations)=>conversations.filter(({origin})=>value==="this_place"?keyOf2(origin)===own:inScope(origin)),placeNameOf:(origin)=>keyOf2(origin)===own?undefined:names.get(keyOf2(origin))??labels.unknownPlace}};var HistoryFilter=({filter,label})=>jsx19(ToggleGroup,{"aria-label":label,className:"w-full",onValueChange:(values)=>{const option=filter.options.find(({value})=>values.includes(value));if(option!==undefined){filter.setValue(option.value)}},size:"sm",spacing:0,value:[filter.value],variant:"outline",children:filter.options.map(({label:optionLabel,value})=>jsx19(ToggleGroupItem,{className:"flex-1",value,children:optionLabel},value))});var timeOf=(value)=>value?.getTime()??0;var splitByProject=(conversations,projects,search)=>{const isSearch=search.trim()!=="";const shown=new Set(projects.map(({id})=>id));const matching=conversations.filter(({title})=>matchesSearch(title,search));const projectGroups=projects.map((project)=>({conversations:matching.filter(({projectId})=>projectId===project.id),latest:Math.max(timeOf(project.updatedAt),...conversations.filter(({projectId})=>projectId===project.id).map(({lastActivityAt})=>timeOf(lastActivityAt))),project})).filter((group)=>!isSearch||group.conversations.length>0).sort((first,second)=>second.latest-first.latest).map(({conversations:rows,project})=>({conversations:rows,project}));return{others:matching.filter(({projectId})=>projectId===null||!shown.has(projectId)),projectGroups}};import{cn as cn9}from"@collective-intelligence/ui-react";import{ChevronDown as ChevronDown2,ChevronRight,Folder,FolderPlus}from"@collective-intelligence/ui-react/icons";import{Button as Button11,Collapsible,CollapsibleContent,CollapsibleTrigger}from"@collective-intelligence/ui-react/ui";import{useState as useState12}from"react";import{MoreHorizontal as MoreHorizontal2,Pencil as Pencil3,Trash2 as Trash22}from"@collective-intelligence/ui-react/icons";import{AlertDialog as AlertDialog2,AlertDialogCancel as AlertDialogCancel2,AlertDialogContent as AlertDialogContent2,AlertDialogDescription as AlertDialogDescription2,AlertDialogFooter as AlertDialogFooter2,AlertDialogHeader as AlertDialogHeader2,AlertDialogTitle as AlertDialogTitle2,Button as Button10,Dialog as Dialog3,DialogContent as DialogContent3,DialogDescription as DialogDescription3,DialogFooter as DialogFooter3,DialogHeader as DialogHeader3,DialogTitle as DialogTitle3,DropdownMenu as DropdownMenu2,DropdownMenuContent as DropdownMenuContent2,DropdownMenuGroup as DropdownMenuGroup3,DropdownMenuItem as DropdownMenuItem2,DropdownMenuTrigger as DropdownMenuTrigger2,Input as Input3,Label}from"@collective-intelligence/ui-react/ui";import{useId as useId3,useState as useState11}from"react";import{jsx as jsx20,jsxs as jsxs17}from"react/jsx-runtime";var projectNameMaxLength=200;var ProjectActions=({labels,onOpen,project})=>jsxs17(DropdownMenu2,{children:[jsx20(DropdownMenuTrigger2,{render:jsx20(Button10,{"aria-label":fillLabel(labels.projectActions,{name:project.name}),size:"icon-sm",variant:"ghost"}),children:jsx20(MoreHorizontal2,{})}),jsx20(DropdownMenuContent2,{align:"end",children:jsxs17(DropdownMenuGroup3,{children:[jsxs17(DropdownMenuItem2,{onClick:()=>{onOpen({kind:"rename",project})},children:[jsx20(Pencil3,{}),labels.renameProject]}),jsxs17(DropdownMenuItem2,{onClick:()=>{onOpen({kind:"delete",project})},variant:"destructive",children:[jsx20(Trash22,{}),labels.deleteProject]})]})})]});var ProjectNameForm=({dialog,labels,onClose,onSaved})=>{const fieldId=useId3();const helpId=useId3();const save=useChatAction();const[value,setValue]=useState11(dialog.kind==="create"?"":dialog.project.name);const name=value.trim();const isName=name.length>0&&name.length<=projectNameMaxLength;return jsxs17("form",{className:"flex flex-col gap-4",onSubmit:(event)=>{event.preventDefault();if(!isName||save.isPending){return}save.run((client)=>dialog.kind==="create"?client.chatProjects.createProject({payload:{name}}):client.chatProjects.updateProject({params:{projectId:dialog.project.id},payload:{name}}),onSaved)},children:[jsxs17(DialogHeader3,{children:[jsx20(DialogTitle3,{children:dialog.kind==="create"?labels.newProject:labels.renameProject}),jsx20(DialogDescription3,{children:labels.projectDescription})]}),jsxs17("div",{className:"flex flex-col gap-2",children:[jsx20(Label,{htmlFor:fieldId,children:labels.projectName}),jsx20(Input3,{"aria-describedby":helpId,"aria-invalid":save.failure!==null,id:fieldId,maxLength:projectNameMaxLength,onChange:(event)=>{setValue(event.target.value)},value}),jsx20("p",{className:"text-xs text-muted-foreground",id:helpId,children:labels.projectNameHelp}),save.failure===null?null:jsx20("p",{className:"text-sm text-destructive",role:"alert",children:labels.projectNotSaved})]}),jsxs17(DialogFooter3,{children:[jsx20(Button10,{disabled:save.isPending,onClick:onClose,type:"button",variant:"outline",children:labels.cancel}),jsx20(Button10,{disabled:!isName||save.isPending,type:"submit",children:dialog.kind==="create"?labels.createProject:labels.save})]})]})};var DeleteProject=({labels,onClose,onDeleted,project})=>{const remove=useChatAction();return jsx20(AlertDialog2,{onOpenChange:(open)=>{if(!open&&!remove.isPending){onClose()}},open:true,children:jsxs17(AlertDialogContent2,{children:[jsxs17(AlertDialogHeader2,{children:[jsx20(AlertDialogTitle2,{children:fillLabel(labels.deleteProjectTitle,{name:project.name})}),jsx20(AlertDialogDescription2,{children:labels.deleteProjectDescription})]}),remove.failure===null?null:jsx20("p",{className:"text-sm text-destructive",role:"alert",children:labels.projectNotDeleted}),jsxs17(AlertDialogFooter2,{children:[jsx20(AlertDialogCancel2,{disabled:remove.isPending,children:labels.cancel}),jsx20(Button10,{disabled:remove.isPending,onClick:()=>{remove.run((client)=>client.chatProjects.deleteProject({params:{projectId:project.id}}),()=>{onDeleted(project.id)})},variant:"destructive",children:labels.deleteProject})]})]})})};var ProjectDialogs=({dialog,labels,newChat,onClose,projects})=>{const session=useChatSession2();if(dialog?.kind==="delete"){return jsx20(DeleteProject,{labels,onClose,onDeleted:(projectId)=>{const open=session.conversations.find(({id})=>id===session.conversationId);if(projects.viewedId===projectId||open?.projectId===projectId){newChat()}projects.reload();onClose()},project:dialog.project})}return jsx20(Dialog3,{onOpenChange:(open)=>{if(!open){onClose()}},open:dialog!==null,children:dialog===null?null:jsx20(DialogContent3,{children:jsx20(ProjectNameForm,{dialog,labels,onClose,onSaved:(project)=>{projects.reload();if(dialog.kind==="create"){projects.openProjectView(project.id)}onClose()}})})})};var useProjectDialog=()=>{const[dialog,setDialog]=useState11(null);return{dialog,handleClose:()=>{setDialog(null)},handleOpen:setDialog}};import{jsx as jsx21,jsxs as jsxs18}from"react/jsx-runtime";var ProjectEntry=({activeConversationId,group:{conversations,project},isSearch,labels,onDialog,placeNameOf,projects,rowActions})=>{const[isFolded,setIsFolded]=useState12(false);const isOpen=isSearch||!isFolded;const isViewed=projects.viewed?.id===project.id;const name={name:project.name};return jsxs18(Collapsible,{onOpenChange:(open)=>{setIsFolded(!open)},open:isOpen,children:[jsxs18("div",{className:cn9("flex items-center gap-1 rounded-md px-1.5 py-1",isViewed&&"bg-accent text-accent-foreground"),"data-part":"project-entry",children:[jsx21(CollapsibleTrigger,{render:jsx21(Button11,{"aria-label":fillLabel(labels.projectConversationsToggle,name),disabled:isSearch,size:"icon-sm",variant:"ghost"}),children:isOpen?jsx21(ChevronDown2,{}):jsx21(ChevronRight,{})}),jsxs18("button",{"aria-current":isViewed?"page":undefined,"aria-label":fillLabel(labels.openProject,name),className:"flex min-w-0 flex-1 items-center gap-2 rounded-md px-1 py-1.5 text-left focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",onClick:()=>{projects.openProjectView(project.id)},type:"button",children:[jsx21(Folder,{className:"shrink-0 text-muted-foreground"}),jsx21("span",{className:"min-w-0 truncate text-sm font-semibold text-foreground",children:project.name})]}),jsx21(ProjectActions,{labels,onOpen:onDialog,project})]}),jsx21(CollapsibleContent,{className:"mt-2 flex flex-col gap-2 pl-4",children:conversations.map((conversation)=>jsx21(ConversationRow,{actions:rowActions,active:conversation.id===activeConversationId,conversation,labels,placeName:placeNameOf(conversation.origin)},conversation.id))})]})};var ProjectsSection=({groups,newChat,...entryProps})=>{const{labels,projects}=entryProps;const dialogs=useProjectDialog();return jsxs18("section",{className:"flex flex-col gap-2","data-part":"projects-section",children:[jsxs18("div",{className:"flex items-center justify-between gap-2",children:[jsx21("h2",{className:"text-sm font-semibold text-muted-foreground",children:labels.projects}),jsx21(Button11,{"aria-label":labels.newProject,onClick:()=>{dialogs.handleOpen({kind:"create"})},size:"icon-sm",variant:"ghost",children:jsx21(FolderPlus,{})})]}),projects.failed?jsx21("p",{className:"text-sm text-destructive",role:"alert",children:labels.projectsNotLoaded}):null,projects.list?.length===0?jsx21("p",{className:"text-sm text-muted-foreground",children:labels.noProjects}):jsx21("div",{className:"flex flex-col gap-2",children:groups.map((group)=>jsx21(ProjectEntry,{group,onDialog:dialogs.handleOpen,...entryProps},group.project.id))}),jsx21(ProjectDialogs,{dialog:dialogs.dialog,labels,newChat,onClose:dialogs.handleClose,projects})]})};import{jsx as jsx22,jsxs as jsxs19}from"react/jsx-runtime";import{createElement}from"react";var groupLabels={earlier:"earlier",previous_seven_days:"previousSevenDays",today:"today",yesterday:"yesterday"};var ConversationSidebar=({className,history,labels,newChat,projects,selectConversation,slots})=>{const session=useChatSession2();const[search,setSearch]=useState13("");const[now]=useState13(()=>new Date);const shownProjects=projects.enabled?projects.list:undefined;const dialogs=useConversationDialogs({onDeletedOpen:newChat,onSelect:selectConversation,projects:shownProjects});const listed=history.listed(session.conversations);const{others,projectGroups}=splitByProject(listed,shownProjects??[],search);const dateGroups=groupByActivity(others,now);const isSearch=search.trim()!=="";const isLoading=session.status==="starting";const isDraft=session.conversationId===null&&projects.viewed===undefined;const rowProps={actions:dialogs.actions,labels};const list=()=>{if(listed.length===0&&!isLoading){return jsx22(Empty2,{children:jsxs19(EmptyHeader2,{children:[jsx22(EmptyTitle2,{children:labels.noConversations}),jsx22(EmptyDescription2,{children:labels.noConversationsDescription})]})})}if(isSearch&&dateGroups.length===0&&projectGroups.length===0){return jsx22("p",{className:"text-sm text-muted-foreground",children:labels.noSearchResults})}return dateGroups.map(({conversations,group})=>jsxs19("section",{className:"flex flex-col gap-2",children:[jsx22("h2",{className:"text-sm font-semibold text-muted-foreground",children:labels[groupLabels[group]]}),conversations.map((conversation)=>createElement(ConversationRow,{...rowProps,active:conversation.id===session.conversationId,conversation,key:conversation.id,placeName:history.placeNameOf(conversation.origin)}))]},group))};return jsxs19("aside",{"aria-busy":isLoading,"aria-label":labels.conversations,className:cn10("flex min-h-0 w-[360px] shrink-0 flex-col border-r border-border bg-background",className),"data-part":"conversation-sidebar",children:[slots.sidebarHeader,jsxs19("div",{className:"flex flex-col gap-4 border-b border-border px-5 py-4",children:[jsxs19(Button12,{className:"w-full",onClick:()=>{newChat()},size:"lg",children:[jsx22(Plus,{"data-icon":"inline-start"}),labels.newChat]}),jsxs19(InputGroup,{children:[jsx22(InputGroupInput,{"aria-label":labels.searchConversations,onChange:(event)=>{setSearch(event.target.value)},placeholder:labels.searchConversations,type:"search",value:search}),jsx22(InputGroupAddon,{children:jsx22(Search,{})})]})]}),history.filter.visible?jsx22("div",{className:"border-b border-border px-5 py-3",children:jsx22(HistoryFilter,{filter:history.filter,label:labels.historyFilter})}):null,jsx22(ScrollArea,{className:"min-h-0 flex-1",children:jsxs19("div",{className:"flex flex-col gap-6 px-5 py-5",children:[isDraft?jsxs19("div",{className:"flex flex-col gap-1 rounded-md bg-accent px-3 py-3 text-sm text-accent-foreground","data-part":"draft-row",children:[jsx22("span",{className:"truncate font-semibold",children:labels.newChat}),jsx22("span",{className:"text-xs text-muted-foreground",children:labels.draft})]}):null,dialogs.dialog===undefined&&dialogs.write.failure!==null?jsx22("p",{className:"text-sm text-destructive",role:"alert",children:labels.conversationNotMoved}):null,shownProjects===undefined&&!projects.failed?null:jsx22(ProjectsSection,{activeConversationId:session.conversationId,groups:projectGroups,isSearch,labels,newChat,placeNameOf:history.placeNameOf,projects,rowActions:dialogs.actions}),list()]})}),slots.sidebarFooter,jsx22(ConversationDialogs,{dialogs,labels})]})};import{cn as cn11}from"@collective-intelligence/ui-react";import{Folder as Folder2}from"@collective-intelligence/ui-react/icons";import{Button as Button14,Empty as Empty4,EmptyDescription as EmptyDescription4,EmptyHeader as EmptyHeader4,EmptyTitle as EmptyTitle4,Label as Label2,Textarea}from"@collective-intelligence/ui-react/ui";import{useId as useId4,useState as useState15}from"react";import{Download,FileText,Trash2 as Trash23,Upload}from"@collective-intelligence/ui-react/icons";import{Badge as Badge4,Button as Button13,Empty as Empty3,EmptyDescription as EmptyDescription3,EmptyHeader as EmptyHeader3,EmptyTitle as EmptyTitle3,Skeleton,Spinner as Spinner2}from"@collective-intelligence/ui-react/ui";import{useRef as useRef2,useState as useState14,useTransition as useTransition2}from"react";import{jsx as jsx23,jsxs as jsxs20,Fragment as Fragment9}from"react/jsx-runtime";var maxFileBytes=10*1024*1024;var maxProjectFiles=20;var serverReasons=["malformed","oversized","too_many_files","unsupported"];var extensionOf=(filename)=>{const dot=filename.lastIndexOf(".");return dot===-1?"":filename.slice(dot).toLowerCase()};var statesOf=({extractionState,inContext})=>{if(extractionState==="failed"){return["failed"]}const states=[];if(extractionState==="truncated"){states.push("truncated")}if(!inContext){states.push("not_in_context")}return states.length===0?["in_context"]:states};var stateVariants={failed:"destructive",in_context:"secondary",not_in_context:"outline",truncated:"outline"};var stateTexts=(labels,budget)=>({failed:{help:labels.projectFileFailedHelp,label:labels.projectFileFailed},in_context:{help:undefined,label:labels.projectFileInContext},not_in_context:{help:fillLabel(labels.projectFileNotInContextHelp,{max:budget}),label:labels.projectFileNotInContext},truncated:{help:labels.projectFileTruncatedHelp,label:labels.projectFileTruncated}});var rejectionTexts=(labels)=>({failed:labels.projectFileNotAdded,malformed:labels.projectFileRejectedMalformed,oversized:labels.projectFileRejectedOversized,too_many_files:labels.projectFileRejectedTooManyFiles,unsupported:labels.projectFileRejectedUnsupported});var sizeUnit=(bytes)=>{if(bytes<1024){return["byte",bytes]}return bytes<1024**2?["kilobyte",bytes/1024]:["megabyte",bytes/1024**2]};var sizeText=(bytes,locale)=>{const[unit,value]=sizeUnit(bytes);return new Intl.NumberFormat(locale,{maximumFractionDigits:1,style:"unit",unit}).format(value)};var FileRow=({file,labels,locale,onChanged,projectId,texts})=>{const session=useChatSession2();const remove=useChatAction();const download=useChatAction();const port=session.controls.files;const params={fileId:file.id,projectId};const states=statesOf(file);const details=[sizeText(file.sizeBytes,locale),...states.flatMap((state)=>texts[state].help??[])];const name={name:file.filename};const downloadFailure=download.failure===null?undefined:labels.projectFileNotDownloaded;const failure=remove.failure===null?downloadFailure:labels.projectFileNotDeleted;return jsxs20("li",{"aria-busy":remove.isPending,className:"flex items-start gap-3 rounded-md border border-border bg-background px-3 py-2",children:[jsx23(FileText,{className:"mt-0.5 shrink-0 text-muted-foreground"}),jsxs20("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[jsxs20("div",{className:"flex flex-wrap items-center gap-2",children:[jsx23("p",{className:"min-w-0 truncate text-sm font-semibold text-foreground",children:file.filename}),states.map((state)=>jsx23(Badge4,{variant:stateVariants[state],children:texts[state].label},state))]}),jsx23("p",{className:"text-xs text-muted-foreground",children:details.join(" · ")}),failure===undefined?null:jsx23("p",{className:"text-xs text-destructive",role:"alert",children:failure})]}),jsxs20("div",{className:"flex shrink-0 items-center gap-1",children:[port===undefined?null:jsx23(Button13,{"aria-busy":download.isPending,"aria-label":fillLabel(labels.downloadProjectFile,name),disabled:download.isPending,onClick:()=>{download.run((client)=>client.chatProjects.getProjectFileDownloadUrl({params}),({url})=>{port.download({filename:file.filename,url})})},size:"icon",type:"button",variant:"ghost",children:download.isPending?jsx23(Spinner2,{}):jsx23(Download,{})}),jsx23(Button13,{"aria-busy":remove.isPending,"aria-label":fillLabel(labels.deleteProjectFile,name),disabled:remove.isPending,onClick:()=>{remove.run((client)=>client.chatProjects.deleteProjectFile({params}),onChanged)},size:"icon",type:"button",variant:"ghost",children:remove.isPending?jsx23(Spinner2,{}):jsx23(Trash23,{})})]})]})};var ProjectFilesSection=({labels,locale,projectId})=>{const{call}=useChatSession2();const params={projectId};const list=useChatRead((client)=>client.chatProjects.listProjectFiles({params}));const capabilities=useChatRead((client)=>client.chatCatalog.getAttachmentCapabilities());const inputRef=useRef2(null);const[isAdding,startAdding]=useTransition2();const[rejections,setRejections]=useState14([]);const data=list.result?.ok===true?list.result.value:undefined;const fileTypes=capabilities.result?.ok===true?capabilities.result.value.projectFileTypes:undefined;const isFull=(data?.files.length??0)>=maxProjectFiles;const canAdd=data!==undefined&&!isFull&&!isAdding;const clientReason=(file,full)=>{if(fileTypes!==undefined&&!fileTypes.some(({extension})=>extension===extensionOf(file.name))){return"unsupported"}if(file.size>maxFileBytes){return"oversized"}return full?"too_many_files":undefined};const upload=(file)=>{const payload=new FormData;payload.append("file",file);return call((client)=>client.chatProjects.uploadProjectFile({params,payload}))};const addFilesAction=(chosen)=>{startAdding(async()=>{const rejected=[];let count=data?.files.length??0;for(const[order,file]of chosen.entries()){let reason=clientReason(file,count>=maxProjectFiles);if(reason===undefined){const result=await upload(file);if(result.ok){count+=1}else{reason=serverReasons.find((known)=>known===result.error.reason)??"failed"}}if(reason==="too_many_files"){count=maxProjectFiles}if(reason!==undefined){rejected.push({filename:file.name,order,reason})}}startAdding(()=>{setRejections(rejected);list.reload()})})};const reasons=rejectionTexts(labels);const files=()=>{if(data===undefined){return list.result?.ok===false?jsxs20("div",{className:"flex items-center justify-between gap-3 text-sm text-destructive",role:"alert",children:[jsx23("span",{children:labels.projectFilesNotLoaded}),jsx23(Button13,{onClick:()=>{list.reload()},size:"sm",type:"button",variant:"outline",children:labels.retry})]}):jsx23(Skeleton,{className:"h-12 w-full"})}const count=new Intl.NumberFormat(locale);const budget=count.format(data.maxCharacters);const texts=stateTexts(labels,budget);return jsxs20(Fragment9,{children:[jsxs20("p",{className:"text-xs text-muted-foreground",children:[labels.projectFilesUsage,":"," ",fillLabel(labels.projectFilesUsageValue,{max:budget,used:count.format(data.usedCharacters)})]}),data.files.length===0?jsx23(Empty3,{className:"border border-dashed border-border",children:jsxs20(EmptyHeader3,{children:[jsx23(EmptyTitle3,{children:labels.noProjectFiles}),jsx23(EmptyDescription3,{children:labels.noProjectFilesDescription})]})}):jsx23("ul",{className:"flex flex-col gap-2",children:data.files.map((file)=>jsx23(FileRow,{file,labels,locale,onChanged:()=>{list.reload()},projectId,texts},file.id))})]})};return jsxs20("section",{"aria-label":labels.projectFiles,className:"flex flex-col gap-3","data-part":"project-files",children:[jsxs20("div",{className:"flex items-center justify-between gap-3",children:[jsxs20("div",{className:"flex flex-col gap-1",children:[jsx23("h3",{className:"text-sm font-semibold text-foreground",children:labels.projectFiles}),jsx23("p",{className:"text-xs text-muted-foreground",children:isFull?labels.projectFilesFull:labels.projectFilesHelp})]}),jsx23("input",{accept:fileTypes?.map(({extension})=>extension).join(","),"aria-hidden":"true",className:"sr-only",disabled:!canAdd,multiple:true,onChange:(event)=>{const chosen=[...event.target.files??[]];event.target.value="";if(chosen.length>0){addFilesAction(chosen)}},ref:inputRef,tabIndex:-1,type:"file"}),jsxs20(Button13,{"aria-busy":isAdding,disabled:!canAdd,onClick:()=>inputRef.current?.click(),size:"sm",type:"button",variant:"outline",children:[isAdding?jsx23(Spinner2,{"data-icon":"inline-start"}):jsx23(Upload,{"data-icon":"inline-start"}),labels.addProjectFiles]})]}),rejections.length===0?null:jsxs20("div",{className:"flex flex-col gap-1 text-sm text-destructive",role:"alert",children:[jsx23("p",{className:"font-semibold",children:labels.projectFilesNotAdded}),jsx23("ul",{className:"flex flex-col gap-1",children:rejections.map(({filename,order,reason})=>jsxs20("li",{children:[filename,": ",reasons[reason]]},order))})]}),files()]})};import{jsx as jsx24,jsxs as jsxs21}from"react/jsx-runtime";var maxInstructions=8000;var InstructionsEditor=({labels,project,projects})=>{const fieldId=useId4();const save=useChatAction();const[text,setText]=useState15(project.instructions??"");const instructions=text.trim()===""?null:text;const isTooLong=text.length>maxInstructions;const canSave=!isTooLong&&!save.isPending&&instructions!==project.instructions;const failed=save.failure===null?undefined:labels.projectInstructionsNotSaved;const error=isTooLong?labels.projectInstructionsTooLong:failed;return jsxs21("form",{"aria-busy":save.isPending,className:"flex flex-col gap-2",onSubmit:(event)=>{event.preventDefault();if(canSave){save.run((client)=>client.chatProjects.updateProject({params:{projectId:project.id},payload:{instructions}}),projects.reload)}},children:[jsx24(Label2,{htmlFor:fieldId,children:labels.projectInstructions}),jsx24(Textarea,{"aria-invalid":error!==undefined,className:"max-h-64 min-h-24",id:fieldId,onChange:(event)=>{setText(event.target.value)},value:text}),jsx24("p",{className:"text-xs text-muted-foreground",children:labels.projectInstructionsHelp}),error===undefined?null:jsx24("p",{className:"text-xs text-destructive",role:"alert",children:error}),jsxs21("div",{className:"flex items-center justify-between gap-2",children:[jsxs21("span",{className:cn11("text-xs",isTooLong?"text-destructive":"text-muted-foreground"),children:[text.length,"/",maxInstructions]}),jsx24(Button14,{disabled:!canSave,size:"sm",type:"submit",children:labels.save})]})]})};var ProjectView=({history,labels,locale,newChat,project,projects,selectConversation})=>{const session=useChatSession2();const projectDialogs=useProjectDialog();const conversationDialogs=useConversationDialogs({onDeletedOpen:newChat,onSelect:selectConversation,projects:projects.list});const conversations=history.listed(session.conversations).filter(({projectId})=>projectId===project.id);return jsxs21("section",{"aria-label":project.name,className:"min-h-0 flex-1 overflow-y-auto","data-part":"project-view",children:[jsxs21("div",{className:"mx-auto flex w-full max-w-[900px] flex-col gap-6 px-6 py-8",children:[jsxs21("div",{className:"flex items-center justify-between gap-3",children:[jsxs21("div",{className:"flex min-w-0 items-center gap-3",children:[jsx24(Folder2,{className:"shrink-0 text-muted-foreground"}),jsx24("h2",{className:"min-w-0 truncate text-2xl font-semibold text-foreground",children:project.name})]}),jsx24(ProjectActions,{labels,onOpen:projectDialogs.handleOpen,project})]}),jsx24(InstructionsEditor,{labels,project,projects},project.id),jsx24(ProjectFilesSection,{labels,locale,projectId:project.id},project.id),jsxs21("div",{className:"flex flex-col gap-3",children:[jsx24("h3",{className:"text-sm font-semibold text-foreground",children:labels.projectConversations}),conversations.length===0?jsx24(Empty4,{className:"border border-dashed border-border",children:jsxs21(EmptyHeader4,{children:[jsx24(EmptyTitle4,{children:labels.projectNoConversations}),jsx24(EmptyDescription4,{children:labels.projectNoConversationsDescription})]})}):jsx24("div",{className:"flex flex-col gap-2",children:conversations.map((conversation)=>jsx24(ConversationRow,{actions:conversationDialogs.actions,active:false,conversation,labels,placeName:history.placeNameOf(conversation.origin)},conversation.id))})]})]}),jsx24(ProjectDialogs,{dialog:projectDialogs.dialog,labels,newChat,onClose:projectDialogs.handleClose,projects}),jsx24(ConversationDialogs,{dialogs:conversationDialogs,labels})]})};import{useState as useState16}from"react";var useChatProjects=()=>{const session=useChatSession2();const enabled=session.controls.projects;const read=useChatRead((client)=>client.chatProjects.listProjects(),enabled);const[viewedId,setViewedId]=useState16();const list=read.result?.ok===true?read.result.value.data:undefined;const failure=read.result?.ok===false?read.result.error:undefined;const offHere=failure?.code==="forbidden"&&failure.reason==="not_available_here";const shownId=session.conversationId===null?viewedId:undefined;return{enabled:enabled&&!offHere,failed:failure!==undefined&&!offHere,leaveProject:()=>{setViewedId(undefined)},list,openProjectView:(projectId)=>{setViewedId(projectId);session.newChat({projectId})},reload:()=>{read.reload();session.reloadConversations()},viewed:shownId===undefined?undefined:list?.find(({id})=>id===shownId),viewedId:shownId}};import{cn as cn14}from"@collective-intelligence/ui-react";import{Conversation,ConversationContent,ConversationEmptyState,ConversationItem,ConversationScrollButton,Message,MessageActions,MessageContent}from"@collective-intelligence/ui-react/ai-elements";import*as Schema6 from"effect/Schema";import{useTransition as useTransition3}from"react";import{cn as cn12}from"@collective-intelligence/ui-react";import{ThumbsDown,ThumbsUp}from"@collective-intelligence/ui-react/icons";import{Button as Button15,Dialog as Dialog4,DialogContent as DialogContent4,DialogDescription as DialogDescription4,DialogFooter as DialogFooter4,DialogHeader as DialogHeader4,DialogTitle as DialogTitle4,Textarea as Textarea2}from"@collective-intelligence/ui-react/ui";import{useState as useState17}from"react";import{jsx as jsx25,jsxs as jsxs22,Fragment as Fragment10}from"react/jsx-runtime";var sentiments=["positive","negative"];var FeedbackButton=({active,disabled,label,onClick,sentiment})=>{const Icon=sentiment==="positive"?ThumbsUp:ThumbsDown;return jsx25(Button15,{"aria-label":label,"aria-pressed":active,className:cn12("text-muted-foreground",active&&(sentiment==="positive"?"border-(--success) text-(--success)":"border-(--danger) text-(--danger)")),disabled,onClick,size:"icon-sm",type:"button",variant:"ghost",children:jsx25(Icon,{"aria-hidden":"true",className:cn12(active&&"fill-current")})})};var NoteForm=({labels,onCancel,onSubmit})=>{const[note,setNote]=useState17("");const trimmed=note.trim();return jsxs22(Fragment10,{children:[jsx25(Textarea2,{"aria-label":labels.feedbackNote,autoFocus:true,onChange:(event)=>{setNote(event.target.value)},placeholder:labels.feedbackNote,required:true,value:note}),jsxs22(DialogFooter4,{children:[jsx25(Button15,{onClick:onCancel,type:"button",variant:"outline",children:labels.cancel}),jsx25(Button15,{disabled:trimmed==="",onClick:()=>{onSubmit(trimmed)},type:"button",children:labels.feedbackSubmit})]})]})};var ChatAnswerFeedback=({className,clear,error,labels,pending,submit,value})=>{const[noteOpen,setNoteOpen]=useState17(false);const press=(sentiment)=>{if(value===sentiment){clear()}else if(sentiment==="positive"){submit({note:null,sentiment})}else{setNoteOpen(true)}};return jsxs22("div",{className:cn12("flex flex-wrap items-center gap-2 text-xs text-muted-foreground",className),"data-part":"answer-feedback",children:[jsx25("fieldset",{"aria-busy":pending,"aria-label":labels.feedbackGroup,className:"flex items-center gap-1",children:sentiments.map((sentiment)=>jsx25(FeedbackButton,{active:value===sentiment,disabled:pending,label:sentiment==="positive"?labels.feedbackPositive:labels.feedbackNegative,onClick:()=>{press(sentiment)},sentiment},sentiment))}),pending?jsx25("span",{children:labels.feedbackSaving}):null,error===null?null:jsx25("span",{className:"text-destructive",role:"alert",children:error}),jsx25(Dialog4,{onOpenChange:setNoteOpen,open:noteOpen,children:jsxs22(DialogContent4,{children:[jsxs22(DialogHeader4,{children:[jsx25(DialogTitle4,{children:labels.feedbackNoteTitle}),jsx25(DialogDescription4,{children:labels.feedbackNoteDescription})]}),jsx25(NoteForm,{labels,onCancel:()=>{setNoteOpen(false)},onSubmit:(note)=>{submit({note,sentiment:"negative"});setNoteOpen(false)}})]})})]})};var useAnswerFeedback=(invocationId,message)=>{const action=useChatAction();const[value,setValue]=useState17(message.metadata?.currentUserFeedback?.sentiment??null);const show=({currentUserFeedback})=>{setValue(currentUserFeedback.sentiment)};return{clear:()=>{action.run((client)=>client.chatFeedback.clearAnswerFeedback({params:{invocationId}}),show)},failed:action.failure!==null,pending:action.isPending,submit:({note,sentiment})=>{action.run((client)=>client.chatFeedback.putAnswerFeedback({params:{invocationId},payload:note===null?{sentiment}:{sentiment,submitterNote:note}}),show)},value}};var AnswerFeedback=({Control,invocationId,labels,message})=>{const{clear,failed,pending,submit,value}=useAnswerFeedback(invocationId,message);return jsx25(Control,{clear,error:failed?labels.actionFailed:null,labels,message,pending,submit,value})};import{getToolName as getToolName2,isToolUIPart as isToolUIPart2}from"ai";import*as Option3 from"effect/Option";import*as Schema4 from"effect/Schema";import{MessageResponse}from"@collective-intelligence/ui-react/ai-elements";import{Alert,AlertDescription,Badge as Badge5,CodeBlock,CodeBlockContent,Table,TableBody,TableCell,TableHead,TableHeader,TableRow}from"@collective-intelligence/ui-react/ui";import*as Schema from"effect/Schema";import{jsx as jsx26,jsxs as jsxs23}from"react/jsx-runtime";var isText=Schema.is(Schema.String);var webUrl=(url)=>{if(!isText(url)){return null}try{const{protocol}=new URL(url);return protocol==="http:"||protocol==="https:"?url:null}catch{return null}};var WebLink=({children,url})=>jsx26("a",{className:"font-medium break-words text-primary underline-offset-4 hover:underline",href:url,rel:"noreferrer",target:"_blank",children});var textOf=(value)=>isText(value)?value:JSON.stringify(value)??"";var TableCellValue=({column,row})=>{const value=row[column.key];const url=webUrl(column.link===null?value:row[column.link.urlKey]);const labelKey=column.link?.labelKey??null;const text=textOf(labelKey===null?value:row[labelKey]??value);return url===null||column.link===null&&column.valueKind!=="url"?text:jsx26(WebLink,{url,children:text})};var EvidenceTable=({evidence})=>jsxs23(Table,{children:[jsx26(TableHeader,{children:jsx26(TableRow,{children:evidence.columns.map((column)=>jsx26(TableHead,{title:column.description??undefined,children:column.label},column.key))})}),jsx26(TableBody,{children:evidence.rows.map((row,index)=>jsx26(TableRow,{children:evidence.columns.map((column)=>jsx26(TableCell,{children:jsx26(TableCellValue,{column,row})},column.key))},index))})]});var EvidenceSources=({evidence,labels})=>jsxs23("div",{className:"flex flex-col gap-3",children:[evidence.groups.map((group)=>jsxs23("section",{className:"flex flex-col gap-2",children:[jsx26("h4",{className:"text-muted-foreground text-xs font-medium",children:group.label}),jsx26("ul",{className:"flex flex-col gap-2",children:group.items.map((item)=>{const url=item.navigation?.kind==="external_url"?webUrl(item.navigation.url):null;return jsxs23("li",{className:"flex flex-col gap-1",children:[jsx26("span",{className:"text-sm font-medium",children:url===null?item.title:jsx26(WebLink,{url,children:item.title})}),jsx26("span",{className:"text-muted-foreground text-xs",children:item.excerpt}),jsxs23("span",{className:"flex flex-wrap gap-1",children:[jsx26(Badge5,{variant:"secondary",children:item.provenanceLabel}),jsx26(Badge5,{variant:"outline",children:fillLabel(labels.evidenceRelevance,{percent:String(Math.round(item.relevanceScore*100))})})]})]},item.evidenceId??`${item.title}:${item.excerpt}`)})})]},group.label)),evidence.omittedCount>0?jsx26("p",{className:"text-muted-foreground text-xs",children:fillLabel(labels.evidenceOmitted,{count:String(evidence.omittedCount)})}):null]});var EvidenceBody=({evidence,labels})=>{switch(evidence.kind){case"table":{return jsx26(EvidenceTable,{evidence})}case"sources":{return jsx26(EvidenceSources,{evidence,labels})}case"links":{return jsx26("ul",{className:"flex flex-col gap-1",children:evidence.links.map((link)=>{const url=webUrl(link.url);return jsxs23("li",{className:"flex flex-col text-sm",children:[url===null?link.label:jsx26(WebLink,{url,children:link.label}),link.description===null?null:jsx26("span",{className:"text-muted-foreground text-xs",children:link.description})]},link.url)})})}case"summary":{return jsx26(MessageResponse,{children:evidence.text})}case"warnings":{return jsx26(Alert,{children:evidence.warnings.map((warning)=>jsx26(AlertDescription,{children:warning},warning))})}case"json":{return jsx26(CodeBlock,{size:"sm",children:jsx26(CodeBlockContent,{children:JSON.stringify(evidence.value,null,2)})})}default:{return jsx26("div",{className:"flex flex-wrap gap-2",children:evidence.images.flatMap((image)=>{const url=webUrl(image.url);return url===null?[]:[jsx26("img",{alt:image.alt??image.filename,className:"max-h-64 max-w-full border object-contain",src:url},image.url)]})})}}};var kindTitle=(labels,kind)=>{switch(kind){case"sources":{return labels.evidenceSources}case"links":{return labels.evidenceLinks}case"warnings":{return labels.evidenceWarnings}default:{return null}}};var EvidencePart=({labels,part})=>{const title=part.title??kindTitle(labels,part.kind);return jsxs23("section",{className:"flex flex-col gap-2 border p-3 text-sm","data-evidence-kind":part.kind,"data-part":"evidence",children:[title===null?null:jsx26("h3",{className:"font-medium",children:title}),part.description===null?null:jsx26("p",{className:"text-muted-foreground text-xs",children:part.description}),jsx26(EvidenceBody,{evidence:part,labels})]})};import{FileText as FileText2}from"@collective-intelligence/ui-react/icons";import{Attachment as Attachment2,AttachmentContent,AttachmentMedia,AttachmentTitle}from"@collective-intelligence/ui-react/ui";import{jsx as jsx27,jsxs as jsxs24}from"react/jsx-runtime";var FilePart=({part})=>{const name=part.filename??part.mediaType;const image=part.mediaType.startsWith("image/")&&part.url!=="";return image?jsxs24(Attachment2,{"data-part":"file",orientation:"vertical",children:[jsx27(AttachmentMedia,{variant:"image",children:jsx27("img",{alt:name,src:part.url})}),jsx27(AttachmentContent,{children:jsx27(AttachmentTitle,{children:name})})]}):jsxs24(Attachment2,{"data-part":"file",children:[jsx27(AttachmentMedia,{children:jsx27(FileText2,{})}),jsx27(AttachmentContent,{children:jsx27(AttachmentTitle,{children:name})})]})};import{isToolUIPart}from"ai";import*as Option from"effect/Option";import*as Schema2 from"effect/Schema";var imageStatuses=["attention_required","cancelled","completed","failed","partial","pending","running"];var OptionalText=Schema2.optionalKey(Schema2.NullOr(Schema2.String));var ImageFileSchema=Schema2.Struct({filename:Schema2.String,id:Schema2.String,mimeType:Schema2.String,source:Schema2.Literal("managed"),url:Schema2.String});var ImageProvenanceSchema=Schema2.Struct({deploymentName:OptionalText,modelName:Schema2.String,modelVersion:OptionalText,providerRoute:Schema2.String,routeModelName:OptionalText});var ImageParametersSchema=Schema2.Struct({aspectRatio:OptionalText,background:OptionalText,count:Schema2.optionalKey(Schema2.NullOr(Schema2.Finite)),format:OptionalText,quality:OptionalText,referenceImages:Schema2.optionalKey(Schema2.NullOr(Schema2.Array(Schema2.Unknown))),resolution:OptionalText});var ImageUsageSchema=Schema2.Struct({amount:OptionalText,currency:OptionalText,kind:Schema2.String,source:OptionalText});var ImageOutputSchema=Schema2.Struct({effectiveParameters:Schema2.optionalKey(Schema2.Unknown),error:Schema2.optionalKey(Schema2.NullOr(Schema2.Struct({code:OptionalText,message:OptionalText}))),files:Schema2.optionalKey(Schema2.Array(Schema2.Unknown)),jobId:Schema2.String,provenance:Schema2.optionalKey(Schema2.Unknown),status:Schema2.Literals(imageStatuses),usage:Schema2.optionalKey(Schema2.Unknown)});var decodeOutput=Schema2.decodeUnknownOption(ImageOutputSchema);var decodeFile=Schema2.decodeUnknownOption(ImageFileSchema);var decodeProvenance=Schema2.decodeUnknownOption(ImageProvenanceSchema);var decodeParameters=Schema2.decodeUnknownOption(ImageParametersSchema);var decodeUsage=Schema2.decodeUnknownOption(ImageUsageSchema);var isWebUrl=(url)=>{try{const{protocol}=new URL(url);return protocol==="http:"||protocol==="https:"}catch{return false}};var shownFiles=(files)=>files.flatMap((value)=>Option.toArray(decodeFile(value)).filter(({mimeType,url})=>mimeType.startsWith("image/")&&isWebUrl(url)));var generationOf=(view)=>({errorMessage:view.error?.message??view.error?.code??globalThis.undefined,files:shownFiles(view.files??[]),jobId:view.jobId,parameters:Option.getOrUndefined(decodeParameters(view.effectiveParameters)),provenance:Option.getOrUndefined(decodeProvenance(view.provenance)),published:view.files!==undefined,status:view.status,usage:Option.getOrUndefined(decodeUsage(view.usage))});var imageGenerationOfPart=(part)=>{const view=part.state==="output-available"?decodeOutput(part.output):Option.none();return Option.isNone(view)?Option.none():Option.some(generationOf(view.value))};var waits=({published,status})=>status==="pending"||status==="running"||!published;var imagePending=(messages)=>messages.some((message)=>message.parts.some((part)=>isToolUIPart(part)&&Option.exists(imageGenerationOfPart(part),waits)));var imageStatusLabels={attention_required:"imageStatusAttentionRequired",cancelled:"imageStatusCancelled",completed:"imageStatusCompleted",failed:"imageStatusFailed",partial:"imageStatusPartial",pending:"imageStatusPending",running:"imageStatusRunning"};var providerName=(route)=>{switch(route){case"azure_flux":case"azure_gpt_image":{return"Azure"}case"bedrock_runtime":{return"Amazon Bedrock"}case"openrouter_images":{return"OpenRouter"}case"regolo_images":{return"Regolo"}default:{return null}}};var textFacts=(pairs)=>pairs.flatMap(([label,value])=>value===null||value===undefined||value===""?[]:[{label,value}]);var provenanceFacts=(labels,provenance)=>provenance===undefined?[]:[{label:labels.imageProvider,value:providerName(provenance.providerRoute)??labels.imageProviderConfigured},{label:labels.imageModel,value:provenance.modelName},...textFacts([[labels.imageModelVersion,provenance.modelVersion],[labels.imageDeployment,provenance.deploymentName],[labels.imageProviderModel,provenance.routeModelName]])];var parameterFacts=(labels,parameters)=>{if(parameters===undefined){return[]}const{count,referenceImages}=parameters;return[...count!==null&&count!==undefined&&Number.isSafeInteger(count)&&count>0?[{label:labels.imageCount,value:String(count)}]:[],...textFacts([[labels.imageFormat,parameters.format?.toUpperCase()],[labels.imageResolution,parameters.resolution],[labels.imageAspectRatio,parameters.aspectRatio],[labels.imageQuality,parameters.quality],[labels.imageBackground,parameters.background]]),...referenceImages===null||referenceImages===undefined?[]:[{label:labels.imageReferenceImages,value:String(referenceImages.length)}]]};var amountPattern=/^(?:0|[1-9]\d*)(?:\.\d+)?$/u;var currencyPattern=/^[A-Z]{3}$/u;var usageFacts=(labels,usage)=>{const amount=usage?.amount??"";const currency=usage?.currency??"";const kind=usage?.kind;const known=(kind==="actual"||kind==="estimate")&&amountPattern.test(amount)&¤cyPattern.test(currency);return[known?{label:kind==="actual"?labels.imageActualCost:labels.imageEstimatedCost,value:`${currency} ${amount}`}:{label:labels.imageCost,value:labels.imageCostUnavailable},...textFacts([[labels.imageCostSource,usage?.source]])]};var imageFactsOf=(labels,generation)=>[...provenanceFacts(labels,generation.provenance),...parameterFacts(labels,generation.parameters),...usageFacts(labels,generation.usage)];import{jsx as jsx28,jsxs as jsxs25}from"react/jsx-runtime";var ImageGenerationPart=({labels,part})=>jsxs25("section",{className:"flex flex-col gap-2 border p-3 text-sm","data-part":"image-generation","data-status":part.status,children:[jsx28("h3",{className:"font-medium",children:labels.imageTitle}),jsx28("p",{"aria-live":"polite",children:labels[imageStatusLabels[part.status]]}),part.errorMessage===undefined?null:jsx28("p",{className:"text-muted-foreground text-xs",children:part.errorMessage}),part.files.length===0?null:jsx28("div",{className:"flex flex-wrap gap-2",children:part.files.map((file)=>jsx28("a",{href:file.url,rel:"noreferrer",target:"_blank",children:jsx28("img",{alt:file.filename,className:"max-h-64 max-w-full border object-contain",src:file.url})},file.id))}),jsx28("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:imageFactsOf(labels,part).map((fact)=>jsxs25("div",{className:"contents",children:[jsx28("dt",{className:"text-muted-foreground",children:fact.label}),jsx28("dd",{className:"min-w-0 break-words",children:fact.value})]},fact.label))})]});import{Badge as Badge6}from"@collective-intelligence/ui-react/ui";import{LifecycleStatusCard}from"@collective-intelligence/ui-react/ui-extensions";import{jsx as jsx29,jsxs as jsxs26}from"react/jsx-runtime";var intentCardLabels={en:{completed:"Completed",ended:"Result no longer available",failed:"Failed",title:"Intent {name}",working:"Working"},it:{completed:"Completato",ended:"Risultato non più disponibile",failed:"Non riuscito",title:"Intent {name}",working:"In corso"}};var resultText=(result)=>hasStringRuntimeKind2(result)?result:JSON.stringify(result,null,2);var statusOf=(labels,state)=>{switch(state.kind){case"running":{return{statusLabel:labels.working,tone:"active"}}case"completed":{return{completedState:jsx29("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm",children:resultText(state.result)}),statusLabel:labels.completed,tone:"success"}}case"failed":{return{error:{summary:state.reason,tone:"destructive"},statusLabel:labels.failed,tone:"danger"}}case"ended":{return{statusLabel:labels.ended,tone:"muted"}}}};var badgeVariant={active:"secondary",danger:"destructive",default:"secondary",muted:"outline",success:"default",warning:"outline"};var intentCardHeader=({model,statusLabel,title})=>jsxs26("div",{className:"flex items-center justify-between gap-2 text-sm",children:[jsx29("span",{className:"font-medium",children:title}),jsx29(Badge6,{variant:badgeVariant[model.tone??"default"],children:statusLabel})]});var intentCardShell=(state)=>function IntentCardShell({children,title}){return jsx29("section",{"aria-label":String(title),"data-slot":"intent-card","data-state":state,children})};var IntentCard=({card,className,labels:custom,locale="en"})=>{const labels={...intentCardLabels[locale],...custom};const title=labels.title.replace("{name}",card.displayName??card.fqn);const model={...statusOf(labels,card.state),description:undefined,title};return jsx29(LifecycleStatusCard,{className,model,slots:{header:intentCardHeader,shell:intentCardShell(card.state.kind)}})};import{jsx as jsx30}from"react/jsx-runtime";var cardState=(part)=>{switch(part.state){case"running":case"ended":{return{kind:part.state}}case"completed":{return{kind:"completed",result:part.result}}case"failed":{return{kind:"failed",reason:part.reason}}}};var IntentCardMessagePart=({labels,part})=>jsx30(IntentCard,{card:{...part.displayName!==undefined&&{displayName:part.displayName},fqn:part.fqn,handle:part.dispatchId,state:cardState(part)},labels:{completed:labels.intentCardCompleted,ended:labels.intentCardEnded,failed:labels.intentCardFailed,title:labels.intentCardTitle,working:labels.intentCardWorking}});import{Badge as Badge7}from"@collective-intelligence/ui-react/ui";import{jsx as jsx31,jsxs as jsxs27}from"react/jsx-runtime";var kindLabels={created:"memoryCreated",merged:"memoryMerged",rejected:"approvalStatusRejected",retrieved:"memoryRetrieved",selected:"memorySelected",skipped:"memorySkipped",suggested:"memorySuggested",superseded:"memorySuperseded",used:"memoryUsedEvent"};var shownEvents=({events})=>{const relevant=events.filter(({kind})=>kind!=="retrieved");return relevant.length>0?relevant:events};var MemoryEvidencePart=({labels,part})=>{const{events}=part;if(events.length===0){return null}const count=(kinds)=>String(events.filter(({kind})=>kinds.includes(kind)).length);const used=count(["used"]);const saved=count(["created","suggested"]);const disabled=events.some(({kind,reason})=>kind==="skipped"&&reason==="memory_disabled");return jsxs27("section",{className:"flex flex-col gap-2 border p-3 text-sm","data-part":"memory-evidence",children:[jsxs27("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[jsx31("h3",{className:"font-medium",children:labels.memoryTitle}),jsxs27("div",{className:"flex flex-wrap gap-1",children:[used==="0"?null:jsx31(Badge7,{variant:"secondary",children:fillLabel(labels.memoryUsed,{count:used})}),saved==="0"?null:jsx31(Badge7,{variant:"secondary",children:fillLabel(labels.memorySaved,{count:saved})}),disabled?jsx31(Badge7,{variant:"outline",children:labels.memoryDisabled}):null]})]}),jsx31("ul",{className:"flex flex-col gap-1",children:shownEvents(part).map((event,index)=>jsxs27("li",{className:"flex flex-wrap items-center gap-2",children:[jsx31("span",{className:"font-medium",children:labels[kindLabels[event.kind]]}),[event.category,event.scope,event.lifecycleStatus,event.reason].filter((detail)=>detail!==null&&detail!=="").map((detail)=>jsx31("span",{className:"text-muted-foreground text-xs",children:detail?.replaceAll("_"," ")},detail))]},index))})]})};import{Questionnaire,QuestionnaireActions,QuestionnaireChoice,QuestionnaireChoiceDescription,QuestionnaireChoices,QuestionnaireInput,QuestionnaireItem,QuestionnaireSubmit,QuestionnaireTitle}from"@collective-intelligence/ui-react/ai-elements";import{Badge as Badge8}from"@collective-intelligence/ui-react/ui";import{jsx as jsx32,jsxs as jsxs28}from"react/jsx-runtime";var answerField="answer";var answerOf=(form)=>{const chosen=form.querySelector('input[type="radio"]:checked');if(chosen!==null){return{kind:"option",optionId:chosen.value}}const text=form.querySelector('[data-slot="questionnaire-input"]')?.value.trim()??"";return text===""?null:{kind:"free_text",text}};var answerText=({input,output})=>{if(output===undefined){return null}return output.kind==="free_text"?output.text:input.options.find(({id})=>id===output.optionId)?.label??output.optionId};var AnsweredQuestion=({labels,question})=>jsxs28("div",{className:"flex flex-col gap-2 border p-4","data-part":"question",children:[jsxs28("div",{className:"flex items-center justify-between gap-2",children:[jsx32("p",{className:"text-sm font-medium",children:question.input.prompt}),jsx32(Badge8,{variant:"secondary",children:labels.questionCompleted})]}),jsx32("p",{className:"text-muted-foreground text-sm",children:answerText(question)})]});var QuestionPart=({answer,labels,part})=>{if(part.output!==undefined){return jsx32(AnsweredQuestion,{labels,question:part})}const{allowFreeText,mode,options,prompt}=part.input;const choices=mode==="single_choice"&&options.length>0;const submit=(event)=>{event.preventDefault();const output=answerOf(event.currentTarget);if(output!==null){answer(output)}};return jsxs28(Questionnaire,{className:"border p-4","data-part":"question",onSubmit:submit,children:[jsxs28(QuestionnaireItem,{name:answerField,required:true,children:[jsx32(QuestionnaireTitle,{children:prompt}),choices?jsx32(QuestionnaireChoices,{children:options.map((option)=>jsxs28(QuestionnaireChoice,{value:option.id,children:[option.label,option.description===null?null:jsx32(QuestionnaireChoiceDescription,{children:option.description})]},option.id))}):null,!choices||allowFreeText?jsx32(QuestionnaireInput,{"aria-label":choices?labels.questionOtherAnswer:labels.questionTextAnswer,placeholder:labels.questionTextPlaceholder}):null]}),jsx32(QuestionnaireActions,{children:jsx32(QuestionnaireSubmit,{children:labels.questionAnswer})})]})};import{MessageAction}from"@collective-intelligence/ui-react/ai-elements";import{Loader2 as Loader22,Pause,Play}from"@collective-intelligence/ui-react/icons";import{useEffect as useEffect2,useRef as useRef3,useState as useState18}from"react";var maxRetries=3;var retryDelayMs=1000;var silence="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQAAAAA=";var unlock=async(audio)=>{try{await audio.play()}catch{}};var useReadAloud=(invocationId)=>{const{call}=useChatSession2();const[playback,setPlayback]=useState18({status:"idle"});const reading=useRef3(0);const player=useRef3(null);const quiet=()=>{player.current?.pause();player.current=null};useEffect2(()=>()=>{reading.current+=1;player.current?.pause()},[]);const play=async(audio,partIndex,retries=0)=>{const own=reading.current;const stillReading=()=>own===reading.current;const fail=()=>{if(stillReading()){reading.current+=1;quiet();setPlayback({status:"failed"})}};setPlayback({partIndex,status:"loading"});const result=await call((client)=>client.chatSpeech.getReadAloudPart({params:{invocationId,partIndex}}));if(!stillReading()){return}if(!result.ok){const{code,retryable}=result.error;if(retries<maxRetries&&(code==="conflict"||retryable)){setTimeout(()=>{if(stillReading()){play(audio,partIndex,retries+1)}},retryDelayMs);return}fail();return}const{partCount,url}=result.value;audio.src=url;audio.addEventListener("ended",()=>{if(!stillReading()){return}if(partIndex+1<partCount){play(audio,partIndex+1);return}player.current=null;setPlayback({status:"idle"})},{once:true});audio.addEventListener("error",fail,{once:true});setPlayback({partIndex,status:"playing"});await audio.play().catch(fail)};const toggle=()=>{reading.current+=1;quiet();if(playback.status==="loading"||playback.status==="playing"){setPlayback({status:"idle"});return}const audio=new Audio(silence);player.current=audio;unlock(audio);play(audio,0)};return{playback,toggle}};import{jsx as jsx33,jsxs as jsxs29,Fragment as Fragment11}from"react/jsx-runtime";var ReadAloudIcon=({status})=>{if(status==="loading"){return jsx33(Loader22,{"aria-hidden":"true",className:"animate-spin"})}return status==="playing"?jsx33(Pause,{"aria-hidden":"true"}):jsx33(Play,{"aria-hidden":"true"})};var ReadAloudButton=({labels,playback,toggle})=>{const reading=playback.status==="loading"||playback.status==="playing";const failed=playback.status==="failed";return jsxs29(Fragment11,{children:[jsx33(MessageAction,{"aria-pressed":reading,className:failed?"text-destructive":undefined,label:reading?labels.readAloudStop:labels.readAloud,onClick:toggle,title:failed?labels.readAloudFailed:undefined,children:jsx33(ReadAloudIcon,{...playback})}),jsx33("output",{"aria-live":"polite",className:"sr-only",children:failed?labels.readAloudFailed:""})]})};var ReadAloud=({Control,invocationId,labels,message})=>{const{playback,toggle}=useReadAloud(invocationId);return jsx33("span",{className:"inline-flex items-center","data-part":"read-aloud",children:jsx33(Control,{labels,message,playback,toggle})})};import{Reasoning,ReasoningContent,ReasoningTrigger}from"@collective-intelligence/ui-react/ai-elements";import{jsx as jsx34,jsxs as jsxs30}from"react/jsx-runtime";var ReasoningPart=({labels,part})=>{const streaming=part.state==="streaming";return jsxs30(Reasoning,{className:"mb-0","data-part":"reasoning",defaultOpen:streaming,isStreaming:streaming,children:[jsx34(ReasoningTrigger,{getThinkingMessage:()=>labels.reasoning}),jsx34(ReasoningContent,{children:part.text})]})};import{Bubble,BubbleContent}from"@collective-intelligence/ui-react/ui";import{jsx as jsx35,jsxs as jsxs31}from"react/jsx-runtime";var SteeringMessagePart=({labels,part})=>jsxs31(Bubble,{align:"end","data-part":"steering-message",children:[jsx35(BubbleContent,{className:"whitespace-pre-wrap",children:part.parts.flatMap((content)=>content.type==="text"?[content.text]:[])}),jsx35("span",{className:"text-muted-foreground self-end text-xs",children:labels.steeringMessageSent})]});import{MessageResponse as MessageResponse2}from"@collective-intelligence/ui-react/ai-elements";import{jsx as jsx36}from"react/jsx-runtime";var TextPart=({part})=>jsx36(MessageResponse2,{isAnimating:part.state==="streaming",children:part.text});import{Confirmation,ConfirmationAccepted,ConfirmationAction,ConfirmationActions,ConfirmationRejected,ConfirmationTitle,Tool,ToolContent,ToolHeader,ToolInput,ToolOutput}from"@collective-intelligence/ui-react/ai-elements";import{getToolName}from"ai";import*as Option2 from"effect/Option";import*as Schema3 from"effect/Schema";import{jsx as jsx37,jsxs as jsxs32}from"react/jsx-runtime";var dispatchIntentToolName="dispatch_intent";var decodeIntentCall=Schema3.decodeUnknownOption(Schema3.Struct({fqn:Schema3.String,inputs:Schema3.Record(Schema3.String,Schema3.Json)}));var intentCallOf=(part)=>getToolName(part)===dispatchIntentToolName?decodeIntentCall(part.input):Option2.none();var isText2=Schema3.is(Schema3.String);var shownValue=(value)=>isText2(value)?value:JSON.stringify(value);var ToolPart=({answerApproval,labels,part})=>{const name=getToolName(part);const intentCall=Option2.getOrUndefined(intentCallOf(part));const{approval}=part;const answer=(approved)=>{if(approval!==undefined){answerApproval({approvalId:approval.id,approved})}};return jsxs32("div",{className:"flex flex-col gap-2","data-part":"tool",children:[jsxs32(Tool,{className:"mb-0",children:[part.type==="dynamic-tool"?jsx37(ToolHeader,{state:part.state,toolName:part.toolName,type:part.type}):jsx37(ToolHeader,{state:part.state,type:part.type}),jsxs32(ToolContent,{children:[jsx37(ToolInput,{input:part.input}),jsx37(ToolOutput,{errorText:part.errorText,output:part.output})]})]}),jsxs32(Confirmation,{approval,state:part.state,children:[jsx37(ConfirmationTitle,{children:intentCall===undefined?fillLabel(labels.permissionTitle,{name}):fillLabel(labels.intentApprovalTitle,{name:part.title??intentCall.fqn})}),intentCall!==undefined&&Object.keys(intentCall.inputs).length>0&&jsx37("dl",{"aria-label":labels.intentApprovalInputs,className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs","data-slot":"intent-approval-inputs",children:Object.entries(intentCall.inputs).map(([key,value])=>jsxs32("div",{className:"contents",children:[jsx37("dt",{className:"text-muted-foreground",children:key}),jsx37("dd",{className:"break-words",children:shownValue(value)})]},key))}),jsx37(ConfirmationAccepted,{children:jsx37("p",{className:"text-xs",children:labels.approvalStatusApproved})}),jsx37(ConfirmationRejected,{children:jsx37("p",{className:"text-xs",children:labels.approvalStatusRejected})}),jsxs32(ConfirmationActions,{children:[jsx37(ConfirmationAction,{onClick:()=>{answer(false)},variant:"outline",children:labels.approvalReject}),jsx37(ConfirmationAction,{onClick:()=>{answer(true)},children:labels.approvalApprove})]})]})]})};import{jsx as jsx38}from"react/jsx-runtime";import{createElement as createElement2}from"react";var partRenderersOf=(components={})=>({AnswerFeedback:components.AnswerFeedback??ChatAnswerFeedback,Evidence:components.Evidence??EvidencePart,File:components.File??FilePart,ImageGeneration:components.ImageGeneration??ImageGenerationPart,IntentCard:components.IntentCard??IntentCardMessagePart,MemoryEvidence:components.MemoryEvidence??MemoryEvidencePart,Question:components.Question??QuestionPart,ReadAloud:components.ReadAloud??ReadAloudButton,Reasoning:components.Reasoning??ReasoningPart,SteeringMessage:components.SteeringMessage??SteeringMessagePart,Text:components.Text??TextPart,Tool:components.Tool??ToolPart});var decodeQuestionInput=Schema4.decodeUnknownOption(ciAskUserSchemas2.input);var decodeQuestionOutput=Schema4.decodeUnknownOption(ciAskUserSchemas2.output);var questionOf=(part)=>{if(getToolName2(part)!==ciAskUserToolName2){return Option3.none()}const{toolCallId}=part;const input=decodeQuestionInput(part.input);if(part.state==="input-available"){return input.pipe(Option3.map((value)=>({input:value,output:undefined,toolCallId})))}return part.state==="output-available"?Option3.all({input,output:decodeQuestionOutput(part.output)}).pipe(Option3.map((question)=>({...question,toolCallId}))):Option3.none()};var MessagePart=({answers,labels,message,part,renderers})=>{const base={labels,message};if(isToolUIPart2(part)){const question=questionOf(part);if(Option3.isSome(question)){return jsx38(renderers.Question,{...base,answer:(output)=>{answers.answerQuestion(question.value.toolCallId,output)},part:question.value})}const image=imageGenerationOfPart(part);return Option3.isSome(image)?jsx38(renderers.ImageGeneration,{...base,part:image.value}):jsx38(renderers.Tool,{...base,answerApproval:answers.answerApproval,part})}switch(part.type){case"text":{return jsx38(renderers.Text,{...base,part})}case"reasoning":{return jsx38(renderers.Reasoning,{...base,part})}case"file":{return jsx38(renderers.File,{...base,part})}case"steering-message":{return jsx38(renderers.SteeringMessage,{...base,part})}case"data-evidence":{return jsx38(renderers.Evidence,{...base,part:part.data})}case"data-memory-evidence":{return jsx38(renderers.MemoryEvidence,{...base,part:part.data})}case"data-intent-card":{return jsx38(renderers.IntentCard,{...base,part:part.data})}default:{return null}}};var MessageParts=({message,...props})=>message.parts.map((part,index)=>createElement2(MessagePart,{...props,key:index,message,part}));import{Activity as Activity2}from"@collective-intelligence/ui-react/icons";import{Trace as Trace3,TraceCollapsible as TraceCollapsible2,TraceCollapsibleContent as TraceCollapsibleContent2,TraceCollapsibleTrigger as TraceCollapsibleTrigger2,TraceIcon as TraceIcon3,TraceLine as TraceLine3,TraceTitle as TraceTitle3}from"@collective-intelligence/ui-react/ui";import{useState as useState20}from"react";import{cn as cn13}from"@collective-intelligence/ui-react";import{Activity,AlertCircle,ExternalLink,Link2}from"@collective-intelligence/ui-react/icons";import{Alert as Alert2,AlertDescription as AlertDescription2,Button as Button16,Trace as Trace2,TraceIcon as TraceIcon2,TraceLine as TraceLine2,TraceTitle as TraceTitle2,TraceDescription as TraceDescription2}from"@collective-intelligence/ui-react/ui";import*as Effect2 from"effect/Effect";import{useState as useState19,useSyncExternalStore as useSyncExternalStore2}from"react";import{parseJsonEventStream,readUIMessageStream,uiMessageChunkSchema}from"ai";import*as Effect from"effect/Effect";import{HttpApiClient}from"effect/http-api";import*as Option4 from"effect/Option";import*as Schema5 from"effect/Schema";import*as Stream from"effect/Stream";var loadingRun={errorText:null,failure:null,message:null,status:"loading"};var cutStream=()=>new AiFailureError2({code:"unavailable",message:"The run stream closed before the run ended.",retryable:true});var ended=new Map([["error","failed"],["other","cancelled"],["stop","completed"]]);var statusAfter=(chunk)=>{switch(chunk.type){case"start":{return{status:"running"}}case"error":{return{errorText:chunk.errorText,status:"failed"}}case"finish":{return{status:chunk.finishReason===undefined?"waiting":ended.get(chunk.finishReason)??"completed"}}default:{return}}};var chunksOf2=(body,update)=>parseJsonEventStream({schema:uiMessageChunkSchema,stream:Stream.toReadableStream(body)}).pipeThrough(new TransformStream({transform:(result,controller)=>{if(!result.success){throw result.error}const status=statusAfter(result.value);if(status!==undefined){update(status)}controller.enqueue(result.value)}}));var decodeRunFailure=HttpApiClient.decodeResponse(ChatSurfaceApi2,{endpoint:"streamRun",group:"chat"});var untilAborted=(signal)=>Effect.callback((resume)=>{if(signal.aborted){resume(Effect.succeed("aborted"));return}const onAbort=()=>{resume(Effect.succeed("aborted"))};signal.addEventListener("abort",onAbort,{once:true});return Effect.sync(()=>{signal.removeEventListener("abort",onAbort)})});var readRunStream=(runId,update,signal)=>(client)=>{const read=Effect.gen(function*readRun(){const response=yield*client.chat.streamRun({params:{runId},responseMode:"response-only"});if(response.status!==200){yield*decodeRunFailure(response);return yield*Effect.fail(cutStream())}let told=false;const messages=readUIMessageStream({stream:chunksOf2(response.stream,(state)=>{told||=state.status!=="running";update(state)})});yield*Stream.runForEach(Stream.fromAsyncIterable(messages,toSessionFailure),(message)=>Effect.sync(()=>{update({message})}));if(!told){return yield*Effect.fail(cutStream())}});return Effect.raceFirst(read,untilAborted(signal))};var decodeRunId=Schema5.decodeUnknownOption(InvocationId2);var unknownRun={code:"not_found",message:"The run id is not a run.",retryable:false};var makeRunTraceStore=(runId,call)=>{const id=decodeRunId(runId);let state=Option4.isSome(id)?loadingRun:{...loadingRun,failure:unknownRun};let reading=null;const listeners=new Set;const publish=(next)=>{state=next;for(const listener of listeners){listener()}};const start=()=>{if(Option4.isNone(id)){return}const own=new AbortController;reading=own;const update=(change)=>{if(!own.signal.aborted){publish({...state,...change})}};const read=async()=>{const result=await call(readRunStream(id.value,update,own.signal));if(!result.ok){update({failure:result.error})}};read()};const stop=()=>{reading?.abort();reading=null};return{getSnapshot:()=>state,retry:()=>{stop();publish(loadingRun);start()},subscribe:(listener)=>{listeners.add(listener);if(reading===null&&Option4.isSome(id)){state=loadingRun;start()}return()=>{listeners.delete(listener);if(listeners.size===0){stop()}}}}};import{ToolInput as ToolInput2,ToolOutput as ToolOutput2}from"@collective-intelligence/ui-react/ai-elements";import{Sparkles as Sparkles2,Wrench as Wrench2}from"@collective-intelligence/ui-react/icons";import{Trace,TraceCollapsible,TraceCollapsibleContent,TraceCollapsibleTrigger,TraceDescription,TraceIcon,TraceLine,TraceTitle}from"@collective-intelligence/ui-react/ui";import{getToolName as getToolName3,isToolUIPart as isToolUIPart3}from"ai";import{jsx as jsx39,jsxs as jsxs33}from"react/jsx-runtime";var isActivity=(part)=>isToolUIPart3(part)||part.type==="reasoning";var statusProp=(status)=>status===undefined?{}:{status};var toolStatus=(part,running)=>{switch(part.state){case"output-denied":case"output-error":{return"error"}case"approval-responded":case"input-available":case"input-streaming":{return running?"running":undefined}default:{return}}};var approvalOf=(part,labels)=>{switch(part.state){case"approval-requested":{return labels.approvalStatusPending}case"approval-responded":{return part.approval.approved?labels.approvalStatusApproved:labels.approvalStatusRejected}case"output-denied":{return labels.approvalStatusRejected}default:{return null}}};var ToolLine=({labels,part,running})=>{const approval=approvalOf(part,labels);const errorText=part.state==="output-error"?part.errorText:undefined;const line=jsxs33(TraceLine,{...statusProp(toolStatus(part,running)),children:[jsx39(TraceIcon,{children:jsx39(Wrench2,{})}),jsx39(TraceTitle,{children:getToolName3(part)}),approval===null?null:jsx39(TraceDescription,{children:approval})]});const output=part.state==="output-available"?part.output:undefined;const hasInput=part.input!==undefined&&part.input!==null;const hasOutput=output!==undefined&&output!==null;if(!hasInput&&!hasOutput&&errorText===undefined){return jsx39("div",{"data-part":"run-trace-tool",children:line})}return jsxs33(TraceCollapsible,{"data-part":"run-trace-tool",children:[jsx39(TraceCollapsibleTrigger,{children:line}),jsxs33(TraceCollapsibleContent,{className:"flex flex-col gap-2",children:[hasInput?jsx39(ToolInput2,{input:part.input}):null,jsx39(ToolOutput2,{errorText,output})]})]})};var ReasoningLine=({labels,part,running})=>{const line=jsxs33(TraceLine,{...statusProp(running&&part.state==="streaming"?"running":undefined),children:[jsx39(TraceIcon,{children:jsx39(Sparkles2,{})}),jsx39(TraceTitle,{children:labels.reasoning})]});if(part.text===""){return jsx39("div",{"data-part":"run-trace-reasoning",children:line})}return jsxs33(TraceCollapsible,{"data-part":"run-trace-reasoning",children:[jsx39(TraceCollapsibleTrigger,{children:line}),jsx39(TraceCollapsibleContent,{children:part.text})]})};var shownKinds=new Set(["data-evidence","data-memory-evidence","file","steering-message","text"]);var groupsOf=(parts)=>{const groups=[];let activity=null;for(const part of parts){if(isActivity(part)){if(activity===null){activity=[];groups.push({kind:"activity",parts:activity})}activity.push(part)}else if(shownKinds.has(part.type)){activity=null;groups.push({kind:"part",part})}}return groups};var PartOfRun=({labels,message,part,renderers})=>{const base={labels,message};switch(part.type){case"text":{return jsx39(renderers.Text,{...base,part})}case"file":{return jsx39(renderers.File,{...base,part})}case"steering-message":{return jsx39(renderers.SteeringMessage,{...base,part})}case"data-evidence":{return jsx39(renderers.Evidence,{...base,part:part.data})}case"data-memory-evidence":{return jsx39(renderers.MemoryEvidence,{...base,part:part.data})}default:{return null}}};var RunTraceParts=({labels,message,renderers,running})=>groupsOf(message.parts).map((group,index)=>group.kind==="activity"?jsx39(Trace,{"data-part":"run-trace-steps",children:group.parts.map((part,line)=>part.type==="reasoning"?jsx39(ReasoningLine,{labels,part,running},line):jsx39(ToolLine,{labels,part,running},part.toolCallId))},index):jsx39(PartOfRun,{labels,message,part:group.part,renderers},index));import{jsx as jsx40,jsxs as jsxs34}from"react/jsx-runtime";var lineStatus=(status)=>{if(status==="failed"){return"error"}return status==="loading"||status==="running"?"running":undefined};var statusLabel=(labels,{message,status})=>{const waitsForApproval=message?.parts.some((part)=>("state"in part)&&part.state==="approval-requested")===true;const words={cancelled:labels.runStatusStopped,completed:labels.runStatusCompleted,failed:labels.runStatusFailed,loading:labels.loading,running:labels.runStatusActive,waiting:waitsForApproval?labels.runStatusWaitingForApproval:labels.runStatusNeedsInput};return words[status]};var RunTraceHead=({labels,state})=>{const traceLink=state.message?.metadata?.traceLink;return jsxs34(Trace2,{"data-part":"run-trace-head",children:[jsxs34(TraceLine2,{...statusProp(lineStatus(state.status)),children:[jsx40(TraceIcon2,{children:jsx40(Activity,{})}),jsx40(TraceTitle2,{children:labels.runCardTitle}),jsx40(TraceDescription2,{children:statusLabel(labels,state)})]}),state.errorText===null?null:jsxs34(TraceLine2,{status:"error",children:[jsx40(TraceIcon2,{children:jsx40(AlertCircle,{})}),jsx40(TraceTitle2,{children:state.errorText})]}),traceLink===undefined?null:jsx40("a",{"aria-label":labels.runCardTraceLink,"data-part":"run-trace-link",href:traceLink,rel:"noreferrer",target:"_blank",children:jsxs34(TraceLine2,{children:[jsx40(TraceIcon2,{children:jsx40(Link2,{})}),jsx40(TraceTitle2,{children:labels.runCardTraceLink}),jsx40(TraceIcon2,{children:jsx40(ExternalLink,{})})]})})]})};var RunTraceView=({call,className,labels,locale="en",messageParts,runId})=>{const[store]=useState19(()=>makeRunTraceStore(runId,call));const state=useSyncExternalStore2(store.subscribe,store.getSnapshot,store.getSnapshot);const shown=labelsOf(locale,labels);return jsx40(ChatRoot,{className:"h-auto",children:jsxs34("div",{className:cn13("flex min-w-0 flex-col gap-3",className),"data-part":"run-trace",children:[jsx40(RunTraceHead,{labels:shown,state}),state.failure===null?null:jsxs34(Alert2,{variant:"destructive",children:[jsx40(AlertCircle,{}),jsxs34(AlertDescription2,{className:"flex items-center justify-between gap-3",children:[jsx40("span",{children:shown.actionFailed}),state.failure.retryable?jsx40(Button16,{onClick:()=>{store.retry()},size:"sm",type:"button",variant:"outline",children:shown.retry}):null]})]}),state.message===null?null:jsx40(RunTraceParts,{labels:shown,message:state.message,renderers:partRenderersOf(messageParts),running:state.status==="running"})]})})};var SessionRunTrace=(props)=>{const{call}=useChatSession2();return jsx40(RunTraceView,{...props,call})};var callOn=(api)=>{const runtime=makeChatSessionRuntime(api);return(operation)=>runtime.runPromise(Effect2.match(callChatSurface(operation),{onFailure:({error})=>({error,ok:false}),onSuccess:(value)=>({ok:true,value})}))};var MountRunTrace=({api,...props})=>{const[call]=useState19(()=>callOn(api));return jsx40(RunTraceView,{...props,call})};var RunTrace=({api,...props})=>api===undefined?jsx40(SessionRunTrace,{...props},props.runId):jsx40(MountRunTrace,{api,...props},props.runId);import{jsx as jsx41,jsxs as jsxs35}from"react/jsx-runtime";var MessageRun=({labels,locale,messageParts,runId})=>{const[open,setOpen]=useState20(false);return jsx41(Trace3,{"data-part":"message-run",children:jsxs35(TraceCollapsible2,{onOpenChange:setOpen,open,children:[jsx41(TraceCollapsibleTrigger2,{children:jsxs35(TraceLine3,{children:[jsx41(TraceIcon3,{children:jsx41(Activity2,{})}),jsx41(TraceTitle3,{children:fillLabel(labels.runCardDetail,{id:runId.slice(0,8)})})]})}),jsx41(TraceCollapsibleContent2,{children:open?jsx41(RunTrace,{labels,locale,messageParts,runId}):null})]})})};import{jsx as jsx42}from"react/jsx-runtime";var SentTrail=({labels,message})=>{const{enabled,visible}=useTrailSwitches();if(!enabled||!visible){return null}return jsx42(TrailChips,{entries:message.metadata?.turnOptions?.contextTrail??[],labels,region:labels.trailSent})};import{useEffect as useEffect3}from"react";var imageReloadMs=2000;var useImageReload=({messages,readMessages,streaming})=>{const waiting=!streaming&&imagePending(messages);useEffect3(()=>{if(!waiting){return}const timer=setInterval(readMessages,imageReloadMs);return()=>{clearInterval(timer)}},[readMessages,waiting])};import{jsx as jsx43,jsxs as jsxs36}from"react/jsx-runtime";var isInvocationId=Schema6.is(InvocationId2);var answeredTurn=(message,streaming)=>{const invocationId=message.metadata?.invocationId;return message.role==="assistant"&&!streaming&&isInvocationId(invocationId)?invocationId:null};var ratableTurn=(message,streaming)=>{const target=message.metadata?.feedbackTargetId;return isInvocationId(target)&&answeredTurn(message,streaming)!==null?target:null};var readableTurn=(message,streaming)=>message.parts.some((part)=>part.type==="text")?answeredTurn(message,streaming):null;var useReadAloudAvailable=()=>{const{result}=useChatRead((client)=>client.chatSpeech.getSpeechAvailability());return result?.ok===true&&result.value.readAloud};var useAnswers=()=>{const{addToolApprovalResponse,addToolOutput,sendMessage}=useCiChat2();const[,startAnswer]=useTransition3();return{answerApproval:({approvalId,approved})=>{startAnswer(async()=>{await addToolApprovalResponse({approved,id:approvalId})})},answerQuestion:(toolCallId,output)=>{startAnswer(async()=>{await addToolOutput({output,tool:ciAskUserToolName2,toolCallId});await sendMessage()})}}};var TranscriptMessage=({answers,labels,locale,message,messageParts,readAloud,renderers,slots,streaming})=>{const run=answeredTurn(message,streaming);const turn=readAloud?readableTurn(message,streaming):null;const rated=ratableTurn(message,streaming);return jsxs36(Message,{from:message.role,children:[jsx43(MessageContent,{children:jsx43(MessageParts,{answers,labels,message,renderers})}),message.role==="user"?jsx43(SentTrail,{labels,message}):null,run===null?null:jsx43(MessageRun,{labels,locale,messageParts,runId:run}),turn===null&&rated===null?null:jsxs36(MessageActions,{children:[rated===null?null:jsx43(AnswerFeedback,{Control:renderers.AnswerFeedback,invocationId:rated,labels,message},rated),turn===null?null:jsx43(ReadAloud,{Control:renderers.ReadAloud,invocationId:turn,labels,message})]}),slots.messageFooter?.(message)]})};var ChatTranscript=({className,labels,locale,messageParts,slots})=>{const{messages,status}=useCiChat2();const{readMessages}=useChatSession2();const readAloud=useReadAloudAvailable();const answers=useAnswers();const renderers=partRenderersOf(messageParts);const last=messages.at(-1);const answering=status==="streaming"||status==="submitted";useImageReload({messages,readMessages,streaming:answering});return jsxs36(Conversation,{className:cn14("min-h-0",className),"data-part":"chat-transcript",children:[jsxs36(ConversationContent,{className:"mx-auto w-full max-w-[900px]",children:[messages.length===0?slots.emptyState??jsx43(ConversationEmptyState,{description:labels.emptyDescription,title:labels.emptyTitle}):messages.map((message)=>jsx43(ConversationItem,{scrollAnchor:message.role==="user",children:jsx43(TranscriptMessage,{answers,labels,locale,message,messageParts,readAloud,renderers,slots,streaming:answering&&message===last})},message.id)),slots.transcriptFooter]}),jsx43(ConversationScrollButton,{})]})};import{jsx as jsx44,jsxs as jsxs37,Fragment as Fragment12}from"react/jsx-runtime";var noSlots={};var noClassNames={};var agentChoiceOf=(pinnedAgentId,plainChat)=>{if(pinnedAgentId!==undefined){return"pinned"}return plainChat?"optional":"required"};var agentRequired={code:"invalid_request",message:"Pick an agent to start a chat.",retryable:false};var partsOf=(components)=>({Blocked:components?.ChatBlockedState??ChatBlockedState,Composer:components?.ChatComposer??ChatComposer,Header:components?.ChatHeader??ChatHeader,Sidebar:components?.ConversationSidebar??ConversationSidebar,Transcript:components?.ChatTranscript??ChatTranscript,composerParts:components?.composerParts,messageParts:components?.messageParts});var ChatLayout=({base,classNames,historyScope,id,onLaunch,parts:{Composer,Header,composerParts,messageParts,Sidebar,Transcript},pinnedAgentId,place,plainChat,preferred})=>{const session=useChatSession2();const projects=useChatProjects();const history=useChatHistory({historyScope,labels:base.labels,place,placeContext:session.placeContext});const[listOpen,setListOpen]=useState21(false);const newChat=(options={})=>{projects.leaveProject();setListOpen(false);session.newChat(pinnedAgentId===undefined?options:{...options,agentId:pinnedAgentId})};useChatLaunchTarget2({id,onLaunch,preferred,session:{...session,newChat:(options)=>{projects.leaveProject();session.newChat(options)},pinnedAgentId,plainChat}});const send=({agentId:picked,...submit})=>{if(session.conversationId===null){const agentId=pinnedAgentId??picked;if(agentId===undefined&&!plainChat){return{error:agentRequired,ok:false}}if(agentId!==undefined){const{capabilities}=session;session.newChat({agentId,...projects.viewedId!==undefined&&{projectId:projects.viewedId}});session.setCapabilities(capabilities)}}session.submit(submit);return{ok:true,value:undefined}};const selectConversation=(conversationId)=>{projects.leaveProject();setListOpen(false);session.selectConversation(conversationId)};const partProps={...base,newChat,send};const sidebarProps={...partProps,history,projects,selectConversation};return jsxs37(Fragment12,{children:[jsx44(Sidebar,{...sidebarProps,className:cn15("hidden @3xl/chat:flex",classNames.ConversationSidebar)}),jsxs37("section",{className:"flex min-h-0 min-w-0 flex-1 flex-col",children:[jsx44(Header,{...partProps,className:classNames.ChatHeader,openConversations:()=>{setListOpen(true)}}),projects.viewed===undefined?jsx44(Transcript,{...partProps,className:classNames.ChatTranscript,messageParts}):jsx44(ProjectView,{history,labels:base.labels,locale:base.locale,newChat,project:projects.viewed,projects,selectConversation}),jsx44(Composer,{...partProps,className:classNames.ChatComposer,composerParts})]}),jsx44(Sheet,{onOpenChange:setListOpen,open:listOpen,children:jsxs37(SheetContent,{className:"w-[320px] p-0",side:"left",children:[jsxs37(SheetHeader,{className:"border-b border-border",children:[jsx44(SheetTitle,{children:base.labels.conversations}),jsx44(SheetDescription,{children:base.labels.conversationsDescription})]}),jsx44(Sidebar,{...sidebarProps,className:cn15("w-full flex-1 border-r-0",classNames.ConversationSidebar)})]})})]})};var Chat=({classNames=noClassNames,components,historyScope,id,labels,locale="en",onLaunch,pinnedAgentId,place,plainChat=true,preferred,slots=noSlots})=>{const{blocked,newChat}=useChatSession2();const ownId=useId5();const parts=partsOf(components);const base={agentChoice:agentChoiceOf(pinnedAgentId,plainChat),labels:labelsOf(locale,labels),locale,slots};return jsx44(ChatRoot,{children:jsx44("div",{className:cn15("@container/chat flex size-full overflow-hidden bg-background text-foreground",classNames.Chat),"data-part":"chat",children:blocked===null?jsx44(ChatLayout,{base,classNames,historyScope,id:id??ownId,onLaunch,parts,pinnedAgentId:pinnedAgentId===undefined?undefined:AgentId2.make(pinnedAgentId),place,plainChat,preferred}):jsx44(parts.Blocked,{...base,blocked,className:classNames.ChatBlockedState,newChat,send:()=>({error:blocked.error,ok:false})})})})};import{ResizableHandle,ResizablePanel,ResizablePanelGroup}from"@collective-intelligence/ui-react/ui";import{createContext,useCallback,useContext,useEffect as useEffect5,useId as useId6,useMemo,useRef as useRef4,useState as useState22}from"react";import{useEffect as useEffect4}from"react";var combinationPattern=/^(?<modifiers>(?:(?:alt|ctrl|meta|shift)\+)*)(?<key>.+)$/iu;var combinationOf=(shortcut)=>{const groups=combinationPattern.exec(shortcut.toLowerCase())?.groups;const modifiers=new Set(groups?.modifiers?.split("+"));return{alt:modifiers.has("alt"),ctrl:modifiers.has("ctrl"),key:groups?.key??"",meta:modifiers.has("meta"),shift:modifiers.has("shift")}};var hasNoCase=(key)=>key.length===1&&key.toLowerCase()===key.toUpperCase();var pressesKey=(combination,event)=>event.key.toLowerCase()===combination.key||combination.alt&&event.code===`Key${combination.key.toUpperCase()}`;var isPress=(combination,event)=>pressesKey(combination,event)&&event.altKey===combination.alt&&event.ctrlKey===combination.ctrl&&event.metaKey===combination.meta&&(event.shiftKey===combination.shift||!combination.shift&&hasNoCase(combination.key));var useShortcut=(shortcut,onPress)=>{useEffect4(()=>{const combination=combinationOf(shortcut);const onKeyDown=(event)=>{if(event.repeat||!isPress(combination,event)){return}event.preventDefault();onPress()};window.addEventListener("keydown",onKeyDown);return()=>{window.removeEventListener("keydown",onKeyDown)}},[onPress,shortcut])};import{jsx as jsx45,jsxs as jsxs38}from"react/jsx-runtime";var AssistantSidebarContext=createContext(undefined);var useAssistantSidebar=()=>{const state=useContext(AssistantSidebarContext);if(state===undefined){throw new Error("Render AssistantSidebar and AssistantSidebarToggle inside an AssistantSidebarLayout.")}return state};var composerInput='[data-part="chat-composer"] textarea:not(:disabled)';var AssistantSidebarLayout=({children,className,sessions,shortcuts,sidebar})=>{const[panelState,setPanelState]=useState22(()=>{const opened=sessions?.readAssistantSidebarOpen?.()??false;return{defaultSize:opened?"30":"0",open:opened}});const{open}=panelState;const latestOpen=useRef4(open);const panel=useRef4(null);const content=useRef4(null);const opener=useRef4(null);const cancelFocus=useRef4(undefined);const controlsId=useId6();const returnFocus=useCallback(()=>{if(!content.current?.contains(document.activeElement)){return}const toggle=[...document.querySelectorAll("[aria-controls]")].find((element)=>element.getAttribute("aria-controls")===controlsId);const target=toggle??opener.current;if(target instanceof HTMLElement){target.focus()}},[controlsId]);const setOpen=useCallback((next)=>{if(next===latestOpen.current){return}latestOpen.current=next;setPanelState((current)=>({...current,open:next}));sessions?.writeAssistantSidebarOpen?.(next);if(next){opener.current=document.activeElement;panel.current?.expand()}else{cancelFocus.current?.();returnFocus();panel.current?.collapse()}},[returnFocus,sessions]);const toggle=useCallback(()=>{setOpen(!latestOpen.current)},[setOpen]);const focusComposer=useCallback(()=>{cancelFocus.current?.();setOpen(true);const root=content.current;const focused=()=>{const input=root?.querySelector(composerInput);input?.focus();return input!==undefined&&document.activeElement===input};if(root===null||focused()){return}const observer=new MutationObserver(()=>{if(focused()){cancelFocus.current?.()}});observer.observe(root,{attributeFilter:["disabled","hidden"],childList:true,subtree:true});cancelFocus.current=()=>{observer.disconnect();cancelFocus.current=undefined}},[setOpen]);useEffect5(()=>()=>{cancelFocus.current?.()},[]);useShortcut(shortcuts?.toggle??"Ctrl+J",toggle);useShortcut(shortcuts?.focusComposer??"Ctrl+/",focusComposer);const state=useMemo(()=>({controlsId,open,setOpen}),[controlsId,open,setOpen]);return jsx45(AssistantSidebarContext.Provider,{value:state,children:jsxs38(ResizablePanelGroup,{className,orientation:"horizontal",children:[jsx45(ResizablePanel,{className:"min-w-0",children}),jsx45(ResizableHandle,{className:open?undefined:"hidden",disabled:!open}),jsx45(ResizablePanel,{collapsedSize:0,collapsible:true,defaultSize:panelState.defaultSize,maxSize:"50",minSize:"25",onResize:(size,_id,before)=>{if(before!==undefined){setOpen(size.asPercentage>0)}},panelRef:panel,children:jsx45("div",{className:"h-full w-full",hidden:!open,id:controlsId,ref:content,children:sidebar})})]})})};import{jsx as jsx46,jsxs as jsxs39}from"react/jsx-runtime";var SidebarTitle=createContext2("");var AssistantSidebarHeader=({className,labels,newChat,openConversations})=>{const title=useContext2(SidebarTitle);const{setOpen}=useAssistantSidebar();const session=useChatSession2();const dialogs=useConversationDialogs({onDeletedOpen:newChat,onSelect:session.selectConversation,projects:undefined});const conversation=session.conversations.find(({id})=>id===session.conversationId);return jsxs39("header",{className:cn16("flex min-h-14 items-center gap-1 border-b border-border bg-background px-3",className),"data-part":"assistant-sidebar-header",children:[jsx46(Button17,{"aria-haspopup":"dialog","aria-label":labels.openConversationList,className:"@3xl/chat:hidden",onClick:openConversations,size:"icon",variant:"ghost",children:jsx46(History,{className:"size-4"})}),jsx46("h2",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-foreground",children:title}),jsx46(Button17,{"aria-label":labels.assistantSidebarDelete,disabled:conversation===undefined,onClick:()=>{if(conversation!==undefined){dialogs.actions.onDelete(conversation)}},size:"icon",variant:"ghost",children:jsx46(Trash24,{className:"size-4"})}),jsx46(Button17,{"aria-label":labels.assistantSidebarCollapse,onClick:()=>{setOpen(false)},size:"icon",variant:"ghost",children:jsx46(ChevronRight2,{className:"size-4"})}),jsx46(ConversationDialogs,{dialogs,labels:{...labels,deleteConversation:labels.assistantSidebarDeleteTitle}})]})};var sidebarParts={ChatHeader:AssistantSidebarHeader};var AssistantSidebar=({title,...chatProps})=>{const{setOpen}=useAssistantSidebar();return jsx46(SidebarTitle.Provider,{value:title,children:jsx46("aside",{"aria-label":title,className:"h-full border-l border-border","data-part":"assistant-sidebar",children:jsx46(Chat,{...chatProps,components:sidebarParts,onLaunch:()=>{setOpen(true)},preferred:true})})})};import{Sparkles as Sparkles3}from"@collective-intelligence/ui-react/icons";import{Button as Button18}from"@collective-intelligence/ui-react/ui";import{jsx as jsx47}from"react/jsx-runtime";var AssistantSidebarToggle=({className,labels,locale="en"})=>{const{controlsId,open,setOpen}=useAssistantSidebar();return jsx47(Button18,{"aria-controls":controlsId,"aria-expanded":open,"aria-label":labels?.assistantSidebarToggle??chatLabels[locale].assistantSidebarToggle,className,"data-slot":"assistant-sidebar-toggle",onClick:()=>{setOpen(!open)},size:"icon",type:"button",variant:"ghost",children:jsx47(Sparkles3,{className:"size-4"})})};import{cn as cn17}from"@collective-intelligence/ui-react";import{MessageSquarePlus}from"@collective-intelligence/ui-react/icons";import{Button as Button19}from"@collective-intelligence/ui-react/ui";import{useEffect as useEffect6,useState as useState23}from"react";import{HttpClient,HttpClientRequest}from"effect/http";import*as Option5 from"effect/Option";import*as Schema7 from"effect/Schema";var chatSubjectHeaderName="x-chat-subject";var chatSubjectHeaderValue=({id,kind})=>`${kind}:${id}`;var withSubjectApi=(api,subject)=>({...api,transformClient:(client)=>HttpClient.mapRequestInput(api.transformClient===undefined?client:api.transformClient(client),HttpClientRequest.setHeader(chatSubjectHeaderName,chatSubjectHeaderValue(subject)))});var decodeDraftUpdate=Schema7.decodeUnknownOption(ciDataPartSchemas2["draft-update"]);var sameSubject=(update,subject)=>update.subject.kind===subject.kind&&update.subject.id===subject.id;var watchDraftUpdates=(stream,subject,onDraftUpdate)=>stream.pipeThrough(new TransformStream({transform:(chunk,controller)=>{if(chunk.type==="data-draft-update"){const update=decodeDraftUpdate(chunk.data);if(Option5.isSome(update)&&sameSubject(update.value,subject)){onDraftUpdate(update.value)}}controller.enqueue(chunk)}}));var withSubjectHeader=(headers,subject)=>({...Object.fromEntries(new Headers(headers).entries()),[chatSubjectHeaderName]:chatSubjectHeaderValue(subject)});var withSubjectTransport=(transport,subject,onDraftUpdate)=>({onResumeEmpty:transport.onResumeEmpty,reconnectToStream:async(request)=>{const stream=await transport.reconnectToStream({...request,headers:withSubjectHeader(request.headers,subject)});return stream===null?null:watchDraftUpdates(stream,subject,onDraftUpdate)},resumeStreamIsReplay:transport.resumeStreamIsReplay??false,sendMessages:async(request)=>watchDraftUpdates(await transport.sendMessages({...request,headers:withSubjectHeader(request.headers,subject)}),subject,onDraftUpdate)});import{jsx as jsx48,jsxs as jsxs40,Fragment as Fragment13}from"react/jsx-runtime";var noHost={};var noSlots2={};var noClassNames2={};var ChatDockHeader=({className,labels,newChat,slots})=>{const session=useChatSession2();const{conversationId}=session;const title=conversationId===null?labels.newChat:session.conversations.find(({id})=>id===conversationId)?.title??"";return jsxs40("header",{className:cn17("flex flex-col border-b border-border bg-background",className),"data-part":"chat-dock-header",children:[jsxs40("div",{className:"flex min-h-12 items-center justify-between gap-2 px-4",children:[jsx48("h2",{className:"truncate text-sm font-semibold text-foreground",children:title}),jsxs40("div",{className:"flex shrink-0 items-center gap-2",children:[jsx48(Button19,{"aria-label":labels.newChat,onClick:()=>{newChat()},size:"icon",type:"button",variant:"outline",children:jsx48(MessageSquarePlus,{})}),slots.headerActions]})]}),session.failure===null?null:jsxs40("div",{className:"flex items-center justify-between gap-3 border-t border-border px-4 py-2 text-sm text-destructive",role:"alert",children:[jsx48("span",{children:failureText(session.failure,labels)}),jsx48(Button19,{onClick:()=>{session.retry()},size:"sm",type:"button",variant:"outline",children:labels.retry})]})]})};var DockView=({agentId,classNames=noClassNames2,components,labels,locale="en",slots=noSlots2})=>{const session=useChatSession2();const Header=components?.ChatDockHeader??ChatDockHeader;const Transcript=components?.ChatTranscript??ChatTranscript;const Composer=components?.ChatComposer??ChatComposer;const Blocked=components?.ChatBlockedState??ChatBlockedState;const newChat=(options={})=>{session.newChat({...options,agentId})};const send=({agentId:_picked,...submit})=>{if(session.conversationId===null){const{capabilities}=session;session.newChat({agentId});session.setCapabilities(capabilities)}session.submit(submit);return{ok:true,value:undefined}};const partProps={agentChoice:"pinned",labels:labelsOf(locale,labels),locale,newChat,send,slots};const{blocked}=session;return jsx48(ChatRoot,{children:jsx48("div",{className:cn17("@container/chat flex size-full flex-col overflow-hidden bg-background text-foreground",classNames.ChatDock),"data-part":"chat-dock",children:blocked===null?jsxs40(Fragment13,{children:[jsx48(Header,{...partProps,className:classNames.ChatDockHeader}),jsx48(Transcript,{...partProps,className:classNames.ChatTranscript,messageParts:components?.messageParts}),jsx48(Composer,{...partProps,className:classNames.ChatComposer})]}):jsx48(Blocked,{...partProps,blocked,className:classNames.ChatBlockedState,send:()=>({error:blocked.error,ok:false})})})})};var makeDraftUpdates=()=>{const listeners=new Set;return{emit:(update)=>{for(const listener of listeners){listener(update)}},subscribe:(listener)=>{listeners.add(listener);return()=>{listeners.delete(listener)}}}};var DockSession=({api,host=noHost,onDraftUpdate,pinnedAgentId,place,subject,transport,...view})=>{const[mount]=useState23(()=>{const updates=makeDraftUpdates();const{sessions:_sessions,...ports}=host;return{api:withSubjectApi(api,subject),host:ports,transport:withSubjectTransport(transport,subject,updates.emit),updates}});const{updates}=mount;useEffect6(()=>onDraftUpdate===undefined?undefined:updates.subscribe(onDraftUpdate),[onDraftUpdate,updates]);return jsx48(ChatSessionProvider2,{api:mount.api,host:mount.host,place,subject,transport:mount.transport,children:jsx48(DockView,{...view,agentId:AgentId2.make(pinnedAgentId)})})};var ChatDock=(props)=>jsx48(DockSession,{...props},chatSubjectHeaderValue(props.subject));import{cn as cn18}from"@collective-intelligence/ui-react";import{Button as Button20,Checkbox,Input as Input4,Label as Label3,Select,SelectContent,SelectItem,SelectTrigger,SelectValue,Textarea as Textarea3}from"@collective-intelligence/ui-react/ui";import{useCallback as useCallback2,useId as useId7,useMemo as useMemo2,useState as useState24}from"react";var isObject=(value)=>hasObjectRuntimeKind2(value)&&!hasNullRuntimeKind2(value)&&!Array.isArray(value);var textOf2=(value)=>hasStringRuntimeKind2(value)?value:undefined;var stringsOf=(value)=>{if(!Array.isArray(value)){return}const strings=value.filter((item)=>hasStringRuntimeKind2(item));return strings.length===value.length?strings:undefined};var kindOf=(property)=>{const options=stringsOf(property["enum"]);if(options!==undefined&&options.length>0){return{kind:"choice",options}}switch(property["type"]){case"boolean":{return{kind:"boolean"}}case"integer":case"number":{return{kind:"number"}}case"string":{return{kind:property["format"]==="date"?"date":"text"}}default:{return{kind:"json"}}}};var fieldsOf=(schema)=>{const{properties,required:requiredNames}=schema;if(!isObject(properties)){return[]}const required=new Set(stringsOf(requiredNames));return Object.entries(properties).map(([name,value])=>{const property=isObject(value)?value:{};return{...kindOf(property),description:textOf2(property["description"]),label:textOf2(property["title"])??name,name,required:required.has(name)}})};var draftValueOf=(field,value)=>{switch(field.kind){case"boolean":{return value===true}case"json":{return value===undefined?"":JSON.stringify(value,null,2)}default:{return hasStringRuntimeKind2(value)||hasNumberRuntimeKind2(value)?String(value):""}}};var draftOf=(fields,values)=>Object.fromEntries(fields.map((field)=>[field.name,draftValueOf(field,values[field.name])]));var parseJson=(text)=>{try{const value=JSON.parse(text);return{kind:"value",value}}catch{return{kind:"unparsed"}}};var parseField=(field,draft)=>{if(field.kind==="boolean"){return{kind:"value",value:draft===true}}const text=hasStringRuntimeKind2(draft)?draft:"";if(text.trim()===""){return{kind:"empty"}}if(field.kind==="json"){return parseJson(text)}if(field.kind!=="number"){return{kind:"value",value:text}}const number=Number(text.trim());return{kind:"value",value:Number.isFinite(number)?number:text}};var inputsOf=(fields,draft,values)=>{const names=new Set(fields.map((field)=>field.name));const parsed=fields.map((field)=>[field.name,parseField(field,draft[field.name])]);const unparsed=parsed.flatMap(([name,value])=>value.kind==="unparsed"?[name]:[]);if(unparsed.length>0){return{unparsed}}return{inputs:Object.fromEntries([...Object.entries(values).filter(([name])=>!names.has(name)),...parsed.flatMap(([name,value])=>value.kind==="value"?[[name,value.value]]:[])])}};var fieldNameOf=(path)=>(path.split("/")[1]??"").replaceAll("~1","/").replaceAll("~0","~");var problemsByField=(fields,problems)=>{const names=new Set(fields.map((field)=>field.name));const byField=new Map;for(const problem of problems){const name=fieldNameOf(problem.path);const key=names.has(name)?name:"";byField.set(key,[...byField.get(key)??[],problem])}return byField};var defaultIntentLabels={choose:"Choose…",dispatched:"Dispatched",done:"Done",failed:"Failed",invalid:"Invalid",invalidJson:"Enter valid JSON",missing:"Required",noChat:"No chat is available",notAllowed:"Not allowed",submit:"Send",working:"Working…"};import{jsx as jsx49,jsxs as jsxs41}from"react/jsx-runtime";var noProblems=[];var noValues={};var FieldControl=({describedBy,disabled,field,id,invalid,labels,onChange,value})=>{const text=hasStringRuntimeKind2(value)?value:"";const common={"aria-describedby":describedBy,"aria-invalid":invalid,"aria-required":field.required?true:undefined,disabled,id};if(field.kind==="boolean"){return jsx49(Checkbox,{...common,checked:value===true,onCheckedChange:(checked)=>{onChange(checked===true)}})}if(field.kind==="choice"){return jsxs41(Select,{disabled,onValueChange:(choice)=>{onChange(choice??"")},value:text,children:[jsx49(SelectTrigger,{...common,children:jsx49(SelectValue,{placeholder:labels.choose})}),jsx49(SelectContent,{children:field.options.map((option)=>jsx49(SelectItem,{value:option,children:option},option))})]})}if(field.kind==="json"){return jsx49(Textarea3,{...common,className:"font-mono",onChange:(event)=>{onChange(event.target.value)},value:text})}return jsx49(Input4,{...common,onChange:(event)=>{onChange(event.target.value)},type:field.kind,value:text})};var IntentFormFields=({className,disabled=false,entry,labels,onSubmit,problems=noProblems,values=noValues})=>{const id=useId7();const fields=useMemo2(()=>fieldsOf(entry.inputSchema),[entry.inputSchema]);const[draft,setDraft]=useState24(()=>draftOf(fields,values));const[unparsed,setUnparsed]=useState24([]);const text={...defaultIntentLabels,...labels};const byField=problemsByField(fields,problems);const formProblems=byField.get("")??[];const focusFirstMark=useCallback2((node)=>{if(node!==null&&problems.length>0){const first=node.querySelector('[aria-invalid="true"]')??node.querySelector("[aria-invalid]");first?.focus()}},[problems]);const submit=(event)=>{event.preventDefault();const answer=inputsOf(fields,draft,values);if("unparsed"in answer){setUnparsed(answer.unparsed);return}setUnparsed([]);onSubmit(answer.inputs)};return jsxs41("form",{className:cn18("grid gap-4",className),"data-slot":"intent-form",noValidate:true,onSubmit:submit,ref:focusFirstMark,children:[formProblems.length>0&&jsx49("ul",{className:"text-destructive grid gap-1 text-sm",children:formProblems.map(({path,reason})=>jsx49("li",{children:reason},`${path}:${reason}`))}),fields.map((field)=>{const fieldProblems=byField.get(field.name)??[];const notJson=unparsed.includes(field.name);const mark=notJson?"invalid":fieldProblems.find(({problem})=>problem==="missing")?.problem??fieldProblems[0]?.problem;const controlId=`${id}-${field.name}`;const descriptionId=`${controlId}-description`;const messageId=`${controlId}-message`;const describedBy=[field.description===undefined?"":descriptionId,mark===undefined?"":messageId].filter(Boolean).join(" ");return jsxs41("div",{className:"grid gap-2","data-problem":mark,"data-slot":"intent-field",children:[jsxs41(Label3,{htmlFor:controlId,children:[field.label,field.required&&jsx49("span",{"aria-hidden":"true",children:"*"})]}),field.description!==undefined&&jsx49("p",{className:"text-muted-foreground text-sm",id:descriptionId,children:field.description}),jsx49(FieldControl,{describedBy:describedBy===""?undefined:describedBy,disabled,field,id:controlId,invalid:mark!==undefined,labels:text,onChange:(value)=>{setDraft((current)=>({...current,[field.name]:value}))},value:draft[field.name]}),mark!==undefined&&jsxs41("div",{className:"text-destructive grid gap-1 text-sm",id:messageId,children:[notJson&&jsx49("p",{children:text.invalidJson}),fieldProblems.map(({path,problem,reason})=>jsxs41("p",{children:[jsx49("span",{className:"font-medium",children:problem==="missing"?text.missing:text.invalid})," ",jsx49("span",{children:reason})]},`${path}:${reason}`))]})]},field.name)}),jsx49(Button20,{className:"justify-self-start",disabled,type:"submit",children:text.submit})]})};var IntentForm=({fqn,...props})=>{const{enabled,list}=useIntents2();const entry=list.data?.find((candidate)=>candidate.fqn===fqn);if(!enabled||entry===undefined){return null}return jsx49(IntentFormFields,{entry,...props})};import{Alert as Alert3,AlertDescription as AlertDescription3,AlertTitle,Button as Button21}from"@collective-intelligence/ui-react/ui";import{useSyncExternalStore as useSyncExternalStore3}from"react";import{jsx as jsx50,jsxs as jsxs42}from"react/jsx-runtime";var intentNoticeLabels={en:{dismiss:"Dismiss",done:"Done",failed:"Failed",region:"Intent results"},it:{dismiss:"Chiudi",done:"Completato",failed:"Non riuscito",region:"Risultati degli Intent"}};var corner={insetBlockEnd:"1rem",insetInlineEnd:"1rem",position:"fixed",zIndex:50};var outcomeText=({outcome},labels)=>outcome.kind==="completed"?labels.done:`${labels.failed}: ${outcome.reason}`;var IntentNotices=({labels:custom,locale="en"})=>{const{registry}=useIntentsScope2();const labels={...intentNoticeLabels[locale],...custom};const notices=useSyncExternalStore3(registry.subscribe,registry.notices,registry.notices);if(notices.length===0){return null}return jsx50("div",{style:corner,children:jsx50(ChatRoot,{className:"size-auto",children:jsx50("section",{"aria-label":labels.region,className:"grid w-80 gap-2",children:notices.map((notice)=>jsxs42(Alert3,{variant:notice.outcome.kind==="failed"?"destructive":"default",children:[jsx50(AlertTitle,{children:notice.displayName}),jsxs42(AlertDescription3,{children:[outcomeText(notice,labels),jsx50(Button21,{onClick:()=>{registry.dismiss(notice.id)},size:"sm",type:"button",variant:"ghost",children:labels.dismiss})]})]},notice.id))})})})};import{cn as cn19}from"@collective-intelligence/ui-react";import{Button as Button22}from"@collective-intelligence/ui-react/ui";import{useId as useId8,useRef as useRef5,useState as useState25}from"react";import{jsx as jsx51,jsxs as jsxs43}from"react/jsx-runtime";var noInputs={};var statusOf2=({error,outcome,state},labels)=>{if(state==="working"){return labels.working}if(error!==undefined){return`${labels.failed}: ${error.message}`}switch(outcome?.kind){case"completed":{return labels.done}case"started":{return labels.dispatched}case"failed":{return`${labels.failed}: ${outcome.reason}`}case"not_allowed":{return labels.notAllowed}default:{return}}};var useListedIntent=(fqn)=>{const{enabled,list}=useIntents2();const displayName=list.data?.find((entry)=>entry.fqn===fqn)?.displayName;return{displayName,enabled}};var LaunchTrigger=({children,className,fqn,inputs=noInputs,labels})=>{const{displayName,enabled}=useListedIntent(fqn);const launch=useLaunch2();const launchable=useHasLaunchTarget2();const reasonId=useId8();if(!enabled){return null}return jsxs43("div",{className:cn19("grid gap-2",className),"data-slot":"intent-trigger",children:[jsx51(Button22,{"aria-describedby":launchable?undefined:reasonId,className:"justify-self-start",disabled:!launchable,onClick:()=>{launch({fqn,inputs,kind:"intent"})},type:"button",children:children??displayName??fqn}),!launchable&&jsx51("p",{className:"text-muted-foreground text-sm",id:reasonId,children:labels?.noChat??defaultIntentLabels.noChat})]})};var DispatchTrigger=(props)=>{const{children,className,fqn,inputs=noInputs,labels,onResult,render}=props;const{displayName,enabled}=useListedIntent(fqn);const intent=useIntentDispatch2(fqn,props);const[sent,setSent]=useState25(inputs);const{registry}=useIntentsScope2();const container=useRef5(null);const delivered=useRef5(undefined);const started=useRef5(undefined);const ends=useRef5(new Map);const deliver=(notice)=>{if(notice!==delivered.current&¬ice.outcome.kind==="completed"){delivered.current=notice;onResult?.(notice.outcome.result)}};useIntentResult2(fqn,(notice)=>{if(notice.handle!==undefined){ends.current.set(notice.handle,notice)}if(notice===registry.adopted(fqn)||notice.handle!==undefined&¬ice.handle===started.current){deliver(notice)}});if(!enabled){return null}const text={...defaultIntentLabels,...labels};const run=async(values)=>{setSent(values);const answer=await intent.dispatch(values);if(!answer.ok){return}if(answer.value.kind==="completed"){onResult?.(answer.value.result)}if(answer.value.kind==="started"){started.current=answer.value.handle;const end=ends.current.get(answer.value.handle);if(end!==undefined){deliver(end)}}};const{outcome,state}=intent;const resultView=outcome?.kind==="completed"&&render!==undefined?render(outcome.result):undefined;const status=resultView===undefined?statusOf2(intent,text):undefined;return jsxs43("div",{className:cn19("grid gap-2 outline-none",className),"data-slot":"intent-trigger","data-state":state,ref:container,tabIndex:-1,children:[outcome?.kind==="needs_input"?jsx51(IntentForm,{fqn,labels:text,onSubmit:(values)=>{container.current?.focus();run(values)},problems:outcome.fields,values:sent}):jsx51(Button22,{"aria-busy":state==="working",className:"justify-self-start",disabled:state==="working",onClick:()=>{run(inputs)},type:"button",children:children??displayName??fqn}),status!==undefined&&jsx51("output",{className:"text-muted-foreground text-sm",children:status}),resultView]})};var IntentTrigger=(props)=>props.resultTarget==="chat"?jsx51(LaunchTrigger,{...props}):jsx51(DispatchTrigger,{...props});import{Button as Button23}from"@collective-intelligence/ui-react/ui";import{useId as useId9}from"react";import{jsx as jsx52,jsxs as jsxs44,Fragment as Fragment14}from"react/jsx-runtime";var ChatLaunchButton=({children,className,labels,locale="en",turn,...options})=>{const launch=useLaunch2();const launchable=useHasLaunchTarget2(options.target);const reasonId=useId9();return jsxs44(Fragment14,{children:[jsx52(Button23,{"aria-describedby":launchable?undefined:reasonId,className,"data-slot":"chat-launch-button",disabled:!launchable,onClick:()=>{launch(turn,options)},type:"button",children}),!launchable&&jsx52("span",{className:"text-muted-foreground text-sm",id:reasonId,children:labels?.noChat??chatLabels[locale].noChat})]})};export{AssistantSidebar,AssistantSidebarLayout,AssistantSidebarToggle,Chat,ChatAgentPicker,ChatAnswerFeedback,ChatBlockedState,ChatCapabilityPickers,ChatComposer,ChatDock,ChatDockHeader,ChatHeader,ChatLaunchButton,ChatPicker,ChatRoot,ChatTranscript,ConversationSidebar,EvidencePart,FilePart,ImageGenerationPart,IntentCard,IntentCardMessagePart,IntentForm,IntentNotices,IntentTrigger,MemoryEvidencePart,QuestionPart,ReadAloudButton,ReasoningPart,RunTrace,SteeringMessagePart,TextPart,ToolPart,chatLabels,chatSubjectHeaderName,chatSubjectHeaderValue,defaultIntentLabels,fillLabel,intentCardLabels,intentNoticeLabels,transcribeRecording};
|
|
2
|
+
import{useIntentsScope2,useIntentResult2,makeChatSessionRuntime,toSessionFailure,callChatSurface,useChatSession2,useCiChat2,ChatSessionProvider2,useIntentDispatch2,useIntents2,useLaunch2,useHasLaunchTarget2,useChatLaunchTarget2,useTrailEntries2}from"./domain-tg4azwc2.js";import{ChatSurfaceApi2}from"./domain-8rwbw2ah.js";import{InvocationId2,AgentId2}from"./domain-5fpd4fte.js";import{ciDataPartSchemas2}from"./domain-50vzrrp9.js";import{ciAskUserToolName2,ciAskUserSchemas2,hasNumberRuntimeKind2,hasNullRuntimeKind2,hasObjectRuntimeKind2,hasStringRuntimeKind2}from"./domain-54qeg701.js";import{AiFailureError2}from"./domain-9wzbv87n.js";import{cn as cn16}from"@collective-intelligence/ui-react";import{ChevronRight as ChevronRight2,History,Trash2 as Trash24}from"@collective-intelligence/ui-react/icons";import{Button as Button17}from"@collective-intelligence/ui-react/ui";import{createContext as createContext2,useContext as useContext2}from"react";import{cn as cn15}from"@collective-intelligence/ui-react";import{Sheet,SheetContent,SheetDescription,SheetHeader,SheetTitle}from"@collective-intelligence/ui-react/ui";import{useId as useId5,useState as useState21}from"react";import{cn}from"@collective-intelligence/ui-react";import{MessageSquare}from"@collective-intelligence/ui-react/icons";import{Button,Empty,EmptyContent,EmptyDescription,EmptyHeader,EmptyMedia,EmptyTitle}from"@collective-intelligence/ui-react/ui";import{jsx,jsxs}from"react/jsx-runtime";var blockedLabels={app_not_available:["appNotAvailable","appNotAvailableDescription"],chat_not_available:["chatNotAvailable","chatNotAvailableDescription"],service_not_available:["serviceNotAvailable","serviceNotAvailableDescription"],sign_in_to_chat:["signInToChat","signInToChatDescription"]};var ChatBlockedState=({blocked,className,labels})=>{const{retry}=useChatSession2();const[title,description]=blockedLabels[blocked.kind];return jsxs(Empty,{className:cn("flex-1",className),"data-kind":blocked.kind,"data-part":"chat-blocked-state",role:"alert",children:[jsxs(EmptyHeader,{children:[jsx(EmptyMedia,{variant:"icon",children:jsx(MessageSquare,{})}),jsx(EmptyTitle,{children:labels[title]}),jsx(EmptyDescription,{children:labels[description]})]}),blocked.kind==="service_not_available"?jsx(EmptyContent,{children:jsx(Button,{onClick:retry,type:"button",variant:"outline",children:labels.retry})}):null]})};import{cn as cn2}from"@collective-intelligence/ui-react";import{PortalContainerProvider}from"@collective-intelligence/ui-react/ui";import{useState}from"react";import{jsx as jsx2}from"react/jsx-runtime";var ChatRoot=({children,className})=>{const[container,setContainer]=useState(null);return jsx2("div",{className:cn2("ci-root size-full",className),"data-ci-root":"",ref:setContainer,children:jsx2(PortalContainerProvider,{container,children})})};import{cn as cn5}from"@collective-intelligence/ui-react";import{PromptInput,PromptInputBody,PromptInputFooter,PromptInputSubmit,PromptInputTextarea,PromptInputTools}from"@collective-intelligence/ui-react/ai-elements";import{useState as useState7}from"react";import{useState as useState4}from"react";import{Bot,Sparkles,Wrench}from"@collective-intelligence/ui-react/icons";import{Badge}from"@collective-intelligence/ui-react/ui";import{IconTile as IconTile2}from"@collective-intelligence/ui-react/ui-extensions";import{useState as useState2,useSyncExternalStore,useTransition}from"react";var offSnapshot={isLoading:false,result:null};var makeReadStore=(read,enabled)=>{let snapshot=enabled?{isLoading:true,result:null}:offSnapshot;let started=false;let latest=0;const listeners=new Set;const publish=(next)=>{snapshot=next;for(const listener of listeners){listener()}};const load=async()=>{latest+=1;const own=latest;if(!snapshot.isLoading){publish({...snapshot,isLoading:true})}const result=await read();if(own===latest){publish({isLoading:false,result})}};return{getSnapshot:()=>snapshot,reload:()=>{if(enabled){load()}},subscribe:(listener)=>{listeners.add(listener);if(enabled&&!started){started=true;load()}return()=>{listeners.delete(listener)}}}};var useChatRead=(operation,enabled=true)=>{const{call}=useChatSession2();const[store]=useState2(()=>makeReadStore(()=>call(operation),enabled));const snapshot=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return{...snapshot,reload:store.reload}};var useChatAction=()=>{const{call}=useChatSession2();const[isPending,startTransition]=useTransition();const[failure,setFailure]=useState2(null);return{failure,isPending,reset:()=>{setFailure(null)},run:(operation,onDone)=>{setFailure(null);startTransition(async()=>{const result=await call(operation);startTransition(()=>{if(result.ok){onDone?.(result.value)}else{setFailure(result.error)}})})}}};var failureText=(failure,labels)=>{if(failure.code==="conflict"&&failure.reason==="intent_turn_busy"){return labels.launchIntoBusyConversation}if(failure.code==="conflict"&&failure.reason==="intent_turn_agent"){return labels.launchIntoAgentConversation}return failure.code==="rate_limited"||failure.code==="unavailable"&&!failure.retryable?failure.message:labels.actionFailed};import{cn as cn3}from"@collective-intelligence/ui-react";import{Check,X}from"@collective-intelligence/ui-react/icons";import{Button as Button2,Command,CommandEmpty,CommandGroup,CommandInput,CommandItem,CommandList,Popover,PopoverContent,PopoverTrigger}from"@collective-intelligence/ui-react/ui";import{IconTile}from"@collective-intelligence/ui-react/ui-extensions";import{useState as useState3}from"react";var en={actionFailed:"This action failed. Try again.",addProjectFiles:"Add files",agent:"Agent",agentConversationNoProjectContext:"This Agent conversation does not receive the project context.",agentRefreshFailed:"Could not refresh the reply.",agentTurnBlocked:"This agent cannot run this message under its current policy.",agentTurnBlockedWithReason:"This agent cannot run this message: {reason}.",agentTurnCancelled:"This request was cancelled.",agentTurnFailed:"The agent could not complete this request.",agentTurnNoReply:"The agent finished without a reply.",agentTurnPaused:"This agent is paused. Your message is queued and will run after it resumes.",agentTurnWorking:"The agent is working on this…",allListedPlaces:"All listed places",appNotAvailable:"App not available",appNotAvailableDescription:"This app cannot use the chat now.",approvalApprove:"Approve",approvalApproving:"Approving…",approvalComment:"Comment (optional)",approvalCommentPlaceholder:"Add a comment",approvalConfirmReject:"Confirm rejection",approvalDecideHint:"Review the approval details and record your decision.",approvalDecision:"{actor} · {decision} · {date}",approvalDecisionApproved:"approved",approvalDecisionRejected:"rejected",approvalDecisions:"Accepted decisions",approvalEligibleDirect:"Eligible through direct assignment",approvalEligibleGroup:"Eligible through group membership",approvalExpires:"Expires {date}",approvalLoadFailed:"The approval details could not load.",approvalModeAll:"All steps",approvalModeAny:"Any step",approvalOutcomeAlreadyApproved:"Already approved",approvalOutcomeAlreadyDecided:"Already decided",approvalOutcomeContinuationFailed:"The run could not continue",approvalOutcomeContinuationInProgress:"The run is continuing",approvalOutcomeReconciliationRequired:"The run needs a check before it continues",approvalOutcomeRecorded:"Decision recorded",approvalReadOnly:"Read only",approvalReadOnlyHint:"Review the recorded approval details.",approvalReject:"Reject",approvalRejectReason:"Reason for rejecting",approvalRejectReasonPlaceholder:"Tell the requester why",approvalResolution:"Resolution: {reason}",approvalStatusApproved:"Approved",approvalStatusCancelled:"Cancelled",approvalStatusExpired:"Expired",approvalStatusPending:"Pending",approvalStatusRejected:"Rejected",approvalStepProgress:"{approved} of {required} approved",approvalSteps:"Approval steps",approvalTitle:"Approval request",artifactCurrent:"Processing {filename}",artifactFailed:"{count} failed",artifactFiles:"Files: {summary}",artifactLeased:"{count} processing",artifactPending:"{count} pending",artifactProcessed:"{count} processed",artifactSkipped:"{count} skipped",assistant:"Assistant",assistantSidebarCollapse:"Collapse",assistantSidebarDelete:"Delete this conversation",assistantSidebarDeleteTitle:"Delete this conversation?",assistantSidebarToggle:"Assistant",attach:"Attach files",attachmentDownload:"Download",attachmentDownloadFile:"Download {name}",attachmentDownloading:"Downloading",attachmentNotAttached:"The file {name} was not attached.",attachmentOversized:"Each file can be 10 MB at most.",attachmentPreview:"Preview {name}",attachmentPreviewDescription:"Preview of the attached image.",attachmentRemove:"Remove {name}",attachmentTooManyFiles:"You can attach 10 files at most to one message.",attachmentUnsupported:"This file type is not supported.",attachmentsNotAttached:"The files were not attached.",cancel:"Cancel",chatNotAvailable:"Chat not available",chatNotAvailableDescription:"Your account cannot use the chat here.",clearAgent:"Clear agent",clearSearch:"Clear search",clearSkills:"Clear selected skills",clearTools:"Clear selected tools",compact:"Compact",compacted:"Compacted",compactedContext:"Compacted context",compactedContextDescription:"The assistant uses this summary for older chat history.",compactionCoveredMessages:"Covered messages",compactionCoveredRuns:"Covered runs",compactionFailed:"The conversation was not compacted. Try again.",compactionMarker:"Older context compacted",compactionMessages:"{count} messages",compactionNotChanged:"The compacted context was not changed. Try again.",compactionRuns:"{count} runs",compactionStatus:"Status",composerDrop:"Drop files to attach them",composerInput:"Message",composerPlaceholder:"Ask anything...",contextUsage:"Context usage",conversationActions:"Manage conversation {title}",conversationNotMoved:"The conversation was not moved. Try again.",conversationTitle:"Conversation title",conversations:"Conversations",conversationsDescription:"Open or manage your conversations.",conversationsNotLoaded:"The conversations were not loaded.",createProject:"Create project",delete:"Delete",deleteConversation:"Delete conversation?",deleteConversationDescription:'This removes "{title}" from your conversations.',deleteProject:"Delete project",deleteProjectDescription:"Its conversations are deleted with it, also those started in other places.",deleteProjectFile:"Delete file {name}",deleteProjectTitle:'Delete project "{name}"?',downloadProjectFile:"Download file {name}",draft:"Draft",earlier:"Earlier",editQueuedMessage:"Edit queued message {content}",emptyDescription:"Ask a question to start a conversation.",emptyTitle:"New chat",evidenceContradiction:"Contradiction: {status}",evidenceEmpty:"No content",evidenceLinks:"Links",evidenceOmitted:"{count} more evidence items were omitted.",evidenceOpen:"Open",evidenceOpenSource:"Open {title}",evidenceOpening:"Checking…",evidenceRelevance:"{percent}% relevant",evidenceShowMore:"Show {count} more",evidenceSources:"Sources",evidenceUnavailable:"This source is not available.",evidenceWarnings:"Warnings",feedbackGroup:"Answer feedback",feedbackNegative:"Rate answer not helpful",feedbackNote:"Note (required)",feedbackNoteDescription:"Tell reviewers what went wrong. A note is required.",feedbackNoteTitle:"Add a note",feedbackPositive:"Rate answer helpful",feedbackSaving:"Saving…",feedbackSubmit:"Submit feedback",fileDownload:"Download {name}",fileOpen:"Open {name}",filePreview:"Preview {name}",filePreviewDescription:"Preview this file or download a copy.",historyFilter:"Conversations to show",imageActualCost:"Actual cost",imageAspectRatio:"Aspect ratio",imageBackground:"Background",imageCost:"Cost",imageCostSource:"Cost source",imageCostUnavailable:"Cost unavailable",imageCount:"Images",imageDeployment:"Deployment",imageDetailsUnavailable:"Image generation details unavailable",imageEstimatedCost:"Estimated cost",imageFormat:"Format",imageModel:"Model",imageModelVersion:"Model version",imageProvider:"Provider",imageProviderConfigured:"Configured provider",imageProviderModel:"Provider model",imageQuality:"Quality",imageReferenceImages:"Reference images",imageResolution:"Resolution",imageStatusAttentionRequired:"Image generation needs attention",imageStatusCancelled:"Image generation cancelled",imageStatusCompleted:"Image generation complete",imageStatusFailed:"Image generation failed",imageStatusPartial:"Some images could not be generated",imageStatusPending:"Image generation pending",imageStatusRunning:"Generating images…",imageTitle:"Image generation",intentApprovalInputs:"Inputs",intentApprovalTitle:"Allow assistant to run the Intent {name}?",intentCardCompleted:"Completed",intentCardEnded:"Result no longer available",intentCardFailed:"Failed",intentCardTitle:"Intent {name}",intentCardWorking:"Working",launchIntoAgentConversation:"This conversation belongs to an Agent. Start a new chat to run this action.",launchIntoBusyConversation:"This conversation is busy. Wait for the answer, then try again.",loading:"Loading...",memoryCreated:"Created",memoryDisabled:"Disabled",memoryMerged:"Merged",memoryNotChanged:"The memory setting was not changed. Try again.",memoryOff:"Memory off",memoryOn:"Memory on",memoryRetrieved:"Retrieved",memorySaved:"{count} saved",memorySelected:"Selected",memorySkipped:"Skipped",memorySuggested:"Suggested",memorySuperseded:"Superseded",memoryTitle:"Memory evidence",memoryUsed:"{count} used",memoryUsedEvent:"Used",moveToProject:"Move to project",multipleSkills:"{count} skills",multipleTools:"{count} tools",newChat:"New chat",newProject:"New project",noAgents:"No agents available.",noChat:"No chat is available",noCompactionSummary:"No active compaction summary is available.",noConversations:"No conversations yet",noConversationsDescription:"Start a new chat to see it listed here.",noProjectFiles:"No files in this project yet",noProjectFilesDescription:"Add a file to give its text to each conversation of this project.",noProjects:"No projects yet",noSearchResults:"No conversations match the search",noSkills:"No skills match.",noTools:"No tools match.",openConversation:"Open conversation {title}",openConversationList:"Open conversations",openProject:"Open project {name}",optionsError:"The list could not load.",permissionAllowAlways:"Allow always",permissionAllowThisConversation:"Allow for this conversation only",permissionDeny:"Do not allow",permissionDescription:"Allow it for this chat, or remember this exact item for later.",permissionRegion:"Permission request for {name}",permissionSkill:"the skill",permissionTitle:"Allow assistant to use {name}?",permissionTool:"the tool",personalAgent:"Personal",pickAgent:"Pick an agent to start a chat.",previousSevenDays:"Previous 7 days",projectActions:"Manage project {name}",projectConversations:"Conversations",projectConversationsToggle:"Show or hide the conversations of {name}",projectDescription:"A project groups the conversations about one subject.",projectFileFailed:"Failed",projectFileFailedHelp:"No text could be read from this file. It is not used.",projectFileInContext:"In context",projectFileNotAdded:"The file was not added. Try again.",projectFileNotDeleted:"The file was not deleted. Try again.",projectFileNotDownloaded:"The file was not downloaded. Try again.",projectFileNotInContext:"Not in context",projectFileNotInContextHelp:"This file does not fit in the {max} characters of file text. It is not used.",projectFileRejectedMalformed:"The file could not be read. It can be damaged.",projectFileRejectedOversized:"The file has more than 10 MB.",projectFileRejectedTooManyFiles:"The project already has 20 files. Delete a file to add another.",projectFileRejectedUnsupported:"This file type is not accepted. Use a docx, pdf, txt or md file.",projectFileTruncated:"Truncated",projectFileTruncatedHelp:"Only the first 12,000 characters of this file are used.",projectFiles:"Project files",projectFilesFull:"This project has 20 files, the most that it can have. Delete a file to add another.",projectFilesHelp:"Each conversation of this project receives the text of these files, except Agent conversations. You can add docx, pdf, txt and md files of 10 MB at most, 20 for each project.",projectFilesNotAdded:"Files not added",projectFilesNotLoaded:"The project files were not loaded.",projectFilesUsage:"File text in context",projectFilesUsageValue:"{used} of {max} characters",projectInstructions:"Project instructions",projectInstructionsHelp:"Each conversation of this project receives these instructions, except Agent conversations. To remove them, save an empty text.",projectInstructionsNotSaved:"The project instructions were not saved. Try again.",projectInstructionsTooLong:"Project instructions can have 8,000 characters at most. Make the text shorter to save it.",projectName:"Project name",projectNameHelp:"Use 1 to 200 characters.",projectNoConversations:"No conversations in this project yet",projectNoConversationsDescription:"Send a message to start the first one.",projectNotDeleted:"The project was not deleted. Try again.",projectNotSaved:"The project was not saved. Try again.",projects:"Projects",projectsNotLoaded:"The projects were not loaded.",questionAnswer:"Answer",questionApprovalCompleted:"Approval resolved",questionApprove:"Approve",questionCancelled:"Cancelled",questionCompleted:"Answer received",questionConfirmHint:"This confirms the current operation only and does not change organization approval status.",questionConfirmTitle:"Direct confirmation",questionContinue:"Continue",questionFailed:"Response failed",questionOtherAnswer:"Other answer",questionOtherOption:"Tell me what to do",questionPreview:"Preview",questionResponding:"Applying…",questionRevise:"Revise",questionReviseLabel:"Tell me what to do differently",questionTextAnswer:"Your answer",questionTextPlaceholder:"Write your answer…",questionTool:"Tool: {name}",queuedMessageNotRemoved:"The queued message was not removed. Try again.",queuedMessages:"Queued messages",readAloud:"Read aloud",readAloudFailed:"The answer was not read aloud. Try again.",readAloudStop:"Stop reading aloud",reasoning:"Reasoning",refreshConversation:"Refresh conversation",regenerate:"Regenerate",removeFromProject:"Remove from project",removeQueuedMessage:"Remove queued message {content}",rename:"Rename",renameConversation:"Rename conversation",renameConversationDescription:"Use a short title that makes this chat easy to find later.",renameProject:"Rename project",reset:"Reset",retry:"Try again",runApprovalNeeded:"Your approval is needed",runCardDetail:"Run {id}",runCardStatus:"Status:",runCardTitle:"Assistant run",runCardTraceLink:"View trace",runInputNeeded:"Your input is needed",runOutputPending:"Finishing the response",runPermissionNeeded:"Your permission is needed",runProcessedCount:"Processed {completed} of {expected}",runProgressLost:"Live progress is not available. Try again to see the latest answer.",runRequestsWaiting:"{count} more requests waiting",runReserved:"Preparing {expected} items",runStatusActive:"Active",runStatusAnswerReceived:"Answer received",runStatusCompleted:"Completed",runStatusFailed:"Failed",runStatusNeedsInput:"Needs your input",runStatusResponseFailed:"Response failed",runStatusStopped:"Stopped",runStatusWaitingForApproval:"Waiting for approval",runTerminal:"Finalizing {completed} processed items",save:"Save",searchAgents:"Search agents...",searchConversations:"Search conversations",searchSkills:"Search skills...",searchTools:"Search tools...",selectAgent:"Select agent",selectSkills:"Select skills",selectTools:"Select tools",selectedSkills:"{count} skills",send:"Send",sendAfterThisAnswer:"Send after this answer",sendFailed:"The message was not sent. Try again.",sendOptions:"More send options",serviceNotAvailable:"Service not available",serviceNotAvailableDescription:"The chat cannot reach the service now. Try again later.",signInToChat:"Sign in to chat",signInToChatDescription:"Sign in to see your conversations and to chat.",skillOwnModeNotice:"A selected skill reads all Organization data in its own mode: every Knowledge schema and document, whatever your access.",skills:"Skills",steeringMessageSent:"Sent while answering",stepAccepted:"Prepared request",stepApproval:"Waiting for approval",stepCommand:"Ran {name}",stepCommandFallback:"command",stepCompacted:"Compacted older context",stepCompacting:"Compacting older context",stepCompactionFailed:"Context compaction failed",stepCompactionReused:"Using compacted context",stepDone:"Done",stepDuration:"{ms} ms",stepFile:"Read {name}",stepFileFallback:"file",stepInput:"Waiting for your input",stepModel:"Queried model",stepPermission:"Waiting for permission",stepRun:"Ran assistant workflow",stepRunFailed:"Assistant run failed",stepSkill:"Skill: {name}",stepSkillFallback:"Skill",stepTool:"Tool: {name}",stepToolFallback:"Tool",stepUpdated:"Assistant step updated",stepsSummary:"Processing steps ({count})",stepsSummaryFailed:"Processing steps ({count}), failed",stop:"Stop",stopFailed:"The answer was not stopped. Try again.",submitting:"Sending",thisPlace:"This place",today:"Today",tools:"Tools",trailChips:"Context Trail",trailEvent:"Event",trailNotice:"The assistant can see the pages you open in this app.",trailPage:"Page",trailRemove:"Remove {chip}",trailSent:"Context Trail of this message",transcriptError:"The conversation could not load.",transcriptErrorDescription:"Something went wrong while loading this conversation. Try again after checking your connection.",unknownPlace:"Unknown place",voiceInput:"Dictate a message",voiceInputFailed:"Voice input did not work. Try again.",voiceInputStop:"Stop and transcribe",voiceInputTimeLimit:"Recording stopped at the time limit.",voiceInputTooLong:"The recording is too long. Record a shorter message.",voiceInputTranscribing:"Transcribing…",working:"Working on it",yesterday:"Yesterday",you:"You"};var it={actionFailed:"Questa azione non è riuscita. Riprova.",addProjectFiles:"Aggiungi file",agent:"Agent",agentConversationNoProjectContext:"Questa conversazione con un agent non riceve il contesto del progetto.",agentRefreshFailed:"Impossibile aggiornare la risposta.",agentTurnBlocked:"Questo agent non può eseguire il messaggio con i criteri attuali.",agentTurnBlockedWithReason:"Questo agent non può eseguire il messaggio: {reason}.",agentTurnCancelled:"Questa richiesta è stata annullata.",agentTurnFailed:"L'agent non è riuscito a completare questa richiesta.",agentTurnNoReply:"L'agent ha terminato senza una risposta.",agentTurnPaused:"Questo agent è in pausa. Il tuo messaggio è in coda e partirà alla ripresa.",agentTurnWorking:"L'agent ci sta lavorando…",allListedPlaces:"Tutti i luoghi elencati",appNotAvailable:"App non disponibile",appNotAvailableDescription:"Questa app non può usare la chat ora.",approvalApprove:"Approva",approvalApproving:"Approvazione in corso…",approvalComment:"Commento (facoltativo)",approvalCommentPlaceholder:"Aggiungi un commento",approvalConfirmReject:"Conferma il rifiuto",approvalDecideHint:"Controlla i dettagli dell'approvazione e registra la tua decisione.",approvalDecision:"{actor} · {decision} · {date}",approvalDecisionApproved:"approvata",approvalDecisionRejected:"rifiutata",approvalDecisions:"Decisioni registrate",approvalEligibleDirect:"Idoneo per assegnazione diretta",approvalEligibleGroup:"Idoneo come membro di un gruppo",approvalExpires:"Scade il {date}",approvalLoadFailed:"Impossibile caricare i dettagli dell'approvazione.",approvalModeAll:"Tutti i passaggi",approvalModeAny:"Un passaggio qualsiasi",approvalOutcomeAlreadyApproved:"Già approvata",approvalOutcomeAlreadyDecided:"Già decisa",approvalOutcomeContinuationFailed:"L'esecuzione non è potuta proseguire",approvalOutcomeContinuationInProgress:"L'esecuzione sta proseguendo",approvalOutcomeReconciliationRequired:"L'esecuzione richiede una verifica prima di proseguire",approvalOutcomeRecorded:"Decisione registrata",approvalReadOnly:"Sola lettura",approvalReadOnlyHint:"Controlla i dettagli registrati dell'approvazione.",approvalReject:"Rifiuta",approvalRejectReason:"Motivo del rifiuto",approvalRejectReasonPlaceholder:"Spiega il motivo a chi ha fatto la richiesta",approvalResolution:"Esito: {reason}",approvalStatusApproved:"Approvata",approvalStatusCancelled:"Annullata",approvalStatusExpired:"Scaduta",approvalStatusPending:"In attesa",approvalStatusRejected:"Rifiutata",approvalStepProgress:"{approved} di {required} approvate",approvalSteps:"Passaggi di approvazione",approvalTitle:"Richiesta di approvazione",artifactCurrent:"Elaborazione di {filename}",artifactFailed:"{count} non riusciti",artifactFiles:"File: {summary}",artifactLeased:"{count} in elaborazione",artifactPending:"{count} in attesa",artifactProcessed:"{count} elaborati",artifactSkipped:"{count} saltati",assistant:"Assistente",assistantSidebarCollapse:"Comprimi",assistantSidebarDelete:"Elimina questa conversazione",assistantSidebarDeleteTitle:"Eliminare questa conversazione?",assistantSidebarToggle:"Assistente",attach:"Allega file",attachmentDownload:"Scarica",attachmentDownloadFile:"Scarica {name}",attachmentDownloading:"Download in corso",attachmentNotAttached:"Il file {name} non è stato allegato.",attachmentOversized:"Ogni file può avere al massimo 10 MB.",attachmentPreview:"Anteprima di {name}",attachmentPreviewDescription:"Anteprima dell'immagine allegata.",attachmentRemove:"Rimuovi {name}",attachmentTooManyFiles:"Puoi allegare al massimo 10 file a un messaggio.",attachmentUnsupported:"Questo tipo di file non è supportato.",attachmentsNotAttached:"I file non sono stati allegati.",cancel:"Annulla",chatNotAvailable:"Chat non disponibile",chatNotAvailableDescription:"Il tuo account non può usare la chat qui.",clearAgent:"Rimuovi agent",clearSearch:"Cancella ricerca",clearSkills:"Rimuovi le skill selezionate",clearTools:"Rimuovi gli strumenti selezionati",compact:"Compatta",compacted:"Compattata",compactedContext:"Contesto compattato",compactedContextDescription:"L'assistente usa questo riepilogo per la cronologia meno recente della chat.",compactionCoveredMessages:"Messaggi inclusi",compactionCoveredRuns:"Esecuzioni incluse",compactionFailed:"La conversazione non è stata compattata. Riprova.",compactionMarker:"Contesto precedente compattato",compactionMessages:"{count} messaggi",compactionNotChanged:"Il contesto compattato non è stato modificato. Riprova.",compactionRuns:"{count} esecuzioni",compactionStatus:"Stato",composerDrop:"Rilascia i file per allegarli",composerInput:"Messaggio",composerPlaceholder:"Chiedi qualsiasi cosa...",contextUsage:"Uso del contesto",conversationActions:"Gestisci la conversazione {title}",conversationNotMoved:"La conversazione non è stata spostata. Riprova.",conversationTitle:"Titolo della conversazione",conversations:"Conversazioni",conversationsDescription:"Apri o gestisci le tue conversazioni.",conversationsNotLoaded:"Le conversazioni non sono state caricate.",createProject:"Crea progetto",delete:"Elimina",deleteConversation:"Eliminare la conversazione?",deleteConversationDescription:'Questa azione rimuove "{title}" dalle tue conversazioni.',deleteProject:"Elimina progetto",deleteProjectDescription:"Le sue conversazioni vengono eliminate insieme al progetto, anche quelle avviate in altri luoghi.",deleteProjectFile:"Elimina il file {name}",deleteProjectTitle:'Eliminare il progetto "{name}"?',downloadProjectFile:"Scarica il file {name}",draft:"Bozza",earlier:"Precedenti",editQueuedMessage:"Modifica il messaggio in coda {content}",emptyDescription:"Fai una domanda per iniziare una conversazione.",emptyTitle:"Nuova chat",evidenceContradiction:"Contraddizione: {status}",evidenceEmpty:"Nessun contenuto",evidenceLinks:"Link",evidenceOmitted:"Altri {count} elementi di evidenza sono stati omessi.",evidenceOpen:"Apri",evidenceOpenSource:"Apri {title}",evidenceOpening:"Verifica in corso…",evidenceRelevance:"Pertinenza {percent}%",evidenceShowMore:"Mostra altri {count}",evidenceSources:"Fonti",evidenceUnavailable:"Questa fonte non è disponibile.",evidenceWarnings:"Avvisi",feedbackGroup:"Valutazione della risposta",feedbackNegative:"Valuta la risposta come non utile",feedbackNote:"Nota (obbligatoria)",feedbackNoteDescription:"Spiega cosa non ha funzionato. La nota è obbligatoria.",feedbackNoteTitle:"Aggiungi una nota",feedbackPositive:"Valuta la risposta come utile",feedbackSaving:"Salvataggio…",feedbackSubmit:"Invia la valutazione",fileDownload:"Scarica {name}",fileOpen:"Apri {name}",filePreview:"Anteprima di {name}",filePreviewDescription:"Visualizza l'anteprima del file o scaricane una copia.",historyFilter:"Conversazioni da mostrare",imageActualCost:"Costo effettivo",imageAspectRatio:"Proporzioni",imageBackground:"Sfondo",imageCost:"Costo",imageCostSource:"Origine del costo",imageCostUnavailable:"Costo non disponibile",imageCount:"Immagini",imageDeployment:"Deployment",imageDetailsUnavailable:"Dettagli della generazione non disponibili",imageEstimatedCost:"Costo stimato",imageFormat:"Formato",imageModel:"Modello",imageModelVersion:"Versione del modello",imageProvider:"Provider",imageProviderConfigured:"Provider configurato",imageProviderModel:"Modello del provider",imageQuality:"Qualità",imageReferenceImages:"Immagini di riferimento",imageResolution:"Risoluzione",imageStatusAttentionRequired:"La generazione delle immagini richiede attenzione",imageStatusCancelled:"Generazione delle immagini annullata",imageStatusCompleted:"Generazione delle immagini completata",imageStatusFailed:"Generazione delle immagini non riuscita",imageStatusPartial:"Alcune immagini non sono state generate",imageStatusPending:"Generazione delle immagini in attesa",imageStatusRunning:"Generazione delle immagini…",imageTitle:"Generazione di immagini",intentApprovalInputs:"Input",intentApprovalTitle:"Consentire all'assistente di eseguire l'Intent {name}?",intentCardCompleted:"Completato",intentCardEnded:"Risultato non più disponibile",intentCardFailed:"Non riuscito",intentCardTitle:"Intent {name}",intentCardWorking:"In corso",launchIntoAgentConversation:"Questa conversazione appartiene a un Agente. Avvia una nuova chat per eseguire questa azione.",launchIntoBusyConversation:"Questa conversazione è occupata. Attendi la risposta, poi riprova.",loading:"Caricamento...",memoryCreated:"Creata",memoryDisabled:"Disattivata",memoryMerged:"Unita",memoryNotChanged:"L'impostazione della memoria non è stata modificata. Riprova.",memoryOff:"Memoria disattivata",memoryOn:"Memoria attiva",memoryRetrieved:"Recuperata",memorySaved:"{count} salvate",memorySelected:"Selezionata",memorySkipped:"Saltata",memorySuggested:"Suggerita",memorySuperseded:"Sostituita",memoryTitle:"Memoria usata",memoryUsed:"{count} usate",memoryUsedEvent:"Usata",moveToProject:"Sposta nel progetto",multipleSkills:"{count} skill",multipleTools:"{count} strumenti",newChat:"Nuova chat",newProject:"Nuovo progetto",noAgents:"Nessun agent disponibile.",noChat:"Nessuna chat disponibile",noCompactionSummary:"Nessun riepilogo di compattazione attivo.",noConversations:"Ancora nessuna conversazione",noConversationsDescription:"Avvia una nuova chat per visualizzarla qui.",noProjectFiles:"Ancora nessun file in questo progetto",noProjectFilesDescription:"Aggiungi un file per fornire il suo testo a ogni conversazione del progetto.",noProjects:"Ancora nessun progetto",noSearchResults:"Nessuna conversazione corrisponde alla ricerca",noSkills:"Nessuna skill corrisponde.",noTools:"Nessuno strumento corrisponde.",openConversation:"Apri la conversazione {title}",openConversationList:"Apri le conversazioni",openProject:"Apri progetto {name}",optionsError:"Impossibile caricare l'elenco.",permissionAllowAlways:"Consenti sempre",permissionAllowThisConversation:"Consenti solo per questa conversazione",permissionDeny:"Non consentire",permissionDescription:"Consentilo per questa chat, o ricorda questo elemento per le prossime volte.",permissionRegion:"Richiesta di autorizzazione per {name}",permissionSkill:"la skill",permissionTitle:"Consentire all'assistente di usare {name}?",permissionTool:"lo strumento",personalAgent:"Personale",pickAgent:"Scegli un agent per iniziare una chat.",previousSevenDays:"Ultimi 7 giorni",projectActions:"Gestisci progetto {name}",projectConversations:"Conversazioni",projectConversationsToggle:"Mostra o nascondi le conversazioni di {name}",projectDescription:"Un progetto raggruppa le conversazioni su un argomento.",projectFileFailed:"Lettura non riuscita",projectFileFailedHelp:"Non è stato possibile leggere il testo di questo file. Non viene usato.",projectFileInContext:"Nel contesto",projectFileNotAdded:"Il file non è stato aggiunto. Riprova.",projectFileNotDeleted:"Il file non è stato eliminato. Riprova.",projectFileNotDownloaded:"Il file non è stato scaricato. Riprova.",projectFileNotInContext:"Fuori dal contesto",projectFileNotInContextHelp:"Questo file non rientra nei {max} caratteri di testo dei file. Non viene usato.",projectFileRejectedMalformed:"Non è stato possibile leggere il file. Potrebbe essere danneggiato.",projectFileRejectedOversized:"Il file supera i 10 MB.",projectFileRejectedTooManyFiles:"Il progetto ha già 20 file. Elimina un file per aggiungerne un altro.",projectFileRejectedUnsupported:"Questo tipo di file non è accettato. Usa un file docx, pdf, txt o md.",projectFileTruncated:"Troncato",projectFileTruncatedHelp:"Vengono usati solo i primi 12.000 caratteri di questo file.",projectFiles:"File del progetto",projectFilesFull:"Questo progetto ha 20 file, il numero massimo. Elimina un file per aggiungerne un altro.",projectFilesHelp:"Ogni conversazione del progetto riceve il testo di questi file, tranne le conversazioni con un agent. Puoi aggiungere file docx, pdf, txt e md di 10 MB al massimo, fino a 20 per progetto.",projectFilesNotAdded:"File non aggiunti",projectFilesNotLoaded:"I file del progetto non sono stati caricati.",projectFilesUsage:"Testo dei file nel contesto",projectFilesUsageValue:"{used} di {max} caratteri",projectInstructions:"Istruzioni del progetto",projectInstructionsHelp:"Ogni conversazione del progetto riceve queste istruzioni, tranne le conversazioni con un agent. Per rimuoverle, salva un testo vuoto.",projectInstructionsNotSaved:"Le istruzioni del progetto non sono state salvate. Riprova.",projectInstructionsTooLong:"Le istruzioni del progetto possono avere al massimo 8.000 caratteri. Accorcia il testo per salvarlo.",projectName:"Nome del progetto",projectNameHelp:"Usa da 1 a 200 caratteri.",projectNoConversations:"Ancora nessuna conversazione in questo progetto",projectNoConversationsDescription:"Invia un messaggio per avviare la prima.",projectNotDeleted:"Il progetto non è stato eliminato. Riprova.",projectNotSaved:"Il progetto non è stato salvato. Riprova.",projects:"Progetti",projectsNotLoaded:"I progetti non sono stati caricati.",questionAnswer:"Rispondi",questionApprovalCompleted:"Approvazione risolta",questionApprove:"Approva",questionCancelled:"Annullata",questionCompleted:"Risposta ricevuta",questionConfirmHint:"Conferma solo l'operazione corrente e non cambia lo stato di approvazione dell'organizzazione.",questionConfirmTitle:"Conferma diretta",questionContinue:"Continua",questionFailed:"Risposta non riuscita",questionOtherAnswer:"Altra risposta",questionOtherOption:"Dimmi cosa fare",questionPreview:"Anteprima",questionResponding:"Applicazione in corso…",questionRevise:"Modifica",questionReviseLabel:"Dimmi cosa fare in modo diverso",questionTextAnswer:"La tua risposta",questionTextPlaceholder:"Scrivi la tua risposta…",questionTool:"Strumento: {name}",queuedMessageNotRemoved:"Il messaggio in coda non è stato rimosso. Riprova.",queuedMessages:"Messaggi in coda",readAloud:"Leggi ad alta voce",readAloudFailed:"Non è stato possibile leggere la risposta ad alta voce. Riprova.",readAloudStop:"Interrompi la lettura",reasoning:"Ragionamento",refreshConversation:"Aggiorna conversazione",regenerate:"Rigenera",removeFromProject:"Rimuovi dal progetto",removeQueuedMessage:"Rimuovi il messaggio in coda {content}",rename:"Rinomina",renameConversation:"Rinomina la conversazione",renameConversationDescription:"Usa un titolo breve, per ritrovare facilmente questa chat.",renameProject:"Rinomina progetto",reset:"Reimposta",retry:"Riprova",runApprovalNeeded:"Serve la tua approvazione",runCardDetail:"Esecuzione {id}",runCardStatus:"Stato:",runCardTitle:"Esecuzione dell'assistente",runCardTraceLink:"Vedi traccia",runInputNeeded:"Serve una tua risposta",runOutputPending:"Completamento della risposta",runPermissionNeeded:"Serve la tua autorizzazione",runProcessedCount:"Elaborati {completed} di {expected}",runProgressLost:"L'avanzamento in tempo reale non è disponibile. Riprova per vedere l'ultima risposta.",runRequestsWaiting:"Altre {count} richieste in attesa",runReserved:"Preparazione di {expected} elementi",runStatusActive:"Attiva",runStatusAnswerReceived:"Risposta ricevuta",runStatusCompleted:"Completata",runStatusFailed:"Non riuscita",runStatusNeedsInput:"Serve una tua risposta",runStatusResponseFailed:"Risposta non riuscita",runStatusStopped:"Interrotta",runStatusWaitingForApproval:"In attesa di approvazione",runTerminal:"Finalizzazione di {completed} elementi elaborati",save:"Salva",searchAgents:"Cerca agent...",searchConversations:"Cerca conversazioni",searchSkills:"Cerca skill...",searchTools:"Cerca strumenti...",selectAgent:"Seleziona agent",selectSkills:"Seleziona skill",selectTools:"Seleziona strumenti",selectedSkills:"{count} skill",send:"Invia",sendAfterThisAnswer:"Invia dopo questa risposta",sendFailed:"Il messaggio non è stato inviato. Riprova.",sendOptions:"Altre opzioni di invio",serviceNotAvailable:"Servizio non disponibile",serviceNotAvailableDescription:"La chat non raggiunge il servizio ora. Riprova più tardi.",signInToChat:"Accedi per chattare",signInToChatDescription:"Accedi per vedere le tue conversazioni e chattare.",skillOwnModeNotice:"Una skill selezionata legge tutti i dati dell’organizzazione nella propria modalità: ogni schema Knowledge e ogni documento, qualunque sia il tuo accesso.",skills:"Skill",steeringMessageSent:"Inviato durante la risposta",stepAccepted:"Richiesta preparata",stepApproval:"In attesa di approvazione",stepCommand:"Eseguito {name}",stepCommandFallback:"comando",stepCompacted:"Contesto precedente compattato",stepCompacting:"Compattazione del contesto precedente",stepCompactionFailed:"Compattazione del contesto non riuscita",stepCompactionReused:"Uso del contesto compattato",stepDone:"Fatto",stepDuration:"{ms} ms",stepFile:"Letto {name}",stepFileFallback:"file",stepInput:"In attesa di una tua risposta",stepModel:"Modello interrogato",stepPermission:"In attesa di autorizzazione",stepRun:"Flusso dell'assistente eseguito",stepRunFailed:"Esecuzione dell'assistente non riuscita",stepSkill:"Skill: {name}",stepSkillFallback:"Skill",stepTool:"Strumento: {name}",stepToolFallback:"Strumento",stepUpdated:"Passaggio dell'assistente aggiornato",stepsSummary:"Passaggi di elaborazione ({count})",stepsSummaryFailed:"Passaggi di elaborazione ({count}), non riuscito",stop:"Interrompi",stopFailed:"La risposta non è stata interrotta. Riprova.",submitting:"Invio in corso",thisPlace:"Questo luogo",today:"Oggi",tools:"Strumenti",trailChips:"Contesto di navigazione",trailEvent:"Evento",trailNotice:"L'assistente può vedere le pagine che apri in questa app.",trailPage:"Pagina",trailRemove:"Rimuovi {chip}",trailSent:"Contesto di navigazione di questo messaggio",transcriptError:"Impossibile caricare la conversazione.",transcriptErrorDescription:"Si è verificato un errore durante il caricamento della conversazione. Controlla la connessione e riprova.",unknownPlace:"Luogo sconosciuto",voiceInput:"Detta un messaggio",voiceInputFailed:"L'input vocale non ha funzionato. Riprova.",voiceInputStop:"Interrompi e trascrivi",voiceInputTimeLimit:"Registrazione interrotta al limite di tempo.",voiceInputTooLong:"La registrazione è troppo lunga. Registra un messaggio più breve.",voiceInputTranscribing:"Trascrizione in corso…",working:"Al lavoro",yesterday:"Ieri",you:"Tu"};var chatLabels={en,it};var labelsOf=(locale,overrides)=>overrides===undefined?chatLabels[locale]:{...chatLabels[locale],...overrides};var fillLabel=(label,values)=>label.replaceAll(/\{(?<name>\w+)\}/gu,(placeholder,name)=>values[name]??placeholder);import{jsx as jsx3,jsxs as jsxs2}from"react/jsx-runtime";var triggerText=(chosen,labels)=>{const[first]=chosen;if(first===undefined){return labels.none}return chosen.length===1?first.name:fillLabel(labels.multiple,{count:String(chosen.length)})};var ChatPicker=({chosen,dataPart,disabled=false,failed,icon,labels,onClear,onToggle,options,single=false})=>{const[open,setOpen]=useState3(false);const chosenIds=new Set(chosen.map(({id})=>id));return jsxs2("div",{className:cn3("flex max-w-48 min-w-0 items-center overflow-hidden rounded-md",chosen.length>0&&"bg-muted"),"data-part":dataPart,children:[jsxs2(Popover,{onOpenChange:setOpen,open,children:[jsxs2(PopoverTrigger,{render:jsx3(Button2,{"aria-label":labels.select,className:"h-8 min-w-0 flex-1 gap-1.5 px-3",disabled,size:"sm",title:chosen.map(({name})=>name).join(", ")||undefined,type:"button",variant:"ghost"}),children:[icon,jsx3("span",{className:"truncate",children:triggerText(chosen,labels)})]}),jsx3(PopoverContent,{align:"start",className:"w-96 p-0",children:jsxs2(Command,{children:[jsx3(CommandInput,{placeholder:labels.search}),jsxs2(CommandList,{children:[jsx3(CommandEmpty,{children:failed?labels.error:labels.empty}),jsx3(CommandGroup,{children:(options??[]).map((option)=>jsxs2(CommandItem,{className:"items-center gap-2.5 px-2 py-2",keywords:[option.name,...option.keywords],onSelect:()=>{onToggle(option);if(single){setOpen(false)}},value:option.id,children:[option.icon??jsx3(IconTile,{initial:option.name,size:"sm"}),jsxs2("span",{className:"min-w-0 flex-1",children:[jsx3("span",{className:"block truncate text-sm font-medium",children:option.name}),option.description===null||option.description.trim()===""?null:jsx3("span",{className:"block truncate text-xs text-muted-foreground",children:option.description})]}),option.end,jsx3(Check,{className:cn3("size-4 shrink-0",chosenIds.has(option.id)?"opacity-100":"opacity-0")})]},option.id))})]})]})})]}),onClear===undefined||chosen.length===0?null:jsx3(Button2,{"aria-label":labels.clear,className:"size-8 shrink-0 rounded-none border-l border-border/70 text-muted-foreground hover:text-foreground",disabled,onClick:onClear,size:"icon",type:"button",variant:"ghost",children:jsx3(X,{className:"size-3.5"})})]})};var capabilityChoice=(capabilities,setCapabilities,kind)=>{const chosen=capabilities.filter((capability)=>capability.kind===kind);const others=capabilities.filter((capability)=>capability.kind!==kind);return{chosen,onClear:()=>{setCapabilities(others)},onToggle:({id,name})=>{setCapabilities(chosen.some((capability)=>capability.id===id)?capabilities.filter((capability)=>capability.id!==id):[...capabilities,{id,kind,name}])}}};import{jsx as jsx4,jsxs as jsxs3,Fragment}from"react/jsx-runtime";var listOf=(read)=>({failed:read.result?.ok===false,items:read.result?.ok===true?read.result.value.data:undefined});var useChatSkills=()=>listOf(useChatRead((client)=>client.chatCatalog.listSkills()));var skillOption=(skill)=>({description:skill.description,id:skill.id,keywords:[skill.slug,`/${skill.slug}`],name:skill.name});var toolOption=(tool)=>({description:tool.description,id:tool.id,keywords:[tool.fqn],name:tool.displayName});var pickerLabels=(labels,kind)=>kind==="skill"?{clear:labels.clearSkills,empty:labels.noSkills,error:labels.optionsError,multiple:labels.multipleSkills,none:labels.skills,search:labels.searchSkills,select:labels.selectSkills}:{clear:labels.clearTools,empty:labels.noTools,error:labels.optionsError,multiple:labels.multipleTools,none:labels.tools,search:labels.searchTools,select:labels.selectTools};var ToolPicker=({capabilities,disabled,labels,setCapabilities})=>{const tools=listOf(useChatRead((client)=>client.chatCatalog.listTools({query:{usageScope:"chat"}})));return jsx4(ChatPicker,{...capabilityChoice(capabilities,setCapabilities,"tool"),dataPart:"tool-picker",disabled,failed:tools.failed,icon:jsx4(Wrench,{className:"size-3.5"}),labels:pickerLabels(labels,"tool"),options:tools.items?.map(toolOption)})};var ChatCapabilityPickers=({capabilities,disabled,labels,setCapabilities,skills})=>jsxs3(Fragment,{children:[jsx4(ChatPicker,{...capabilityChoice(capabilities,setCapabilities,"skill"),dataPart:"skill-picker",disabled,failed:skills.failed,icon:jsx4(Sparkles,{className:"size-3.5"}),labels:pickerLabels(labels,"skill"),options:skills.items?.map(skillOption)}),jsx4(ToolPicker,{capabilities,disabled,labels,setCapabilities})]});var ChatAgentPicker=({agentId,clearable,disabled,labels,onChange})=>{const agents=listOf(useChatRead((client)=>client.chatCatalog.listAgents()));const picked=agents.items?.find(({id})=>id===agentId);return jsx4(ChatPicker,{chosen:agentId===null?[]:[{id:agentId,name:picked?.displayName??labels.agent}],dataPart:"agent-picker",disabled,failed:agents.failed,icon:jsx4(Bot,{className:"size-3.5 shrink-0"}),labels:{clear:labels.clearAgent,empty:labels.noAgents,error:labels.optionsError,multiple:labels.agent,none:labels.agent,search:labels.searchAgents,select:labels.selectAgent},onClear:clearable?()=>{onChange(null)}:undefined,onToggle:({id})=>{const agent=agents.items?.find((item)=>item.id===id);if(agent!==undefined){onChange(agent.id)}},options:agents.items?.map((agent)=>({description:agent.responsibility,...agent.agentType==="personal"&&{end:jsx4(Badge,{className:"text-muted-foreground",variant:"outline",children:labels.personalAgent})},icon:jsx4(IconTile2,{size:"sm",tone:"accent",children:jsx4(Bot,{})}),id:agent.id,keywords:[agent.displayName,agent.responsibility],name:agent.displayName})),single:true})};var skillSources=["datasets","documents","knowledge"];var picksOwnModeSkill=(skills,capabilities)=>skills.some(({dataAccess,id})=>capabilities.some((capability)=>capability.kind==="skill"&&capability.id===id)&&skillSources.some((source)=>dataAccess?.[source]!=="user"));import{Button as Button3}from"@collective-intelligence/ui-react/ui";import{IconTile as IconTile3}from"@collective-intelligence/ui-react/ui-extensions";import{jsx as jsx5,jsxs as jsxs4}from"react/jsx-runtime";var maxSuggestions=5;var slashWord=/(?:^|\s)\/(?<word>[a-z0-9_-]*)$/iu;var slashMatches=(draft,skills,capabilities)=>{const word=slashWord.exec(draft)?.groups?.word?.toLowerCase();if(word===undefined){return[]}return skills.filter(({id})=>!capabilities.some((capability)=>capability.id===id)).filter(({name,slug})=>slug.toLowerCase().startsWith(word)||name.toLowerCase().includes(word)).slice(0,maxSuggestions)};var withoutSlashWord=(draft)=>draft.replace(slashWord,"").trimStart();var choosingKeys=new Set(["Enter","Tab"," "]);var useSlashSkills=(session,skills,enabled)=>{const matches=enabled?slashMatches(session.draft,skills,session.capabilities):[];const handleChoose=({id,name})=>{session.setCapabilities([...session.capabilities,{id,kind:"skill",name}]);session.setDraft(withoutSlashWord(session.draft))};const handleKeyDown=(event)=>{const[first]=matches;if(first!==undefined&&choosingKeys.has(event.key)){event.preventDefault();handleChoose(first)}};return{handleChoose,handleKeyDown,matches}};var SlashSuggestions=({matches,onChoose})=>matches.length===0?null:jsx5("div",{className:"flex w-[min(400px,100%)] flex-col overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md","data-part":"slash-suggestions",children:matches.map((skill)=>jsxs4(Button3,{className:"h-auto justify-start gap-2.5 px-2 py-1.5 text-left",onClick:()=>{onChoose(skill)},type:"button",variant:"ghost",children:[jsx5(IconTile3,{initial:skill.name,size:"sm"}),jsxs4("span",{className:"min-w-0 flex-1",children:[jsx5("span",{className:"block truncate font-medium",children:skill.name}),skill.description===null||skill.description.trim()===""?null:jsx5("span",{className:"block truncate text-xs font-normal text-muted-foreground",children:skill.description})]}),jsxs4("span",{className:"shrink-0 text-xs font-normal text-muted-foreground",children:["/",skill.slug]})]},skill.id))});import{jsx as jsx6,jsxs as jsxs5,Fragment as Fragment2}from"react/jsx-runtime";var modelAnswers=({conversationId,conversations},agentChoice,pickedAgentId)=>conversationId===null?agentChoice==="optional"&&pickedAgentId===null:conversations.some(({agentId,id})=>id===conversationId&&agentId===null);var useComposerPicks=({agentChoice,composerParts,disabled,labels,onAgentPicked,running,session})=>{const[agentId,setAgentId]=useState4(null);const skills=useChatSkills();const newChat=session.conversationId===null;const takesCapabilities=modelAnswers(session,agentChoice,agentId);const slash=useSlashSkills(session,skills.items??[],takesCapabilities);const AgentPicker=composerParts?.AgentPicker??ChatAgentPicker;const CapabilityPickers=composerParts?.CapabilityPickers??ChatCapabilityPickers;const pickAgent=(next)=>{setAgentId(next);session.setCapabilities([]);onAgentPicked()};const ownModeSkill=takesCapabilities&&picksOwnModeSkill(skills.items??[],session.capabilities);return{agentId:newChat?agentId:null,handleKeyDown:slash.handleKeyDown,notice:ownModeSkill?jsx6("output",{className:"block text-sm text-muted-foreground","data-part":"own-mode-notice",children:labels.skillOwnModeNotice}):null,pickers:jsxs5(Fragment2,{children:[takesCapabilities?jsx6(CapabilityPickers,{capabilities:session.capabilities,disabled,labels,setCapabilities:session.setCapabilities,skills}):null,newChat&&agentChoice!=="pinned"?jsx6(AgentPicker,{agentId,clearable:agentChoice==="optional",disabled:disabled||running,labels,onChange:pickAgent}):null]}),suggestions:jsx6(SlashSuggestions,{matches:slash.matches,onChoose:slash.handleChoose}),takesCapabilities}};import{X as X2}from"@collective-intelligence/ui-react/icons";import{Badge as Badge2}from"@collective-intelligence/ui-react/ui";import{jsx as jsx7,jsxs as jsxs6}from"react/jsx-runtime";var chipText=(entry,labels)=>{if("event"in entry){return`${labels.trailEvent}: ${entry.event}`}if("source"in entry){const{"@type":type,name}=entry.data;return hasStringRuntimeKind2(name)?`${type}: ${name}`:type}return`${labels.trailPage}: ${entry.title}`};var entryKeys=new WeakMap;var lastKey=0;var keyOf=(entry)=>{const known=entryKeys.get(entry);if(known!==undefined){return known}lastKey+=1;entryKeys.set(entry,lastKey);return lastKey};var TrailChips=({entries,labels,onRemove,region})=>{if(entries.length===0){return null}return jsx7("ul",{"aria-label":region,className:"flex flex-wrap gap-1.5","data-part":"trail-chips",children:entries.map((entry)=>{const text=chipText(entry,labels);return jsx7("li",{children:jsxs6(Badge2,{variant:"outline",children:[text,onRemove===undefined?null:jsx7("button",{"aria-label":fillLabel(labels.trailRemove,{chip:text}),className:"rounded-sm text-muted-foreground hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",onClick:()=>{onRemove(entry)},type:"button",children:jsx7(X2,{className:"size-3.5"})})]})},keyOf(entry))})})};import{jsx as jsx8}from"react/jsx-runtime";var useTrailSwitches=()=>{const{placeContext}=useChatSession2();return{enabled:placeContext?.contextTrailEnabled===true,visible:placeContext?.contextTrailVisible===true}};var ComposerTrailChips=({labels})=>{const{enabled,visible}=useTrailSwitches();const{trail}=useChatSession2().controls;const entries=useTrailEntries2(trail);if(!enabled||!visible||trail===undefined){return null}return jsx8(TrailChips,{entries,labels,onRemove:(entry)=>{trail.remove(entry)},region:labels.trailChips})};var ComposerTrailNotice=({labels})=>{const{enabled,visible}=useTrailSwitches();if(!enabled||visible){return null}return jsx8("p",{className:"text-xs text-muted-foreground","data-part":"trail-notice",children:labels.trailNotice})};import{Attachment,AttachmentInfo,AttachmentPreview,AttachmentRemove,Attachments,PromptInputButton,PromptInputHeader,usePromptInputAttachments}from"@collective-intelligence/ui-react/ai-elements";import{Paperclip}from"@collective-intelligence/ui-react/icons";import{jsx as jsx9,jsxs as jsxs7}from"react/jsx-runtime";var maxDraftFiles=10;var maxDraftFileBytes=10*1024*1024;var rejectionText=(rejection,takesFiles,labels)=>{if(!takesFiles){return labels.attachmentsNotAttached}const reasons={accept:labels.attachmentUnsupported,max_file_size:labels.attachmentOversized,max_files:labels.attachmentTooManyFiles};return`${labels.attachmentsNotAttached} ${reasons[rejection]}`};var useDraftFileTypes=()=>{const capabilities=useChatRead((client)=>client.chatCatalog.getAttachmentCapabilities());return capabilities.result?.ok===true?capabilities.result.value.fileTypes.flatMap(({extension,mediaTypes})=>[extension,...mediaTypes]).join(","):undefined};var bytesOf=(dataUrl)=>{const comma=dataUrl.indexOf(",");const payload=dataUrl.slice(comma+1);if(!dataUrl.slice(0,comma).endsWith(";base64")){return new TextEncoder().encode(decodeURIComponent(payload))}const binary=atob(payload);return Uint8Array.from(binary,(char)=>char.codePointAt(0)??0)};var filesOf=(parts)=>parts.map(({filename,mediaType,url})=>new File([bytesOf(url)],filename??"file",{type:mediaType}));var AttachButton=({labels})=>{const attachments=usePromptInputAttachments();return jsx9(PromptInputButton,{"aria-label":labels.attach,"data-part":"attach",onClick:()=>{attachments.openFileDialog()},children:jsx9(Paperclip,{})})};var DraftAttachments=({labels})=>{const attachments=usePromptInputAttachments();if(attachments.files.length===0){return null}return jsx9(PromptInputHeader,{"data-part":"draft-attachments",children:jsx9(Attachments,{variant:"inline",children:attachments.files.map((file)=>jsxs7(Attachment,{data:file,onRemove:()=>{attachments.remove(file.id)},children:[jsx9(AttachmentPreview,{}),jsx9(AttachmentInfo,{}),jsx9(AttachmentRemove,{label:fillLabel(labels.attachmentRemove,{name:file.filename??""})})]},file.id))})})};import{Pencil,X as X3}from"@collective-intelligence/ui-react/icons";import{Button as Button4,Input}from"@collective-intelligence/ui-react/ui";import{useId,useState as useState5}from"react";import{jsx as jsx10,jsxs as jsxs8,Fragment as Fragment3}from"react/jsx-runtime";var QueuedMessageEdit=({labels,message,onDone})=>{const session=useChatSession2();const[content,setContent]=useState5(message.content);const label=fillLabel(labels.editQueuedMessage,{content:message.content});return jsxs8("form",{className:"flex min-w-0 flex-1 items-center gap-1",onSubmit:(event)=>{event.preventDefault();session.updateQueuedMessage(message.id,content.trim(),message.revision);onDone()},children:[jsx10(Input,{"aria-label":label,autoFocus:true,className:"h-7 min-w-0 flex-1",onChange:(event)=>{setContent(event.target.value)},value:content}),jsx10(Button4,{disabled:content.trim()==="",size:"sm",type:"submit",children:labels.save}),jsx10(Button4,{onClick:onDone,size:"sm",type:"button",variant:"ghost",children:labels.cancel})]})};var QueuedMessages=({labels})=>{const session=useChatSession2();const headingId=useId();const[editing,setEditing]=useState5(null);const waiting=session.queuedMessages.filter(({status})=>status==="waiting");if(waiting.length===0){return null}return jsxs8("section",{className:"rounded-none border border-border bg-muted/30 px-3 py-2","data-part":"queued-messages",children:[jsx10("h3",{className:"text-xs font-medium text-muted-foreground",id:headingId,children:labels.queuedMessages}),jsx10("ul",{"aria-labelledby":headingId,className:"mt-1 flex flex-col gap-1",children:waiting.map((message)=>jsx10("li",{className:"flex min-w-0 items-center gap-1",children:editing===message.id?jsx10(QueuedMessageEdit,{labels,message,onDone:()=>{setEditing(null)}}):jsxs8(Fragment3,{children:[jsx10("p",{className:"min-w-0 flex-1 truncate text-sm text-foreground",children:message.content}),jsx10(Button4,{"aria-label":fillLabel(labels.editQueuedMessage,{content:message.content}),onClick:()=>{setEditing(message.id)},size:"icon-sm",type:"button",variant:"ghost",children:jsx10(Pencil,{})}),jsx10(Button4,{"aria-label":fillLabel(labels.removeQueuedMessage,{content:message.content}),onClick:()=>{session.removeQueuedMessage(message.id,message.revision)},size:"icon-sm",type:"button",variant:"ghost",children:jsx10(X3,{})})]})},message.id))})]})};import{PromptInputActionMenu,PromptInputActionMenuContent,PromptInputActionMenuItem,PromptInputActionMenuTrigger}from"@collective-intelligence/ui-react/ai-elements";import{ChevronDown}from"@collective-intelligence/ui-react/icons";import{DropdownMenuGroup}from"@collective-intelligence/ui-react/ui";import{jsx as jsx11,jsxs as jsxs9}from"react/jsx-runtime";var SendMenu=({disabled,labels,onQueue})=>jsxs9(PromptInputActionMenu,{children:[jsx11(PromptInputActionMenuTrigger,{"aria-label":labels.sendOptions,"data-part":"send-options",children:jsx11(ChevronDown,{})}),jsx11(PromptInputActionMenuContent,{align:"end",children:jsx11(DropdownMenuGroup,{children:jsx11(PromptInputActionMenuItem,{disabled,onClick:onQueue,children:labels.sendAfterThisAnswer})})})]});import{cn as cn4}from"@collective-intelligence/ui-react";import{PromptInputButton as PromptInputButton2}from"@collective-intelligence/ui-react/ai-elements";import{Loader2,Mic}from"@collective-intelligence/ui-react/icons";var noMicrophone={code:"forbidden",message:"The microphone is not available.",retryable:false};var recorderFailed={code:"unavailable",message:"The recording could not start.",retryable:true};var preferredTypes=["audio/webm;codecs=opus","audio/webm","audio/mp4"];var chunksOf=(recorder)=>new ReadableStream({start:(controller)=>{recorder.addEventListener("dataavailable",(event)=>{if(event.data.size>0){controller.enqueue(event.data)}});recorder.addEventListener("stop",()=>{controller.close()},{once:true})}});var readAll=async(reader,chunks=[])=>{const{done,value}=await reader.read();return done?chunks:await readAll(reader,[...chunks,value])};var captureMicrophone=async()=>{if(!("mediaDevices"in navigator)||!("MediaRecorder"in globalThis)){return{error:noMicrophone,ok:false}}let stream;try{stream=await navigator.mediaDevices.getUserMedia({audio:true})}catch{return{error:noMicrophone,ok:false}}const release=()=>{for(const track of stream.getTracks()){track.stop()}};try{const mimeType=preferredTypes.find((type)=>MediaRecorder.isTypeSupported(type));const recorder=new MediaRecorder(stream,mimeType===undefined?{}:{mimeType});const chunks=chunksOf(recorder).getReader();recorder.start();return{ok:true,value:{cancel:()=>{recorder.stop();release()},stop:async()=>{recorder.stop();const audio=await readAll(chunks);release();return new Blob([...audio],{type:recorder.mimeType})}}}}catch{release();return{error:recorderFailed,ok:false}}};var uploadFailed={code:"unavailable",message:"The voice clip could not be uploaded.",retryable:true};var fallbackContentType="audio/webm";var maxClipBytes=25*1024*1024;var clipTooLarge={code:"invalid_request",message:"The voice clip is larger than 25 MiB.",retryable:false};var putClip=async(audio,{headers,method,url})=>{try{const upload=await fetch(url,{body:audio,headers,method});return upload.ok}catch{return false}};var transcribeRecording=async(call,audio)=>{if(audio.size>maxClipBytes){return{error:clipTooLarge,ok:false}}const clip=await call((client)=>client.chatSpeech.createSpeechClip({payload:{contentType:audio.type===""?fallbackContentType:audio.type,size:audio.size}}));if(!clip.ok){return clip}if(!await putClip(audio,clip.value)){return{error:uploadFailed,ok:false}}const transcription=await call((client)=>client.chatSpeech.transcribeSpeechClip({payload:{clipId:clip.value.clipId}}));return transcription.ok?{ok:true,value:transcription.value.text}:transcription};import{useEffect,useRef,useState as useState6}from"react";var maxRecordingMs=30000;var idle={status:"idle",stoppedAtLimit:false};var withDictation=(draft,text)=>{const dictated=text.trim();const kept=draft.trimEnd();if(dictated.length===0){return draft}return kept.length===0?dictated:`${kept}
|
|
3
|
+
${dictated}`};var useVoiceInput=(port,draft)=>{const[state,setState]=useState6(idle);const recording=useRef(null);const timeLimit=useRef(undefined);const mounted=useRef(false);const latestDraft=useRef(draft);useEffect(()=>{latestDraft.current=draft});useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;globalThis.clearTimeout(timeLimit.current);recording.current?.cancel()}},[]);const finish=async(current,stoppedAtLimit)=>{if(recording.current!==current){return}globalThis.clearTimeout(timeLimit.current);recording.current=null;setState({status:"transcribing",stoppedAtLimit});try{const text=await current.finish();if(!text.ok){setState({status:"failed",tooLong:text.error.code==="invalid_request"});return}const{setValue,value}=latestDraft.current;setValue(withDictation(value,text.value));setState({status:"idle",stoppedAtLimit})}catch{setState({status:"failed",tooLong:false})}};const start=async()=>{setState({status:"starting"});try{const started=await port.record();if(!mounted.current){if(started.ok){started.value.cancel()}return}if(!started.ok){setState({status:"failed",tooLong:false});return}recording.current=started.value;timeLimit.current=globalThis.setTimeout(()=>{finish(started.value,true)},maxRecordingMs);setState({status:"recording"})}catch{setState({status:"failed",tooLong:false})}};const toggle=()=>{const{current}=recording;current===null?start():finish(current,false)};return{state,toggle}};import{jsx as jsx12,jsxs as jsxs10,Fragment as Fragment4}from"react/jsx-runtime";var buttonLabel=({status},labels)=>{if(status==="recording"){return labels.voiceInputStop}return status==="transcribing"?labels.voiceInputTranscribing:labels.voiceInput};var noticeOf=(state,labels)=>{if(state.status==="failed"){return state.tooLong?labels.voiceInputTooLong:labels.voiceInputFailed}return(state.status==="idle"||state.status==="transcribing")&&state.stoppedAtLimit?labels.voiceInputTimeLimit:undefined};var ButtonIcon=({status})=>status==="starting"||status==="transcribing"?jsx12(Loader2,{className:"animate-spin"}):jsx12(Mic,{className:cn4(status==="recording"&&"animate-pulse text-destructive")});var useRemoteSpeechInput=()=>{const{call}=useChatSession2();return{record:async()=>{const capture=await captureMicrophone();if(!capture.ok){return capture}const{cancel,stop}=capture.value;return{ok:true,value:{cancel,finish:async()=>await transcribeRecording(call,await stop())}}}}};var VoiceButton=({draft,labels})=>{const port=useRemoteSpeechInput();const{state,toggle}=useVoiceInput(port,draft);const notice=noticeOf(state,labels);return jsxs10(Fragment4,{children:[jsx12(PromptInputButton2,{"aria-label":buttonLabel(state,labels),"aria-pressed":state.status==="recording",className:cn4(state.status==="failed"&&"text-destructive"),"data-part":"voice-input",disabled:draft.disabled||state.status==="starting"||state.status==="transcribing",onClick:toggle,title:notice,children:jsx12(ButtonIcon,{...state})}),jsx12("output",{"aria-live":"polite",className:"sr-only",children:notice??""})]})};var ChatVoiceInput=({draft,labels})=>{const{controls}=useChatSession2();const availability=useChatRead((client)=>client.chatSpeech.getSpeechAvailability(),controls.voiceInput===undefined);const available=availability.result?.ok===true&&availability.result.value.remoteTranscription;return available?jsx12(VoiceButton,{draft,labels}):null};import{jsx as jsx13,jsxs as jsxs11,Fragment as Fragment5}from"react/jsx-runtime";var accessoryFor=(slot,draft)=>typeof slot==="function"?slot(draft):slot;var ChatComposer=({agentChoice,className,composerParts,labels,send,slots})=>{const session=useChatSession2();const[refusal,setRefusal]=useState7(null);const[rejection,setRejection]=useState7(null);const disabled=session.status!=="ready";const cannotSend=disabled||session.busy||session.draft.trim()==="";const running=session.sendMode==="running";const picks=useComposerPicks({agentChoice,composerParts,disabled,labels,onAgentPicked:()=>{setRefusal(null)},running,session});const canAttach=!disabled&&!running&&picks.takesCapabilities;const accept=useDraftFileTypes();const draft={disabled,setValue:session.setDraft,value:session.draft};const notices=[refusal?.message,rejection===null?undefined:rejectionText(rejection,canAttach,labels)].filter((notice)=>notice!==undefined);return jsxs11("div",{className:cn5("mx-auto flex w-full max-w-[900px] flex-col gap-2 px-6 pb-6",className),"data-part":"chat-composer",children:[notices.map((notice)=>jsx13("p",{className:"text-sm text-destructive",role:"alert",children:notice},notice)),picks.notice,jsx13(QueuedMessages,{labels}),jsx13(ComposerTrailChips,{labels}),picks.suggestions,jsxs11(PromptInput,{...accept!==undefined&&{accept},maxFileSize:maxDraftFileBytes,maxFiles:canAttach?maxDraftFiles:0,multiple:true,onError:({code})=>{setRejection(code)},onSubmit:({files,text})=>{if(disabled||session.busy||text.trim()===""){return}const sent=send({text,...picks.agentId!==null&&{agentId:picks.agentId},...files.length>0&&{files:filesOf(files)}});setRefusal(sent.ok?null:sent.error);setRejection(null)},children:[jsx13(DraftAttachments,{labels}),jsx13(PromptInputBody,{children:jsx13(PromptInputTextarea,{"aria-label":labels.composerInput,disabled,onChange:(event)=>{session.setDraft(event.target.value)},onKeyDown:picks.handleKeyDown,placeholder:labels.composerPlaceholder,value:session.draft})}),jsxs11(PromptInputFooter,{children:[jsxs11(PromptInputTools,{children:[canAttach?jsx13(AttachButton,{labels}):null,jsx13(ChatVoiceInput,{draft,labels}),slots.composerAccessory===undefined?null:accessoryFor(slots.composerAccessory,draft),picks.pickers]}),jsxs11(PromptInputTools,{children:[running?jsxs11(Fragment5,{children:[jsx13(SendMenu,{disabled:cannotSend,labels,onQueue:()=>{session.queue(session.draft.trim())}}),jsx13(PromptInputSubmit,{"aria-label":labels.stop,"data-part":"stop",onStop:()=>{session.stop()},status:"streaming",variant:"outline"})]}):null,jsx13(PromptInputSubmit,{"aria-label":labels.send,"data-part":"send",disabled:cannotSend})]})]})]}),jsx13(ComposerTrailNotice,{labels})]})};import{cn as cn7}from"@collective-intelligence/ui-react";import{Bot as Bot2,PanelLeftIcon,RefreshCw as RefreshCw2}from"@collective-intelligence/ui-react/icons";import{Badge as Badge3,Button as Button7}from"@collective-intelligence/ui-react/ui";import{RefreshCw,RotateCcw}from"@collective-intelligence/ui-react/icons";import{Button as Button5,Dialog,DialogBody,DialogContent,DialogDescription,DialogFooter,DialogHeader,DialogTitle,Spinner}from"@collective-intelligence/ui-react/ui";import{useState as useState8}from"react";import{jsx as jsx14,jsxs as jsxs12,Fragment as Fragment6}from"react/jsx-runtime";var Meta=({label,value})=>value===undefined||value===""?null:jsxs12("div",{children:[jsx14("dt",{className:"text-xs text-muted-foreground uppercase",children:label}),jsx14("dd",{className:"font-medium text-foreground",children:value})]});var CompactionControls=({conversationId,labels,write})=>{const params={conversationId};const read=useChatRead((client)=>client.chat.getCompaction({params}));const[isSummaryOpen,setIsSummaryOpen]=useState8(false);if(read.result?.ok!==true){return null}const{compaction}=read.result.value;const summary=compaction.activeSummary;const operate=(operation,onDone)=>{write.run((client)=>{switch(operation){case"compact":{return client.chat.compact({params})}case"regenerateCompaction":{return client.chat.regenerateCompaction({params})}default:{return client.chat.resetCompaction({params})}}},()=>{read.reload();onDone?.()})};if(!compaction.active){return jsx14(Button5,{disabled:write.isPending,onClick:()=>{operate("compact")},type:"button",variant:"outline",children:labels.compact})}return jsxs12(Fragment6,{children:[jsx14(Button5,{onClick:()=>{setIsSummaryOpen(true)},type:"button",variant:"outline",children:labels.compacted}),jsx14(Dialog,{onOpenChange:setIsSummaryOpen,open:isSummaryOpen,children:jsxs12(DialogContent,{size:"lg",children:[jsxs12(DialogHeader,{children:[jsx14(DialogTitle,{children:labels.compactedContext}),jsx14(DialogDescription,{children:labels.compactedContextDescription})]}),jsx14(DialogBody,{children:summary===null?jsx14("p",{className:"text-sm text-muted-foreground",children:labels.noCompactionSummary}):jsxs12("div",{className:"flex flex-col gap-4",children:[jsx14("div",{className:"rounded-md border border-border bg-muted p-4 text-sm leading-6 whitespace-pre-wrap text-foreground",children:summary.summary}),jsxs12("dl",{className:"grid gap-2 text-sm text-muted-foreground sm:grid-cols-2",children:[jsx14(Meta,{label:labels.compactionCoveredMessages,value:compaction.boundary?.coveredMessageCount}),jsx14(Meta,{label:labels.compactionCoveredRuns,value:compaction.boundary?.coveredInvocationCount}),jsx14(Meta,{label:labels.compactionStatus,value:summary.status})]})]})}),jsxs12(DialogFooter,{children:[jsxs12(Button5,{disabled:summary===null||write.isPending,onClick:()=>{operate("regenerateCompaction")},type:"button",variant:"outline",children:[write.isPending?jsx14(Spinner,{"data-icon":"inline-start"}):jsx14(RefreshCw,{"data-icon":"inline-start"}),labels.regenerate]}),jsxs12(Button5,{disabled:summary===null||write.isPending,onClick:()=>{operate("resetCompaction",()=>{setIsSummaryOpen(false)})},type:"button",variant:"secondary",children:[jsx14(RotateCcw,{"data-icon":"inline-start"}),labels.reset]})]})]})})]})};import{cn as cn6}from"@collective-intelligence/ui-react";import{Button as Button6}from"@collective-intelligence/ui-react/ui";import{jsx as jsx15,jsxs as jsxs13}from"react/jsx-runtime";var MemorySwitch=({conversation,labels,write})=>{const session=useChatSession2();const{memoryEnabled}=conversation;return jsxs13(Button6,{"aria-pressed":memoryEnabled,disabled:write.isPending,onClick:()=>{write.run((client)=>client.chat.updateConversation({params:{conversationId:conversation.id},payload:{memoryEnabled:!memoryEnabled}}),session.reloadConversations)},type:"button",variant:memoryEnabled?"outline":"secondary",children:[jsx15("span",{"aria-hidden":"true",className:cn6("size-2 rounded-full",memoryEnabled?"bg-primary":"bg-muted-foreground"),"data-icon":"inline-start"}),memoryEnabled?labels.memoryOn:labels.memoryOff]})};import{jsx as jsx16,jsxs as jsxs14}from"react/jsx-runtime";var AgentBadge=({agentId,labels})=>{const read=useChatRead((client)=>client.chatCatalog.listAgents());const agent=read.result?.ok===true?read.result.value.data.find(({id})=>id===agentId):undefined;return jsxs14(Badge3,{"data-part":"chat-header-agent",variant:"secondary",children:[jsx16(Bot2,{"data-icon":"inline-start"}),agent?.displayName??labels.agent]})};var headerNotices=({compaction,isAgentInProject,labels,memory})=>[isAgentInProject&&{alert:false,text:labels.agentConversationNoProjectContext},memory.failure!==null&&{alert:true,text:labels.memoryNotChanged},compaction.failure!==null&&{alert:true,text:labels.compactionFailed}].filter((notice)=>notice!==false);var ChatHeader=({className,labels,openConversations,slots})=>{const session=useChatSession2();const memory=useChatAction();const compaction=useChatAction();const{conversationId}=session;const listed=session.conversations.find(({id})=>id===conversationId);const agentId=listed?.agentId??null;const title=conversationId===null?labels.newChat:listed?.title??"";const notices=headerNotices({compaction,isAgentInProject:session.controls.projects&&agentId!==null&&(listed?.projectId??null)!==null,labels,memory});return jsxs14("header",{className:cn7("flex flex-col border-b border-border bg-background",className),"data-part":"chat-header",children:[jsxs14("div",{className:"flex min-h-16 items-center justify-between gap-3 px-6",children:[jsxs14("div",{className:"flex min-w-0 items-center gap-2",children:[jsx16(Button7,{"aria-haspopup":"dialog","aria-label":labels.openConversationList,className:"@3xl/chat:hidden",onClick:openConversations,size:"icon",variant:"outline",children:jsx16(PanelLeftIcon,{})}),jsx16("h1",{className:"truncate text-lg font-semibold text-foreground",children:title}),agentId===null?null:jsx16(AgentBadge,{agentId,labels},agentId)]}),jsxs14("div",{className:"flex shrink-0 items-center gap-2",children:[listed===undefined||agentId!==null||!session.controls.memory?null:jsx16(MemorySwitch,{conversation:listed,labels,write:memory}),conversationId===null||agentId!==null?null:jsx16(CompactionControls,{conversationId,labels,write:compaction},conversationId),conversationId===null?null:jsx16(Button7,{"aria-label":labels.refreshConversation,onClick:()=>{session.retry()},size:"icon",variant:"outline",children:jsx16(RefreshCw2,{})}),slots.headerActions]})]}),notices.map(({alert,text})=>jsx16("p",{className:cn7("border-t border-border px-6 py-2 text-sm",alert?"text-destructive":"text-muted-foreground"),role:alert?"alert":undefined,children:text},text)),session.failure===null?null:jsxs14("div",{className:"flex items-center justify-between gap-3 border-t border-border px-6 py-2 text-sm text-destructive",role:"alert",children:[jsx16("span",{children:failureText(session.failure,labels)}),jsx16(Button7,{onClick:()=>{session.retry()},size:"sm",type:"button",variant:"outline",children:labels.retry})]})]})};import{cn as cn10}from"@collective-intelligence/ui-react";import{Plus,Search}from"@collective-intelligence/ui-react/icons";import{Button as Button12,Empty as Empty2,EmptyDescription as EmptyDescription2,EmptyHeader as EmptyHeader2,EmptyTitle as EmptyTitle2,InputGroup,InputGroupAddon,InputGroupInput,ScrollArea}from"@collective-intelligence/ui-react/ui";import{useState as useState13}from"react";import{AlertDialog,AlertDialogCancel,AlertDialogContent,AlertDialogDescription,AlertDialogFooter,AlertDialogHeader,AlertDialogTitle,Button as Button8,Dialog as Dialog2,DialogContent as DialogContent2,DialogDescription as DialogDescription2,DialogFooter as DialogFooter2,DialogHeader as DialogHeader2,DialogTitle as DialogTitle2,Input as Input2}from"@collective-intelligence/ui-react/ui";import{useState as useState9}from"react";import{jsx as jsx17,jsxs as jsxs15,Fragment as Fragment7}from"react/jsx-runtime";var useConversationDialogs=({onDeletedOpen,onSelect,projects})=>{const session=useChatSession2();const[dialog,setDialog]=useState9();const write=useChatAction();const close=()=>{write.reset();setDialog(undefined)};const actions={onDelete:(conversation)=>{write.reset();setDialog({conversation,kind:"delete"})},onMove:({id},projectId)=>{write.run((client)=>client.chat.updateConversation({params:{conversationId:id},payload:{projectId}}),session.reloadConversations)},onRename:(conversation)=>{write.reset();setDialog({conversation,kind:"rename"})},onSelect,projects};const remove=({id})=>{write.run((client)=>client.chat.deleteConversation({params:{conversationId:id}}),()=>{setDialog(undefined);if(id===session.conversationId){onDeletedOpen()}session.reloadConversations()})};return{actions,close,dialog,remove,write}};var RenameForm=({conversation,labels,onClose,write})=>{const session=useChatSession2();const[title,setTitle]=useState9(conversation.title);const trimmed=title.trim();return jsxs15("form",{className:"flex flex-col gap-4",onSubmit:(event)=>{event.preventDefault();if(trimmed===""){return}write.run((client)=>client.chat.updateConversation({params:{conversationId:conversation.id},payload:{title:trimmed}}),()=>{session.reloadConversations();onClose()})},children:[jsxs15(DialogHeader2,{children:[jsx17(DialogTitle2,{children:labels.renameConversation}),jsx17(DialogDescription2,{children:labels.renameConversationDescription})]}),jsx17(Input2,{"aria-label":labels.conversationTitle,onChange:(event)=>{setTitle(event.target.value)},value:title}),write.failure===null?null:jsx17("p",{className:"text-sm text-destructive",role:"alert",children:labels.actionFailed}),jsxs15(DialogFooter2,{children:[jsx17(Button8,{onClick:onClose,type:"button",variant:"outline",children:labels.cancel}),jsx17(Button8,{disabled:trimmed===""||write.isPending,type:"submit",children:labels.save})]})]})};var ConversationDialogs=({dialogs:{close,dialog,remove,write},labels})=>{const closeWhenShut=(open)=>{if(!open){close()}};return jsxs15(Fragment7,{children:[jsx17(Dialog2,{onOpenChange:closeWhenShut,open:dialog?.kind==="rename",children:jsx17(DialogContent2,{children:dialog?.kind==="rename"?jsx17(RenameForm,{conversation:dialog.conversation,labels,onClose:close,write},dialog.conversation.id):null})}),jsx17(AlertDialog,{onOpenChange:closeWhenShut,open:dialog?.kind==="delete",children:jsxs15(AlertDialogContent,{children:[jsxs15(AlertDialogHeader,{children:[jsx17(AlertDialogTitle,{children:labels.deleteConversation}),jsx17(AlertDialogDescription,{children:fillLabel(labels.deleteConversationDescription,{title:dialog?.conversation.title??""})})]}),write.failure===null?null:jsx17("p",{className:"text-sm text-destructive",role:"alert",children:labels.actionFailed}),jsxs15(AlertDialogFooter,{children:[jsx17(AlertDialogCancel,{children:labels.cancel}),jsx17(Button8,{disabled:write.isPending,onClick:()=>{if(dialog!==undefined){remove(dialog.conversation)}},variant:"destructive",children:labels.delete})]})]})})]})};import{cn as cn8}from"@collective-intelligence/ui-react";import{FolderInput,MoreHorizontal,Pencil as Pencil2,Trash2,X as X4}from"@collective-intelligence/ui-react/icons";import{Button as Button9,DropdownMenu,DropdownMenuContent,DropdownMenuGroup as DropdownMenuGroup2,DropdownMenuItem,DropdownMenuSub,DropdownMenuSubContent,DropdownMenuSubTrigger,DropdownMenuTrigger}from"@collective-intelligence/ui-react/ui";import{useId as useId2}from"react";import{jsx as jsx18,jsxs as jsxs16,Fragment as Fragment8}from"react/jsx-runtime";var ProjectItems=({actions,conversation,labels,projects})=>{const targets=projects.filter(({id})=>id!==conversation.projectId);return jsxs16(Fragment8,{children:[jsxs16(DropdownMenuSub,{children:[jsxs16(DropdownMenuSubTrigger,{disabled:targets.length===0,children:[jsx18(FolderInput,{}),labels.moveToProject]}),jsx18(DropdownMenuSubContent,{children:jsx18(DropdownMenuGroup2,{children:targets.map((project)=>jsx18(DropdownMenuItem,{onClick:()=>{actions.onMove(conversation,project.id)},children:project.name},project.id))})})]}),conversation.projectId===null?null:jsxs16(DropdownMenuItem,{onClick:()=>{actions.onMove(conversation,null)},children:[jsx18(X4,{}),labels.removeFromProject]})]})};var ConversationRow=({actions,active,conversation,labels,placeName})=>{const placeholders={title:conversation.title};const placeNameId=useId2();return jsxs16("div",{className:cn8("relative flex items-center gap-2 rounded-md border px-2.5 py-2 transition-colors",active?"border-transparent bg-accent text-accent-foreground":"border-border bg-background text-muted-foreground hover:text-foreground"),"data-active":active?"":undefined,"data-part":"conversation-row",children:[jsx18("button",{"aria-current":active?"true":undefined,"aria-describedby":placeName===undefined?undefined:placeNameId,"aria-label":fillLabel(labels.openConversation,placeholders),className:"absolute inset-0 rounded-md focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",onClick:()=>{actions.onSelect(conversation.id)},type:"button"}),jsxs16("span",{className:"pointer-events-none flex min-w-0 flex-1 flex-col",children:[jsx18("span",{className:"truncate text-sm font-semibold text-foreground",children:conversation.title}),placeName===undefined?null:jsx18("span",{className:"truncate text-xs text-muted-foreground",id:placeNameId,children:placeName})]}),jsx18("div",{className:"relative z-10",children:jsxs16(DropdownMenu,{children:[jsx18(DropdownMenuTrigger,{render:jsx18(Button9,{"aria-label":fillLabel(labels.conversationActions,placeholders),size:"icon-sm",variant:"ghost"}),children:jsx18(MoreHorizontal,{})}),jsx18(DropdownMenuContent,{align:"end",children:jsxs16(DropdownMenuGroup2,{children:[jsxs16(DropdownMenuItem,{onClick:()=>{actions.onRename(conversation)},children:[jsx18(Pencil2,{}),labels.rename]}),actions.projects===undefined?null:jsx18(ProjectItems,{actions,conversation,labels,projects:actions.projects}),jsxs16(DropdownMenuItem,{onClick:()=>{actions.onDelete(conversation)},variant:"destructive",children:[jsx18(Trash2,{}),labels.delete]})]})})]})})]})};var groupOrder=["today","yesterday","previous_seven_days","earlier"];var dayMs=86400000;var startOfDay=(value)=>new Date(value.getFullYear(),value.getMonth(),value.getDate()).getTime();var activityOf=({createdAt,lastActivityAt,updatedAt})=>lastActivityAt??updatedAt??createdAt;var groupOf=(conversation,now)=>{const activity=activityOf(conversation);if(activity===null){return"earlier"}const days=Math.round((startOfDay(now)-startOfDay(activity))/dayMs);if(days<=0){return"today"}if(days===1){return"yesterday"}return days<7?"previous_seven_days":"earlier"};var groupByActivity=(conversations,now)=>groupOrder.map((group)=>({conversations:conversations.filter((conversation)=>groupOf(conversation,now)===group),group})).filter(({conversations:rows})=>rows.length>0);var matchesSearch=(title,search)=>title.toLowerCase().includes(search.trim().toLowerCase());import{ToggleGroup,ToggleGroupItem}from"@collective-intelligence/ui-react/ui";import{useState as useState10}from"react";import{jsx as jsx19}from"react/jsx-runtime";var keyOf2=({id,kind})=>`${kind}:${id}`;var useChatHistory=({historyScope,labels,place,placeContext})=>{const[value,setValue]=useState10("this_place");const own=keyOf2(place);const developerScope=historyScope===undefined?undefined:new Set([own,...historyScope.map(keyOf2)]);const inScope=(origin)=>developerScope===undefined||developerScope.has(keyOf2(origin));const others=(placeContext?.places??[]).filter((entry)=>keyOf2(entry)!==own&&inScope(entry));const names=new Map((placeContext?.places??[]).map((entry)=>[keyOf2(entry),entry.name]));return{filter:{options:[{label:labels.thisPlace,value:"this_place"},{label:labels.allListedPlaces,value:"all_listed"}],setValue,value,visible:others.length>0},listed:(conversations)=>conversations.filter(({origin})=>value==="this_place"?keyOf2(origin)===own:inScope(origin)),placeNameOf:(origin)=>keyOf2(origin)===own?undefined:names.get(keyOf2(origin))??labels.unknownPlace}};var HistoryFilter=({filter,label})=>jsx19(ToggleGroup,{"aria-label":label,className:"w-full",onValueChange:(values)=>{const option=filter.options.find(({value})=>values.includes(value));if(option!==undefined){filter.setValue(option.value)}},size:"sm",spacing:0,value:[filter.value],variant:"outline",children:filter.options.map(({label:optionLabel,value})=>jsx19(ToggleGroupItem,{className:"flex-1",value,children:optionLabel},value))});var timeOf=(value)=>value?.getTime()??0;var splitByProject=(conversations,projects,search)=>{const isSearch=search.trim()!=="";const shown=new Set(projects.map(({id})=>id));const matching=conversations.filter(({title})=>matchesSearch(title,search));const projectGroups=projects.map((project)=>({conversations:matching.filter(({projectId})=>projectId===project.id),latest:Math.max(timeOf(project.updatedAt),...conversations.filter(({projectId})=>projectId===project.id).map(({lastActivityAt})=>timeOf(lastActivityAt))),project})).filter((group)=>!isSearch||group.conversations.length>0).sort((first,second)=>second.latest-first.latest).map(({conversations:rows,project})=>({conversations:rows,project}));return{others:matching.filter(({projectId})=>projectId===null||!shown.has(projectId)),projectGroups}};import{cn as cn9}from"@collective-intelligence/ui-react";import{ChevronDown as ChevronDown2,ChevronRight,Folder,FolderPlus}from"@collective-intelligence/ui-react/icons";import{Button as Button11,Collapsible,CollapsibleContent,CollapsibleTrigger}from"@collective-intelligence/ui-react/ui";import{useState as useState12}from"react";import{MoreHorizontal as MoreHorizontal2,Pencil as Pencil3,Trash2 as Trash22}from"@collective-intelligence/ui-react/icons";import{AlertDialog as AlertDialog2,AlertDialogCancel as AlertDialogCancel2,AlertDialogContent as AlertDialogContent2,AlertDialogDescription as AlertDialogDescription2,AlertDialogFooter as AlertDialogFooter2,AlertDialogHeader as AlertDialogHeader2,AlertDialogTitle as AlertDialogTitle2,Button as Button10,Dialog as Dialog3,DialogContent as DialogContent3,DialogDescription as DialogDescription3,DialogFooter as DialogFooter3,DialogHeader as DialogHeader3,DialogTitle as DialogTitle3,DropdownMenu as DropdownMenu2,DropdownMenuContent as DropdownMenuContent2,DropdownMenuGroup as DropdownMenuGroup3,DropdownMenuItem as DropdownMenuItem2,DropdownMenuTrigger as DropdownMenuTrigger2,Input as Input3,Label}from"@collective-intelligence/ui-react/ui";import{useId as useId3,useState as useState11}from"react";import{jsx as jsx20,jsxs as jsxs17}from"react/jsx-runtime";var projectNameMaxLength=200;var ProjectActions=({labels,onOpen,project})=>jsxs17(DropdownMenu2,{children:[jsx20(DropdownMenuTrigger2,{render:jsx20(Button10,{"aria-label":fillLabel(labels.projectActions,{name:project.name}),size:"icon-sm",variant:"ghost"}),children:jsx20(MoreHorizontal2,{})}),jsx20(DropdownMenuContent2,{align:"end",children:jsxs17(DropdownMenuGroup3,{children:[jsxs17(DropdownMenuItem2,{onClick:()=>{onOpen({kind:"rename",project})},children:[jsx20(Pencil3,{}),labels.renameProject]}),jsxs17(DropdownMenuItem2,{onClick:()=>{onOpen({kind:"delete",project})},variant:"destructive",children:[jsx20(Trash22,{}),labels.deleteProject]})]})})]});var ProjectNameForm=({dialog,labels,onClose,onSaved})=>{const fieldId=useId3();const helpId=useId3();const save=useChatAction();const[value,setValue]=useState11(dialog.kind==="create"?"":dialog.project.name);const name=value.trim();const isName=name.length>0&&name.length<=projectNameMaxLength;return jsxs17("form",{className:"flex flex-col gap-4",onSubmit:(event)=>{event.preventDefault();if(!isName||save.isPending){return}save.run((client)=>dialog.kind==="create"?client.chatProjects.createProject({payload:{name}}):client.chatProjects.updateProject({params:{projectId:dialog.project.id},payload:{name}}),onSaved)},children:[jsxs17(DialogHeader3,{children:[jsx20(DialogTitle3,{children:dialog.kind==="create"?labels.newProject:labels.renameProject}),jsx20(DialogDescription3,{children:labels.projectDescription})]}),jsxs17("div",{className:"flex flex-col gap-2",children:[jsx20(Label,{htmlFor:fieldId,children:labels.projectName}),jsx20(Input3,{"aria-describedby":helpId,"aria-invalid":save.failure!==null,id:fieldId,maxLength:projectNameMaxLength,onChange:(event)=>{setValue(event.target.value)},value}),jsx20("p",{className:"text-xs text-muted-foreground",id:helpId,children:labels.projectNameHelp}),save.failure===null?null:jsx20("p",{className:"text-sm text-destructive",role:"alert",children:labels.projectNotSaved})]}),jsxs17(DialogFooter3,{children:[jsx20(Button10,{disabled:save.isPending,onClick:onClose,type:"button",variant:"outline",children:labels.cancel}),jsx20(Button10,{disabled:!isName||save.isPending,type:"submit",children:dialog.kind==="create"?labels.createProject:labels.save})]})]})};var DeleteProject=({labels,onClose,onDeleted,project})=>{const remove=useChatAction();return jsx20(AlertDialog2,{onOpenChange:(open)=>{if(!open&&!remove.isPending){onClose()}},open:true,children:jsxs17(AlertDialogContent2,{children:[jsxs17(AlertDialogHeader2,{children:[jsx20(AlertDialogTitle2,{children:fillLabel(labels.deleteProjectTitle,{name:project.name})}),jsx20(AlertDialogDescription2,{children:labels.deleteProjectDescription})]}),remove.failure===null?null:jsx20("p",{className:"text-sm text-destructive",role:"alert",children:labels.projectNotDeleted}),jsxs17(AlertDialogFooter2,{children:[jsx20(AlertDialogCancel2,{disabled:remove.isPending,children:labels.cancel}),jsx20(Button10,{disabled:remove.isPending,onClick:()=>{remove.run((client)=>client.chatProjects.deleteProject({params:{projectId:project.id}}),()=>{onDeleted(project.id)})},variant:"destructive",children:labels.deleteProject})]})]})})};var ProjectDialogs=({dialog,labels,newChat,onClose,projects})=>{const session=useChatSession2();if(dialog?.kind==="delete"){return jsx20(DeleteProject,{labels,onClose,onDeleted:(projectId)=>{const open=session.conversations.find(({id})=>id===session.conversationId);if(projects.viewedId===projectId||open?.projectId===projectId){newChat()}projects.reload();onClose()},project:dialog.project})}return jsx20(Dialog3,{onOpenChange:(open)=>{if(!open){onClose()}},open:dialog!==null,children:dialog===null?null:jsx20(DialogContent3,{children:jsx20(ProjectNameForm,{dialog,labels,onClose,onSaved:(project)=>{projects.reload();if(dialog.kind==="create"){projects.openProjectView(project.id)}onClose()}})})})};var useProjectDialog=()=>{const[dialog,setDialog]=useState11(null);return{dialog,handleClose:()=>{setDialog(null)},handleOpen:setDialog}};import{jsx as jsx21,jsxs as jsxs18}from"react/jsx-runtime";var ProjectEntry=({activeConversationId,group:{conversations,project},isSearch,labels,onDialog,placeNameOf,projects,rowActions})=>{const[isFolded,setIsFolded]=useState12(false);const isOpen=isSearch||!isFolded;const isViewed=projects.viewed?.id===project.id;const name={name:project.name};return jsxs18(Collapsible,{onOpenChange:(open)=>{setIsFolded(!open)},open:isOpen,children:[jsxs18("div",{className:cn9("flex items-center gap-1 rounded-md px-1.5 py-1",isViewed&&"bg-accent text-accent-foreground"),"data-part":"project-entry",children:[jsx21(CollapsibleTrigger,{render:jsx21(Button11,{"aria-label":fillLabel(labels.projectConversationsToggle,name),disabled:isSearch,size:"icon-sm",variant:"ghost"}),children:isOpen?jsx21(ChevronDown2,{}):jsx21(ChevronRight,{})}),jsxs18("button",{"aria-current":isViewed?"page":undefined,"aria-label":fillLabel(labels.openProject,name),className:"flex min-w-0 flex-1 items-center gap-2 rounded-md px-1 py-1.5 text-left focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",onClick:()=>{projects.openProjectView(project.id)},type:"button",children:[jsx21(Folder,{className:"shrink-0 text-muted-foreground"}),jsx21("span",{className:"min-w-0 truncate text-sm font-semibold text-foreground",children:project.name})]}),jsx21(ProjectActions,{labels,onOpen:onDialog,project})]}),jsx21(CollapsibleContent,{className:"mt-2 flex flex-col gap-2 pl-4",children:conversations.map((conversation)=>jsx21(ConversationRow,{actions:rowActions,active:conversation.id===activeConversationId,conversation,labels,placeName:placeNameOf(conversation.origin)},conversation.id))})]})};var ProjectsSection=({groups,newChat,...entryProps})=>{const{labels,projects}=entryProps;const dialogs=useProjectDialog();return jsxs18("section",{className:"flex flex-col gap-2","data-part":"projects-section",children:[jsxs18("div",{className:"flex items-center justify-between gap-2",children:[jsx21("h2",{className:"text-sm font-semibold text-muted-foreground",children:labels.projects}),jsx21(Button11,{"aria-label":labels.newProject,onClick:()=>{dialogs.handleOpen({kind:"create"})},size:"icon-sm",variant:"ghost",children:jsx21(FolderPlus,{})})]}),projects.failed?jsx21("p",{className:"text-sm text-destructive",role:"alert",children:labels.projectsNotLoaded}):null,projects.list?.length===0?jsx21("p",{className:"text-sm text-muted-foreground",children:labels.noProjects}):jsx21("div",{className:"flex flex-col gap-2",children:groups.map((group)=>jsx21(ProjectEntry,{group,onDialog:dialogs.handleOpen,...entryProps},group.project.id))}),jsx21(ProjectDialogs,{dialog:dialogs.dialog,labels,newChat,onClose:dialogs.handleClose,projects})]})};import{jsx as jsx22,jsxs as jsxs19}from"react/jsx-runtime";import{createElement}from"react";var groupLabels={earlier:"earlier",previous_seven_days:"previousSevenDays",today:"today",yesterday:"yesterday"};var ConversationSidebar=({className,history,labels,newChat,projects,selectConversation,slots})=>{const session=useChatSession2();const[search,setSearch]=useState13("");const[now]=useState13(()=>new Date);const shownProjects=projects.enabled?projects.list:undefined;const dialogs=useConversationDialogs({onDeletedOpen:newChat,onSelect:selectConversation,projects:shownProjects});const listed=history.listed(session.conversations);const{others,projectGroups}=splitByProject(listed,shownProjects??[],search);const dateGroups=groupByActivity(others,now);const isSearch=search.trim()!=="";const isLoading=session.status==="starting";const isDraft=session.conversationId===null&&projects.viewed===undefined;const rowProps={actions:dialogs.actions,labels};const list=()=>{if(listed.length===0&&!isLoading){return jsx22(Empty2,{children:jsxs19(EmptyHeader2,{children:[jsx22(EmptyTitle2,{children:labels.noConversations}),jsx22(EmptyDescription2,{children:labels.noConversationsDescription})]})})}if(isSearch&&dateGroups.length===0&&projectGroups.length===0){return jsx22("p",{className:"text-sm text-muted-foreground",children:labels.noSearchResults})}return dateGroups.map(({conversations,group})=>jsxs19("section",{className:"flex flex-col gap-2",children:[jsx22("h2",{className:"text-sm font-semibold text-muted-foreground",children:labels[groupLabels[group]]}),conversations.map((conversation)=>createElement(ConversationRow,{...rowProps,active:conversation.id===session.conversationId,conversation,key:conversation.id,placeName:history.placeNameOf(conversation.origin)}))]},group))};return jsxs19("aside",{"aria-busy":isLoading,"aria-label":labels.conversations,className:cn10("flex min-h-0 w-[360px] shrink-0 flex-col border-r border-border bg-background",className),"data-part":"conversation-sidebar",children:[slots.sidebarHeader,jsxs19("div",{className:"flex flex-col gap-4 border-b border-border px-5 py-4",children:[jsxs19(Button12,{className:"w-full",onClick:()=>{newChat()},size:"lg",children:[jsx22(Plus,{"data-icon":"inline-start"}),labels.newChat]}),jsxs19(InputGroup,{children:[jsx22(InputGroupInput,{"aria-label":labels.searchConversations,onChange:(event)=>{setSearch(event.target.value)},placeholder:labels.searchConversations,type:"search",value:search}),jsx22(InputGroupAddon,{children:jsx22(Search,{})})]})]}),history.filter.visible?jsx22("div",{className:"border-b border-border px-5 py-3",children:jsx22(HistoryFilter,{filter:history.filter,label:labels.historyFilter})}):null,jsx22(ScrollArea,{className:"min-h-0 flex-1",children:jsxs19("div",{className:"flex flex-col gap-6 px-5 py-5",children:[isDraft?jsxs19("div",{className:"flex flex-col gap-1 rounded-md bg-accent px-3 py-3 text-sm text-accent-foreground","data-part":"draft-row",children:[jsx22("span",{className:"truncate font-semibold",children:labels.newChat}),jsx22("span",{className:"text-xs text-muted-foreground",children:labels.draft})]}):null,dialogs.dialog===undefined&&dialogs.write.failure!==null?jsx22("p",{className:"text-sm text-destructive",role:"alert",children:labels.conversationNotMoved}):null,shownProjects===undefined&&!projects.failed?null:jsx22(ProjectsSection,{activeConversationId:session.conversationId,groups:projectGroups,isSearch,labels,newChat,placeNameOf:history.placeNameOf,projects,rowActions:dialogs.actions}),list()]})}),slots.sidebarFooter,jsx22(ConversationDialogs,{dialogs,labels})]})};import{cn as cn11}from"@collective-intelligence/ui-react";import{Folder as Folder2}from"@collective-intelligence/ui-react/icons";import{Button as Button14,Empty as Empty4,EmptyDescription as EmptyDescription4,EmptyHeader as EmptyHeader4,EmptyTitle as EmptyTitle4,Label as Label2,Textarea}from"@collective-intelligence/ui-react/ui";import{useId as useId4,useState as useState15}from"react";import{Download,FileText,Trash2 as Trash23,Upload}from"@collective-intelligence/ui-react/icons";import{Badge as Badge4,Button as Button13,Empty as Empty3,EmptyDescription as EmptyDescription3,EmptyHeader as EmptyHeader3,EmptyTitle as EmptyTitle3,Skeleton,Spinner as Spinner2}from"@collective-intelligence/ui-react/ui";import{useRef as useRef2,useState as useState14,useTransition as useTransition2}from"react";import{jsx as jsx23,jsxs as jsxs20,Fragment as Fragment9}from"react/jsx-runtime";var maxFileBytes=10*1024*1024;var maxProjectFiles=20;var serverReasons=["malformed","oversized","too_many_files","unsupported"];var extensionOf=(filename)=>{const dot=filename.lastIndexOf(".");return dot===-1?"":filename.slice(dot).toLowerCase()};var statesOf=({extractionState,inContext})=>{if(extractionState==="failed"){return["failed"]}const states=[];if(extractionState==="truncated"){states.push("truncated")}if(!inContext){states.push("not_in_context")}return states.length===0?["in_context"]:states};var stateVariants={failed:"destructive",in_context:"secondary",not_in_context:"outline",truncated:"outline"};var stateTexts=(labels,budget)=>({failed:{help:labels.projectFileFailedHelp,label:labels.projectFileFailed},in_context:{help:undefined,label:labels.projectFileInContext},not_in_context:{help:fillLabel(labels.projectFileNotInContextHelp,{max:budget}),label:labels.projectFileNotInContext},truncated:{help:labels.projectFileTruncatedHelp,label:labels.projectFileTruncated}});var rejectionTexts=(labels)=>({failed:labels.projectFileNotAdded,malformed:labels.projectFileRejectedMalformed,oversized:labels.projectFileRejectedOversized,too_many_files:labels.projectFileRejectedTooManyFiles,unsupported:labels.projectFileRejectedUnsupported});var sizeUnit=(bytes)=>{if(bytes<1024){return["byte",bytes]}return bytes<1024**2?["kilobyte",bytes/1024]:["megabyte",bytes/1024**2]};var sizeText=(bytes,locale)=>{const[unit,value]=sizeUnit(bytes);return new Intl.NumberFormat(locale,{maximumFractionDigits:1,style:"unit",unit}).format(value)};var FileRow=({file,labels,locale,onChanged,projectId,texts})=>{const session=useChatSession2();const remove=useChatAction();const download=useChatAction();const port=session.controls.files;const params={fileId:file.id,projectId};const states=statesOf(file);const details=[sizeText(file.sizeBytes,locale),...states.flatMap((state)=>texts[state].help??[])];const name={name:file.filename};const downloadFailure=download.failure===null?undefined:labels.projectFileNotDownloaded;const failure=remove.failure===null?downloadFailure:labels.projectFileNotDeleted;return jsxs20("li",{"aria-busy":remove.isPending,className:"flex items-start gap-3 rounded-md border border-border bg-background px-3 py-2",children:[jsx23(FileText,{className:"mt-0.5 shrink-0 text-muted-foreground"}),jsxs20("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[jsxs20("div",{className:"flex flex-wrap items-center gap-2",children:[jsx23("p",{className:"min-w-0 truncate text-sm font-semibold text-foreground",children:file.filename}),states.map((state)=>jsx23(Badge4,{variant:stateVariants[state],children:texts[state].label},state))]}),jsx23("p",{className:"text-xs text-muted-foreground",children:details.join(" · ")}),failure===undefined?null:jsx23("p",{className:"text-xs text-destructive",role:"alert",children:failure})]}),jsxs20("div",{className:"flex shrink-0 items-center gap-1",children:[port===undefined?null:jsx23(Button13,{"aria-busy":download.isPending,"aria-label":fillLabel(labels.downloadProjectFile,name),disabled:download.isPending,onClick:()=>{download.run((client)=>client.chatProjects.getProjectFileDownloadUrl({params}),({url})=>{port.download({filename:file.filename,url})})},size:"icon",type:"button",variant:"ghost",children:download.isPending?jsx23(Spinner2,{}):jsx23(Download,{})}),jsx23(Button13,{"aria-busy":remove.isPending,"aria-label":fillLabel(labels.deleteProjectFile,name),disabled:remove.isPending,onClick:()=>{remove.run((client)=>client.chatProjects.deleteProjectFile({params}),onChanged)},size:"icon",type:"button",variant:"ghost",children:remove.isPending?jsx23(Spinner2,{}):jsx23(Trash23,{})})]})]})};var ProjectFilesSection=({labels,locale,projectId})=>{const{call}=useChatSession2();const params={projectId};const list=useChatRead((client)=>client.chatProjects.listProjectFiles({params}));const capabilities=useChatRead((client)=>client.chatCatalog.getAttachmentCapabilities());const inputRef=useRef2(null);const[isAdding,startAdding]=useTransition2();const[rejections,setRejections]=useState14([]);const data=list.result?.ok===true?list.result.value:undefined;const fileTypes=capabilities.result?.ok===true?capabilities.result.value.projectFileTypes:undefined;const isFull=(data?.files.length??0)>=maxProjectFiles;const canAdd=data!==undefined&&!isFull&&!isAdding;const clientReason=(file,full)=>{if(fileTypes!==undefined&&!fileTypes.some(({extension})=>extension===extensionOf(file.name))){return"unsupported"}if(file.size>maxFileBytes){return"oversized"}return full?"too_many_files":undefined};const upload=(file)=>{const payload=new FormData;payload.append("file",file);return call((client)=>client.chatProjects.uploadProjectFile({params,payload}))};const addFilesAction=(chosen)=>{startAdding(async()=>{const rejected=[];let count=data?.files.length??0;for(const[order,file]of chosen.entries()){let reason=clientReason(file,count>=maxProjectFiles);if(reason===undefined){const result=await upload(file);if(result.ok){count+=1}else{reason=serverReasons.find((known)=>known===result.error.reason)??"failed"}}if(reason==="too_many_files"){count=maxProjectFiles}if(reason!==undefined){rejected.push({filename:file.name,order,reason})}}startAdding(()=>{setRejections(rejected);list.reload()})})};const reasons=rejectionTexts(labels);const files=()=>{if(data===undefined){return list.result?.ok===false?jsxs20("div",{className:"flex items-center justify-between gap-3 text-sm text-destructive",role:"alert",children:[jsx23("span",{children:labels.projectFilesNotLoaded}),jsx23(Button13,{onClick:()=>{list.reload()},size:"sm",type:"button",variant:"outline",children:labels.retry})]}):jsx23(Skeleton,{className:"h-12 w-full"})}const count=new Intl.NumberFormat(locale);const budget=count.format(data.maxCharacters);const texts=stateTexts(labels,budget);return jsxs20(Fragment9,{children:[jsxs20("p",{className:"text-xs text-muted-foreground",children:[labels.projectFilesUsage,":"," ",fillLabel(labels.projectFilesUsageValue,{max:budget,used:count.format(data.usedCharacters)})]}),data.files.length===0?jsx23(Empty3,{className:"border border-dashed border-border",children:jsxs20(EmptyHeader3,{children:[jsx23(EmptyTitle3,{children:labels.noProjectFiles}),jsx23(EmptyDescription3,{children:labels.noProjectFilesDescription})]})}):jsx23("ul",{className:"flex flex-col gap-2",children:data.files.map((file)=>jsx23(FileRow,{file,labels,locale,onChanged:()=>{list.reload()},projectId,texts},file.id))})]})};return jsxs20("section",{"aria-label":labels.projectFiles,className:"flex flex-col gap-3","data-part":"project-files",children:[jsxs20("div",{className:"flex items-center justify-between gap-3",children:[jsxs20("div",{className:"flex flex-col gap-1",children:[jsx23("h3",{className:"text-sm font-semibold text-foreground",children:labels.projectFiles}),jsx23("p",{className:"text-xs text-muted-foreground",children:isFull?labels.projectFilesFull:labels.projectFilesHelp})]}),jsx23("input",{accept:fileTypes?.map(({extension})=>extension).join(","),"aria-hidden":"true",className:"sr-only",disabled:!canAdd,multiple:true,onChange:(event)=>{const chosen=[...event.target.files??[]];event.target.value="";if(chosen.length>0){addFilesAction(chosen)}},ref:inputRef,tabIndex:-1,type:"file"}),jsxs20(Button13,{"aria-busy":isAdding,disabled:!canAdd,onClick:()=>inputRef.current?.click(),size:"sm",type:"button",variant:"outline",children:[isAdding?jsx23(Spinner2,{"data-icon":"inline-start"}):jsx23(Upload,{"data-icon":"inline-start"}),labels.addProjectFiles]})]}),rejections.length===0?null:jsxs20("div",{className:"flex flex-col gap-1 text-sm text-destructive",role:"alert",children:[jsx23("p",{className:"font-semibold",children:labels.projectFilesNotAdded}),jsx23("ul",{className:"flex flex-col gap-1",children:rejections.map(({filename,order,reason})=>jsxs20("li",{children:[filename,": ",reasons[reason]]},order))})]}),files()]})};import{jsx as jsx24,jsxs as jsxs21}from"react/jsx-runtime";var maxInstructions=8000;var InstructionsEditor=({labels,project,projects})=>{const fieldId=useId4();const save=useChatAction();const[text,setText]=useState15(project.instructions??"");const instructions=text.trim()===""?null:text;const isTooLong=text.length>maxInstructions;const canSave=!isTooLong&&!save.isPending&&instructions!==project.instructions;const failed=save.failure===null?undefined:labels.projectInstructionsNotSaved;const error=isTooLong?labels.projectInstructionsTooLong:failed;return jsxs21("form",{"aria-busy":save.isPending,className:"flex flex-col gap-2",onSubmit:(event)=>{event.preventDefault();if(canSave){save.run((client)=>client.chatProjects.updateProject({params:{projectId:project.id},payload:{instructions}}),projects.reload)}},children:[jsx24(Label2,{htmlFor:fieldId,children:labels.projectInstructions}),jsx24(Textarea,{"aria-invalid":error!==undefined,className:"max-h-64 min-h-24",id:fieldId,onChange:(event)=>{setText(event.target.value)},value:text}),jsx24("p",{className:"text-xs text-muted-foreground",children:labels.projectInstructionsHelp}),error===undefined?null:jsx24("p",{className:"text-xs text-destructive",role:"alert",children:error}),jsxs21("div",{className:"flex items-center justify-between gap-2",children:[jsxs21("span",{className:cn11("text-xs",isTooLong?"text-destructive":"text-muted-foreground"),children:[text.length,"/",maxInstructions]}),jsx24(Button14,{disabled:!canSave,size:"sm",type:"submit",children:labels.save})]})]})};var ProjectView=({history,labels,locale,newChat,project,projects,selectConversation})=>{const session=useChatSession2();const projectDialogs=useProjectDialog();const conversationDialogs=useConversationDialogs({onDeletedOpen:newChat,onSelect:selectConversation,projects:projects.list});const conversations=history.listed(session.conversations).filter(({projectId})=>projectId===project.id);return jsxs21("section",{"aria-label":project.name,className:"min-h-0 flex-1 overflow-y-auto","data-part":"project-view",children:[jsxs21("div",{className:"mx-auto flex w-full max-w-[900px] flex-col gap-6 px-6 py-8",children:[jsxs21("div",{className:"flex items-center justify-between gap-3",children:[jsxs21("div",{className:"flex min-w-0 items-center gap-3",children:[jsx24(Folder2,{className:"shrink-0 text-muted-foreground"}),jsx24("h2",{className:"min-w-0 truncate text-2xl font-semibold text-foreground",children:project.name})]}),jsx24(ProjectActions,{labels,onOpen:projectDialogs.handleOpen,project})]}),jsx24(InstructionsEditor,{labels,project,projects},project.id),jsx24(ProjectFilesSection,{labels,locale,projectId:project.id},project.id),jsxs21("div",{className:"flex flex-col gap-3",children:[jsx24("h3",{className:"text-sm font-semibold text-foreground",children:labels.projectConversations}),conversations.length===0?jsx24(Empty4,{className:"border border-dashed border-border",children:jsxs21(EmptyHeader4,{children:[jsx24(EmptyTitle4,{children:labels.projectNoConversations}),jsx24(EmptyDescription4,{children:labels.projectNoConversationsDescription})]})}):jsx24("div",{className:"flex flex-col gap-2",children:conversations.map((conversation)=>jsx24(ConversationRow,{actions:conversationDialogs.actions,active:false,conversation,labels,placeName:history.placeNameOf(conversation.origin)},conversation.id))})]})]}),jsx24(ProjectDialogs,{dialog:projectDialogs.dialog,labels,newChat,onClose:projectDialogs.handleClose,projects}),jsx24(ConversationDialogs,{dialogs:conversationDialogs,labels})]})};import{useState as useState16}from"react";var useChatProjects=()=>{const session=useChatSession2();const enabled=session.controls.projects;const read=useChatRead((client)=>client.chatProjects.listProjects(),enabled);const[viewedId,setViewedId]=useState16();const list=read.result?.ok===true?read.result.value.data:undefined;const failure=read.result?.ok===false?read.result.error:undefined;const offHere=failure?.code==="forbidden"&&failure.reason==="not_available_here";const shownId=session.conversationId===null?viewedId:undefined;return{enabled:enabled&&!offHere,failed:failure!==undefined&&!offHere,leaveProject:()=>{setViewedId(undefined)},list,openProjectView:(projectId)=>{setViewedId(projectId);session.newChat({projectId})},reload:()=>{read.reload();session.reloadConversations()},viewed:shownId===undefined?undefined:list?.find(({id})=>id===shownId),viewedId:shownId}};import{cn as cn14}from"@collective-intelligence/ui-react";import{Conversation,ConversationContent,ConversationEmptyState,ConversationItem,ConversationScrollButton,Message,MessageActions,MessageContent}from"@collective-intelligence/ui-react/ai-elements";import*as Schema6 from"effect/Schema";import{useTransition as useTransition3}from"react";import{cn as cn12}from"@collective-intelligence/ui-react";import{ThumbsDown,ThumbsUp}from"@collective-intelligence/ui-react/icons";import{Button as Button15,Dialog as Dialog4,DialogContent as DialogContent4,DialogDescription as DialogDescription4,DialogFooter as DialogFooter4,DialogHeader as DialogHeader4,DialogTitle as DialogTitle4,Textarea as Textarea2}from"@collective-intelligence/ui-react/ui";import{useState as useState17}from"react";import{jsx as jsx25,jsxs as jsxs22,Fragment as Fragment10}from"react/jsx-runtime";var sentiments=["positive","negative"];var FeedbackButton=({active,disabled,label,onClick,sentiment})=>{const Icon=sentiment==="positive"?ThumbsUp:ThumbsDown;return jsx25(Button15,{"aria-label":label,"aria-pressed":active,className:cn12("text-muted-foreground",active&&(sentiment==="positive"?"border-(--success) text-(--success)":"border-(--danger) text-(--danger)")),disabled,onClick,size:"icon-sm",type:"button",variant:"ghost",children:jsx25(Icon,{"aria-hidden":"true",className:cn12(active&&"fill-current")})})};var NoteForm=({labels,onCancel,onSubmit})=>{const[note,setNote]=useState17("");const trimmed=note.trim();return jsxs22(Fragment10,{children:[jsx25(Textarea2,{"aria-label":labels.feedbackNote,autoFocus:true,onChange:(event)=>{setNote(event.target.value)},placeholder:labels.feedbackNote,required:true,value:note}),jsxs22(DialogFooter4,{children:[jsx25(Button15,{onClick:onCancel,type:"button",variant:"outline",children:labels.cancel}),jsx25(Button15,{disabled:trimmed==="",onClick:()=>{onSubmit(trimmed)},type:"button",children:labels.feedbackSubmit})]})]})};var ChatAnswerFeedback=({className,clear,error,labels,pending,submit,value})=>{const[noteOpen,setNoteOpen]=useState17(false);const press=(sentiment)=>{if(value===sentiment){clear()}else if(sentiment==="positive"){submit({note:null,sentiment})}else{setNoteOpen(true)}};return jsxs22("div",{className:cn12("flex flex-wrap items-center gap-2 text-xs text-muted-foreground",className),"data-part":"answer-feedback",children:[jsx25("fieldset",{"aria-busy":pending,"aria-label":labels.feedbackGroup,className:"flex items-center gap-1",children:sentiments.map((sentiment)=>jsx25(FeedbackButton,{active:value===sentiment,disabled:pending,label:sentiment==="positive"?labels.feedbackPositive:labels.feedbackNegative,onClick:()=>{press(sentiment)},sentiment},sentiment))}),pending?jsx25("span",{children:labels.feedbackSaving}):null,error===null?null:jsx25("span",{className:"text-destructive",role:"alert",children:error}),jsx25(Dialog4,{onOpenChange:setNoteOpen,open:noteOpen,children:jsxs22(DialogContent4,{children:[jsxs22(DialogHeader4,{children:[jsx25(DialogTitle4,{children:labels.feedbackNoteTitle}),jsx25(DialogDescription4,{children:labels.feedbackNoteDescription})]}),jsx25(NoteForm,{labels,onCancel:()=>{setNoteOpen(false)},onSubmit:(note)=>{submit({note,sentiment:"negative"});setNoteOpen(false)}})]})})]})};var useAnswerFeedback=(invocationId,message)=>{const action=useChatAction();const[value,setValue]=useState17(message.metadata?.currentUserFeedback?.sentiment??null);const show=({currentUserFeedback})=>{setValue(currentUserFeedback.sentiment)};return{clear:()=>{action.run((client)=>client.chatFeedback.clearAnswerFeedback({params:{invocationId}}),show)},failed:action.failure!==null,pending:action.isPending,submit:({note,sentiment})=>{action.run((client)=>client.chatFeedback.putAnswerFeedback({params:{invocationId},payload:note===null?{sentiment}:{sentiment,submitterNote:note}}),show)},value}};var AnswerFeedback=({Control,invocationId,labels,message})=>{const{clear,failed,pending,submit,value}=useAnswerFeedback(invocationId,message);return jsx25(Control,{clear,error:failed?labels.actionFailed:null,labels,message,pending,submit,value})};import{getToolName as getToolName2,isToolUIPart as isToolUIPart2}from"ai";import*as Option3 from"effect/Option";import*as Schema4 from"effect/Schema";import{MessageResponse}from"@collective-intelligence/ui-react/ai-elements";import{Alert,AlertDescription,Badge as Badge5,CodeBlock,CodeBlockContent,Table,TableBody,TableCell,TableHead,TableHeader,TableRow}from"@collective-intelligence/ui-react/ui";import*as Schema from"effect/Schema";import{jsx as jsx26,jsxs as jsxs23}from"react/jsx-runtime";var isText=Schema.is(Schema.String);var webUrl=(url)=>{if(!isText(url)){return null}try{const{protocol}=new URL(url);return protocol==="http:"||protocol==="https:"?url:null}catch{return null}};var WebLink=({children,url})=>jsx26("a",{className:"font-medium break-words text-primary underline-offset-4 hover:underline",href:url,rel:"noreferrer",target:"_blank",children});var textOf=(value)=>isText(value)?value:JSON.stringify(value)??"";var TableCellValue=({column,row})=>{const value=row[column.key];const url=webUrl(column.link===null?value:row[column.link.urlKey]);const labelKey=column.link?.labelKey??null;const text=textOf(labelKey===null?value:row[labelKey]??value);return url===null||column.link===null&&column.valueKind!=="url"?text:jsx26(WebLink,{url,children:text})};var EvidenceTable=({evidence})=>jsxs23(Table,{children:[jsx26(TableHeader,{children:jsx26(TableRow,{children:evidence.columns.map((column)=>jsx26(TableHead,{title:column.description??undefined,children:column.label},column.key))})}),jsx26(TableBody,{children:evidence.rows.map((row,index)=>jsx26(TableRow,{children:evidence.columns.map((column)=>jsx26(TableCell,{children:jsx26(TableCellValue,{column,row})},column.key))},index))})]});var EvidenceSources=({evidence,labels})=>jsxs23("div",{className:"flex flex-col gap-3",children:[evidence.groups.map((group)=>jsxs23("section",{className:"flex flex-col gap-2",children:[jsx26("h4",{className:"text-muted-foreground text-xs font-medium",children:group.label}),jsx26("ul",{className:"flex flex-col gap-2",children:group.items.map((item,index)=>{const url=item.navigation?.kind==="external_url"?webUrl(item.navigation.url):null;return jsxs23("li",{className:"flex flex-col gap-1",children:[jsx26("span",{className:"text-sm font-medium",children:url===null?item.title:jsx26(WebLink,{url,children:item.title})}),jsx26("span",{className:"text-muted-foreground text-xs",children:item.excerpt}),jsxs23("span",{className:"flex flex-wrap gap-1",children:[jsx26(Badge5,{variant:"secondary",children:item.provenanceLabel}),item.relevanceScore>0?jsx26(Badge5,{variant:"outline",children:fillLabel(labels.evidenceRelevance,{percent:String(Math.round(item.relevanceScore*100))})}):null]})]},item.evidenceId??`row-${index}`)})})]},group.label)),evidence.omittedCount>0?jsx26("p",{className:"text-muted-foreground text-xs",children:fillLabel(labels.evidenceOmitted,{count:String(evidence.omittedCount)})}):null]});var EvidenceBody=({evidence,labels})=>{switch(evidence.kind){case"table":{return jsx26(EvidenceTable,{evidence})}case"sources":{return jsx26(EvidenceSources,{evidence,labels})}case"links":{return jsx26("ul",{className:"flex flex-col gap-1",children:evidence.links.map((link)=>{const url=webUrl(link.url);return jsxs23("li",{className:"flex flex-col text-sm",children:[url===null?link.label:jsx26(WebLink,{url,children:link.label}),link.description===null?null:jsx26("span",{className:"text-muted-foreground text-xs",children:link.description})]},link.url)})})}case"summary":{return jsx26(MessageResponse,{children:evidence.text})}case"warnings":{return jsx26(Alert,{children:evidence.warnings.map((warning)=>jsx26(AlertDescription,{children:warning},warning))})}case"json":{return jsx26(CodeBlock,{size:"sm",children:jsx26(CodeBlockContent,{children:JSON.stringify(evidence.value,null,2)})})}default:{return jsx26("div",{className:"flex flex-wrap gap-2",children:evidence.images.flatMap((image)=>{const url=webUrl(image.url);return url===null?[]:[jsx26("img",{alt:image.alt??image.filename,className:"max-h-64 max-w-full border object-contain",src:url},image.url)]})})}}};var kindTitle=(labels,kind)=>{switch(kind){case"sources":{return labels.evidenceSources}case"links":{return labels.evidenceLinks}case"warnings":{return labels.evidenceWarnings}default:{return null}}};var EvidencePart=({labels,part})=>{const title=part.title??kindTitle(labels,part.kind);return jsxs23("section",{className:"flex flex-col gap-2 border p-3 text-sm","data-evidence-kind":part.kind,"data-part":"evidence",children:[title===null?null:jsx26("h3",{className:"font-medium",children:title}),part.description===null?null:jsx26("p",{className:"text-muted-foreground text-xs",children:part.description}),jsx26(EvidenceBody,{evidence:part,labels})]})};import{FileText as FileText2}from"@collective-intelligence/ui-react/icons";import{Attachment as Attachment2,AttachmentContent,AttachmentMedia,AttachmentTitle}from"@collective-intelligence/ui-react/ui";import{jsx as jsx27,jsxs as jsxs24}from"react/jsx-runtime";var FilePart=({part})=>{const name=part.filename??part.mediaType;const image=part.mediaType.startsWith("image/")&&part.url!=="";return image?jsxs24(Attachment2,{"data-part":"file",orientation:"vertical",children:[jsx27(AttachmentMedia,{variant:"image",children:jsx27("img",{alt:name,src:part.url})}),jsx27(AttachmentContent,{children:jsx27(AttachmentTitle,{children:name})})]}):jsxs24(Attachment2,{"data-part":"file",children:[jsx27(AttachmentMedia,{children:jsx27(FileText2,{})}),jsx27(AttachmentContent,{children:jsx27(AttachmentTitle,{children:name})})]})};import{isToolUIPart}from"ai";import*as Option from"effect/Option";import*as Schema2 from"effect/Schema";var imageStatuses=["attention_required","cancelled","completed","failed","partial","pending","running"];var OptionalText=Schema2.optionalKey(Schema2.NullOr(Schema2.String));var ImageFileSchema=Schema2.Struct({filename:Schema2.String,id:Schema2.String,mimeType:Schema2.String,source:Schema2.Literal("managed"),url:Schema2.String});var ImageProvenanceSchema=Schema2.Struct({deploymentName:OptionalText,modelName:Schema2.String,modelVersion:OptionalText,providerRoute:Schema2.String,routeModelName:OptionalText});var ImageParametersSchema=Schema2.Struct({aspectRatio:OptionalText,background:OptionalText,count:Schema2.optionalKey(Schema2.NullOr(Schema2.Finite)),format:OptionalText,quality:OptionalText,referenceImages:Schema2.optionalKey(Schema2.NullOr(Schema2.Array(Schema2.Unknown))),resolution:OptionalText});var ImageUsageSchema=Schema2.Struct({amount:OptionalText,currency:OptionalText,kind:Schema2.String,source:OptionalText});var ImageOutputSchema=Schema2.Struct({effectiveParameters:Schema2.optionalKey(Schema2.Unknown),error:Schema2.optionalKey(Schema2.NullOr(Schema2.Struct({code:OptionalText,message:OptionalText}))),files:Schema2.optionalKey(Schema2.Array(Schema2.Unknown)),jobId:Schema2.String,provenance:Schema2.optionalKey(Schema2.Unknown),status:Schema2.Literals(imageStatuses),usage:Schema2.optionalKey(Schema2.Unknown)});var decodeOutput=Schema2.decodeUnknownOption(ImageOutputSchema);var decodeFile=Schema2.decodeUnknownOption(ImageFileSchema);var decodeProvenance=Schema2.decodeUnknownOption(ImageProvenanceSchema);var decodeParameters=Schema2.decodeUnknownOption(ImageParametersSchema);var decodeUsage=Schema2.decodeUnknownOption(ImageUsageSchema);var isWebUrl=(url)=>{try{const{protocol}=new URL(url);return protocol==="http:"||protocol==="https:"}catch{return false}};var shownFiles=(files)=>files.flatMap((value)=>Option.toArray(decodeFile(value)).filter(({mimeType,url})=>mimeType.startsWith("image/")&&isWebUrl(url)));var generationOf=(view)=>({errorMessage:view.error?.message??view.error?.code??globalThis.undefined,files:shownFiles(view.files??[]),jobId:view.jobId,parameters:Option.getOrUndefined(decodeParameters(view.effectiveParameters)),provenance:Option.getOrUndefined(decodeProvenance(view.provenance)),published:view.files!==undefined,status:view.status,usage:Option.getOrUndefined(decodeUsage(view.usage))});var imageGenerationOfPart=(part)=>{const view=part.state==="output-available"?decodeOutput(part.output):Option.none();return Option.isNone(view)?Option.none():Option.some(generationOf(view.value))};var waits=({published,status})=>status==="pending"||status==="running"||!published;var imagePending=(messages)=>messages.some((message)=>message.parts.some((part)=>isToolUIPart(part)&&Option.exists(imageGenerationOfPart(part),waits)));var imageStatusLabels={attention_required:"imageStatusAttentionRequired",cancelled:"imageStatusCancelled",completed:"imageStatusCompleted",failed:"imageStatusFailed",partial:"imageStatusPartial",pending:"imageStatusPending",running:"imageStatusRunning"};var providerName=(route)=>{switch(route){case"azure_flux":case"azure_gpt_image":{return"Azure"}case"bedrock_runtime":{return"Amazon Bedrock"}case"openrouter_images":{return"OpenRouter"}case"regolo_images":{return"Regolo"}default:{return null}}};var textFacts=(pairs)=>pairs.flatMap(([label,value])=>value===null||value===undefined||value===""?[]:[{label,value}]);var provenanceFacts=(labels,provenance)=>provenance===undefined?[]:[{label:labels.imageProvider,value:providerName(provenance.providerRoute)??labels.imageProviderConfigured},{label:labels.imageModel,value:provenance.modelName},...textFacts([[labels.imageModelVersion,provenance.modelVersion],[labels.imageDeployment,provenance.deploymentName],[labels.imageProviderModel,provenance.routeModelName]])];var parameterFacts=(labels,parameters)=>{if(parameters===undefined){return[]}const{count,referenceImages}=parameters;return[...count!==null&&count!==undefined&&Number.isSafeInteger(count)&&count>0?[{label:labels.imageCount,value:String(count)}]:[],...textFacts([[labels.imageFormat,parameters.format?.toUpperCase()],[labels.imageResolution,parameters.resolution],[labels.imageAspectRatio,parameters.aspectRatio],[labels.imageQuality,parameters.quality],[labels.imageBackground,parameters.background]]),...referenceImages===null||referenceImages===undefined?[]:[{label:labels.imageReferenceImages,value:String(referenceImages.length)}]]};var amountPattern=/^(?:0|[1-9]\d*)(?:\.\d+)?$/u;var currencyPattern=/^[A-Z]{3}$/u;var usageFacts=(labels,usage)=>{const amount=usage?.amount??"";const currency=usage?.currency??"";const kind=usage?.kind;const known=(kind==="actual"||kind==="estimate")&&amountPattern.test(amount)&¤cyPattern.test(currency);return[known?{label:kind==="actual"?labels.imageActualCost:labels.imageEstimatedCost,value:`${currency} ${amount}`}:{label:labels.imageCost,value:labels.imageCostUnavailable},...textFacts([[labels.imageCostSource,usage?.source]])]};var imageFactsOf=(labels,generation)=>[...provenanceFacts(labels,generation.provenance),...parameterFacts(labels,generation.parameters),...usageFacts(labels,generation.usage)];import{jsx as jsx28,jsxs as jsxs25}from"react/jsx-runtime";var ImageGenerationPart=({labels,part})=>jsxs25("section",{className:"flex flex-col gap-2 border p-3 text-sm","data-part":"image-generation","data-status":part.status,children:[jsx28("h3",{className:"font-medium",children:labels.imageTitle}),jsx28("p",{"aria-live":"polite",children:labels[imageStatusLabels[part.status]]}),part.errorMessage===undefined?null:jsx28("p",{className:"text-muted-foreground text-xs",children:part.errorMessage}),part.files.length===0?null:jsx28("div",{className:"flex flex-wrap gap-2",children:part.files.map((file)=>jsx28("a",{href:file.url,rel:"noreferrer",target:"_blank",children:jsx28("img",{alt:file.filename,className:"max-h-64 max-w-full border object-contain",src:file.url})},file.id))}),jsx28("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:imageFactsOf(labels,part).map((fact)=>jsxs25("div",{className:"contents",children:[jsx28("dt",{className:"text-muted-foreground",children:fact.label}),jsx28("dd",{className:"min-w-0 break-words",children:fact.value})]},fact.label))})]});import{Badge as Badge6}from"@collective-intelligence/ui-react/ui";import{LifecycleStatusCard}from"@collective-intelligence/ui-react/ui-extensions";import{jsx as jsx29,jsxs as jsxs26}from"react/jsx-runtime";var intentCardLabels={en:{completed:"Completed",ended:"Result no longer available",failed:"Failed",title:"Intent {name}",working:"Working"},it:{completed:"Completato",ended:"Risultato non più disponibile",failed:"Non riuscito",title:"Intent {name}",working:"In corso"}};var resultText=(result)=>hasStringRuntimeKind2(result)?result:JSON.stringify(result,null,2);var statusOf=(labels,state)=>{switch(state.kind){case"running":{return{statusLabel:labels.working,tone:"active"}}case"completed":{return{completedState:jsx29("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm",children:resultText(state.result)}),statusLabel:labels.completed,tone:"success"}}case"failed":{return{error:{summary:state.reason,tone:"destructive"},statusLabel:labels.failed,tone:"danger"}}case"ended":{return{statusLabel:labels.ended,tone:"muted"}}}};var badgeVariant={active:"secondary",danger:"destructive",default:"secondary",muted:"outline",success:"default",warning:"outline"};var intentCardHeader=({model,statusLabel,title})=>jsxs26("div",{className:"flex items-center justify-between gap-2 text-sm",children:[jsx29("span",{className:"font-medium",children:title}),jsx29(Badge6,{variant:badgeVariant[model.tone??"default"],children:statusLabel})]});var intentCardShell=(state)=>function IntentCardShell({children,title}){return jsx29("section",{"aria-label":String(title),"data-slot":"intent-card","data-state":state,children})};var IntentCard=({card,className,labels:custom,locale="en"})=>{const labels={...intentCardLabels[locale],...custom};const title=labels.title.replace("{name}",card.displayName??card.fqn);const model={...statusOf(labels,card.state),description:undefined,title};return jsx29(LifecycleStatusCard,{className,model,slots:{header:intentCardHeader,shell:intentCardShell(card.state.kind)}})};import{jsx as jsx30}from"react/jsx-runtime";var cardState=(part)=>{switch(part.state){case"running":case"ended":{return{kind:part.state}}case"completed":{return{kind:"completed",result:part.result}}case"failed":{return{kind:"failed",reason:part.reason}}}};var IntentCardMessagePart=({labels,part})=>jsx30(IntentCard,{card:{...part.displayName!==undefined&&{displayName:part.displayName},fqn:part.fqn,handle:part.dispatchId,state:cardState(part)},labels:{completed:labels.intentCardCompleted,ended:labels.intentCardEnded,failed:labels.intentCardFailed,title:labels.intentCardTitle,working:labels.intentCardWorking}});import{Badge as Badge7}from"@collective-intelligence/ui-react/ui";import{jsx as jsx31,jsxs as jsxs27}from"react/jsx-runtime";var kindLabels={created:"memoryCreated",merged:"memoryMerged",rejected:"approvalStatusRejected",retrieved:"memoryRetrieved",selected:"memorySelected",skipped:"memorySkipped",suggested:"memorySuggested",superseded:"memorySuperseded",used:"memoryUsedEvent"};var shownEvents=({events})=>{const relevant=events.filter(({kind})=>kind!=="retrieved");return relevant.length>0?relevant:events};var MemoryEvidencePart=({labels,part})=>{const{events}=part;if(events.length===0){return null}const count=(kinds)=>String(events.filter(({kind})=>kinds.includes(kind)).length);const used=count(["used"]);const saved=count(["created","suggested"]);const disabled=events.some(({kind,reason})=>kind==="skipped"&&reason==="memory_disabled");return jsxs27("section",{className:"flex flex-col gap-2 border p-3 text-sm","data-part":"memory-evidence",children:[jsxs27("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[jsx31("h3",{className:"font-medium",children:labels.memoryTitle}),jsxs27("div",{className:"flex flex-wrap gap-1",children:[used==="0"?null:jsx31(Badge7,{variant:"secondary",children:fillLabel(labels.memoryUsed,{count:used})}),saved==="0"?null:jsx31(Badge7,{variant:"secondary",children:fillLabel(labels.memorySaved,{count:saved})}),disabled?jsx31(Badge7,{variant:"outline",children:labels.memoryDisabled}):null]})]}),jsx31("ul",{className:"flex flex-col gap-1",children:shownEvents(part).map((event,index)=>jsxs27("li",{className:"flex flex-wrap items-center gap-2",children:[jsx31("span",{className:"font-medium",children:labels[kindLabels[event.kind]]}),[event.category,event.scope,event.lifecycleStatus,event.reason].filter((detail)=>detail!==null&&detail!=="").map((detail)=>jsx31("span",{className:"text-muted-foreground text-xs",children:detail?.replaceAll("_"," ")},detail))]},index))})]})};import{Questionnaire,QuestionnaireActions,QuestionnaireChoice,QuestionnaireChoiceDescription,QuestionnaireChoices,QuestionnaireInput,QuestionnaireItem,QuestionnaireSubmit,QuestionnaireTitle}from"@collective-intelligence/ui-react/ai-elements";import{Badge as Badge8}from"@collective-intelligence/ui-react/ui";import{jsx as jsx32,jsxs as jsxs28}from"react/jsx-runtime";var answerField="answer";var answerOf=(form)=>{const chosen=form.querySelector('input[type="radio"]:checked');if(chosen!==null){return{kind:"option",optionId:chosen.value}}const text=form.querySelector('[data-slot="questionnaire-input"]')?.value.trim()??"";return text===""?null:{kind:"free_text",text}};var answerText=({input,output})=>{if(output===undefined){return null}return output.kind==="free_text"?output.text:input.options.find(({id})=>id===output.optionId)?.label??output.optionId};var AnsweredQuestion=({labels,question})=>jsxs28("div",{className:"flex flex-col gap-2 border p-4","data-part":"question",children:[jsxs28("div",{className:"flex items-center justify-between gap-2",children:[jsx32("p",{className:"text-sm font-medium",children:question.input.prompt}),jsx32(Badge8,{variant:"secondary",children:labels.questionCompleted})]}),jsx32("p",{className:"text-muted-foreground text-sm",children:answerText(question)})]});var QuestionPart=({answer,labels,part})=>{if(part.output!==undefined){return jsx32(AnsweredQuestion,{labels,question:part})}const{allowFreeText,mode,options,prompt}=part.input;const choices=mode==="single_choice"&&options.length>0;const submit=(event)=>{event.preventDefault();const output=answerOf(event.currentTarget);if(output!==null){answer(output)}};return jsxs28(Questionnaire,{className:"border p-4","data-part":"question",onSubmit:submit,children:[jsxs28(QuestionnaireItem,{name:answerField,required:true,children:[jsx32(QuestionnaireTitle,{children:prompt}),choices?jsx32(QuestionnaireChoices,{children:options.map((option)=>jsxs28(QuestionnaireChoice,{value:option.id,children:[option.label,option.description===null?null:jsx32(QuestionnaireChoiceDescription,{children:option.description})]},option.id))}):null,!choices||allowFreeText?jsx32(QuestionnaireInput,{"aria-label":choices?labels.questionOtherAnswer:labels.questionTextAnswer,placeholder:labels.questionTextPlaceholder}):null]}),jsx32(QuestionnaireActions,{children:jsx32(QuestionnaireSubmit,{children:labels.questionAnswer})})]})};import{MessageAction}from"@collective-intelligence/ui-react/ai-elements";import{Loader2 as Loader22,Pause,Play}from"@collective-intelligence/ui-react/icons";import{useEffect as useEffect2,useRef as useRef3,useState as useState18}from"react";var maxRetries=3;var retryDelayMs=1000;var silence="data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQAAAAA=";var unlock=async(audio)=>{try{await audio.play()}catch{}};var useReadAloud=(invocationId)=>{const{call}=useChatSession2();const[playback,setPlayback]=useState18({status:"idle"});const reading=useRef3(0);const player=useRef3(null);const quiet=()=>{player.current?.pause();player.current=null};useEffect2(()=>()=>{reading.current+=1;player.current?.pause()},[]);const play=async(audio,partIndex,retries=0)=>{const own=reading.current;const stillReading=()=>own===reading.current;const fail=()=>{if(stillReading()){reading.current+=1;quiet();setPlayback({status:"failed"})}};setPlayback({partIndex,status:"loading"});const result=await call((client)=>client.chatSpeech.getReadAloudPart({params:{invocationId,partIndex}}));if(!stillReading()){return}if(!result.ok){const{code,retryable}=result.error;if(retries<maxRetries&&(code==="conflict"||retryable)){setTimeout(()=>{if(stillReading()){play(audio,partIndex,retries+1)}},retryDelayMs);return}fail();return}const{partCount,url}=result.value;audio.src=url;audio.addEventListener("ended",()=>{if(!stillReading()){return}if(partIndex+1<partCount){play(audio,partIndex+1);return}player.current=null;setPlayback({status:"idle"})},{once:true});audio.addEventListener("error",fail,{once:true});setPlayback({partIndex,status:"playing"});await audio.play().catch(fail)};const toggle=()=>{reading.current+=1;quiet();if(playback.status==="loading"||playback.status==="playing"){setPlayback({status:"idle"});return}const audio=new Audio(silence);player.current=audio;unlock(audio);play(audio,0)};return{playback,toggle}};import{jsx as jsx33,jsxs as jsxs29,Fragment as Fragment11}from"react/jsx-runtime";var ReadAloudIcon=({status})=>{if(status==="loading"){return jsx33(Loader22,{"aria-hidden":"true",className:"animate-spin"})}return status==="playing"?jsx33(Pause,{"aria-hidden":"true"}):jsx33(Play,{"aria-hidden":"true"})};var ReadAloudButton=({labels,playback,toggle})=>{const reading=playback.status==="loading"||playback.status==="playing";const failed=playback.status==="failed";return jsxs29(Fragment11,{children:[jsx33(MessageAction,{"aria-pressed":reading,className:failed?"text-destructive":undefined,label:reading?labels.readAloudStop:labels.readAloud,onClick:toggle,title:failed?labels.readAloudFailed:undefined,children:jsx33(ReadAloudIcon,{...playback})}),jsx33("output",{"aria-live":"polite",className:"sr-only",children:failed?labels.readAloudFailed:""})]})};var ReadAloud=({Control,invocationId,labels,message})=>{const{playback,toggle}=useReadAloud(invocationId);return jsx33("span",{className:"inline-flex items-center","data-part":"read-aloud",children:jsx33(Control,{labels,message,playback,toggle})})};import{Reasoning,ReasoningContent,ReasoningTrigger}from"@collective-intelligence/ui-react/ai-elements";import{jsx as jsx34,jsxs as jsxs30}from"react/jsx-runtime";var ReasoningPart=({labels,part})=>{const streaming=part.state==="streaming";return jsxs30(Reasoning,{className:"mb-0","data-part":"reasoning",defaultOpen:streaming,isStreaming:streaming,children:[jsx34(ReasoningTrigger,{getThinkingMessage:()=>labels.reasoning}),jsx34(ReasoningContent,{children:part.text})]})};import{Bubble,BubbleContent}from"@collective-intelligence/ui-react/ui";import{jsx as jsx35,jsxs as jsxs31}from"react/jsx-runtime";var SteeringMessagePart=({labels,part})=>jsxs31(Bubble,{align:"end","data-part":"steering-message",children:[jsx35(BubbleContent,{className:"whitespace-pre-wrap",children:part.parts.flatMap((content)=>content.type==="text"?[content.text]:[])}),jsx35("span",{className:"text-muted-foreground self-end text-xs",children:labels.steeringMessageSent})]});import{MessageResponse as MessageResponse2}from"@collective-intelligence/ui-react/ai-elements";import{jsx as jsx36}from"react/jsx-runtime";var TextPart=({part})=>jsx36(MessageResponse2,{isAnimating:part.state==="streaming",children:part.text});import{Confirmation,ConfirmationAccepted,ConfirmationAction,ConfirmationActions,ConfirmationRejected,ConfirmationTitle,Tool,ToolContent,ToolHeader,ToolInput,ToolOutput}from"@collective-intelligence/ui-react/ai-elements";import{getToolName}from"ai";import*as Option2 from"effect/Option";import*as Schema3 from"effect/Schema";import{jsx as jsx37,jsxs as jsxs32}from"react/jsx-runtime";var dispatchIntentToolName="dispatch_intent";var decodeIntentCall=Schema3.decodeUnknownOption(Schema3.Struct({fqn:Schema3.String,inputs:Schema3.Record(Schema3.String,Schema3.Json)}));var intentCallOf=(part)=>getToolName(part)===dispatchIntentToolName?decodeIntentCall(part.input):Option2.none();var isText2=Schema3.is(Schema3.String);var shownValue=(value)=>isText2(value)?value:JSON.stringify(value);var ToolPart=({answerApproval,labels,part})=>{const name=getToolName(part);const intentCall=Option2.getOrUndefined(intentCallOf(part));const{approval}=part;const answer=(approved)=>{if(approval!==undefined){answerApproval({approvalId:approval.id,approved})}};return jsxs32("div",{className:"flex flex-col gap-2","data-part":"tool",children:[jsxs32(Tool,{className:"mb-0",children:[part.type==="dynamic-tool"?jsx37(ToolHeader,{state:part.state,toolName:part.toolName,type:part.type}):jsx37(ToolHeader,{state:part.state,type:part.type}),jsxs32(ToolContent,{children:[jsx37(ToolInput,{input:part.input}),jsx37(ToolOutput,{errorText:part.errorText,output:part.output})]})]}),jsxs32(Confirmation,{approval,state:part.state,children:[jsx37(ConfirmationTitle,{children:intentCall===undefined?fillLabel(labels.permissionTitle,{name}):fillLabel(labels.intentApprovalTitle,{name:part.title??intentCall.fqn})}),intentCall!==undefined&&Object.keys(intentCall.inputs).length>0&&jsx37("dl",{"aria-label":labels.intentApprovalInputs,className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs","data-slot":"intent-approval-inputs",children:Object.entries(intentCall.inputs).map(([key,value])=>jsxs32("div",{className:"contents",children:[jsx37("dt",{className:"text-muted-foreground",children:key}),jsx37("dd",{className:"break-words",children:shownValue(value)})]},key))}),jsx37(ConfirmationAccepted,{children:jsx37("p",{className:"text-xs",children:labels.approvalStatusApproved})}),jsx37(ConfirmationRejected,{children:jsx37("p",{className:"text-xs",children:labels.approvalStatusRejected})}),jsxs32(ConfirmationActions,{children:[jsx37(ConfirmationAction,{onClick:()=>{answer(false)},variant:"outline",children:labels.approvalReject}),jsx37(ConfirmationAction,{onClick:()=>{answer(true)},children:labels.approvalApprove})]})]})]})};import{jsx as jsx38}from"react/jsx-runtime";import{createElement as createElement2}from"react";var partRenderersOf=(components={})=>({AnswerFeedback:components.AnswerFeedback??ChatAnswerFeedback,Evidence:components.Evidence??EvidencePart,File:components.File??FilePart,ImageGeneration:components.ImageGeneration??ImageGenerationPart,IntentCard:components.IntentCard??IntentCardMessagePart,MemoryEvidence:components.MemoryEvidence??MemoryEvidencePart,Question:components.Question??QuestionPart,ReadAloud:components.ReadAloud??ReadAloudButton,Reasoning:components.Reasoning??ReasoningPart,SteeringMessage:components.SteeringMessage??SteeringMessagePart,Text:components.Text??TextPart,Tool:components.Tool??ToolPart});var decodeQuestionInput=Schema4.decodeUnknownOption(ciAskUserSchemas2.input);var decodeQuestionOutput=Schema4.decodeUnknownOption(ciAskUserSchemas2.output);var questionOf=(part)=>{if(getToolName2(part)!==ciAskUserToolName2){return Option3.none()}const{toolCallId}=part;const input=decodeQuestionInput(part.input);if(part.state==="input-available"){return input.pipe(Option3.map((value)=>({input:value,output:undefined,toolCallId})))}return part.state==="output-available"?Option3.all({input,output:decodeQuestionOutput(part.output)}).pipe(Option3.map((question)=>({...question,toolCallId}))):Option3.none()};var MessagePart=({answers,labels,message,part,renderers})=>{const base={labels,message};if(isToolUIPart2(part)){const question=questionOf(part);if(Option3.isSome(question)){return jsx38(renderers.Question,{...base,answer:(output)=>{answers.answerQuestion(question.value.toolCallId,output)},part:question.value})}const image=imageGenerationOfPart(part);return Option3.isSome(image)?jsx38(renderers.ImageGeneration,{...base,part:image.value}):jsx38(renderers.Tool,{...base,answerApproval:answers.answerApproval,part})}switch(part.type){case"text":{return jsx38(renderers.Text,{...base,part})}case"reasoning":{return jsx38(renderers.Reasoning,{...base,part})}case"file":{return jsx38(renderers.File,{...base,part})}case"steering-message":{return jsx38(renderers.SteeringMessage,{...base,part})}case"data-evidence":{return jsx38(renderers.Evidence,{...base,part:part.data})}case"data-memory-evidence":{return jsx38(renderers.MemoryEvidence,{...base,part:part.data})}case"data-intent-card":{return jsx38(renderers.IntentCard,{...base,part:part.data})}default:{return null}}};var MessageParts=({message,...props})=>message.parts.map((part,index)=>createElement2(MessagePart,{...props,key:index,message,part}));import{Activity as Activity2}from"@collective-intelligence/ui-react/icons";import{Trace as Trace3,TraceCollapsible as TraceCollapsible2,TraceCollapsibleContent as TraceCollapsibleContent2,TraceCollapsibleTrigger as TraceCollapsibleTrigger2,TraceIcon as TraceIcon3,TraceLine as TraceLine3,TraceTitle as TraceTitle3}from"@collective-intelligence/ui-react/ui";import{useState as useState20}from"react";import{cn as cn13}from"@collective-intelligence/ui-react";import{Activity,AlertCircle,ExternalLink,Link2}from"@collective-intelligence/ui-react/icons";import{Alert as Alert2,AlertDescription as AlertDescription2,Button as Button16,Trace as Trace2,TraceIcon as TraceIcon2,TraceLine as TraceLine2,TraceTitle as TraceTitle2,TraceDescription as TraceDescription2}from"@collective-intelligence/ui-react/ui";import*as Effect2 from"effect/Effect";import{useState as useState19,useSyncExternalStore as useSyncExternalStore2}from"react";import{parseJsonEventStream,readUIMessageStream,uiMessageChunkSchema}from"ai";import*as Effect from"effect/Effect";import{HttpApiClient}from"effect/http-api";import*as Option4 from"effect/Option";import*as Schema5 from"effect/Schema";import*as Stream from"effect/Stream";var loadingRun={errorText:null,failure:null,message:null,status:"loading"};var cutStream=()=>new AiFailureError2({code:"unavailable",message:"The run stream closed before the run ended.",retryable:true});var ended=new Map([["error","failed"],["other","cancelled"],["stop","completed"]]);var statusAfter=(chunk)=>{switch(chunk.type){case"start":{return{status:"running"}}case"error":{return{errorText:chunk.errorText,status:"failed"}}case"finish":{return{status:chunk.finishReason===undefined?"waiting":ended.get(chunk.finishReason)??"completed"}}default:{return}}};var chunksOf2=(body,update)=>parseJsonEventStream({schema:uiMessageChunkSchema,stream:Stream.toReadableStream(body)}).pipeThrough(new TransformStream({transform:(result,controller)=>{if(!result.success){throw result.error}const status=statusAfter(result.value);if(status!==undefined){update(status)}controller.enqueue(result.value)}}));var decodeRunFailure=HttpApiClient.decodeResponse(ChatSurfaceApi2,{endpoint:"streamRun",group:"chat"});var untilAborted=(signal)=>Effect.callback((resume)=>{if(signal.aborted){resume(Effect.succeed("aborted"));return}const onAbort=()=>{resume(Effect.succeed("aborted"))};signal.addEventListener("abort",onAbort,{once:true});return Effect.sync(()=>{signal.removeEventListener("abort",onAbort)})});var readRunStream=(runId,update,signal)=>(client)=>{const read=Effect.gen(function*readRun(){const response=yield*client.chat.streamRun({params:{runId},responseMode:"response-only"});if(response.status!==200){yield*decodeRunFailure(response);return yield*Effect.fail(cutStream())}let told=false;const messages=readUIMessageStream({stream:chunksOf2(response.stream,(state)=>{told||=state.status!=="running";update(state)})});yield*Stream.runForEach(Stream.fromAsyncIterable(messages,toSessionFailure),(message)=>Effect.sync(()=>{update({message})}));if(!told){return yield*Effect.fail(cutStream())}});return Effect.raceFirst(read,untilAborted(signal))};var decodeRunId=Schema5.decodeUnknownOption(InvocationId2);var unknownRun={code:"not_found",message:"The run id is not a run.",retryable:false};var makeRunTraceStore=(runId,call)=>{const id=decodeRunId(runId);let state=Option4.isSome(id)?loadingRun:{...loadingRun,failure:unknownRun};let reading=null;const listeners=new Set;const publish=(next)=>{state=next;for(const listener of listeners){listener()}};const start=()=>{if(Option4.isNone(id)){return}const own=new AbortController;reading=own;const update=(change)=>{if(!own.signal.aborted){publish({...state,...change})}};const read=async()=>{const result=await call(readRunStream(id.value,update,own.signal));if(!result.ok){update({failure:result.error})}};read()};const stop=()=>{reading?.abort();reading=null};return{getSnapshot:()=>state,retry:()=>{stop();publish(loadingRun);start()},subscribe:(listener)=>{listeners.add(listener);if(reading===null&&Option4.isSome(id)){state=loadingRun;start()}return()=>{listeners.delete(listener);if(listeners.size===0){stop()}}}}};import{ToolInput as ToolInput2,ToolOutput as ToolOutput2}from"@collective-intelligence/ui-react/ai-elements";import{Sparkles as Sparkles2,Wrench as Wrench2}from"@collective-intelligence/ui-react/icons";import{Trace,TraceCollapsible,TraceCollapsibleContent,TraceCollapsibleTrigger,TraceDescription,TraceIcon,TraceLine,TraceTitle}from"@collective-intelligence/ui-react/ui";import{getToolName as getToolName3,isToolUIPart as isToolUIPart3}from"ai";import{jsx as jsx39,jsxs as jsxs33}from"react/jsx-runtime";var isActivity=(part)=>isToolUIPart3(part)||part.type==="reasoning";var statusProp=(status)=>status===undefined?{}:{status};var toolStatus=(part,running)=>{switch(part.state){case"output-denied":case"output-error":{return"error"}case"approval-responded":case"input-available":case"input-streaming":{return running?"running":undefined}default:{return}}};var approvalOf=(part,labels)=>{switch(part.state){case"approval-requested":{return labels.approvalStatusPending}case"approval-responded":{return part.approval.approved?labels.approvalStatusApproved:labels.approvalStatusRejected}case"output-denied":{return labels.approvalStatusRejected}default:{return null}}};var ToolLine=({labels,part,running})=>{const approval=approvalOf(part,labels);const errorText=part.state==="output-error"?part.errorText:undefined;const line=jsxs33(TraceLine,{...statusProp(toolStatus(part,running)),children:[jsx39(TraceIcon,{children:jsx39(Wrench2,{})}),jsx39(TraceTitle,{children:getToolName3(part)}),approval===null?null:jsx39(TraceDescription,{children:approval})]});const output=part.state==="output-available"?part.output:undefined;const hasInput=part.input!==undefined&&part.input!==null;const hasOutput=output!==undefined&&output!==null;if(!hasInput&&!hasOutput&&errorText===undefined){return jsx39("div",{"data-part":"run-trace-tool",children:line})}return jsxs33(TraceCollapsible,{"data-part":"run-trace-tool",children:[jsx39(TraceCollapsibleTrigger,{children:line}),jsxs33(TraceCollapsibleContent,{className:"flex flex-col gap-2",children:[hasInput?jsx39(ToolInput2,{input:part.input}):null,jsx39(ToolOutput2,{errorText,output})]})]})};var ReasoningLine=({labels,part,running})=>{const line=jsxs33(TraceLine,{...statusProp(running&&part.state==="streaming"?"running":undefined),children:[jsx39(TraceIcon,{children:jsx39(Sparkles2,{})}),jsx39(TraceTitle,{children:labels.reasoning})]});if(part.text===""){return jsx39("div",{"data-part":"run-trace-reasoning",children:line})}return jsxs33(TraceCollapsible,{"data-part":"run-trace-reasoning",children:[jsx39(TraceCollapsibleTrigger,{children:line}),jsx39(TraceCollapsibleContent,{children:part.text})]})};var shownKinds=new Set(["data-evidence","data-memory-evidence","file","steering-message","text"]);var groupsOf=(parts)=>{const groups=[];let activity=null;for(const part of parts){if(isActivity(part)){if(activity===null){activity=[];groups.push({kind:"activity",parts:activity})}activity.push(part)}else if(shownKinds.has(part.type)){activity=null;groups.push({kind:"part",part})}}return groups};var PartOfRun=({labels,message,part,renderers})=>{const base={labels,message};switch(part.type){case"text":{return jsx39(renderers.Text,{...base,part})}case"file":{return jsx39(renderers.File,{...base,part})}case"steering-message":{return jsx39(renderers.SteeringMessage,{...base,part})}case"data-evidence":{return jsx39(renderers.Evidence,{...base,part:part.data})}case"data-memory-evidence":{return jsx39(renderers.MemoryEvidence,{...base,part:part.data})}default:{return null}}};var RunTraceParts=({labels,message,renderers,running})=>groupsOf(message.parts).map((group,index)=>group.kind==="activity"?jsx39(Trace,{"data-part":"run-trace-steps",children:group.parts.map((part,line)=>part.type==="reasoning"?jsx39(ReasoningLine,{labels,part,running},line):jsx39(ToolLine,{labels,part,running},part.toolCallId))},index):jsx39(PartOfRun,{labels,message,part:group.part,renderers},index));import{jsx as jsx40,jsxs as jsxs34}from"react/jsx-runtime";var lineStatus=(status)=>{if(status==="failed"){return"error"}return status==="loading"||status==="running"?"running":undefined};var statusLabel=(labels,{message,status})=>{const waitsForApproval=message?.parts.some((part)=>("state"in part)&&part.state==="approval-requested")===true;const words={cancelled:labels.runStatusStopped,completed:labels.runStatusCompleted,failed:labels.runStatusFailed,loading:labels.loading,running:labels.runStatusActive,waiting:waitsForApproval?labels.runStatusWaitingForApproval:labels.runStatusNeedsInput};return words[status]};var RunTraceHead=({labels,state})=>{const traceLink=state.message?.metadata?.traceLink;return jsxs34(Trace2,{"data-part":"run-trace-head",children:[jsxs34(TraceLine2,{...statusProp(lineStatus(state.status)),children:[jsx40(TraceIcon2,{children:jsx40(Activity,{})}),jsx40(TraceTitle2,{children:labels.runCardTitle}),jsx40(TraceDescription2,{children:statusLabel(labels,state)})]}),state.errorText===null?null:jsxs34(TraceLine2,{status:"error",children:[jsx40(TraceIcon2,{children:jsx40(AlertCircle,{})}),jsx40(TraceTitle2,{children:state.errorText})]}),traceLink===undefined?null:jsx40("a",{"aria-label":labels.runCardTraceLink,"data-part":"run-trace-link",href:traceLink,rel:"noreferrer",target:"_blank",children:jsxs34(TraceLine2,{children:[jsx40(TraceIcon2,{children:jsx40(Link2,{})}),jsx40(TraceTitle2,{children:labels.runCardTraceLink}),jsx40(TraceIcon2,{children:jsx40(ExternalLink,{})})]})})]})};var RunTraceView=({call,className,labels,locale="en",messageParts,runId})=>{const[store]=useState19(()=>makeRunTraceStore(runId,call));const state=useSyncExternalStore2(store.subscribe,store.getSnapshot,store.getSnapshot);const shown=labelsOf(locale,labels);return jsx40(ChatRoot,{className:"h-auto",children:jsxs34("div",{className:cn13("flex min-w-0 flex-col gap-3",className),"data-part":"run-trace",children:[jsx40(RunTraceHead,{labels:shown,state}),state.failure===null?null:jsxs34(Alert2,{variant:"destructive",children:[jsx40(AlertCircle,{}),jsxs34(AlertDescription2,{className:"flex items-center justify-between gap-3",children:[jsx40("span",{children:shown.actionFailed}),state.failure.retryable?jsx40(Button16,{onClick:()=>{store.retry()},size:"sm",type:"button",variant:"outline",children:shown.retry}):null]})]}),state.message===null?null:jsx40(RunTraceParts,{labels:shown,message:state.message,renderers:partRenderersOf(messageParts),running:state.status==="running"})]})})};var SessionRunTrace=(props)=>{const{call}=useChatSession2();return jsx40(RunTraceView,{...props,call})};var callOn=(api)=>{const runtime=makeChatSessionRuntime(api);return(operation)=>runtime.runPromise(Effect2.match(callChatSurface(operation),{onFailure:({error})=>({error,ok:false}),onSuccess:(value)=>({ok:true,value})}))};var MountRunTrace=({api,...props})=>{const[call]=useState19(()=>callOn(api));return jsx40(RunTraceView,{...props,call})};var RunTrace=({api,...props})=>api===undefined?jsx40(SessionRunTrace,{...props},props.runId):jsx40(MountRunTrace,{api,...props},props.runId);import{jsx as jsx41,jsxs as jsxs35}from"react/jsx-runtime";var MessageRun=({labels,locale,messageParts,runId})=>{const[open,setOpen]=useState20(false);return jsx41(Trace3,{"data-part":"message-run",children:jsxs35(TraceCollapsible2,{onOpenChange:setOpen,open,children:[jsx41(TraceCollapsibleTrigger2,{children:jsxs35(TraceLine3,{children:[jsx41(TraceIcon3,{children:jsx41(Activity2,{})}),jsx41(TraceTitle3,{children:fillLabel(labels.runCardDetail,{id:runId.slice(0,8)})})]})}),jsx41(TraceCollapsibleContent2,{children:open?jsx41(RunTrace,{labels,locale,messageParts,runId}):null})]})})};import{jsx as jsx42}from"react/jsx-runtime";var SentTrail=({labels,message})=>{const{enabled,visible}=useTrailSwitches();if(!enabled||!visible){return null}return jsx42(TrailChips,{entries:message.metadata?.turnOptions?.contextTrail??[],labels,region:labels.trailSent})};import{useEffect as useEffect3}from"react";var imageReloadMs=2000;var useImageReload=({messages,readMessages,streaming})=>{const waiting=!streaming&&imagePending(messages);useEffect3(()=>{if(!waiting){return}const timer=setInterval(readMessages,imageReloadMs);return()=>{clearInterval(timer)}},[readMessages,waiting])};import{jsx as jsx43,jsxs as jsxs36}from"react/jsx-runtime";var isInvocationId=Schema6.is(InvocationId2);var answeredTurn=(message,streaming)=>{const invocationId=message.metadata?.invocationId;return message.role==="assistant"&&!streaming&&isInvocationId(invocationId)?invocationId:null};var ratableTurn=(message,streaming)=>{const target=message.metadata?.feedbackTargetId;return isInvocationId(target)&&answeredTurn(message,streaming)!==null?target:null};var readableTurn=(message,streaming)=>message.parts.some((part)=>part.type==="text")?answeredTurn(message,streaming):null;var useReadAloudAvailable=()=>{const{result}=useChatRead((client)=>client.chatSpeech.getSpeechAvailability());return result?.ok===true&&result.value.readAloud};var useAnswers=()=>{const{addToolApprovalResponse,addToolOutput,sendMessage}=useCiChat2();const[,startAnswer]=useTransition3();return{answerApproval:({approvalId,approved})=>{startAnswer(async()=>{await addToolApprovalResponse({approved,id:approvalId})})},answerQuestion:(toolCallId,output)=>{startAnswer(async()=>{await addToolOutput({output,tool:ciAskUserToolName2,toolCallId});await sendMessage()})}}};var TranscriptMessage=({answers,labels,locale,message,messageParts,readAloud,renderers,slots,streaming})=>{const run=answeredTurn(message,streaming);const turn=readAloud?readableTurn(message,streaming):null;const rated=ratableTurn(message,streaming);return jsxs36(Message,{from:message.role,children:[jsx43(MessageContent,{children:jsx43(MessageParts,{answers,labels,message,renderers})}),message.role==="user"?jsx43(SentTrail,{labels,message}):null,run===null?null:jsx43(MessageRun,{labels,locale,messageParts,runId:run}),turn===null&&rated===null?null:jsxs36(MessageActions,{children:[rated===null?null:jsx43(AnswerFeedback,{Control:renderers.AnswerFeedback,invocationId:rated,labels,message},rated),turn===null?null:jsx43(ReadAloud,{Control:renderers.ReadAloud,invocationId:turn,labels,message})]}),slots.messageFooter?.(message)]})};var ChatTranscript=({className,labels,locale,messageParts,slots})=>{const{messages,status}=useCiChat2();const{readMessages}=useChatSession2();const readAloud=useReadAloudAvailable();const answers=useAnswers();const renderers=partRenderersOf(messageParts);const last=messages.at(-1);const answering=status==="streaming"||status==="submitted";useImageReload({messages,readMessages,streaming:answering});return jsxs36(Conversation,{className:cn14("min-h-0",className),"data-part":"chat-transcript",children:[jsxs36(ConversationContent,{className:"mx-auto w-full max-w-[900px]",children:[messages.length===0?slots.emptyState??jsx43(ConversationEmptyState,{description:labels.emptyDescription,title:labels.emptyTitle}):messages.map((message)=>jsx43(ConversationItem,{scrollAnchor:message.role==="user",children:jsx43(TranscriptMessage,{answers,labels,locale,message,messageParts,readAloud,renderers,slots,streaming:answering&&message===last})},message.id)),slots.transcriptFooter]}),jsx43(ConversationScrollButton,{})]})};import{jsx as jsx44,jsxs as jsxs37,Fragment as Fragment12}from"react/jsx-runtime";var noSlots={};var noClassNames={};var agentChoiceOf=(pinnedAgentId,plainChat)=>{if(pinnedAgentId!==undefined){return"pinned"}return plainChat?"optional":"required"};var agentRequired={code:"invalid_request",message:"Pick an agent to start a chat.",retryable:false};var partsOf=(components)=>({Blocked:components?.ChatBlockedState??ChatBlockedState,Composer:components?.ChatComposer??ChatComposer,Header:components?.ChatHeader??ChatHeader,Sidebar:components?.ConversationSidebar??ConversationSidebar,Transcript:components?.ChatTranscript??ChatTranscript,composerParts:components?.composerParts,messageParts:components?.messageParts});var ChatLayout=({base,classNames,historyScope,id,onLaunch,parts:{Composer,Header,composerParts,messageParts,Sidebar,Transcript},pinnedAgentId,place,plainChat,preferred})=>{const session=useChatSession2();const projects=useChatProjects();const history=useChatHistory({historyScope,labels:base.labels,place,placeContext:session.placeContext});const[listOpen,setListOpen]=useState21(false);const newChat=(options={})=>{projects.leaveProject();setListOpen(false);session.newChat(pinnedAgentId===undefined?options:{...options,agentId:pinnedAgentId})};useChatLaunchTarget2({id,onLaunch,preferred,session:{...session,newChat:(options)=>{projects.leaveProject();session.newChat(options)},pinnedAgentId,plainChat}});const send=({agentId:picked,...submit})=>{if(session.conversationId===null){const agentId=pinnedAgentId??picked;if(agentId===undefined&&!plainChat){return{error:agentRequired,ok:false}}if(agentId!==undefined){const{capabilities}=session;session.newChat({agentId,...projects.viewedId!==undefined&&{projectId:projects.viewedId}});session.setCapabilities(capabilities)}}session.submit(submit);return{ok:true,value:undefined}};const selectConversation=(conversationId)=>{projects.leaveProject();setListOpen(false);session.selectConversation(conversationId)};const partProps={...base,newChat,send};const sidebarProps={...partProps,history,projects,selectConversation};return jsxs37(Fragment12,{children:[jsx44(Sidebar,{...sidebarProps,className:cn15("hidden @3xl/chat:flex",classNames.ConversationSidebar)}),jsxs37("section",{className:"flex min-h-0 min-w-0 flex-1 flex-col",children:[jsx44(Header,{...partProps,className:classNames.ChatHeader,openConversations:()=>{setListOpen(true)}}),projects.viewed===undefined?jsx44(Transcript,{...partProps,className:classNames.ChatTranscript,messageParts}):jsx44(ProjectView,{history,labels:base.labels,locale:base.locale,newChat,project:projects.viewed,projects,selectConversation}),jsx44(Composer,{...partProps,className:classNames.ChatComposer,composerParts})]}),jsx44(Sheet,{onOpenChange:setListOpen,open:listOpen,children:jsxs37(SheetContent,{className:"w-[320px] p-0",side:"left",children:[jsxs37(SheetHeader,{className:"border-b border-border",children:[jsx44(SheetTitle,{children:base.labels.conversations}),jsx44(SheetDescription,{children:base.labels.conversationsDescription})]}),jsx44(Sidebar,{...sidebarProps,className:cn15("w-full flex-1 border-r-0",classNames.ConversationSidebar)})]})})]})};var Chat=({classNames=noClassNames,components,historyScope,id,labels,locale="en",onLaunch,pinnedAgentId,place,plainChat=true,preferred,slots=noSlots})=>{const{blocked,newChat}=useChatSession2();const ownId=useId5();const parts=partsOf(components);const base={agentChoice:agentChoiceOf(pinnedAgentId,plainChat),labels:labelsOf(locale,labels),locale,slots};return jsx44(ChatRoot,{children:jsx44("div",{className:cn15("@container/chat flex size-full overflow-hidden bg-background text-foreground",classNames.Chat),"data-part":"chat",children:blocked===null?jsx44(ChatLayout,{base,classNames,historyScope,id:id??ownId,onLaunch,parts,pinnedAgentId:pinnedAgentId===undefined?undefined:AgentId2.make(pinnedAgentId),place,plainChat,preferred}):jsx44(parts.Blocked,{...base,blocked,className:classNames.ChatBlockedState,newChat,send:()=>({error:blocked.error,ok:false})})})})};import{ResizableHandle,ResizablePanel,ResizablePanelGroup}from"@collective-intelligence/ui-react/ui";import{createContext,useCallback,useContext,useEffect as useEffect5,useId as useId6,useMemo,useRef as useRef4,useState as useState22}from"react";import{useEffect as useEffect4}from"react";var combinationPattern=/^(?<modifiers>(?:(?:alt|ctrl|meta|shift)\+)*)(?<key>.+)$/iu;var combinationOf=(shortcut)=>{const groups=combinationPattern.exec(shortcut.toLowerCase())?.groups;const modifiers=new Set(groups?.modifiers?.split("+"));return{alt:modifiers.has("alt"),ctrl:modifiers.has("ctrl"),key:groups?.key??"",meta:modifiers.has("meta"),shift:modifiers.has("shift")}};var hasNoCase=(key)=>key.length===1&&key.toLowerCase()===key.toUpperCase();var pressesKey=(combination,event)=>event.key.toLowerCase()===combination.key||combination.alt&&event.code===`Key${combination.key.toUpperCase()}`;var isPress=(combination,event)=>pressesKey(combination,event)&&event.altKey===combination.alt&&event.ctrlKey===combination.ctrl&&event.metaKey===combination.meta&&(event.shiftKey===combination.shift||!combination.shift&&hasNoCase(combination.key));var useShortcut=(shortcut,onPress)=>{useEffect4(()=>{const combination=combinationOf(shortcut);const onKeyDown=(event)=>{if(event.repeat||!isPress(combination,event)){return}event.preventDefault();onPress()};window.addEventListener("keydown",onKeyDown);return()=>{window.removeEventListener("keydown",onKeyDown)}},[onPress,shortcut])};import{jsx as jsx45,jsxs as jsxs38}from"react/jsx-runtime";var AssistantSidebarContext=createContext(undefined);var useAssistantSidebar=()=>{const state=useContext(AssistantSidebarContext);if(state===undefined){throw new Error("Render AssistantSidebar and AssistantSidebarToggle inside an AssistantSidebarLayout.")}return state};var composerInput='[data-part="chat-composer"] textarea:not(:disabled)';var AssistantSidebarLayout=({children,className,sessions,shortcuts,sidebar})=>{const[panelState,setPanelState]=useState22(()=>{const opened=sessions?.readAssistantSidebarOpen?.()??false;return{defaultSize:opened?"30":"0",open:opened}});const{open}=panelState;const latestOpen=useRef4(open);const panel=useRef4(null);const content=useRef4(null);const opener=useRef4(null);const cancelFocus=useRef4(undefined);const controlsId=useId6();const returnFocus=useCallback(()=>{if(!content.current?.contains(document.activeElement)){return}const toggle=[...document.querySelectorAll("[aria-controls]")].find((element)=>element.getAttribute("aria-controls")===controlsId);const target=toggle??opener.current;if(target instanceof HTMLElement){target.focus()}},[controlsId]);const setOpen=useCallback((next)=>{if(next===latestOpen.current){return}latestOpen.current=next;setPanelState((current)=>({...current,open:next}));sessions?.writeAssistantSidebarOpen?.(next);if(next){opener.current=document.activeElement;panel.current?.expand()}else{cancelFocus.current?.();returnFocus();panel.current?.collapse()}},[returnFocus,sessions]);const toggle=useCallback(()=>{setOpen(!latestOpen.current)},[setOpen]);const focusComposer=useCallback(()=>{cancelFocus.current?.();setOpen(true);const root=content.current;const focused=()=>{const input=root?.querySelector(composerInput);input?.focus();return input!==undefined&&document.activeElement===input};if(root===null||focused()){return}const observer=new MutationObserver(()=>{if(focused()){cancelFocus.current?.()}});observer.observe(root,{attributeFilter:["disabled","hidden"],childList:true,subtree:true});cancelFocus.current=()=>{observer.disconnect();cancelFocus.current=undefined}},[setOpen]);useEffect5(()=>()=>{cancelFocus.current?.()},[]);useShortcut(shortcuts?.toggle??"Ctrl+J",toggle);useShortcut(shortcuts?.focusComposer??"Ctrl+/",focusComposer);const state=useMemo(()=>({controlsId,open,setOpen}),[controlsId,open,setOpen]);return jsx45(AssistantSidebarContext.Provider,{value:state,children:jsxs38(ResizablePanelGroup,{className,orientation:"horizontal",children:[jsx45(ResizablePanel,{className:"min-w-0",children}),jsx45(ResizableHandle,{className:open?undefined:"hidden",disabled:!open}),jsx45(ResizablePanel,{collapsedSize:0,collapsible:true,defaultSize:panelState.defaultSize,maxSize:"50",minSize:"25",onResize:(size,_id,before)=>{if(before!==undefined){setOpen(size.asPercentage>0)}},panelRef:panel,children:jsx45("div",{className:"h-full w-full",hidden:!open,id:controlsId,ref:content,children:sidebar})})]})})};import{jsx as jsx46,jsxs as jsxs39}from"react/jsx-runtime";var SidebarTitle=createContext2("");var AssistantSidebarHeader=({className,labels,newChat,openConversations})=>{const title=useContext2(SidebarTitle);const{setOpen}=useAssistantSidebar();const session=useChatSession2();const dialogs=useConversationDialogs({onDeletedOpen:newChat,onSelect:session.selectConversation,projects:undefined});const conversation=session.conversations.find(({id})=>id===session.conversationId);return jsxs39("header",{className:cn16("flex min-h-14 items-center gap-1 border-b border-border bg-background px-3",className),"data-part":"assistant-sidebar-header",children:[jsx46(Button17,{"aria-haspopup":"dialog","aria-label":labels.openConversationList,className:"@3xl/chat:hidden",onClick:openConversations,size:"icon",variant:"ghost",children:jsx46(History,{className:"size-4"})}),jsx46("h2",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-foreground",children:title}),jsx46(Button17,{"aria-label":labels.assistantSidebarDelete,disabled:conversation===undefined,onClick:()=>{if(conversation!==undefined){dialogs.actions.onDelete(conversation)}},size:"icon",variant:"ghost",children:jsx46(Trash24,{className:"size-4"})}),jsx46(Button17,{"aria-label":labels.assistantSidebarCollapse,onClick:()=>{setOpen(false)},size:"icon",variant:"ghost",children:jsx46(ChevronRight2,{className:"size-4"})}),jsx46(ConversationDialogs,{dialogs,labels:{...labels,deleteConversation:labels.assistantSidebarDeleteTitle}})]})};var sidebarParts={ChatHeader:AssistantSidebarHeader};var AssistantSidebar=({title,...chatProps})=>{const{setOpen}=useAssistantSidebar();return jsx46(SidebarTitle.Provider,{value:title,children:jsx46("aside",{"aria-label":title,className:"h-full border-l border-border","data-part":"assistant-sidebar",children:jsx46(Chat,{...chatProps,components:sidebarParts,onLaunch:()=>{setOpen(true)},preferred:true})})})};import{Sparkles as Sparkles3}from"@collective-intelligence/ui-react/icons";import{Button as Button18}from"@collective-intelligence/ui-react/ui";import{jsx as jsx47}from"react/jsx-runtime";var AssistantSidebarToggle=({className,labels,locale="en"})=>{const{controlsId,open,setOpen}=useAssistantSidebar();return jsx47(Button18,{"aria-controls":controlsId,"aria-expanded":open,"aria-label":labels?.assistantSidebarToggle??chatLabels[locale].assistantSidebarToggle,className,"data-slot":"assistant-sidebar-toggle",onClick:()=>{setOpen(!open)},size:"icon",type:"button",variant:"ghost",children:jsx47(Sparkles3,{className:"size-4"})})};import{cn as cn17}from"@collective-intelligence/ui-react";import{MessageSquarePlus}from"@collective-intelligence/ui-react/icons";import{Button as Button19}from"@collective-intelligence/ui-react/ui";import{useEffect as useEffect6,useState as useState23}from"react";import{HttpClient,HttpClientRequest}from"effect/http";import*as Option5 from"effect/Option";import*as Schema7 from"effect/Schema";var chatSubjectHeaderName="x-chat-subject";var chatSubjectHeaderValue=({id,kind})=>`${kind}:${id}`;var withSubjectApi=(api,subject)=>({...api,transformClient:(client)=>HttpClient.mapRequestInput(api.transformClient===undefined?client:api.transformClient(client),HttpClientRequest.setHeader(chatSubjectHeaderName,chatSubjectHeaderValue(subject)))});var decodeDraftUpdate=Schema7.decodeUnknownOption(ciDataPartSchemas2["draft-update"]);var sameSubject=(update,subject)=>update.subject.kind===subject.kind&&update.subject.id===subject.id;var watchDraftUpdates=(stream,subject,onDraftUpdate)=>stream.pipeThrough(new TransformStream({transform:(chunk,controller)=>{if(chunk.type==="data-draft-update"){const update=decodeDraftUpdate(chunk.data);if(Option5.isSome(update)&&sameSubject(update.value,subject)){onDraftUpdate(update.value)}}controller.enqueue(chunk)}}));var withSubjectHeader=(headers,subject)=>({...Object.fromEntries(new Headers(headers).entries()),[chatSubjectHeaderName]:chatSubjectHeaderValue(subject)});var withSubjectTransport=(transport,subject,onDraftUpdate)=>({onResumeEmpty:transport.onResumeEmpty,reconnectToStream:async(request)=>{const stream=await transport.reconnectToStream({...request,headers:withSubjectHeader(request.headers,subject)});return stream===null?null:watchDraftUpdates(stream,subject,onDraftUpdate)},resumeStreamIsReplay:transport.resumeStreamIsReplay??false,sendMessages:async(request)=>watchDraftUpdates(await transport.sendMessages({...request,headers:withSubjectHeader(request.headers,subject)}),subject,onDraftUpdate)});import{jsx as jsx48,jsxs as jsxs40,Fragment as Fragment13}from"react/jsx-runtime";var noHost={};var noSlots2={};var noClassNames2={};var ChatDockHeader=({className,labels,newChat,slots})=>{const session=useChatSession2();const{conversationId}=session;const title=conversationId===null?labels.newChat:session.conversations.find(({id})=>id===conversationId)?.title??"";return jsxs40("header",{className:cn17("flex flex-col border-b border-border bg-background",className),"data-part":"chat-dock-header",children:[jsxs40("div",{className:"flex min-h-12 items-center justify-between gap-2 px-4",children:[jsx48("h2",{className:"truncate text-sm font-semibold text-foreground",children:title}),jsxs40("div",{className:"flex shrink-0 items-center gap-2",children:[jsx48(Button19,{"aria-label":labels.newChat,onClick:()=>{newChat()},size:"icon",type:"button",variant:"outline",children:jsx48(MessageSquarePlus,{})}),slots.headerActions]})]}),session.failure===null?null:jsxs40("div",{className:"flex items-center justify-between gap-3 border-t border-border px-4 py-2 text-sm text-destructive",role:"alert",children:[jsx48("span",{children:failureText(session.failure,labels)}),jsx48(Button19,{onClick:()=>{session.retry()},size:"sm",type:"button",variant:"outline",children:labels.retry})]})]})};var DockView=({agentId,classNames=noClassNames2,components,labels,locale="en",slots=noSlots2})=>{const session=useChatSession2();const Header=components?.ChatDockHeader??ChatDockHeader;const Transcript=components?.ChatTranscript??ChatTranscript;const Composer=components?.ChatComposer??ChatComposer;const Blocked=components?.ChatBlockedState??ChatBlockedState;const newChat=(options={})=>{session.newChat({...options,agentId})};const send=({agentId:_picked,...submit})=>{if(session.conversationId===null){const{capabilities}=session;session.newChat({agentId});session.setCapabilities(capabilities)}session.submit(submit);return{ok:true,value:undefined}};const partProps={agentChoice:"pinned",labels:labelsOf(locale,labels),locale,newChat,send,slots};const{blocked}=session;return jsx48(ChatRoot,{children:jsx48("div",{className:cn17("@container/chat flex size-full flex-col overflow-hidden bg-background text-foreground",classNames.ChatDock),"data-part":"chat-dock",children:blocked===null?jsxs40(Fragment13,{children:[jsx48(Header,{...partProps,className:classNames.ChatDockHeader}),jsx48(Transcript,{...partProps,className:classNames.ChatTranscript,messageParts:components?.messageParts}),jsx48(Composer,{...partProps,className:classNames.ChatComposer})]}):jsx48(Blocked,{...partProps,blocked,className:classNames.ChatBlockedState,send:()=>({error:blocked.error,ok:false})})})})};var makeDraftUpdates=()=>{const listeners=new Set;return{emit:(update)=>{for(const listener of listeners){listener(update)}},subscribe:(listener)=>{listeners.add(listener);return()=>{listeners.delete(listener)}}}};var DockSession=({api,host=noHost,onDraftUpdate,pinnedAgentId,place,subject,transport,...view})=>{const[mount]=useState23(()=>{const updates=makeDraftUpdates();const{sessions:_sessions,...ports}=host;return{api:withSubjectApi(api,subject),host:ports,transport:withSubjectTransport(transport,subject,updates.emit),updates}});const{updates}=mount;useEffect6(()=>onDraftUpdate===undefined?undefined:updates.subscribe(onDraftUpdate),[onDraftUpdate,updates]);return jsx48(ChatSessionProvider2,{api:mount.api,host:mount.host,place,subject,transport:mount.transport,children:jsx48(DockView,{...view,agentId:AgentId2.make(pinnedAgentId)})})};var ChatDock=(props)=>jsx48(DockSession,{...props},chatSubjectHeaderValue(props.subject));import{cn as cn18}from"@collective-intelligence/ui-react";import{Button as Button20,Checkbox,Input as Input4,Label as Label3,Select,SelectContent,SelectItem,SelectTrigger,SelectValue,Textarea as Textarea3}from"@collective-intelligence/ui-react/ui";import{useCallback as useCallback2,useId as useId7,useMemo as useMemo2,useState as useState24}from"react";var isObject=(value)=>hasObjectRuntimeKind2(value)&&!hasNullRuntimeKind2(value)&&!Array.isArray(value);var textOf2=(value)=>hasStringRuntimeKind2(value)?value:undefined;var stringsOf=(value)=>{if(!Array.isArray(value)){return}const strings=value.filter((item)=>hasStringRuntimeKind2(item));return strings.length===value.length?strings:undefined};var kindOf=(property)=>{const options=stringsOf(property["enum"]);if(options!==undefined&&options.length>0){return{kind:"choice",options}}switch(property["type"]){case"boolean":{return{kind:"boolean"}}case"integer":case"number":{return{kind:"number"}}case"string":{return{kind:property["format"]==="date"?"date":"text"}}default:{return{kind:"json"}}}};var fieldsOf=(schema)=>{const{properties,required:requiredNames}=schema;if(!isObject(properties)){return[]}const required=new Set(stringsOf(requiredNames));return Object.entries(properties).map(([name,value])=>{const property=isObject(value)?value:{};return{...kindOf(property),description:textOf2(property["description"]),label:textOf2(property["title"])??name,name,required:required.has(name)}})};var draftValueOf=(field,value)=>{switch(field.kind){case"boolean":{return value===true}case"json":{return value===undefined?"":JSON.stringify(value,null,2)}default:{return hasStringRuntimeKind2(value)||hasNumberRuntimeKind2(value)?String(value):""}}};var draftOf=(fields,values)=>Object.fromEntries(fields.map((field)=>[field.name,draftValueOf(field,values[field.name])]));var parseJson=(text)=>{try{const value=JSON.parse(text);return{kind:"value",value}}catch{return{kind:"unparsed"}}};var parseField=(field,draft)=>{if(field.kind==="boolean"){return{kind:"value",value:draft===true}}const text=hasStringRuntimeKind2(draft)?draft:"";if(text.trim()===""){return{kind:"empty"}}if(field.kind==="json"){return parseJson(text)}if(field.kind!=="number"){return{kind:"value",value:text}}const number=Number(text.trim());return{kind:"value",value:Number.isFinite(number)?number:text}};var inputsOf=(fields,draft,values)=>{const names=new Set(fields.map((field)=>field.name));const parsed=fields.map((field)=>[field.name,parseField(field,draft[field.name])]);const unparsed=parsed.flatMap(([name,value])=>value.kind==="unparsed"?[name]:[]);if(unparsed.length>0){return{unparsed}}return{inputs:Object.fromEntries([...Object.entries(values).filter(([name])=>!names.has(name)),...parsed.flatMap(([name,value])=>value.kind==="value"?[[name,value.value]]:[])])}};var fieldNameOf=(path)=>(path.split("/")[1]??"").replaceAll("~1","/").replaceAll("~0","~");var problemsByField=(fields,problems)=>{const names=new Set(fields.map((field)=>field.name));const byField=new Map;for(const problem of problems){const name=fieldNameOf(problem.path);const key=names.has(name)?name:"";byField.set(key,[...byField.get(key)??[],problem])}return byField};var defaultIntentLabels={choose:"Choose…",dispatched:"Dispatched",done:"Done",failed:"Failed",invalid:"Invalid",invalidJson:"Enter valid JSON",missing:"Required",noChat:"No chat is available",notAllowed:"Not allowed",submit:"Send",working:"Working…"};import{jsx as jsx49,jsxs as jsxs41}from"react/jsx-runtime";var noProblems=[];var noValues={};var FieldControl=({describedBy,disabled,field,id,invalid,labels,onChange,value})=>{const text=hasStringRuntimeKind2(value)?value:"";const common={"aria-describedby":describedBy,"aria-invalid":invalid,"aria-required":field.required?true:undefined,disabled,id};if(field.kind==="boolean"){return jsx49(Checkbox,{...common,checked:value===true,onCheckedChange:(checked)=>{onChange(checked===true)}})}if(field.kind==="choice"){return jsxs41(Select,{disabled,onValueChange:(choice)=>{onChange(choice??"")},value:text,children:[jsx49(SelectTrigger,{...common,children:jsx49(SelectValue,{placeholder:labels.choose})}),jsx49(SelectContent,{children:field.options.map((option)=>jsx49(SelectItem,{value:option,children:option},option))})]})}if(field.kind==="json"){return jsx49(Textarea3,{...common,className:"font-mono",onChange:(event)=>{onChange(event.target.value)},value:text})}return jsx49(Input4,{...common,onChange:(event)=>{onChange(event.target.value)},type:field.kind,value:text})};var IntentFormFields=({className,disabled=false,entry,labels,onSubmit,problems=noProblems,values=noValues})=>{const id=useId7();const fields=useMemo2(()=>fieldsOf(entry.inputSchema),[entry.inputSchema]);const[draft,setDraft]=useState24(()=>draftOf(fields,values));const[unparsed,setUnparsed]=useState24([]);const text={...defaultIntentLabels,...labels};const byField=problemsByField(fields,problems);const formProblems=byField.get("")??[];const focusFirstMark=useCallback2((node)=>{if(node!==null&&problems.length>0){const first=node.querySelector('[aria-invalid="true"]')??node.querySelector("[aria-invalid]");first?.focus()}},[problems]);const submit=(event)=>{event.preventDefault();const answer=inputsOf(fields,draft,values);if("unparsed"in answer){setUnparsed(answer.unparsed);return}setUnparsed([]);onSubmit(answer.inputs)};return jsxs41("form",{className:cn18("grid gap-4",className),"data-slot":"intent-form",noValidate:true,onSubmit:submit,ref:focusFirstMark,children:[formProblems.length>0&&jsx49("ul",{className:"text-destructive grid gap-1 text-sm",children:formProblems.map(({path,reason})=>jsx49("li",{children:reason},`${path}:${reason}`))}),fields.map((field)=>{const fieldProblems=byField.get(field.name)??[];const notJson=unparsed.includes(field.name);const mark=notJson?"invalid":fieldProblems.find(({problem})=>problem==="missing")?.problem??fieldProblems[0]?.problem;const controlId=`${id}-${field.name}`;const descriptionId=`${controlId}-description`;const messageId=`${controlId}-message`;const describedBy=[field.description===undefined?"":descriptionId,mark===undefined?"":messageId].filter(Boolean).join(" ");return jsxs41("div",{className:"grid gap-2","data-problem":mark,"data-slot":"intent-field",children:[jsxs41(Label3,{htmlFor:controlId,children:[field.label,field.required&&jsx49("span",{"aria-hidden":"true",children:"*"})]}),field.description!==undefined&&jsx49("p",{className:"text-muted-foreground text-sm",id:descriptionId,children:field.description}),jsx49(FieldControl,{describedBy:describedBy===""?undefined:describedBy,disabled,field,id:controlId,invalid:mark!==undefined,labels:text,onChange:(value)=>{setDraft((current)=>({...current,[field.name]:value}))},value:draft[field.name]}),mark!==undefined&&jsxs41("div",{className:"text-destructive grid gap-1 text-sm",id:messageId,children:[notJson&&jsx49("p",{children:text.invalidJson}),fieldProblems.map(({path,problem,reason})=>jsxs41("p",{children:[jsx49("span",{className:"font-medium",children:problem==="missing"?text.missing:text.invalid})," ",jsx49("span",{children:reason})]},`${path}:${reason}`))]})]},field.name)}),jsx49(Button20,{className:"justify-self-start",disabled,type:"submit",children:text.submit})]})};var IntentForm=({fqn,...props})=>{const{enabled,list}=useIntents2();const entry=list.data?.find((candidate)=>candidate.fqn===fqn);if(!enabled||entry===undefined){return null}return jsx49(IntentFormFields,{entry,...props})};import{Alert as Alert3,AlertDescription as AlertDescription3,AlertTitle,Button as Button21}from"@collective-intelligence/ui-react/ui";import{useSyncExternalStore as useSyncExternalStore3}from"react";import{jsx as jsx50,jsxs as jsxs42}from"react/jsx-runtime";var intentNoticeLabels={en:{dismiss:"Dismiss",done:"Done",failed:"Failed",region:"Intent results"},it:{dismiss:"Chiudi",done:"Completato",failed:"Non riuscito",region:"Risultati degli Intent"}};var corner={insetBlockEnd:"1rem",insetInlineEnd:"1rem",position:"fixed",zIndex:50};var outcomeText=({outcome},labels)=>outcome.kind==="completed"?labels.done:`${labels.failed}: ${outcome.reason}`;var IntentNotices=({labels:custom,locale="en"})=>{const{registry}=useIntentsScope2();const labels={...intentNoticeLabels[locale],...custom};const notices=useSyncExternalStore3(registry.subscribe,registry.notices,registry.notices);if(notices.length===0){return null}return jsx50("div",{style:corner,children:jsx50(ChatRoot,{className:"size-auto",children:jsx50("section",{"aria-label":labels.region,className:"grid w-80 gap-2",children:notices.map((notice)=>jsxs42(Alert3,{variant:notice.outcome.kind==="failed"?"destructive":"default",children:[jsx50(AlertTitle,{children:notice.displayName}),jsxs42(AlertDescription3,{children:[outcomeText(notice,labels),jsx50(Button21,{onClick:()=>{registry.dismiss(notice.id)},size:"sm",type:"button",variant:"ghost",children:labels.dismiss})]})]},notice.id))})})})};import{cn as cn19}from"@collective-intelligence/ui-react";import{Button as Button22}from"@collective-intelligence/ui-react/ui";import{useId as useId8,useRef as useRef5,useState as useState25}from"react";import{jsx as jsx51,jsxs as jsxs43}from"react/jsx-runtime";var noInputs={};var statusOf2=({error,outcome,state},labels)=>{if(state==="working"){return labels.working}if(error!==undefined){return`${labels.failed}: ${error.message}`}switch(outcome?.kind){case"completed":{return labels.done}case"started":{return labels.dispatched}case"failed":{return`${labels.failed}: ${outcome.reason}`}case"not_allowed":{return labels.notAllowed}default:{return}}};var useListedIntent=(fqn)=>{const{enabled,list}=useIntents2();const displayName=list.data?.find((entry)=>entry.fqn===fqn)?.displayName;return{displayName,enabled}};var LaunchTrigger=({children,className,fqn,inputs=noInputs,labels})=>{const{displayName,enabled}=useListedIntent(fqn);const launch=useLaunch2();const launchable=useHasLaunchTarget2();const reasonId=useId8();if(!enabled){return null}return jsxs43("div",{className:cn19("grid gap-2",className),"data-slot":"intent-trigger",children:[jsx51(Button22,{"aria-describedby":launchable?undefined:reasonId,className:"justify-self-start",disabled:!launchable,onClick:()=>{launch({fqn,inputs,kind:"intent"})},type:"button",children:children??displayName??fqn}),!launchable&&jsx51("p",{className:"text-muted-foreground text-sm",id:reasonId,children:labels?.noChat??defaultIntentLabels.noChat})]})};var DispatchTrigger=(props)=>{const{children,className,fqn,inputs=noInputs,labels,onResult,render}=props;const{displayName,enabled}=useListedIntent(fqn);const intent=useIntentDispatch2(fqn,props);const[sent,setSent]=useState25(inputs);const{registry}=useIntentsScope2();const container=useRef5(null);const delivered=useRef5(undefined);const started=useRef5(undefined);const ends=useRef5(new Map);const deliver=(notice)=>{if(notice!==delivered.current&¬ice.outcome.kind==="completed"){delivered.current=notice;onResult?.(notice.outcome.result)}};useIntentResult2(fqn,(notice)=>{if(notice.handle!==undefined){ends.current.set(notice.handle,notice)}if(notice===registry.adopted(fqn)||notice.handle!==undefined&¬ice.handle===started.current){deliver(notice)}});if(!enabled){return null}const text={...defaultIntentLabels,...labels};const run=async(values)=>{setSent(values);const answer=await intent.dispatch(values);if(!answer.ok){return}if(answer.value.kind==="completed"){onResult?.(answer.value.result)}if(answer.value.kind==="started"){started.current=answer.value.handle;const end=ends.current.get(answer.value.handle);if(end!==undefined){deliver(end)}}};const{outcome,state}=intent;const resultView=outcome?.kind==="completed"&&render!==undefined?render(outcome.result):undefined;const status=resultView===undefined?statusOf2(intent,text):undefined;return jsxs43("div",{className:cn19("grid gap-2 outline-none",className),"data-slot":"intent-trigger","data-state":state,ref:container,tabIndex:-1,children:[outcome?.kind==="needs_input"?jsx51(IntentForm,{fqn,labels:text,onSubmit:(values)=>{container.current?.focus();run(values)},problems:outcome.fields,values:sent}):jsx51(Button22,{"aria-busy":state==="working",className:"justify-self-start",disabled:state==="working",onClick:()=>{run(inputs)},type:"button",children:children??displayName??fqn}),status!==undefined&&jsx51("output",{className:"text-muted-foreground text-sm",children:status}),resultView]})};var IntentTrigger=(props)=>props.resultTarget==="chat"?jsx51(LaunchTrigger,{...props}):jsx51(DispatchTrigger,{...props});import{Button as Button23}from"@collective-intelligence/ui-react/ui";import{useId as useId9}from"react";import{jsx as jsx52,jsxs as jsxs44,Fragment as Fragment14}from"react/jsx-runtime";var ChatLaunchButton=({children,className,labels,locale="en",turn,...options})=>{const launch=useLaunch2();const launchable=useHasLaunchTarget2(options.target);const reasonId=useId9();return jsxs44(Fragment14,{children:[jsx52(Button23,{"aria-describedby":launchable?undefined:reasonId,className,"data-slot":"chat-launch-button",disabled:!launchable,onClick:()=>{launch(turn,options)},type:"button",children}),!launchable&&jsx52("span",{className:"text-muted-foreground text-sm",id:reasonId,children:labels?.noChat??chatLabels[locale].noChat})]})};export{AssistantSidebar,AssistantSidebarLayout,AssistantSidebarToggle,Chat,ChatAgentPicker,ChatAnswerFeedback,ChatBlockedState,ChatCapabilityPickers,ChatComposer,ChatDock,ChatDockHeader,ChatHeader,ChatLaunchButton,ChatPicker,ChatRoot,ChatTranscript,ConversationSidebar,EvidencePart,FilePart,ImageGenerationPart,IntentCard,IntentCardMessagePart,IntentForm,IntentNotices,IntentTrigger,MemoryEvidencePart,QuestionPart,ReadAloudButton,ReasoningPart,RunTrace,SteeringMessagePart,TextPart,ToolPart,chatLabels,chatSubjectHeaderName,chatSubjectHeaderValue,defaultIntentLabels,fillLabel,intentCardLabels,intentNoticeLabels,transcribeRecording};
|