@plaisolutions/react 0.10.1 → 0.12.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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { PlaiChat } from "@plaisolutions/client";
1
+ import { HttpStatusError, PlaiChat } from "@plaisolutions/client";
2
2
  import { createContext, forwardRef, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
3
3
  import { Bot, Brain, Check, CheckCircle2, ChevronDown, CircleX, Copy, Database, File, FileText, Globe, LoaderCircle, MessageSquare, Minus, Plug, Plus, RotateCcw, ThumbsDown, ThumbsUp, Workflow, XCircle } from "lucide-react";
4
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
@@ -30,6 +30,10 @@ function useChat(options) {
30
30
  const actions = useMemo(() => ({
31
31
  sendMessage: chat.sendMessage.bind(chat),
32
32
  rateMessage: chat.rateMessage.bind(chat),
33
+ getMemoryProposal: chat.getMemoryProposal.bind(chat),
34
+ acceptMemoryProposal: chat.acceptMemoryProposal.bind(chat),
35
+ rejectMemoryProposal: chat.rejectMemoryProposal.bind(chat),
36
+ getResourceDownloadUrl: chat.getResourceDownloadUrl.bind(chat),
33
37
  resendMessage: chat.resendMessage.bind(chat),
34
38
  transcribeAudio: chat.transcribeAudio.bind(chat),
35
39
  uploadFile: chat.uploadFile.bind(chat),
@@ -162,8 +166,64 @@ function ResourceCardContent({ icon, type, title, description }) {
162
166
  ] });
163
167
  }
164
168
  function ResourceCard(props) {
165
- const { className: customClassName, variant = "card",...contentProps } = props;
169
+ const { className: customClassName, variant = "card", resourceId, requiresDownloadUrl = false, getResourceDownloadUrl,...contentProps } = props;
170
+ const [downloadState, setDownloadState] = useState("idle");
171
+ const abortControllerRef = useRef(null);
166
172
  const className = joinClasses("block rounded-lg bg-neutral-100 p-4 text-left text-neutral-950", variant === "card" ? "min-h-[183px] w-[186px] max-w-full" : "w-full", customClassName);
173
+ const interactiveClassName = `${className} transition-colors hover:bg-neutral-200 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950`;
174
+ useEffect(() => () => {
175
+ abortControllerRef.current?.abort();
176
+ }, []);
177
+ const openProtectedResource = useCallback(async () => {
178
+ if (!resourceId || !getResourceDownloadUrl || downloadState === "loading") return;
179
+ abortControllerRef.current?.abort();
180
+ const abortController = new AbortController();
181
+ abortControllerRef.current = abortController;
182
+ setDownloadState("loading");
183
+ const popup = window.open("about:blank", "_blank");
184
+ if (popup) popup.opener = null;
185
+ try {
186
+ const downloadUrl = await getResourceDownloadUrl({
187
+ resourceId,
188
+ signal: abortController.signal
189
+ });
190
+ if (abortController.signal.aborted) {
191
+ popup?.close();
192
+ return;
193
+ }
194
+ if (!downloadUrl.trim()) throw new Error("The resource download URL is empty.");
195
+ if (popup && !popup.closed) popup.location.replace(downloadUrl);
196
+ else if (!window.open(downloadUrl, "_blank", "noopener,noreferrer")) throw new Error("The resource window was blocked.");
197
+ setDownloadState("idle");
198
+ } catch {
199
+ popup?.close();
200
+ if (!abortController.signal.aborted) setDownloadState("error");
201
+ }
202
+ }, [
203
+ downloadState,
204
+ getResourceDownloadUrl,
205
+ resourceId
206
+ ]);
207
+ if (requiresDownloadUrl && resourceId && getResourceDownloadUrl) return /* @__PURE__ */ jsxs("button", {
208
+ type: "button",
209
+ className: `${interactiveClassName} border-0 disabled:cursor-wait disabled:opacity-70`,
210
+ onClick: openProtectedResource,
211
+ disabled: downloadState === "loading",
212
+ "aria-busy": downloadState === "loading",
213
+ children: [
214
+ /* @__PURE__ */ jsx(ResourceCardContent, { ...contentProps }),
215
+ downloadState === "loading" ? /* @__PURE__ */ jsx("span", {
216
+ className: "mt-2 block text-xs text-neutral-600",
217
+ "aria-live": "polite",
218
+ children: "Opening resource…"
219
+ }) : null,
220
+ downloadState === "error" ? /* @__PURE__ */ jsx("span", {
221
+ className: "mt-2 block text-xs text-red-700",
222
+ role: "alert",
223
+ children: "Unable to open resource. Try again."
224
+ }) : null
225
+ ]
226
+ });
167
227
  if (!contentProps.url) return /* @__PURE__ */ jsx("article", {
168
228
  "aria-label": `${contentProps.title}: ${contentProps.description}`,
169
229
  className,
@@ -173,7 +233,7 @@ function ResourceCard(props) {
173
233
  href: contentProps.url,
174
234
  target: "_blank",
175
235
  rel: "noreferrer noopener",
176
- className: `${className} transition-colors hover:bg-neutral-200 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950`,
236
+ className: interactiveClassName,
177
237
  children: /* @__PURE__ */ jsx(ResourceCardContent, { ...contentProps })
178
238
  });
179
239
  }
@@ -661,6 +721,9 @@ function isGoogleDriveResource(resource) {
661
721
  readNestedString(records, ["datasource", "origin"])
662
722
  ].some((candidate) => candidate?.toUpperCase() === "GOOGLE_DRIVE") || isGoogleDriveUrl(resource.external_url) || isGoogleDriveUrl(resource.url);
663
723
  }
724
+ function requiresResourceDownloadUrl(resource, locale) {
725
+ return Boolean(resource.store && !resource.external_url && !getLocalizedOpenGraphValue(resource, "url", locale) && !isGoogleDriveResource(resource));
726
+ }
664
727
  function getResourceUrl(resource, locale) {
665
728
  const openGraphUrl = getLocalizedOpenGraphValue(resource, "url", locale);
666
729
  if (openGraphUrl) return openGraphUrl;
@@ -696,16 +759,20 @@ function readString(value, key) {
696
759
  const candidate = value?.[key];
697
760
  return typeof candidate === "string" && candidate.trim() ? candidate : null;
698
761
  }
699
- function toResourceCardProps(resource, locale) {
762
+ function toResourceCardProps(resource, locale, getResourceDownloadUrl) {
763
+ const requiresDownloadUrl = requiresResourceDownloadUrl(resource, locale);
700
764
  return {
701
765
  icon: getResourceIcon(resource, locale),
702
766
  type: getResourceType(resource, locale),
703
767
  title: getResourceTitle(resource, locale),
704
768
  description: getResourceDescription(resource, locale),
705
- url: getResourceUrl(resource, locale)
769
+ url: requiresDownloadUrl ? null : getResourceUrl(resource, locale),
770
+ resourceId: resource.id,
771
+ getResourceDownloadUrl: requiresDownloadUrl ? getResourceDownloadUrl : void 0,
772
+ requiresDownloadUrl
706
773
  };
707
774
  }
708
- function toFolderCardProps(folder, group, locale) {
775
+ function toFolderCardProps(folder, group, locale, getResourceDownloadUrl) {
709
776
  const datasource = group[0]?.datasource;
710
777
  const type = getLocalizedOpenGraphValue(folder, "type", locale) ?? readString(folder.extra_info, "type") ?? datasource?.type ?? "FOLDER";
711
778
  return {
@@ -714,7 +781,7 @@ function toFolderCardProps(folder, group, locale) {
714
781
  description: getLocalizedOpenGraphValue(folder, "description", locale) ?? readString(folder.extra_info, "description") ?? readString(folder.extra_info, "summary") ?? datasource?.description ?? datasource?.summary ?? "",
715
782
  type,
716
783
  url: getLocalizedOpenGraphValue(folder, "url", locale),
717
- resources: group.map((resource) => toResourceCardProps(resource, locale))
784
+ resources: group.map((resource) => toResourceCardProps(resource, locale, getResourceDownloadUrl))
718
785
  };
719
786
  }
720
787
  function isDatasourceResource(value) {
@@ -723,7 +790,7 @@ function isDatasourceResource(value) {
723
790
  const datasource = value.datasource;
724
791
  return typeof value.id === "string" && typeof value.name === "string" && typeof value.type === "string" && (value.url === null || typeof value.url === "string") && (value.external_url === null || typeof value.external_url === "string") && isObject(value.metadata) && isObject(value.extra_info) && (folder === null || isObject(folder) && typeof folder.id === "string" && typeof folder.name === "string" && isObject(folder.extra_info)) && (datasource === null || isObject(datasource) && typeof datasource.type === "string" && (datasource.description === null || typeof datasource.description === "string") && (datasource.summary === null || typeof datasource.summary === "string"));
725
792
  }
726
- function getDatasourceResourceCards(resources, locale) {
793
+ function getDatasourceResourceCards(resources, locale, getResourceDownloadUrl) {
727
794
  const folderGroups = /* @__PURE__ */ new Map();
728
795
  const ungroupedResources = [];
729
796
  const seenUrls = /* @__PURE__ */ new Set();
@@ -748,11 +815,11 @@ function getDatasourceResourceCards(resources, locale) {
748
815
  return [...Array.from(folderGroups.values()).map(({ folder, resources: group }) => ({
749
816
  kind: "folder",
750
817
  key: `folder-${folder.id}`,
751
- props: toFolderCardProps(folder, group, locale)
818
+ props: toFolderCardProps(folder, group, locale, getResourceDownloadUrl)
752
819
  })), ...ungroupedResources.map((resource) => ({
753
820
  kind: "resource",
754
821
  key: `resource-${resource.id}`,
755
- props: toResourceCardProps(resource, locale)
822
+ props: toResourceCardProps(resource, locale, getResourceDownloadUrl)
756
823
  }))];
757
824
  }
758
825
  function DatasourceResourceCardView({ card, variant = "card" }) {
@@ -765,8 +832,8 @@ function DatasourceResourceCardView({ card, variant = "card" }) {
765
832
  variant
766
833
  });
767
834
  }
768
- function DatasourceToolResources({ resources, locale, className }) {
769
- const cards = getDatasourceResourceCards(resources, locale);
835
+ function DatasourceToolResources({ resources, locale, className, getResourceDownloadUrl }) {
836
+ const cards = getDatasourceResourceCards(resources, locale, getResourceDownloadUrl);
770
837
  return /* @__PURE__ */ jsx("section", {
771
838
  "aria-label": "Recursos de la fuente de datos",
772
839
  className: joinClasses("flex flex-wrap gap-3", className),
@@ -1002,8 +1069,8 @@ function getDatasourceResources$2(part) {
1002
1069
  const resources = part.metadata?.resources;
1003
1070
  return Array.isArray(resources) ? resources.filter(isDatasourceResource) : [];
1004
1071
  }
1005
- function getAggregatedCards(parts, locale) {
1006
- const datasourceCards = parts.filter((part) => part.toolType === "datasource").flatMap((part) => getDatasourceResourceCards(getDatasourceResources$2(part), locale).map((card) => ({
1072
+ function getAggregatedCards(parts, locale, getResourceDownloadUrl) {
1073
+ const datasourceCards = parts.filter((part) => part.toolType === "datasource").flatMap((part) => getDatasourceResourceCards(getDatasourceResources$2(part), locale, getResourceDownloadUrl).map((card) => ({
1007
1074
  kind: "datasource",
1008
1075
  key: `${part.id}-${card.key}`,
1009
1076
  card
@@ -1038,8 +1105,8 @@ function SourceCard({ source, variant = "card" }) {
1038
1105
  function getTotalSourceCount(cards) {
1039
1106
  return cards.reduce((count, source) => count + (source.kind === "web" ? getWebSearchResults(source.part).length : 1), 0);
1040
1107
  }
1041
- function AggregatedSourceResults({ parts, locale, maxVisible = 3, className }) {
1042
- const cards = getAggregatedCards(parts, locale);
1108
+ function AggregatedSourceResults({ parts, locale, maxVisible = 3, className, getResourceDownloadUrl }) {
1109
+ const cards = getAggregatedCards(parts, locale, getResourceDownloadUrl);
1043
1110
  if (cards.length === 0) return null;
1044
1111
  const visibleLimit = Number.isFinite(maxVisible) && maxVisible >= 1 ? Math.floor(maxVisible) : 3;
1045
1112
  const visibleCards = cards.slice(0, visibleLimit);
@@ -2339,6 +2406,7 @@ const TOOL_USE_ACTIONS = {
2339
2406
  external_datasource: "query",
2340
2407
  firecrawl_search: "web",
2341
2408
  http_request: "request",
2409
+ memory_proposal: "tool",
2342
2410
  mcp_tool: "request",
2343
2411
  office_documents: "documents",
2344
2412
  perplexity: "web",
@@ -2477,6 +2545,357 @@ function ToolUseIndicator({ part, locale, className,...props }) {
2477
2545
  });
2478
2546
  }
2479
2547
 
2548
+ //#endregion
2549
+ //#region src/components/memory-proposal-card.tsx
2550
+ const COPY = {
2551
+ en: {
2552
+ title: "Memory proposal",
2553
+ user: "Personal memory",
2554
+ project: "Project learning",
2555
+ create: "Create",
2556
+ update: "Update",
2557
+ delete: "Delete",
2558
+ previous: "Previous content",
2559
+ proposed: "Proposed content",
2560
+ accept: "Accept",
2561
+ reject: "Reject",
2562
+ review: "Sent for admin review",
2563
+ unavailable: "This proposal cannot be resolved here",
2564
+ accepted: "Accepted",
2565
+ rejected: "Rejected",
2566
+ expired: "Expired",
2567
+ conflicted: "Could not be applied because the memory changed",
2568
+ conflictError: "The memory changed. The latest status has been loaded.",
2569
+ expiredError: "This proposal is no longer available.",
2570
+ permissionError: "You no longer have permission to resolve this proposal.",
2571
+ genericError: "The proposal could not be resolved."
2572
+ },
2573
+ es: {
2574
+ title: "Propuesta de memoria",
2575
+ user: "Memoria personal",
2576
+ project: "Aprendizaje del proyecto",
2577
+ create: "Crear",
2578
+ update: "Actualizar",
2579
+ delete: "Eliminar",
2580
+ previous: "Contenido anterior",
2581
+ proposed: "Contenido propuesto",
2582
+ accept: "Aceptar",
2583
+ reject: "Rechazar",
2584
+ review: "Enviado para revisión de un administrador",
2585
+ unavailable: "Esta propuesta no se puede resolver aquí",
2586
+ accepted: "Aceptada",
2587
+ rejected: "Rechazada",
2588
+ expired: "Caducada",
2589
+ conflicted: "No se pudo aplicar porque la memoria cambió",
2590
+ conflictError: "La memoria cambió. Se ha cargado el estado más reciente.",
2591
+ expiredError: "Esta propuesta ya no está disponible.",
2592
+ permissionError: "Ya no tienes permiso para resolver esta propuesta.",
2593
+ genericError: "No se pudo resolver la propuesta."
2594
+ },
2595
+ ca: {
2596
+ title: "Proposta de memòria",
2597
+ user: "Memòria personal",
2598
+ project: "Aprenentatge del projecte",
2599
+ create: "Crear",
2600
+ update: "Actualitzar",
2601
+ delete: "Eliminar",
2602
+ previous: "Contingut anterior",
2603
+ proposed: "Contingut proposat",
2604
+ accept: "Acceptar",
2605
+ reject: "Rebutjar",
2606
+ review: "Enviat per a revisió d'un administrador",
2607
+ unavailable: "Aquesta proposta no es pot resoldre aquí",
2608
+ accepted: "Acceptada",
2609
+ rejected: "Rebutjada",
2610
+ expired: "Caducada",
2611
+ conflicted: "No s'ha pogut aplicar perquè la memòria ha canviat",
2612
+ conflictError: "La memòria ha canviat. S'ha carregat l'estat més recent.",
2613
+ expiredError: "Aquesta proposta ja no està disponible.",
2614
+ permissionError: "Ja no tens permís per resoldre aquesta proposta.",
2615
+ genericError: "No s'ha pogut resoldre la proposta."
2616
+ },
2617
+ da: {
2618
+ title: "Hukommelsesforslag",
2619
+ user: "Personlig hukommelse",
2620
+ project: "Projektlæring",
2621
+ create: "Opret",
2622
+ update: "Opdater",
2623
+ delete: "Slet",
2624
+ previous: "Tidligere indhold",
2625
+ proposed: "Foreslået indhold",
2626
+ accept: "Acceptér",
2627
+ reject: "Afvis",
2628
+ review: "Sendt til administratorgennemgang",
2629
+ unavailable: "Forslaget kan ikke behandles her",
2630
+ accepted: "Accepteret",
2631
+ rejected: "Afvist",
2632
+ expired: "Udløbet",
2633
+ conflicted: "Kunne ikke anvendes, fordi hukommelsen blev ændret",
2634
+ conflictError: "Hukommelsen blev ændret. Den seneste status er indlæst.",
2635
+ expiredError: "Forslaget er ikke længere tilgængeligt.",
2636
+ permissionError: "Du har ikke længere tilladelse til at behandle forslaget.",
2637
+ genericError: "Forslaget kunne ikke behandles."
2638
+ },
2639
+ de: {
2640
+ title: "Speichervorschlag",
2641
+ user: "Persönliche Erinnerung",
2642
+ project: "Projektwissen",
2643
+ create: "Erstellen",
2644
+ update: "Aktualisieren",
2645
+ delete: "Löschen",
2646
+ previous: "Vorheriger Inhalt",
2647
+ proposed: "Vorgeschlagener Inhalt",
2648
+ accept: "Akzeptieren",
2649
+ reject: "Ablehnen",
2650
+ review: "Zur Administratorprüfung gesendet",
2651
+ unavailable: "Dieser Vorschlag kann hier nicht bearbeitet werden",
2652
+ accepted: "Akzeptiert",
2653
+ rejected: "Abgelehnt",
2654
+ expired: "Abgelaufen",
2655
+ conflicted: "Nicht angewendet, da sich die Erinnerung geändert hat",
2656
+ conflictError: "Die Erinnerung hat sich geändert. Der aktuelle Status wurde geladen.",
2657
+ expiredError: "Dieser Vorschlag ist nicht mehr verfügbar.",
2658
+ permissionError: "Sie dürfen diesen Vorschlag nicht mehr bearbeiten.",
2659
+ genericError: "Der Vorschlag konnte nicht bearbeitet werden."
2660
+ },
2661
+ fr: {
2662
+ title: "Proposition de mémoire",
2663
+ user: "Mémoire personnelle",
2664
+ project: "Apprentissage du projet",
2665
+ create: "Créer",
2666
+ update: "Modifier",
2667
+ delete: "Supprimer",
2668
+ previous: "Contenu précédent",
2669
+ proposed: "Contenu proposé",
2670
+ accept: "Accepter",
2671
+ reject: "Refuser",
2672
+ review: "Envoyé à un administrateur pour examen",
2673
+ unavailable: "Cette proposition ne peut pas être traitée ici",
2674
+ accepted: "Acceptée",
2675
+ rejected: "Refusée",
2676
+ expired: "Expirée",
2677
+ conflicted: "Impossible à appliquer car la mémoire a changé",
2678
+ conflictError: "La mémoire a changé. Le dernier état a été chargé.",
2679
+ expiredError: "Cette proposition n'est plus disponible.",
2680
+ permissionError: "Vous n'avez plus l'autorisation de traiter cette proposition.",
2681
+ genericError: "La proposition n'a pas pu être traitée."
2682
+ },
2683
+ it: {
2684
+ title: "Proposta di memoria",
2685
+ user: "Memoria personale",
2686
+ project: "Apprendimento del progetto",
2687
+ create: "Crea",
2688
+ update: "Aggiorna",
2689
+ delete: "Elimina",
2690
+ previous: "Contenuto precedente",
2691
+ proposed: "Contenuto proposto",
2692
+ accept: "Accetta",
2693
+ reject: "Rifiuta",
2694
+ review: "Inviata alla revisione di un amministratore",
2695
+ unavailable: "Questa proposta non può essere gestita qui",
2696
+ accepted: "Accettata",
2697
+ rejected: "Rifiutata",
2698
+ expired: "Scaduta",
2699
+ conflicted: "Non applicata perché la memoria è cambiata",
2700
+ conflictError: "La memoria è cambiata. È stato caricato lo stato più recente.",
2701
+ expiredError: "Questa proposta non è più disponibile.",
2702
+ permissionError: "Non hai più il permesso di gestire questa proposta.",
2703
+ genericError: "Impossibile gestire la proposta."
2704
+ },
2705
+ no: {
2706
+ title: "Minneforslag",
2707
+ user: "Personlig minne",
2708
+ project: "Prosjektlæring",
2709
+ create: "Opprett",
2710
+ update: "Oppdater",
2711
+ delete: "Slett",
2712
+ previous: "Tidligere innhold",
2713
+ proposed: "Foreslått innhold",
2714
+ accept: "Godta",
2715
+ reject: "Avvis",
2716
+ review: "Sendt til administratorgjennomgang",
2717
+ unavailable: "Forslaget kan ikke behandles her",
2718
+ accepted: "Godtatt",
2719
+ rejected: "Avvist",
2720
+ expired: "Utløpt",
2721
+ conflicted: "Kunne ikke brukes fordi minnet ble endret",
2722
+ conflictError: "Minnet ble endret. Den nyeste statusen er lastet inn.",
2723
+ expiredError: "Forslaget er ikke lenger tilgjengelig.",
2724
+ permissionError: "Du har ikke lenger tillatelse til å behandle forslaget.",
2725
+ genericError: "Forslaget kunne ikke behandles."
2726
+ },
2727
+ pt: {
2728
+ title: "Proposta de memória",
2729
+ user: "Memória pessoal",
2730
+ project: "Aprendizagem do projeto",
2731
+ create: "Criar",
2732
+ update: "Atualizar",
2733
+ delete: "Eliminar",
2734
+ previous: "Conteúdo anterior",
2735
+ proposed: "Conteúdo proposto",
2736
+ accept: "Aceitar",
2737
+ reject: "Rejeitar",
2738
+ review: "Enviado para revisão de um administrador",
2739
+ unavailable: "Esta proposta não pode ser resolvida aqui",
2740
+ accepted: "Aceite",
2741
+ rejected: "Rejeitada",
2742
+ expired: "Expirada",
2743
+ conflicted: "Não aplicada porque a memória foi alterada",
2744
+ conflictError: "A memória foi alterada. O estado mais recente foi carregado.",
2745
+ expiredError: "Esta proposta já não está disponível.",
2746
+ permissionError: "Já não tem permissão para resolver esta proposta.",
2747
+ genericError: "Não foi possível resolver a proposta."
2748
+ },
2749
+ sv: {
2750
+ title: "Minnesförslag",
2751
+ user: "Personligt minne",
2752
+ project: "Projektlärdom",
2753
+ create: "Skapa",
2754
+ update: "Uppdatera",
2755
+ delete: "Ta bort",
2756
+ previous: "Tidigare innehåll",
2757
+ proposed: "Föreslaget innehåll",
2758
+ accept: "Godkänn",
2759
+ reject: "Avvisa",
2760
+ review: "Skickat för administratörsgranskning",
2761
+ unavailable: "Förslaget kan inte hanteras här",
2762
+ accepted: "Godkänt",
2763
+ rejected: "Avvisat",
2764
+ expired: "Utgånget",
2765
+ conflicted: "Kunde inte tillämpas eftersom minnet ändrades",
2766
+ conflictError: "Minnet ändrades. Den senaste statusen har lästs in.",
2767
+ expiredError: "Förslaget är inte längre tillgängligt.",
2768
+ permissionError: "Du har inte längre behörighet att hantera förslaget.",
2769
+ genericError: "Förslaget kunde inte hanteras."
2770
+ }
2771
+ };
2772
+ const REDACTED = "[redacted]";
2773
+ function MemoryProposalCard({ proposal: initial, actions, activeAgentId, locale, className }) {
2774
+ const copy = COPY[getSupportedToolLocale(locale)];
2775
+ const [proposal, setProposal] = useState(initial);
2776
+ const [resolving, setResolving] = useState(false);
2777
+ const [error, setError] = useState(null);
2778
+ useEffect(() => setProposal((current) => mergeProposal(current, initial)), [initial]);
2779
+ async function resolve(accept) {
2780
+ if (resolving) return;
2781
+ setResolving(true);
2782
+ setError(null);
2783
+ try {
2784
+ const next = accept ? await actions.acceptMemoryProposal({ proposalId: proposal.id }) : await actions.rejectMemoryProposal({ proposalId: proposal.id });
2785
+ setProposal((current) => mergeProposal(current, next));
2786
+ } catch (cause) {
2787
+ const status = cause instanceof HttpStatusError ? cause.status : 0;
2788
+ setError(status === 409 ? copy.conflictError : status === 410 ? copy.expiredError : status === 401 || status === 403 ? copy.permissionError : copy.genericError);
2789
+ try {
2790
+ const latest = await actions.getMemoryProposal({ proposalId: proposal.id });
2791
+ setProposal((current) => mergeProposal(current, latest));
2792
+ } catch {}
2793
+ } finally {
2794
+ setResolving(false);
2795
+ }
2796
+ }
2797
+ const canResolve = proposal.status === "PENDING" && proposal.can_resolve === true && proposal.agent_id === activeAgentId;
2798
+ const statusCopy = proposal.status === "ACCEPTED" ? copy.accepted : proposal.status === "REJECTED" ? copy.rejected : proposal.status === "EXPIRED" ? copy.expired : proposal.status === "CONFLICTED" ? copy.conflicted : null;
2799
+ const operation = proposal.operation === "CREATE" ? copy.create : proposal.operation === "UPDATE" ? copy.update : copy.delete;
2800
+ return /* @__PURE__ */ jsxs("section", {
2801
+ className: joinClasses("space-y-3 rounded-lg border border-emerald-200 bg-emerald-50/30 p-4 text-left", className),
2802
+ "data-memory-proposal-id": proposal.id,
2803
+ children: [
2804
+ /* @__PURE__ */ jsxs("header", {
2805
+ className: "space-y-2",
2806
+ children: [/* @__PURE__ */ jsxs("h4", {
2807
+ className: "flex items-center gap-2 text-sm font-semibold text-slate-900",
2808
+ children: [/* @__PURE__ */ jsx(Brain, { className: "size-4" }), copy.title]
2809
+ }), /* @__PURE__ */ jsxs("div", {
2810
+ className: "flex flex-wrap gap-2 text-xs",
2811
+ children: [
2812
+ /* @__PURE__ */ jsx("span", {
2813
+ className: "rounded-full border border-slate-300 bg-white px-2 py-0.5",
2814
+ children: proposal.scope === "USER" ? copy.user : copy.project
2815
+ }),
2816
+ /* @__PURE__ */ jsx("span", {
2817
+ className: "rounded-full bg-slate-100 px-2 py-0.5",
2818
+ children: operation
2819
+ }),
2820
+ /* @__PURE__ */ jsx("span", {
2821
+ className: "rounded-full bg-slate-100 px-2 py-0.5",
2822
+ children: formatCategory(proposal.category)
2823
+ })
2824
+ ]
2825
+ })]
2826
+ }),
2827
+ proposal.previous_content && proposal.previous_content !== REDACTED ? /* @__PURE__ */ jsxs("div", {
2828
+ className: "rounded-md bg-slate-100 p-3 text-sm",
2829
+ children: [/* @__PURE__ */ jsx("span", {
2830
+ className: "mb-1 block text-xs font-medium text-slate-500",
2831
+ children: copy.previous
2832
+ }), /* @__PURE__ */ jsx("p", {
2833
+ className: "whitespace-pre-wrap break-words",
2834
+ children: proposal.previous_content
2835
+ })]
2836
+ }) : null,
2837
+ proposal.content && proposal.content !== REDACTED ? /* @__PURE__ */ jsxs("div", {
2838
+ className: "text-sm",
2839
+ children: [/* @__PURE__ */ jsx("span", {
2840
+ className: "mb-1 block text-xs font-medium text-slate-500",
2841
+ children: copy.proposed
2842
+ }), /* @__PURE__ */ jsx("p", {
2843
+ className: "whitespace-pre-wrap break-words",
2844
+ children: proposal.content
2845
+ })]
2846
+ }) : null,
2847
+ canResolve ? /* @__PURE__ */ jsxs("div", {
2848
+ className: "flex gap-2",
2849
+ children: [/* @__PURE__ */ jsxs("button", {
2850
+ type: "button",
2851
+ disabled: resolving,
2852
+ onClick: () => void resolve(true),
2853
+ className: "inline-flex items-center rounded-md bg-slate-900 px-3 py-1.5 text-xs font-medium text-white disabled:opacity-50",
2854
+ children: [resolving ? /* @__PURE__ */ jsx(LoaderCircle, { className: "mr-2 size-3 animate-spin" }) : null, copy.accept]
2855
+ }), /* @__PURE__ */ jsx("button", {
2856
+ type: "button",
2857
+ disabled: resolving,
2858
+ onClick: () => void resolve(false),
2859
+ className: "rounded-md border border-slate-300 bg-white px-3 py-1.5 text-xs font-medium disabled:opacity-50",
2860
+ children: copy.reject
2861
+ })]
2862
+ }) : null,
2863
+ proposal.status === "PENDING" && !canResolve ? /* @__PURE__ */ jsx("p", {
2864
+ className: "text-xs font-medium text-slate-500",
2865
+ children: proposal.scope === "PROJECT" ? copy.review : copy.unavailable
2866
+ }) : null,
2867
+ proposal.status === "ACCEPTED" && statusCopy ? /* @__PURE__ */ jsxs("span", {
2868
+ className: "inline-flex items-center gap-1.5 rounded-full border bg-white px-3 py-1 text-xs font-medium text-slate-900 shadow-sm",
2869
+ children: [statusCopy, /* @__PURE__ */ jsx(Check, {
2870
+ className: "size-3.5 stroke-[2.5] text-emerald-600",
2871
+ "aria-hidden": "true"
2872
+ })]
2873
+ }) : null,
2874
+ statusCopy && proposal.status !== "ACCEPTED" ? /* @__PURE__ */ jsx("p", {
2875
+ className: "text-xs font-medium text-slate-500",
2876
+ children: statusCopy
2877
+ }) : null,
2878
+ error ? /* @__PURE__ */ jsx("p", {
2879
+ className: "text-xs text-red-600",
2880
+ children: error
2881
+ }) : null
2882
+ ]
2883
+ });
2884
+ }
2885
+ function mergeProposal(current, incoming) {
2886
+ if (current.id !== incoming.id) return incoming;
2887
+ return {
2888
+ ...incoming,
2889
+ content: incoming.content === REDACTED ? current.content : incoming.content,
2890
+ previous_content: incoming.previous_content === REDACTED ? current.previous_content : incoming.previous_content,
2891
+ rationale: incoming.rationale === REDACTED ? current.rationale : incoming.rationale
2892
+ };
2893
+ }
2894
+ function formatCategory(category) {
2895
+ const value = category.replaceAll("_", " ").toLowerCase();
2896
+ return `${value.charAt(0).toUpperCase()}${value.slice(1)}`;
2897
+ }
2898
+
2480
2899
  //#endregion
2481
2900
  //#region src/components/tool-result-card.tsx
2482
2901
  function formatJson(value) {
@@ -2494,7 +2913,18 @@ function getDatasourceResources$1(part) {
2494
2913
  const resources = part.metadata.resources;
2495
2914
  return Array.isArray(resources) ? resources.filter(isDatasourceResource) : [];
2496
2915
  }
2497
- function ToolResultCard({ part, className, detailsOpen = true, locale, onOpenAgentThread }) {
2916
+ function ToolResultCard({ part, className, detailsOpen = true, locale, onOpenAgentThread, getResourceDownloadUrl, memoryProposal }) {
2917
+ if (part.toolType === "memory_proposal") {
2918
+ const proposal = part.metadata?.proposal;
2919
+ if (!memoryProposal || !proposal || typeof proposal !== "object") return null;
2920
+ return /* @__PURE__ */ jsx(MemoryProposalCard, {
2921
+ proposal,
2922
+ actions: memoryProposal.actions,
2923
+ activeAgentId: memoryProposal.activeAgentId,
2924
+ locale,
2925
+ className
2926
+ });
2927
+ }
2498
2928
  if (part.state === "pending") return /* @__PURE__ */ jsx(ToolUseIndicator, {
2499
2929
  part,
2500
2930
  locale,
@@ -2547,7 +2977,8 @@ function ToolResultCard({ part, className, detailsOpen = true, locale, onOpenAge
2547
2977
  if (datasourceResources.length > 0) return /* @__PURE__ */ jsx(DatasourceToolResources, {
2548
2978
  resources: datasourceResources,
2549
2979
  locale,
2550
- className
2980
+ className,
2981
+ getResourceDownloadUrl
2551
2982
  });
2552
2983
  if (part.toolType === "datasource") return null;
2553
2984
  return /* @__PURE__ */ jsxs("section", {
@@ -2755,7 +3186,7 @@ function getMessageTextClassName(role) {
2755
3186
  function getMessageTextAlignmentClassName(role) {
2756
3187
  return role === "user" ? "text-right" : "text-left";
2757
3188
  }
2758
- function renderPart(part, index, message, isStreaming, onOpenAgentThread, locale, renderText, renderToolCall, renderThinking, thinkingLabel, completedThinkingLabel, textClassName) {
3189
+ function renderPart(part, index, message, isStreaming, onOpenAgentThread, getResourceDownloadUrl, locale, memoryProposal, renderText, renderToolCall, renderThinking, thinkingLabel, completedThinkingLabel, textClassName) {
2759
3190
  if (part.type === "text") {
2760
3191
  if (renderText) return /* @__PURE__ */ jsx("div", { children: renderText(part, {
2761
3192
  message,
@@ -2811,7 +3242,9 @@ function renderPart(part, index, message, isStreaming, onOpenAgentThread, locale
2811
3242
  return /* @__PURE__ */ jsx(ToolResultCard, {
2812
3243
  part,
2813
3244
  locale,
2814
- onOpenAgentThread
3245
+ onOpenAgentThread,
3246
+ getResourceDownloadUrl,
3247
+ memoryProposal
2815
3248
  }, `tool-${part.id}-${index}`);
2816
3249
  }
2817
3250
  if (part.type === "thinking") {
@@ -2867,7 +3300,7 @@ function aggregateSourceToolParts(parts, position) {
2867
3300
  ...remainingParts.slice(insertionIndex)
2868
3301
  ];
2869
3302
  }
2870
- function MessageParts({ message, collapseThreshold = DEFAULT_COLLAPSE_THRESHOLD, sourceToolResultsLayout = "aggregated", sourceToolResultsPosition, maxVisibleSourceCards = 3, datasourceToolResultsPosition, onOpenAgentThread, locale, renderText, renderToolCall, renderThinking, isStreaming = false, thinkingLabel, completedThinkingLabel, readMoreLabel = "Read more", readLessLabel = "Read less", className,...props }) {
3303
+ function MessageParts({ message, collapseThreshold = DEFAULT_COLLAPSE_THRESHOLD, sourceToolResultsLayout = "aggregated", sourceToolResultsPosition, maxVisibleSourceCards = 3, datasourceToolResultsPosition, onOpenAgentThread, getResourceDownloadUrl, locale, memoryProposal, renderText, renderToolCall, renderThinking, isStreaming = false, thinkingLabel, completedThinkingLabel, readMoreLabel = "Read more", readLessLabel = "Read less", className,...props }) {
2871
3304
  const [isExpanded, setIsExpanded] = useState(false);
2872
3305
  const textContent = useMemo(() => message.parts.filter((part) => part.type === "text").map((part) => part.text).join("\n"), [message.parts]);
2873
3306
  const canCollapse = message.role === "user" && message.parts.every((part) => part.type === "text") && textContent.length > collapseThreshold;
@@ -2895,8 +3328,9 @@ function MessageParts({ message, collapseThreshold = DEFAULT_COLLAPSE_THRESHOLD,
2895
3328
  }) : orderedParts.map((item) => item.kind === "source-results" ? /* @__PURE__ */ jsx(AggregatedSourceResults, {
2896
3329
  parts: item.parts,
2897
3330
  locale,
2898
- maxVisible: maxVisibleSourceCards
2899
- }, `source-results-${item.index}`) : renderPart(item.part, item.index, message, isStreaming, onOpenAgentThread, locale, renderText, renderToolCall, renderThinking, thinkingLabel, completedThinkingLabel, textClassName)), canCollapse ? /* @__PURE__ */ jsx("button", {
3331
+ maxVisible: maxVisibleSourceCards,
3332
+ getResourceDownloadUrl
3333
+ }, `source-results-${item.index}`) : renderPart(item.part, item.index, message, isStreaming, onOpenAgentThread, getResourceDownloadUrl, locale, memoryProposal, renderText, renderToolCall, renderThinking, thinkingLabel, completedThinkingLabel, textClassName)), canCollapse ? /* @__PURE__ */ jsx("button", {
2900
3334
  type: "button",
2901
3335
  className: "text-xs font-medium text-slate-600 hover:text-slate-900",
2902
3336
  onClick: () => setIsExpanded((previous) => !previous),
@@ -2912,7 +3346,8 @@ function getDatasourceResources(part) {
2912
3346
  const resources = part.metadata?.resources;
2913
3347
  return Array.isArray(resources) ? resources.filter(isDatasourceResource) : [];
2914
3348
  }
2915
- function isRenderableToolPart(part, locale, hasCustomRenderer = false) {
3349
+ function isRenderableToolPart(part, locale, hasCustomRenderer = false, hasMemoryProposalClient = false) {
3350
+ if (part.toolType === "memory_proposal") return hasMemoryProposalClient;
2916
3351
  if (hasCustomRenderer || part.toolType !== "datasource") return true;
2917
3352
  if (part.state !== "completed") return true;
2918
3353
  return getDatasourceResourceCards(getDatasourceResources(part), locale).length > 0;
@@ -2926,7 +3361,7 @@ function withParts(message, parts) {
2926
3361
  function AssistantMessage({ message, avatar, footer, messageClassName, contentClassName, toolResultsClassName, toolPartsClassName, contentPartsClassName, messagePartsProps, className,...props }) {
2927
3362
  const toolParts = message.parts.filter((part) => part.type === "tool-call");
2928
3363
  const contentParts = message.parts.filter((part) => part.type !== "tool-call");
2929
- const renderableToolParts = toolParts.filter((part) => isRenderableToolPart(part, messagePartsProps?.locale, Boolean(messagePartsProps?.renderToolCall)));
3364
+ const renderableToolParts = toolParts.filter((part) => isRenderableToolPart(part, messagePartsProps?.locale, Boolean(messagePartsProps?.renderToolCall), Boolean(messagePartsProps?.memoryProposal)));
2930
3365
  const hasContentRow = contentParts.length > 0 || footer !== void 0;
2931
3366
  return /* @__PURE__ */ jsxs("div", {
2932
3367
  className: joinClasses("plai-assistant-message flex w-full flex-col gap-2", className),
@@ -2984,7 +3419,11 @@ function isRoutedMessageProps(props) {
2984
3419
  }
2985
3420
  function Message(props) {
2986
3421
  if (!isRoutedMessageProps(props)) return /* @__PURE__ */ jsx(MessageRoot, { ...props });
2987
- const { message, avatar, footer, messageClassName, contentClassName, partsClassName, toolResultsClassName, toolPartsClassName, messagePartsProps, className,...rootProps } = props;
3422
+ const { message, avatar, footer, messageClassName, contentClassName, partsClassName, toolResultsClassName, toolPartsClassName, messagePartsProps, getResourceDownloadUrl, className,...rootProps } = props;
3423
+ const routedMessagePartsProps = getResourceDownloadUrl ? {
3424
+ ...messagePartsProps,
3425
+ getResourceDownloadUrl
3426
+ } : messagePartsProps;
2988
3427
  if (message.role === "assistant") return /* @__PURE__ */ jsx(AssistantMessage, {
2989
3428
  ...rootProps,
2990
3429
  className,
@@ -2996,7 +3435,7 @@ function Message(props) {
2996
3435
  contentPartsClassName: partsClassName,
2997
3436
  toolResultsClassName,
2998
3437
  toolPartsClassName,
2999
- messagePartsProps
3438
+ messagePartsProps: routedMessagePartsProps
3000
3439
  });
3001
3440
  if (message.role === "user") return /* @__PURE__ */ jsx(UserMessage, {
3002
3441
  ...rootProps,
@@ -3006,7 +3445,7 @@ function Message(props) {
3006
3445
  footer,
3007
3446
  contentClassName,
3008
3447
  partsClassName,
3009
- messagePartsProps
3448
+ messagePartsProps: routedMessagePartsProps
3010
3449
  });
3011
3450
  return /* @__PURE__ */ jsxs(MessageRoot, {
3012
3451
  ...rootProps,
@@ -3015,7 +3454,7 @@ function Message(props) {
3015
3454
  children: [avatar, /* @__PURE__ */ jsxs(MessageContent, {
3016
3455
  className: contentClassName,
3017
3456
  children: [/* @__PURE__ */ jsx(MessageParts, {
3018
- ...messagePartsProps,
3457
+ ...routedMessagePartsProps,
3019
3458
  message,
3020
3459
  className: partsClassName
3021
3460
  }), footer]
@@ -3613,5 +4052,5 @@ async function dummyTranscribeAudio(_audio, signal) {
3613
4052
  }
3614
4053
 
3615
4054
  //#endregion
3616
- export { AggregatedSourceResults, ArrowUp, AssistantMessage, Clipboard, DatasourceFolderCard, DatasourceToolResources, DatasourceToolResultCard, Loader, Message, MessageAvatar, MessageContent, MessageFooter, MessageHeader, MessageParts, MessageRoot, Microphone, PROMPT_FORM_FILE_ACCEPT, Paperclip, PromptForm, PromptFormAttachButton, PromptFormIconButton, Reload, ResourceCard, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle, SheetTrigger, SpeechToTextToggle, Stop, Thinking, ThumbDown, ThumbUp, ToolError, ToolResultAgentInvocationCard, ToolResultBrowserCard, ToolResultCard, ToolResultExternalDatasourceCard, ToolResultHttpRequestCard, ToolResultMcpCard, ToolResultOfficeDocumentsCard, ToolResultWebSearchCard, ToolResultWorkflowDispatchCard, ToolUseIndicator, UserMessage, X, dummyTranscribeAudio, getLocalizedOpenGraphValue, getResourceDescription, getResourceIcon, getResourceOpenGraphImage, getResourceOpenGraphType, getResourceTitle, getResourceType, getResourceUrl, getToolUseLabel, isAllowedPromptFormFile, partitionPromptFormFiles, useChat, useSpeechToText };
4055
+ export { AggregatedSourceResults, ArrowUp, AssistantMessage, Clipboard, DatasourceFolderCard, DatasourceToolResources, DatasourceToolResultCard, Loader, MemoryProposalCard, Message, MessageAvatar, MessageContent, MessageFooter, MessageHeader, MessageParts, MessageRoot, Microphone, PROMPT_FORM_FILE_ACCEPT, Paperclip, PromptForm, PromptFormAttachButton, PromptFormIconButton, Reload, ResourceCard, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle, SheetTrigger, SpeechToTextToggle, Stop, Thinking, ThumbDown, ThumbUp, ToolError, ToolResultAgentInvocationCard, ToolResultBrowserCard, ToolResultCard, ToolResultExternalDatasourceCard, ToolResultHttpRequestCard, ToolResultMcpCard, ToolResultOfficeDocumentsCard, ToolResultWebSearchCard, ToolResultWorkflowDispatchCard, ToolUseIndicator, UserMessage, X, dummyTranscribeAudio, getLocalizedOpenGraphValue, getResourceDescription, getResourceIcon, getResourceOpenGraphImage, getResourceOpenGraphType, getResourceTitle, getResourceType, getResourceUrl, getToolUseLabel, isAllowedPromptFormFile, partitionPromptFormFiles, useChat, useSpeechToText };
3617
4056
  //# sourceMappingURL=index.js.map