@aintela/chat 0.4.34 → 0.4.35

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/services.js CHANGED
@@ -1,6 +1,6 @@
1
- import { A as t, a as s, E as r, H as o, I as c, L as n, W as i } from "./httpArtifactService-_66bhjGo.js";
1
+ import { A as t, a as s, E as r, H as o, I as c, L as n, W as i } from "./httpArtifactService-BiKPHn_3.js";
2
2
  import { A as v } from "./artifactHtmlHandler-CMQJf1cX.js";
3
- import { H, d as f, r as p } from "./httpSessionService-B3CxFtl1.js";
3
+ import { H, d as f, r as p } from "./httpSessionService-BmJH0CZd.js";
4
4
  export {
5
5
  t as AgentGatewayService,
6
6
  s as AgentGatewayWSAsync,
@@ -25,6 +25,8 @@ export interface AiChatContextState {
25
25
  showStatistics: boolean;
26
26
  showStickyHeader: boolean;
27
27
  showToolCalls: boolean;
28
+ summarizedReasoning: boolean;
29
+ showReasoningTrace: boolean;
28
30
  showModelSelector: boolean;
29
31
  showSessionInfo: boolean;
30
32
  showConnectionState: boolean;
@@ -152,6 +152,17 @@ export interface AiChatBaseProps extends AiChatStyleProps {
152
152
  showPromptHistory?: boolean;
153
153
  showStatistics?: boolean;
154
154
  showToolCalls?: boolean;
155
+ /**
156
+ * Summarized reasoning (reasoning-trace localization): the thought block shows only the Portuguese
157
+ * headlines the agents server derives from the model's reasoning, never the raw trace. The raw trace comes
158
+ * back under `showToolCalls` (the host's diagnostic toggle). Default off: the trace renders as before.
159
+ */
160
+ summarizedReasoning?: boolean;
161
+ /**
162
+ * In summarized reasoning, also show the RAW reasoning trace after the highlights (the host's diagnostic
163
+ * toggle). Independent of `showToolCalls`, which governs tool calls and is on by default in obtapp.
164
+ */
165
+ showReasoningTrace?: boolean;
155
166
  showStickyHeader?: boolean;
156
167
  showModelSelector?: boolean;
157
168
  showSessionInfo?: boolean;
@@ -6,6 +6,20 @@ export interface ThoughtRunProps {
6
6
  /** Whether this run is the thought the turn is CURRENTLY writing (open + labelled "Pensando…"). */
7
7
  isLive: boolean;
8
8
  friendlyMode?: boolean;
9
+ /** The headlines the server derived from this thought's reasoning (reasoning-trace localization), in order.
10
+ * The last one is the live label in place of "Pensando..."; the whole trail stays under the header once the
11
+ * thought settles, because a thought on a fast model lives half a second and a live-only label would never be
12
+ * read. */
13
+ headlines?: string[];
14
+ /** Summarized reasoning (the host's `summarizedReasoning`): the collapsible block holds the headline trail, and
15
+ * in diagnostic mode (`showTrace`) the raw trace after it. Open while live, collapsed once settled. A settled
16
+ * thought with no headline and no diagnostics renders nothing at all. */
17
+ summarized?: boolean;
18
+ /** Diagnostics (`showReasoningTrace`): in summarized mode, shows the raw trace after the highlights. */
19
+ showTrace?: boolean;
20
+ /** Summarized mode: whether this is the message's LAST thought. Only that one stays open; an earlier one folds
21
+ * the moment a new thought begins, its highlights one click away. */
22
+ isLastThought?: boolean;
9
23
  /** One `<MessagePart>` per part — each still its own memoized component. */
10
24
  children: React.ReactNode;
11
25
  }
@@ -0,0 +1,10 @@
1
+ import { InteractionPart } from '../../../models/InteractionPart';
2
+ /** The tool event the agents server emits for each classified reasoning sentence (reasoning-trace localization). */
3
+ export declare const REASONING_HEADLINE_EVENT = "reasoningHeadline";
4
+ /**
5
+ * The reasoning headlines of each thought, in order of the thoughts. A thought is the run of Thought and ToolEvent
6
+ * parts between two parts of any other kind (text, a function call…); its trail is the `reasoningHeadline` tool
7
+ * events inside it, each headline once. Pure, so it is testable without a DOM.
8
+ */
9
+ export declare function reasoningHeadlineTrails(parts: InteractionPart[]): string[][];
10
+ export declare function headlineText(raw: string): string | undefined;
@@ -62,6 +62,9 @@ export interface FunctionDetails {
62
62
  }
63
63
  export interface ThoughtDetails {
64
64
  text: string;
65
+ /** The Portuguese headlines the agents server derived from this thought (reasoning-trace localization), as
66
+ * persisted on the message (`ChatResponseMessage.ReasoningHeadlines`). Live, they arrive as tool events instead. */
67
+ headlines?: string[];
65
68
  }
66
69
  export interface ToolEventDetails {
67
70
  eventName: string;
@@ -1,7 +1,7 @@
1
1
  var L = Object.defineProperty;
2
2
  var d = (e, t) => L(e, "name", { value: t, configurable: !0 });
3
3
  import { useMemo as h, useState as v, useCallback as g, useEffect as C } from "react";
4
- import { H } from "./httpSessionService-B3CxFtl1.js";
4
+ import { H } from "./httpSessionService-BmJH0CZd.js";
5
5
  const w = 6e4, y = 60 * w, l = 24 * y;
6
6
  function k(e) {
7
7
  if (!e) return;
@@ -104,4 +104,4 @@ d(Y, "useChatSessions");
104
104
  export {
105
105
  Y as u
106
106
  };
107
- //# sourceMappingURL=useChatSessions-BzgPYfyj.js.map
107
+ //# sourceMappingURL=useChatSessions-C2ufnYox.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useChatSessions-BzgPYfyj.js","sources":["../src/hooks/useChatSessions.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useState } from 'react';\nimport type { ChatSession } from '@lib/models/ChatSession';\nimport type { ISessionService } from '@lib/services/servers/sessionService/ISessionService';\nimport { HttpSessionService } from '../services';\n\n/**\n * One row in a session-picker UI. `raw` is the original ChatSession the\n * server returned; everything else is a derived label the hook computed\n * (and the host's `decorate` callback may have overridden).\n */\nexport interface ChatSessionListItem {\n id: string;\n title: string;\n snippet?: string;\n /** Compact relative-time label (\"now\", \"5m\", \"2h\", \"Mar 14\"). */\n timeLabel?: string;\n /** Optional per-row tag — host-supplied via the `decorate` callback. */\n kind?: string;\n updatedAt?: Date;\n raw: ChatSession;\n}\n\n/**\n * Sessions bucketed by recency. The order of `label` reflects display\n * order top-down (\"Today\" first, \"Older\" last).\n */\nexport interface ChatSessionGroup {\n label: string;\n items: ChatSessionListItem[];\n}\n\nexport interface UseChatSessionsOptions {\n sessionService?: ISessionService;\n /**\n * If provided, the live (current) session is merged into the list —\n * replacing an existing entry by id, or prepended if not yet on the\n * server. Lets a \"New chat\" row appear instantly without waiting for\n * the server roundtrip.\n */\n liveSession?: ChatSession | null;\n\n accessToken: string,\n serverBaseUrl: string,\n /**\n * Per-row override hook. Whatever fields you return are merged on top\n * of the hook's computed item — typical use is adding a `kind` tag for\n * application-specific session types (`'chat' | 'composer' | ...`) the\n * library doesn't know about.\n */\n decorate?: (session: ChatSession) => Partial<ChatSessionListItem>;\n}\n\nexport interface UseChatSessionsResult {\n /** Flat list (live session merged in, server order preserved). */\n sessions: ChatSession[];\n /** Same data bucketed by recency. */\n groups: ChatSessionGroup[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n /** Optimistic rename — patches local state immediately, rolls back on failure. */\n rename: (id: string, title: string) => Promise<void>;\n /** Optimistic remove — drops from local state immediately, rolls back on failure. */\n remove: (id: string) => Promise<void>;\n}\n\nconst MINUTE_MS = 60_000;\nconst HOUR_MS = 60 * MINUTE_MS;\nconst DAY_MS = 24 * HOUR_MS;\n\nfunction toDate(value: Date | string | undefined | null): Date | undefined {\n if (!value) return undefined;\n if (value instanceof Date) return value;\n const d = new Date(value);\n return Number.isNaN(d.getTime()) ? undefined : d;\n}\n\nfunction formatTimeLabel(date: Date | undefined): string {\n if (!date) return '';\n const diff = Date.now() - date.getTime();\n if (diff < MINUTE_MS) return 'now';\n if (diff < HOUR_MS) return `${Math.floor(diff / MINUTE_MS)}m`;\n if (diff < DAY_MS) return `${Math.floor(diff / HOUR_MS)}h`;\n if (diff < 7 * DAY_MS) return `${Math.floor(diff / DAY_MS)}d`;\n return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });\n}\n\nfunction startOfToday(): Date {\n const d = new Date();\n d.setHours(0, 0, 0, 0);\n return d;\n}\n\nfunction groupByTime(items: ChatSessionListItem[]): ChatSessionGroup[] {\n const today = startOfToday();\n const yesterday = new Date(today.getTime() - DAY_MS);\n const weekAgo = new Date(today.getTime() - 7 * DAY_MS);\n const monthAgo = new Date(today.getTime() - 30 * DAY_MS);\n\n // Insertion-ordered map preserves the bucket display order.\n const buckets: Array<[string, ChatSessionListItem[]]> = [\n ['Today', []],\n ['Yesterday', []],\n ['This Week', []],\n ['This Month', []],\n ['Older', []],\n ];\n\n for (const item of items) {\n const u = item.updatedAt;\n if (!u) { buckets[4][1].push(item); continue; }\n if (u >= today) buckets[0][1].push(item);\n else if (u >= yesterday) buckets[1][1].push(item);\n else if (u >= weekAgo) buckets[2][1].push(item);\n else if (u >= monthAgo) buckets[3][1].push(item);\n else buckets[4][1].push(item);\n }\n\n return buckets\n .filter(([, list]) => list.length > 0)\n .map(([label, list]) => ({ label, items: list }));\n}\n\nfunction buildItem(\n session: ChatSession,\n decorate?: (s: ChatSession) => Partial<ChatSessionListItem>,\n): ChatSessionListItem {\n const updatedAt = toDate(session.updatedAt) ?? toDate(session.created);\n const base: ChatSessionListItem = {\n id: session.id ?? session.browserScopeId ?? '',\n title: session.overview || session.userDescription || '(untitled chat)',\n snippet: session.lastQuestion ?? undefined,\n timeLabel: formatTimeLabel(updatedAt),\n kind: session.agentType as string | undefined,\n updatedAt,\n raw: session,\n };\n return { ...base, ...(decorate?.(session) ?? {}) };\n}\n\n/**\n * Fetch + organise the user's chat sessions for a picker UI. Backend-agnostic\n * — the host injects an `ISessionService` so the same hook drives an HTTP\n * client, an in-memory fake, or whatever else.\n *\n * Replaces the duplicated `useEffect(async () => sessionService.getAllSessions())`\n * + grouping logic that lived in DataExplorerViewV2 and MobileSessionsList,\n * and consolidates the optimistic rename/delete pattern.\n */\nexport function useChatSessions(opts: UseChatSessionsOptions): UseChatSessionsResult {\n\n const defaultSessionService = useMemo(() => {\n return new HttpSessionService(opts.serverBaseUrl, opts.accessToken);\n }, [opts.accessToken, opts.serverBaseUrl]);\n\n const { sessionService, liveSession, decorate } = {\n sessionService: defaultSessionService,\n liveSession: opts.liveSession,\n decorate: opts.decorate\n };\n const [sessions, setSessions] = useState<ChatSession[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n\n const refresh = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const list = await sessionService.getAllSessions();\n setSessions(list);\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n }, [sessionService]);\n\n useEffect(() => { void refresh(); }, [refresh]);\n\n const merged = useMemo(() => {\n if (!liveSession?.id) return sessions;\n const idx = sessions.findIndex(s => s.id === liveSession.id);\n if (idx === -1) return [liveSession, ...sessions];\n const copy = sessions.slice();\n copy[idx] = liveSession;\n return copy;\n }, [sessions, liveSession]);\n\n const items = useMemo(\n () => merged.map(s => buildItem(s, decorate)),\n [merged, decorate],\n );\n\n const groups = useMemo(() => groupByTime(items), [items]);\n\n const rename = useCallback(async (id: string, title: string) => {\n setSessions(current =>\n current.map(s => (s.id === id ? { ...s, overview: title } : s)),\n );\n try {\n await sessionService.patchSession(id, { overview: title });\n } catch (err) {\n console.error('[useChatSessions] rename failed; refreshing to roll back:', err);\n void refresh();\n }\n }, [sessionService, refresh]);\n\n const remove = useCallback(async (id: string) => {\n setSessions(current => current.filter(s => s.id !== id));\n try {\n await sessionService.removeSession(id);\n } catch (err) {\n console.error('[useChatSessions] remove failed; refreshing to roll back:', err);\n void refresh();\n }\n }, [sessionService, refresh]);\n\n return { sessions: merged, groups, isLoading, error, refresh, rename, remove };\n}\n"],"names":["MINUTE_MS","HOUR_MS","DAY_MS","toDate","value","d","__name","formatTimeLabel","date","diff","startOfToday","groupByTime","items","today","yesterday","weekAgo","monthAgo","buckets","item","u","list","label","buildItem","session","decorate","updatedAt","useChatSessions","opts","defaultSessionService","useMemo","HttpSessionService","sessionService","liveSession","sessions","setSessions","useState","isLoading","setIsLoading","error","setError","refresh","useCallback","err","useEffect","merged","idx","s","copy","groups","rename","id","title","current","remove"],"mappings":";;;;AAkEA,MAAMA,IAAY,KACZC,IAAU,KAAKD,GACfE,IAAS,KAAKD;AAEpB,SAASE,EAAOC,GAA2D;AACvE,MAAI,CAACA,EAAO;AACZ,MAAIA,aAAiB,KAAM,QAAOA;AAClC,QAAMC,IAAI,IAAI,KAAKD,CAAK;AACxB,SAAO,OAAO,MAAMC,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UL,CAAE;AAAA,IAAA;AAElE,QAAI;AACA,YAAMf,EAAe,aAAamB,GAAI,EAAE,UAAUC,GAAO;AAAA,IAC7D,SAAST,GAAK;AACV,cAAQ,MAAM,6DAA6DA,CAAG,GACzEF,EAAA;AAAA,IACT;AAAA,EACJ,GAAG,CAACT,GAAgBS,CAAO,CAAC,GAEtBa,IAASZ,EAAY,OAAOS,MAAe;AAC7C,IAAAhB,EAAY,OAAWkB,EAAQ,OAAO,OAAKN,EAAE,OAAOI,CAAE,CAAC;AACvD,QAAI;AACA,YAAMnB,EAAe,cAAcmB,CAAE;AAAA,IACzC,SAASR,GAAK;AACV,cAAQ,MAAM,6DAA6DA,CAAG,GACzEF,EAAA;AAAA,IACT;AAAA,EACJ,GAAG,CAACT,GAAgBS,CAAO,CAAC;AAE5B,SAAO,EAAE,UAAUI,GAAQ,QAAAI,GAAQ,WAAAZ,GAAW,OAAAE,GAAO,SAAAE,GAAS,QAAAS,GAAQ,QAAAI,EAAA;AAC1E;AAtEgB/C,EAAAoB,GAAA;"}
1
+ {"version":3,"file":"useChatSessions-C2ufnYox.js","sources":["../src/hooks/useChatSessions.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useState } from 'react';\nimport type { ChatSession } from '@lib/models/ChatSession';\nimport type { ISessionService } from '@lib/services/servers/sessionService/ISessionService';\nimport { HttpSessionService } from '../services';\n\n/**\n * One row in a session-picker UI. `raw` is the original ChatSession the\n * server returned; everything else is a derived label the hook computed\n * (and the host's `decorate` callback may have overridden).\n */\nexport interface ChatSessionListItem {\n id: string;\n title: string;\n snippet?: string;\n /** Compact relative-time label (\"now\", \"5m\", \"2h\", \"Mar 14\"). */\n timeLabel?: string;\n /** Optional per-row tag — host-supplied via the `decorate` callback. */\n kind?: string;\n updatedAt?: Date;\n raw: ChatSession;\n}\n\n/**\n * Sessions bucketed by recency. The order of `label` reflects display\n * order top-down (\"Today\" first, \"Older\" last).\n */\nexport interface ChatSessionGroup {\n label: string;\n items: ChatSessionListItem[];\n}\n\nexport interface UseChatSessionsOptions {\n sessionService?: ISessionService;\n /**\n * If provided, the live (current) session is merged into the list —\n * replacing an existing entry by id, or prepended if not yet on the\n * server. Lets a \"New chat\" row appear instantly without waiting for\n * the server roundtrip.\n */\n liveSession?: ChatSession | null;\n\n accessToken: string,\n serverBaseUrl: string,\n /**\n * Per-row override hook. Whatever fields you return are merged on top\n * of the hook's computed item — typical use is adding a `kind` tag for\n * application-specific session types (`'chat' | 'composer' | ...`) the\n * library doesn't know about.\n */\n decorate?: (session: ChatSession) => Partial<ChatSessionListItem>;\n}\n\nexport interface UseChatSessionsResult {\n /** Flat list (live session merged in, server order preserved). */\n sessions: ChatSession[];\n /** Same data bucketed by recency. */\n groups: ChatSessionGroup[];\n isLoading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n /** Optimistic rename — patches local state immediately, rolls back on failure. */\n rename: (id: string, title: string) => Promise<void>;\n /** Optimistic remove — drops from local state immediately, rolls back on failure. */\n remove: (id: string) => Promise<void>;\n}\n\nconst MINUTE_MS = 60_000;\nconst HOUR_MS = 60 * MINUTE_MS;\nconst DAY_MS = 24 * HOUR_MS;\n\nfunction toDate(value: Date | string | undefined | null): Date | undefined {\n if (!value) return undefined;\n if (value instanceof Date) return value;\n const d = new Date(value);\n return Number.isNaN(d.getTime()) ? undefined : d;\n}\n\nfunction formatTimeLabel(date: Date | undefined): string {\n if (!date) return '';\n const diff = Date.now() - date.getTime();\n if (diff < MINUTE_MS) return 'now';\n if (diff < HOUR_MS) return `${Math.floor(diff / MINUTE_MS)}m`;\n if (diff < DAY_MS) return `${Math.floor(diff / HOUR_MS)}h`;\n if (diff < 7 * DAY_MS) return `${Math.floor(diff / DAY_MS)}d`;\n return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });\n}\n\nfunction startOfToday(): Date {\n const d = new Date();\n d.setHours(0, 0, 0, 0);\n return d;\n}\n\nfunction groupByTime(items: ChatSessionListItem[]): ChatSessionGroup[] {\n const today = startOfToday();\n const yesterday = new Date(today.getTime() - DAY_MS);\n const weekAgo = new Date(today.getTime() - 7 * DAY_MS);\n const monthAgo = new Date(today.getTime() - 30 * DAY_MS);\n\n // Insertion-ordered map preserves the bucket display order.\n const buckets: Array<[string, ChatSessionListItem[]]> = [\n ['Today', []],\n ['Yesterday', []],\n ['This Week', []],\n ['This Month', []],\n ['Older', []],\n ];\n\n for (const item of items) {\n const u = item.updatedAt;\n if (!u) { buckets[4][1].push(item); continue; }\n if (u >= today) buckets[0][1].push(item);\n else if (u >= yesterday) buckets[1][1].push(item);\n else if (u >= weekAgo) buckets[2][1].push(item);\n else if (u >= monthAgo) buckets[3][1].push(item);\n else buckets[4][1].push(item);\n }\n\n return buckets\n .filter(([, list]) => list.length > 0)\n .map(([label, list]) => ({ label, items: list }));\n}\n\nfunction buildItem(\n session: ChatSession,\n decorate?: (s: ChatSession) => Partial<ChatSessionListItem>,\n): ChatSessionListItem {\n const updatedAt = toDate(session.updatedAt) ?? toDate(session.created);\n const base: ChatSessionListItem = {\n id: session.id ?? session.browserScopeId ?? '',\n title: session.overview || session.userDescription || '(untitled chat)',\n snippet: session.lastQuestion ?? undefined,\n timeLabel: formatTimeLabel(updatedAt),\n kind: session.agentType as string | undefined,\n updatedAt,\n raw: session,\n };\n return { ...base, ...(decorate?.(session) ?? {}) };\n}\n\n/**\n * Fetch + organise the user's chat sessions for a picker UI. Backend-agnostic\n * — the host injects an `ISessionService` so the same hook drives an HTTP\n * client, an in-memory fake, or whatever else.\n *\n * Replaces the duplicated `useEffect(async () => sessionService.getAllSessions())`\n * + grouping logic that lived in DataExplorerViewV2 and MobileSessionsList,\n * and consolidates the optimistic rename/delete pattern.\n */\nexport function useChatSessions(opts: UseChatSessionsOptions): UseChatSessionsResult {\n\n const defaultSessionService = useMemo(() => {\n return new HttpSessionService(opts.serverBaseUrl, opts.accessToken);\n }, [opts.accessToken, opts.serverBaseUrl]);\n\n const { sessionService, liveSession, decorate } = {\n sessionService: defaultSessionService,\n liveSession: opts.liveSession,\n decorate: opts.decorate\n };\n const [sessions, setSessions] = useState<ChatSession[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n\n\n const refresh = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const list = await sessionService.getAllSessions();\n setSessions(list);\n } catch (err) {\n setError(err instanceof Error ? err : new Error(String(err)));\n } finally {\n setIsLoading(false);\n }\n }, [sessionService]);\n\n useEffect(() => { void refresh(); }, [refresh]);\n\n const merged = useMemo(() => {\n if (!liveSession?.id) return sessions;\n const idx = sessions.findIndex(s => s.id === liveSession.id);\n if (idx === -1) return [liveSession, ...sessions];\n const copy = sessions.slice();\n copy[idx] = liveSession;\n return copy;\n }, [sessions, liveSession]);\n\n const items = useMemo(\n () => merged.map(s => buildItem(s, decorate)),\n [merged, decorate],\n );\n\n const groups = useMemo(() => groupByTime(items), [items]);\n\n const rename = useCallback(async (id: string, title: string) => {\n setSessions(current =>\n current.map(s => (s.id === id ? { ...s, overview: title } : s)),\n );\n try {\n await sessionService.patchSession(id, { overview: title });\n } catch (err) {\n console.error('[useChatSessions] rename failed; refreshing to roll back:', err);\n void refresh();\n }\n }, [sessionService, refresh]);\n\n const remove = useCallback(async (id: string) => {\n setSessions(current => current.filter(s => s.id !== id));\n try {\n await sessionService.removeSession(id);\n } catch (err) {\n console.error('[useChatSessions] remove failed; refreshing to roll back:', err);\n void refresh();\n }\n }, [sessionService, refresh]);\n\n return { sessions: merged, groups, isLoading, error, refresh, rename, remove };\n}\n"],"names":["MINUTE_MS","HOUR_MS","DAY_MS","toDate","value","d","__name","formatTimeLabel","date","diff","startOfToday","groupByTime","items","today","yesterday","weekAgo","monthAgo","buckets","item","u","list","label","buildItem","session","decorate","updatedAt","useChatSessions","opts","defaultSessionService","useMemo","HttpSessionService","sessionService","liveSession","sessions","setSessions","useState","isLoading","setIsLoading","error","setError","refresh","useCallback","err","useEffect","merged","idx","s","copy","groups","rename","id","title","current","remove"],"mappings":";;;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lB,EAAYC,CAAK,GAAG,CAACA,CAAK,CAAC,GAElDqC,IAASR,EAAY,OAAOS,GAAYC,MAAkB;AAC5D,IAAAjB;AAAA,MAAY,CAAAkB,MACRA,EAAQ,IAAI,CAAAN,MAAMA,EAAE,OAAOI,IAAK,EAAE,GAAGJ,GAAG,UAAUK,EAAA,IAAUL,CAAE;AAAA,IAAA;AAElE,QAAI;AACA,YAAMf,EAAe,aAAamB,GAAI,EAAE,UAAUC,GAAO;AAAA,IAC7D,SAAST,GAAK;AACV,cAAQ,MAAM,6DAA6DA,CAAG,GACzEF,EAAA;AAAA,IACT;AAAA,EACJ,GAAG,CAACT,GAAgBS,CAAO,CAAC,GAEtBa,IAASZ,EAAY,OAAOS,MAAe;AAC7C,IAAAhB,EAAY,OAAWkB,EAAQ,OAAO,OAAKN,EAAE,OAAOI,CAAE,CAAC;AACvD,QAAI;AACA,YAAMnB,EAAe,cAAcmB,CAAE;AAAA,IACzC,SAASR,GAAK;AACV,cAAQ,MAAM,6DAA6DA,CAAG,GACzEF,EAAA;AAAA,IACT;AAAA,EACJ,GAAG,CAACT,GAAgBS,CAAO,CAAC;AAE5B,SAAO,EAAE,UAAUI,GAAQ,QAAAI,GAAQ,WAAAZ,GAAW,OAAAE,GAAO,SAAAE,GAAS,QAAAS,GAAQ,QAAAI,EAAA;AAC1E;AAtEgB/C,EAAAoB,GAAA;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aintela/chat",
3
- "version": "0.4.34",
3
+ "version": "0.4.35",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -1 +0,0 @@
1
- {"version":3,"file":"httpSessionService-B3CxFtl1.js","sources":["../src/services/sessionEventDecoder.ts","../src/services/accessTokenProvider.ts","../src/services/httpSessionService.ts"],"sourcesContent":["import { ServerEvent } from '../models/ServerEvent';\nimport { LlmEvent } from '../models/semanticKernelModel/models';\nimport { createEventSerializer } from '../models/semanticKernelModel/serializer';\nimport { EventType } from '../models/enums';\nimport type { Interaction } from '../models/Interaction';\nimport type { InteractionPart } from '../models/InteractionPart';\nimport type { Artifact } from '../models/Artifact';\n\n/**\n * Strip the persistence-only `$type: \"MongoDbEvent\"` marker from the wire\n * object before handing it to typedjson. The server's session-detail endpoint\n * returns base-class `Event` instances (not `MongoDbEvent`), but downstream\n * resources that come through other code paths sometimes carry that marker;\n * leaving it in confuses typedjson because it isn't registered in\n * `KNOWN_CONTENT_TYPES`.\n */\nfunction stripMongoDbDiscriminator(raw: unknown): unknown {\n if (raw === null || typeof raw !== 'object') return raw;\n const obj = raw as Record<string, unknown>;\n if (obj['$type'] === 'MongoDbEvent') {\n const { ['$type']: _drop, ...rest } = obj;\n return rest;\n }\n return obj;\n}\n\nfunction firstUserText(events: LlmEvent[]): string | undefined {\n for (const e of events) {\n if (e.role?.label?.toLowerCase() !== 'user') continue;\n const item = e.content?.items?.find(p => 'text' in p && typeof (p as Record<string, unknown>).text === 'string');\n if (item) return (item as { text?: string }).text;\n }\n return undefined;\n}\n\n// The .NET semantic-kernel metadata key that carries the model's reasoning\n// trace on persisted (consolidated) events. typedjson drops `metadata` on\n// KernelContent-derived items (it's undecorated), so the reasoning only\n// survives on the RAW wire object — we read it from there.\nconst REASONING_METADATA_KEY = 'ChatResponseMessage.ReasoningContent';\n\n/**\n * Pull the reasoning trace out of a raw wire event. The server duplicates it\n * onto the message `content.metadata` and onto each text item's `metadata`;\n * prefer the event-level copy, fall back to the first item that carries one.\n */\nfunction extractReasoning(rawEvent: unknown): string | undefined {\n const content = (rawEvent as { content?: Record<string, any> })?.content;\n if (!content) return undefined;\n const fromContent = content.metadata?.[REASONING_METADATA_KEY];\n if (typeof fromContent === 'string' && fromContent.trim()) return fromContent.trim();\n for (const item of content.items ?? []) {\n const r = item?.metadata?.[REASONING_METADATA_KEY];\n if (typeof r === 'string' && r.trim()) return r.trim();\n }\n return undefined;\n}\n\nfunction isFunctionCallType(t: EventType): boolean {\n return t === EventType.FunctionCall || t === EventType.PartialFunctionCall;\n}\n\n/**\n * Fold a FunctionResponse part onto the call part it answers, mirroring the\n * final state a live `merge` would have reached for that call: the call's\n * parsed `args`/`name`/`start` are preserved and the response's\n * `response`/`status`/`end` are layered on. eventType flips to\n * FunctionResponse, which is the completed-call shape the UI renders.\n */\nfunction foldResponseIntoCall(call: InteractionPart, response: InteractionPart): InteractionPart {\n return {\n ...call,\n eventType: EventType.FunctionResponse,\n functionDetails: {\n id: call.functionDetails!.id,\n name: response.functionDetails?.name ?? call.functionDetails!.name,\n args: call.functionDetails!.args ?? response.functionDetails?.args,\n text: call.functionDetails!.text,\n response: response.functionDetails?.response,\n status: response.functionDetails?.status ?? 'Done',\n start: call.functionDetails!.start,\n end: response.functionDetails?.end ?? call.functionDetails!.end,\n silent: call.functionDetails!.silent,\n },\n };\n}\n\n/**\n * Rebuilds the `Interaction[]` the chat UI renders from the historical event\n * log returned by <c>GET /sessions/{id}</c>.\n *\n * Unlike the live turn loop, this does NOT route events through\n * `InteractionService.merge`. The merge pipeline (and its `FlatParts` step) is\n * built for the *live* stream, where each event carries a single content item\n * arriving incrementally; it flattens every event down to one part. The\n * *persisted* log is different: the server stores consolidated blocks where a\n * single event's `content.items` holds many parts at once — e.g. a text\n * preamble plus several FunctionCalls. Running those through `merge` collapsed\n * each event to one part and silently dropped the rest (every function call in\n * a multi-item event disappeared on replay).\n *\n * This restore path instead reads *every* item as its own `InteractionPart`\n * (via `ServerEvent.parseFromTypedEvent`, which already maps one part per\n * item) and only applies the one piece of merge logic replay genuinely needs:\n * folding each FunctionResponse onto the call it answers, keyed by `callId`.\n * No copy-on-write cloning, no event-bus side effects, no streaming-append.\n */\nexport function decodeSessionEvents(rawEvents: unknown[]): Interaction[] {\n const serializer = createEventSerializer();\n\n // Parse + group by interactionId, preserving first-seen order so the\n // rendered timeline mirrors the wire-log order. Keep the typed LlmEvent\n // alongside the mapped ServerEvent — the former carries the role label\n // used to derive the interaction's question.\n const order: string[] = [];\n const grouped = new Map<string, { llm: LlmEvent[]; server: ServerEvent[]; raw: unknown[] }>();\n for (const raw of rawEvents) {\n const stripped = stripMongoDbDiscriminator(raw);\n const llmEvent = serializer.parse(stripped as Record<string, unknown>);\n if (!llmEvent) continue;\n const serverEvent = ServerEvent.parseFromTypedEvent(llmEvent);\n if (!serverEvent) continue;\n\n const key = serverEvent.interactionId ?? '__root__';\n let bucket = grouped.get(key);\n if (!bucket) {\n bucket = { llm: [], server: [], raw: [] };\n grouped.set(key, bucket);\n order.push(key);\n }\n bucket.llm.push(llmEvent);\n bucket.server.push(serverEvent);\n // Keep the stripped raw object — typedjson drops the item `metadata`\n // that holds the reasoning trace, so we recover it from here.\n bucket.raw.push(stripped);\n }\n\n const interactions: Interaction[] = [];\n for (const interactionId of order) {\n const { llm, server, raw } = grouped.get(interactionId)!;\n\n const parts: InteractionPart[] = [];\n const artifactData: Artifact[] = [];\n // callId → index in `parts` of the (possibly already folded) call part.\n const callIndex = new Map<string, number>();\n\n const pushPart = (part: InteractionPart) => {\n const stamped: InteractionPart = {\n ...part,\n id: `${parts.length + 1}-${interactionId}`,\n partial: false,\n isStillWriting: false,\n };\n parts.push(stamped);\n return parts.length - 1;\n };\n\n for (let i = 0; i < server.length; i++) {\n const event = server[i];\n\n // `user` events are the question (captured below as\n // interactionQuestion), and `system` events are injected context\n // (schema, instructions) — neither renders as a chat part. The\n // live turn loop never feeds these through merge either; only the\n // persisted log co-locates them under the turn's interactionId.\n const role = llm[i].role?.label?.toLowerCase();\n if (role === 'user' || role === 'system') {\n // The user/system text isn't a chat part (the question is captured as\n // interactionQuestion via firstUserText). But a user turn may carry a client-only\n // UI representation — a UserUiContent that ServerEvent mapped to a UserAnswer part —\n // which must re-hydrate on reload. Push those; drop everything else on this event.\n if (role === 'user') {\n for (const part of event.parts) {\n if (part.eventType === EventType.UserAnswer) pushPart(part);\n }\n }\n continue;\n }\n\n // Artifacts: dedupe by id, last write wins (same as the live merge).\n if (event.llmArtifacts && event.llmArtifacts.length > 0) {\n for (const llmArtifact of event.llmArtifacts) {\n const artifact = llmArtifact.toArtifact();\n const i = artifactData.findIndex(a => a.id === artifact.id);\n if (i === -1) artifactData.push(artifact);\n else artifactData[i] = artifact;\n }\n }\n\n // The model's reasoning trace for this step lives in the event's\n // metadata (dropped by typedjson — read from raw). It rides the\n // event's text item, so attach it to the first text part: a\n // non-empty answer keeps its body and carries the trace in the\n // thinking strip; an empty \"thinking-only\" step becomes a Thought.\n const reasoning = extractReasoning(raw[i]);\n let reasoningUsed = false;\n\n for (const part of event.parts) {\n const callId = part.functionDetails?.id;\n\n // A response folds onto its matching call rather than becoming\n // a separate part.\n if (part.eventType === EventType.FunctionResponse && callId && callIndex.has(callId)) {\n const idx = callIndex.get(callId)!;\n parts[idx] = foldResponseIntoCall(parts[idx], part);\n continue;\n }\n\n // A client-only output sibling folds its payload onto the call it belongs to\n // (never a separate part). This is the persisted/replay counterpart of the live\n // StreamingFinalFunctionResultContent.clientOutput; a uiTool renderer reads it.\n if (part.eventType === EventType.FunctionClientOutput && callId) {\n if (callIndex.has(callId)) {\n const idx = callIndex.get(callId)!;\n const prev = parts[idx];\n parts[idx] = {\n ...prev,\n functionDetails: {\n ...prev.functionDetails!,\n clientOutput: part.functionDetails?.clientOutput,\n },\n };\n }\n // No matching call (shouldn't happen — the call precedes its Tool message):\n // drop it rather than render a standalone part.\n continue;\n }\n\n // A repeated full call for an id we've already seen (e.g. a\n // full FunctionCall following a PartialFunctionCall) updates the\n // existing part in place instead of duplicating it.\n if (isFunctionCallType(part.eventType) && callId && callIndex.has(callId)) {\n const idx = callIndex.get(callId)!;\n const prev = parts[idx];\n parts[idx] = {\n ...prev,\n eventType: part.eventType,\n functionDetails: { ...prev.functionDetails!, ...part.functionDetails! },\n };\n continue;\n }\n\n if (part.eventType === EventType.Text) {\n const hasText = !!part.text && part.text.length > 0;\n const attachReasoning = !!reasoning && !reasoningUsed;\n\n // Empty text with no reasoning to carry is a bare\n // placeholder — the consolidated log emits these alongside\n // function calls; dropping them keeps the timeline clean.\n if (!hasText && !attachReasoning && !part.thoughtDetails) {\n continue;\n }\n\n if (attachReasoning) {\n pushPart({\n ...part,\n eventType: hasText ? EventType.Text : EventType.Thought,\n thoughtDetails: { text: reasoning! },\n // A step with no answer text BECOMES the thought, and\n // `ThoughtPart` renders `part.text` (via\n // getPartTextContent) — leaving it empty drew the\n // \"Pensou por 12s\" header over a blank window. The live\n // path already sets both (see `createFromThought`); this\n // is the same part rebuilt from Session.Events, so it has\n // to agree. When there IS answer text the part stays a\n // Text and keeps it — the reasoning rides the strip.\n text: hasText ? part.text : reasoning!,\n });\n reasoningUsed = true;\n continue;\n }\n\n pushPart(part);\n continue;\n }\n\n const idx = pushPart(part);\n if (isFunctionCallType(part.eventType) && callId) {\n callIndex.set(callId, idx);\n }\n }\n\n // Reasoning with no text item to ride on (rare) — surface it so\n // the trace isn't silently lost.\n if (reasoning && !reasoningUsed) {\n pushPart({\n id: '', author: event.author, eventType: EventType.Thought,\n created: event.created, partial: false, isStillWriting: false,\n mustPush: false, textAppendable: false,\n thoughtDetails: { text: reasoning },\n // Both, for the same reason as above: the renderer reads `text`.\n text: reasoning,\n });\n }\n }\n\n const functionMap = new Map<string, InteractionPart>();\n for (const [callId, idx] of callIndex) functionMap.set(callId, parts[idx]);\n\n interactions.push({\n created: server[0]?.created ?? new Date(),\n interactionId,\n artifactData,\n partial: false,\n turn_complete: true,\n parts,\n version: server.length,\n functionMap,\n interactionQuestion: firstUserText(llm) ?? '',\n });\n }\n\n return interactions;\n}\n","/**\n * A bearer-token source for the library's HTTP clients: either a fixed token\n * string (legacy behavior) or a callback resolved on EVERY request, so a\n * long-lived service always sends the freshest JWT (sign-in, silent refresh,\n * guest→real promotion) instead of the one captured at construction.\n */\nexport type AccessTokenProvider = string | (() => string | undefined);\n\n/** The current token for `provider` (empty string when a callback yields none). */\nexport function resolveAccessToken(provider: AccessTokenProvider): string {\n return (typeof provider === 'function' ? provider() : provider) ?? '';\n}\n","import { ChatSession, Customer, decodeSessionEvents, Interaction, ISessionService } from \"..\";\nimport { resolveAccessToken, type AccessTokenProvider } from \"./accessTokenProvider\";\n\n/**\n * Wire shape returned by `GET /sessions` and the `.header` of `GET /sessions/{id}`.\n * Mirrors `Envision.SemanticKernel.Models.Session.SessionHeader` on the C#\n * side after the default camelCase rename ASP.NET Core applies on serialize.\n */\ninterface SessionHeaderWire {\n id: string;\n created?: string | null;\n updatedAt?: string | null;\n user?: ChatSession['user'];\n customer?: ChatSession['customer'];\n overview?: string | null;\n agentType?: ChatSession['agentType'];\n userDescription?: string | null;\n lastQuestion?: string | null;\n activityCount?: number;\n lastGeneratedOverview?: string | null;\n artifacts?: string[];\n}\n\ninterface SessionDetailWire {\n header: SessionHeaderWire;\n events: unknown[];\n}\n\nfunction headerToChatSession(h: SessionHeaderWire, interactions: Interaction[] = []): ChatSession {\n return {\n id: h.id,\n browserScopeId: h.id,\n fullyLoaded: interactions.length > 0,\n interactions,\n artifacts: h.artifacts ?? [],\n overview: h.overview ?? '',\n agentType: h.agentType as ChatSession['agentType'],\n userDescription: h.userDescription ?? undefined,\n lastQuestion: h.lastQuestion ?? undefined,\n customer: h.customer ?? null,\n activityCount: h.activityCount ?? 0,\n user: h.user as ChatSession['user'],\n lastGeneratedOverview: h.lastGeneratedOverview ? new Date(h.lastGeneratedOverview) : null,\n sessionRunMode: 'normal' as ChatSession['sessionRunMode'],\n created: h.created ? new Date(h.created) : undefined,\n updatedAt: h.updatedAt ? new Date(h.updatedAt) : undefined,\n } as ChatSession;\n}\n\n/**\n * Minimal ISessionService over the WSServer's REST `/sessions` endpoints.\n *\n * Reads from the unified `Sessions` collection. The list endpoint returns\n * header projections; the detail endpoint returns header + the raw\n * `LlmEvent[]` log which we replay through `decodeSessionEvents` to rebuild\n * the chat UI's `Interaction[]`. Mutation methods are no-ops — write paths\n * are exercised by the live agent turn loop and the WS connection, not by\n * REST calls from the picker.\n */\nexport class HttpSessionService implements ISessionService {\n private serverBaseUrl: string;\n private accessToken: AccessTokenProvider;\n\n constructor(serverBaseUrl: string, accessToken: AccessTokenProvider) {\n this.serverBaseUrl = serverBaseUrl.replace(/\\/$/, '');\n this.accessToken = accessToken;\n }\n\n private get headers(): HeadersInit {\n return {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${resolveAccessToken(this.accessToken)}`,\n };\n }\n\n async getAllSessions(): Promise<ChatSession[]> {\n const r = await fetch(`${this.serverBaseUrl}/sessions?top=50`, {\n headers: this.headers,\n });\n if (!r.ok) throw new Error(`getAllSessions HTTP ${r.status}`);\n const headers = (await r.json()) as SessionHeaderWire[];\n return headers.map(h => headerToChatSession(h));\n }\n\n async retrieveSession(sessionId: string): Promise<ChatSession | null> {\n const r = await fetch(`${this.serverBaseUrl}/sessions/${sessionId}`, {\n headers: this.headers,\n });\n if (r.status === 404) return null;\n if (!r.ok) throw new Error(`retrieveSession HTTP ${r.status}`);\n const detail = (await r.json()) as SessionDetailWire;\n const interactions = decodeSessionEvents(detail.events ?? []);\n // The decoder doesn't know the sessionId — stamp it now so downstream\n // consumers (artifact loaders, debugging surfaces) can correlate back.\n for (const it of interactions) it.sessionId = detail.header.id;\n return headerToChatSession(detail.header, interactions);\n }\n\n async getLastUsedSession(): Promise<ChatSession | null> {\n const all = await this.getAllSessions();\n return all[0] ?? null;\n }\n\n // — Most write paths are inert: after the dual-collection collapse the\n // server populates Session UI-header fields automatically during the turn.\n // The two exceptions are rename (`patchSession` → PATCH /Session/Overview)\n // and delete (`removeSession` → DELETE /Session/{id}), which are driven by\n // the picker UI and have no WS-side equivalent. —\n\n async removeSession(sessionId: string): Promise<void> {\n const r = await fetch(`${this.serverBaseUrl}/Session/${encodeURIComponent(sessionId)}`, {\n method: 'DELETE',\n headers: this.headers,\n });\n if (!r.ok) throw new Error(`removeSession HTTP ${r.status}`);\n }\n async createSession(_sessionId: string, _agentName: string, _customer?: Customer): Promise<ChatSession | null> { return null; }\n async createAgentSession(): Promise<any> { return { sessionId: null }; }\n async closeSession(_sessionId: string): Promise<void> { /* no-op */ }\n async generateOverviewForCurrentSession(_sys: string, _model: string): Promise<string | null> { return null; }\n async storeSession(session: ChatSession): Promise<any> { return { data: session }; }\n async patchSession(sessionId: string, partial: Partial<ChatSession>): Promise<void> {\n // SessionController.PatchOverview binds sessionId/overview from the\n // query string (no body, no route params). Anything else on `partial`\n // has no server-side endpoint yet — ignore it instead of guessing.\n if (partial.overview == null) return;\n const url =\n `${this.serverBaseUrl}/Session/Overview` +\n `?sessionId=${encodeURIComponent(sessionId)}` +\n `&overview=${encodeURIComponent(partial.overview)}`;\n const r = await fetch(url, { method: 'PATCH', headers: this.headers });\n if (!r.ok) throw new Error(`patchSession HTTP ${r.status}`);\n }\n delayedPatchActiveSession(_partial: Partial<ChatSession>): void { /* no-op */ }\n\n async patchActiveSession(_partial: Partial<ChatSession>): Promise<ChatSession | null> {\n return Promise.resolve(null);\n }\n async getLlmSessionInformation(): Promise<any> { return { id: null, instructionSummaries: [] }; }\n transformIntoInstances(session: ChatSession): ChatSession { return session; }\n}\n"],"names":["stripMongoDbDiscriminator","raw","obj","_drop","rest","__name","firstUserText","events","e","_b","_a","item","_d","_c","p","REASONING_METADATA_KEY","extractReasoning","rawEvent","content","fromContent","r","isFunctionCallType","t","EventType","foldResponseIntoCall","call","response","_e","decodeSessionEvents","rawEvents","serializer","createEventSerializer","order","grouped","stripped","llmEvent","serverEvent","ServerEvent","key","bucket","interactions","interactionId","llm","server","parts","artifactData","callIndex","pushPart","part","stamped","i","event","role","llmArtifact","artifact","a","reasoning","reasoningUsed","callId","idx","prev","hasText","attachReasoning","functionMap","resolveAccessToken","provider","headerToChatSession","h","_HttpSessionService","serverBaseUrl","accessToken","__publicField","sessionId","detail","it","_sessionId","_agentName","_customer","_sys","_model","session","partial","url","_partial","HttpSessionService"],"mappings":";;;;;;AAgBA,SAASA,EAA0BC,GAAuB;AACtD,MAAIA,MAAQ,QAAQ,OAAOA,KAAQ,SAAU,QAAOA;AACpD,QAAMC,IAAMD;AACZ,M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