@aintela/chat 0.5.3 → 0.7.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 +46 -3
- package/dist/Memory-BUnmYGNv.js +37 -0
- package/dist/Memory-BUnmYGNv.js.map +1 -0
- package/dist/components.js +7782 -7222
- package/dist/components.js.map +1 -1
- package/dist/{httpArtifactService-EEhF_mp9.js → detachedRunActivity-CjyFTKSw.js} +784 -339
- package/dist/detachedRunActivity-CjyFTKSw.js.map +1 -0
- package/dist/detachedRunModel-X59Pb5V-.js +67 -0
- package/dist/detachedRunModel-X59Pb5V-.js.map +1 -0
- package/dist/hooks.js +1 -1
- package/dist/httpSessionService-Ckb9Cxia.js +320 -0
- package/dist/httpSessionService-Ckb9Cxia.js.map +1 -0
- package/dist/index.js +291 -265
- package/dist/models.js +46 -39
- package/dist/{serializer-CC-nM3ig.js → serializer-DNUH6kgE.js} +607 -547
- package/dist/serializer-DNUH6kgE.js.map +1 -0
- package/dist/services.js +22 -15
- package/dist/src/components/AiChat/AiChatContext.d.ts +3 -1
- package/dist/src/components/AiChat/AiChatTypes.d.ts +7 -1
- package/dist/src/components/AiChat/ChatPane/InteractionOriginBadge.d.ts +15 -0
- package/dist/src/components/AiChat/ChatPane/messageUserOrigin.test.d.ts +1 -0
- package/dist/src/components/AiChat/ChatPane/parts/uiToolRegistry.d.ts +1 -1
- package/dist/src/components/AiChat/aiChatEngine.d.ts +13 -1
- package/dist/src/components/AiChat/index.d.ts +1 -1
- package/dist/src/components/AiChat/stateConfiguration.d.ts +5 -5
- package/dist/src/components/index.d.ts +3 -1
- package/dist/src/components/v2/{SubAgentBoxV2.d.ts → DetachedRunBoxV2.d.ts} +6 -6
- package/dist/src/components/v2/DetachedRunTaskBox.d.ts +68 -0
- package/dist/src/components/v2/DetachedRunTaskBox.live.test.d.ts +1 -0
- package/dist/src/components/v2/DetachedRunTaskBox.test.d.ts +1 -0
- package/dist/src/components/v2/DetachedRunTranscript.d.ts +89 -0
- package/dist/src/components/v2/DetachedRunTranscript.test.d.ts +1 -0
- package/dist/src/components/v2/index.d.ts +9 -2
- package/dist/src/components/v2/toolCategories.d.ts +1 -1
- package/dist/src/components/v2/useDetachedRunLiveActivity.d.ts +30 -0
- package/dist/src/components/v2/useDetachedRunResumeKey.d.ts +15 -0
- package/dist/src/components/v2/useDetachedRunResumeKey.test.d.ts +1 -0
- package/dist/src/models/Interaction.d.ts +15 -0
- package/dist/src/models/ServerEvent.d.ts +3 -3
- package/dist/src/models/detachedRunModel.d.ts +59 -0
- package/dist/src/models/detachedRunModel.test.d.ts +1 -0
- package/dist/src/models/enums.d.ts +3 -1
- package/dist/src/models/index.d.ts +5 -4
- package/dist/src/models/semanticKernelModel/models.d.ts +27 -6
- package/dist/src/services/WebSocketConnection/WebSocketConnectionV2.d.ts +2 -1
- package/dist/src/services/WebSocketConnection/streamStats.d.ts +2 -2
- package/dist/src/services/WebSocketConnection/webSocketConnection.d.ts +15 -2
- package/dist/src/services/detachedRun/DetachedRunFramesTransport.d.ts +68 -0
- package/dist/src/services/detachedRun/DetachedRunFramesTransport.test.d.ts +1 -0
- package/dist/src/services/detachedRun/detachedRunActivity.d.ts +25 -0
- package/dist/src/services/detachedRun/streamDetachedRunFrames.d.ts +110 -0
- package/dist/src/services/detachedRun/streamDetachedRunFrames.test.d.ts +1 -0
- package/dist/src/services/index.d.ts +7 -0
- package/dist/src/services/servers/AgentGatewayService.d.ts +1 -1
- package/dist/src/services/servers/AgentGatewayWSAsync.d.ts +72 -6
- package/dist/src/services/servers/gatewayAnnounceDetachedRun.test.d.ts +1 -0
- package/dist/src/services/servers/gatewayInteractionStarted.test.d.ts +1 -0
- package/dist/src/services/wire/decodeFrame.d.ts +7 -2
- package/dist/tests/fakes/fakeWebSocket.d.ts +8 -2
- package/dist/tests/fakes/makeGateway.d.ts +3 -1
- package/dist/tests/fixtures.d.ts +8 -8
- package/dist/{useChatSessions-C6sYF4U6.js → useChatSessions-aTjNcj8q.js} +2 -2
- package/dist/{useChatSessions-C6sYF4U6.js.map → useChatSessions-aTjNcj8q.js.map} +1 -1
- package/package.json +1 -1
- package/dist/ClientMessage-DUby3KyC.js +0 -34
- package/dist/ClientMessage-DUby3KyC.js.map +0 -1
- package/dist/Memory-CjrYSkzB.js +0 -47
- package/dist/Memory-CjrYSkzB.js.map +0 -1
- package/dist/httpArtifactService-EEhF_mp9.js.map +0 -1
- package/dist/httpSessionService-wBby4ggl.js +0 -309
- package/dist/httpSessionService-wBby4ggl.js.map +0 -1
- package/dist/serializer-CC-nM3ig.js.map +0 -1
- package/dist/src/models/subAgentModel.d.ts +0 -48
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { TodoList } from '../../models/todoListModel';
|
|
2
|
+
/**
|
|
3
|
+
* What one frame of a detached run says about its progress, as far as a task box reads it (AIA Issue 1548 §3b):
|
|
4
|
+
* a tool it called, a piece of what it is writing, or its task list changing.
|
|
5
|
+
*/
|
|
6
|
+
export type DetachedRunActivitySignal = {
|
|
7
|
+
kind: 'tool';
|
|
8
|
+
name: string;
|
|
9
|
+
interactionId: string;
|
|
10
|
+
} | {
|
|
11
|
+
kind: 'text';
|
|
12
|
+
text: string;
|
|
13
|
+
partial: boolean;
|
|
14
|
+
interactionId: string;
|
|
15
|
+
} | {
|
|
16
|
+
kind: 'todo';
|
|
17
|
+
todoList: TodoList;
|
|
18
|
+
};
|
|
19
|
+
/** The tool event the agent emits whenever its task list changes; its data is the list as JSON. */
|
|
20
|
+
export declare const TODO_LIST_UPDATED_EVENT = "todolistUpdated";
|
|
21
|
+
/**
|
|
22
|
+
* The progress signals in one frame of a run's stream, in order — decoded exactly as the chat decodes the frame.
|
|
23
|
+
* Anything else (an announcement, reasoning, a tool's result) says nothing a one-line activity needs.
|
|
24
|
+
*/
|
|
25
|
+
export declare function readDetachedRunActivity(raw: unknown, serializer?: import('typedjson').TypedJSON<import('../..').StreamingResponse>): DetachedRunActivitySignal[];
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Following a detached run's frames over server-sent events (AIA Issue 1548, phase 5).
|
|
3
|
+
*
|
|
4
|
+
* The SDK serves `GET {baseUrl}/detached-runs/{id}/frames?afterSeq=N` as `text/event-stream`: one event per frame —
|
|
5
|
+
* `id: {seq}` + `data: {the frame exactly as the chat socket sends it}` — plus `event: end` + `data: {its seq}` for
|
|
6
|
+
* every turn's end marker, and `: alive` comments in between to keep proxies from idling the request out.
|
|
7
|
+
*
|
|
8
|
+
* <p><b>An `end` event is advisory; the CLOSE is what ends the stream.</b> A resumed run's turns all live in one
|
|
9
|
+
* session, each closed by its own end marker, and the server relays every one of them — it closes the response only
|
|
10
|
+
* after an end that is the last thing saved for a run no longer active. So the reader records an end's seq (a
|
|
11
|
+
* reconnect then asks from after it), keeps reading into the next turn, and decides on the close: a body that finished
|
|
12
|
+
* right after an end is over; one that finished after frames past the last end (or with no end at all) dropped, and is
|
|
13
|
+
* reconnected. Stopping at the first end froze a run opened in its second turn at the end of its first.</p>
|
|
14
|
+
*
|
|
15
|
+
* <p><b>`fetch`, not `EventSource`.</b> The route is behind a bearer token, and `EventSource` cannot send an
|
|
16
|
+
* `Authorization` header. So the body is read as a stream and parsed here, and the reconnect `EventSource` would have
|
|
17
|
+
* done is done here too: a connection that drops anywhere but right after an `end` is reopened from the last seq it delivered, on a bounded
|
|
18
|
+
* backoff, until the caller aborts.</p>
|
|
19
|
+
*
|
|
20
|
+
* <p><b>The HTTP layer is the host's to supply.</b> A host with its own auth (a refresh on 401, a tenant header) passes
|
|
21
|
+
* a fetch-compatible `fetchImpl`; a host with only a token passes `getToken`. Both may be given — the token is set as
|
|
22
|
+
* the `Authorization` header and the host's fetch may override it.</p>
|
|
23
|
+
*
|
|
24
|
+
* <p><b>A 401 gets one second chance.</b> A long follow outlives a token: on a 401 the reader asks the host's
|
|
25
|
+
* `onUnauthorized` to refresh (true ⇒ retry), or else re-reads `getToken` and retries if the token changed. A second
|
|
26
|
+
* 401 in a row is final.</p>
|
|
27
|
+
*/
|
|
28
|
+
/** The slice of `fetch` the reader uses. A host's authenticated wrapper around `window.fetch` fits it. */
|
|
29
|
+
export type DetachedRunFetch = (input: string, init: RequestInit) => Promise<Response>;
|
|
30
|
+
export interface DetachedRunFramesRetry {
|
|
31
|
+
/** First delay after a dropped connection. Default 500 ms. */
|
|
32
|
+
initialMs?: number;
|
|
33
|
+
/** The ceiling the doubling stops at. Default 15 s. */
|
|
34
|
+
maxMs?: number;
|
|
35
|
+
/** Consecutive failed attempts before the reader gives up and rejects. Default: never gives up. */
|
|
36
|
+
maxAttempts?: number;
|
|
37
|
+
}
|
|
38
|
+
export interface StreamDetachedRunFramesOptions {
|
|
39
|
+
/** The agents server the run lives on (the same base URL the chat socket dials). */
|
|
40
|
+
baseUrl: string;
|
|
41
|
+
runId: string;
|
|
42
|
+
/** The HTTP layer. Default: the global `fetch`. */
|
|
43
|
+
fetchImpl?: DetachedRunFetch;
|
|
44
|
+
/** The bearer token, read before EVERY request so a refreshed token is picked up on a reconnect. */
|
|
45
|
+
getToken?: () => string | undefined | null | Promise<string | undefined | null>;
|
|
46
|
+
/** Deliver frames after this seq. Default 0 (the run's whole history). */
|
|
47
|
+
afterSeq?: number;
|
|
48
|
+
/** Stops the reader — the open request is cancelled and the promise resolves `aborted`. */
|
|
49
|
+
signal?: AbortSignal;
|
|
50
|
+
/** One frame, parsed from its `data:` JSON, with its seq (`id:`). Frames at or below the cursor are skipped. */
|
|
51
|
+
onFrame: (frame: unknown, seq: number | undefined) => void;
|
|
52
|
+
/**
|
|
53
|
+
* The run's stream is over — the server closed it right after an `event: end` — and nothing will follow until the
|
|
54
|
+
* run is resumed. An end the server keeps streaming past (a finished turn of a run still going) does not fire it.
|
|
55
|
+
*/
|
|
56
|
+
onEnd?: (lastSeq: number) => void;
|
|
57
|
+
/** A request was answered with a stream (every successful (re)connect). */
|
|
58
|
+
onOpen?: () => void;
|
|
59
|
+
/**
|
|
60
|
+
* A request was answered 401. Refresh the credentials and resolve true to retry once with a fresh `getToken`;
|
|
61
|
+
* false (or no hook) retries only when `getToken` already returns a different token.
|
|
62
|
+
*/
|
|
63
|
+
onUnauthorized?: () => Promise<boolean>;
|
|
64
|
+
/** A connection failed or dropped and will be retried in `retryInMs`. */
|
|
65
|
+
onRetry?: (error: unknown, attempt: number, retryInMs: number) => void;
|
|
66
|
+
retry?: DetachedRunFramesRetry;
|
|
67
|
+
}
|
|
68
|
+
export interface DetachedRunFramesResult {
|
|
69
|
+
/** `end`: the server closed the stream right after an end marker; `aborted`: the caller stopped it. */
|
|
70
|
+
reason: 'end' | 'aborted';
|
|
71
|
+
/** The highest seq delivered, end markers included — where a later follow resumes. */
|
|
72
|
+
lastSeq: number;
|
|
73
|
+
}
|
|
74
|
+
/** An answer no retry will change: the run is not there, or the caller may not see it. */
|
|
75
|
+
export declare class DetachedRunFramesHttpError extends Error {
|
|
76
|
+
readonly status: number;
|
|
77
|
+
constructor(status: number, message?: string);
|
|
78
|
+
}
|
|
79
|
+
/** Why following a run stopped for good — what a page tells the reader. */
|
|
80
|
+
export interface DetachedRunFollowError {
|
|
81
|
+
/** `notFound` 404/410 · `forbidden` 403 · `unauthorized` 401 (after the second chance) · `gaveUp` anything else. */
|
|
82
|
+
kind: 'notFound' | 'forbidden' | 'gaveUp' | 'unauthorized';
|
|
83
|
+
status?: number;
|
|
84
|
+
cause?: unknown;
|
|
85
|
+
}
|
|
86
|
+
/** Classify what {@link streamDetachedRunFrames} rejected with. */
|
|
87
|
+
export declare function toDetachedRunFollowError(error: unknown): DetachedRunFollowError;
|
|
88
|
+
/** One dispatched server-sent event. */
|
|
89
|
+
export interface SseEvent {
|
|
90
|
+
event?: string;
|
|
91
|
+
data: string;
|
|
92
|
+
id?: string;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* A server-sent-events parser over text chunks that may split anywhere — mid-line, mid-field, between the `\r` and
|
|
96
|
+
* `\n` of a CRLF. Fields per the HTML spec: `field: value` with one optional space after the colon, `data` lines joined
|
|
97
|
+
* by `\n`, a line starting with `:` is a comment, a blank line dispatches. An event with neither data nor a name is
|
|
98
|
+
* dropped (that is what a lone comment block amounts to).
|
|
99
|
+
*/
|
|
100
|
+
export declare function createSseParser(onEvent: (event: SseEvent) => void): {
|
|
101
|
+
push(chunk: string): void;
|
|
102
|
+
flush(): void;
|
|
103
|
+
idle(): boolean;
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* Follow a detached run's frames until the server ends the stream or `signal` aborts. Resolves with why it stopped
|
|
107
|
+
* and the last seq delivered; rejects with {@link DetachedRunFramesHttpError} for an answer a retry will not change
|
|
108
|
+
* (4xx other than 408/429), or with the last error once `retry.maxAttempts` consecutive attempts failed.
|
|
109
|
+
*/
|
|
110
|
+
export declare function streamDetachedRunFrames(options: StreamDetachedRunFramesOptions): Promise<DetachedRunFramesResult>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -6,6 +6,7 @@ export { EventBusService } from './eventBusService';
|
|
|
6
6
|
export type { FirstTokenEventDetails } from './eventBusService';
|
|
7
7
|
export { AgentGatewayService } from './servers/AgentGatewayService';
|
|
8
8
|
export type { GatewaySendMessageOptions } from './servers/AgentGatewayService';
|
|
9
|
+
export type { AgentGatewayOptions, AnnounceDetachedRunResult } from './servers/AgentGatewayWSAsync';
|
|
9
10
|
export { AgentGatewayWSAsync } from './servers/AgentGatewayWSAsync';
|
|
10
11
|
export { WebSocketConnecionV2 } from './WebSocketConnection/WebSocketConnectionV2';
|
|
11
12
|
export type { IWebSocketConnection, IMessage } from './WebSocketConnection/webSocketConnection';
|
|
@@ -17,3 +18,9 @@ export { HttpSessionService } from './httpSessionService';
|
|
|
17
18
|
export { HttpArtifactService } from './httpArtifactService';
|
|
18
19
|
export { resolveAccessToken } from './accessTokenProvider';
|
|
19
20
|
export type { AccessTokenProvider } from './accessTokenProvider';
|
|
21
|
+
export { streamDetachedRunFrames, createSseParser, DetachedRunFramesHttpError, toDetachedRunFollowError, } from './detachedRun/streamDetachedRunFrames';
|
|
22
|
+
export type { StreamDetachedRunFramesOptions, DetachedRunFramesResult, DetachedRunFramesRetry, DetachedRunFetch, DetachedRunFollowError, SseEvent, } from './detachedRun/streamDetachedRunFrames';
|
|
23
|
+
export { DetachedRunFramesTransport } from './detachedRun/DetachedRunFramesTransport';
|
|
24
|
+
export { readDetachedRunActivity, TODO_LIST_UPDATED_EVENT } from './detachedRun/detachedRunActivity';
|
|
25
|
+
export type { DetachedRunActivitySignal } from './detachedRun/detachedRunActivity';
|
|
26
|
+
export type { DetachedRunFramesTransportOptions } from './detachedRun/DetachedRunFramesTransport';
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { AgentGatewayWSAsync as AgentGatewayService } from './AgentGatewayWSAsync';
|
|
2
|
-
export type { GatewaySendMessageOptions } from './AgentGatewayWSAsync';
|
|
2
|
+
export type { GatewaySendMessageOptions, AnnounceDetachedRunResult } from './AgentGatewayWSAsync';
|
|
3
3
|
export type { OpenOptions as GatewayOpenOptions, HaltReason } from './connectionSupervisor';
|
|
@@ -13,10 +13,27 @@ import { AiChatState, AiChatStore } from '../../components/AiChat/stateConfigura
|
|
|
13
13
|
import { INotificationPort } from '../../interfaces/INotificationPort';
|
|
14
14
|
import { IStorageService } from '../storageService';
|
|
15
15
|
import { HaltReason, OpenOptions } from './connectionSupervisor';
|
|
16
|
+
import { InteractionStart } from '../../models/semanticKernelModel/models';
|
|
16
17
|
import { IWebSocketConnection } from '../WebSocketConnection/webSocketConnection';
|
|
17
18
|
export interface GatewaySendMessageOptions {
|
|
18
19
|
callId?: string;
|
|
19
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* What {@link AgentGatewayWSAsync.announceDetachedRun} did: `sent` — on the socket now; `queued` — a turn is open in
|
|
23
|
+
* this tab (or the socket is down), it goes out when the chat is idle and connected; `duplicate` — this tab already
|
|
24
|
+
* asked for this run's settle.
|
|
25
|
+
*/
|
|
26
|
+
export type AnnounceDetachedRunResult = 'sent' | 'queued' | 'duplicate';
|
|
27
|
+
/** Construction-time switches of {@link AgentGatewayWSAsync}. */
|
|
28
|
+
export interface AgentGatewayOptions {
|
|
29
|
+
/**
|
|
30
|
+
* The gateway shows ONE detached run's own session as its transcript (AIA Issue 1548, `DetachedRunTranscript`).
|
|
31
|
+
* Every frame on a run's session carries `detachedRunId`, which normally routes it to the run's box
|
|
32
|
+
* ({@link AgentGatewayWSAsync.handleDetachedRunEvent}) instead of the conversation; in this mode those frames ARE
|
|
33
|
+
* the conversation, and are treated as ordinary transcript frames.
|
|
34
|
+
*/
|
|
35
|
+
transcriptOfDetachedRun?: boolean;
|
|
36
|
+
}
|
|
20
37
|
/**
|
|
21
38
|
* The agent gateway: owns the live session's interactions, turns server events
|
|
22
39
|
* into interaction trees (through {@link InteractionService} and the reducer),
|
|
@@ -41,6 +58,19 @@ export declare class AgentGatewayWSAsync {
|
|
|
41
58
|
protected interactionCallIds: Map<string, string>;
|
|
42
59
|
/** Interactions whose turn was committed (turn-complete or a server error); a second close is ignored. */
|
|
43
60
|
protected committedTurns: Set<string>;
|
|
61
|
+
/** Interactions this tab sent. An `InteractionStarted` for one of them announces what is already here. */
|
|
62
|
+
protected localInteractionIds: Set<string>;
|
|
63
|
+
/**
|
|
64
|
+
* Turns open right now, local and remote. `turnOpen` in the store is "any of these": a remote turn finishing
|
|
65
|
+
* must not unlock the composer under a local turn still streaming, nor the other way round.
|
|
66
|
+
*/
|
|
67
|
+
protected openTurns: Set<string>;
|
|
68
|
+
protected readonly options: AgentGatewayOptions;
|
|
69
|
+
/** Announcements asked for in this tab, by `runId|settleKey` — a second request for the same settle is a no-op. */
|
|
70
|
+
protected announceRequested: Set<string>;
|
|
71
|
+
/** Announcements waiting for the chat to be idle (no open turn) and connected, in request order. */
|
|
72
|
+
protected pendingAnnouncements: string[];
|
|
73
|
+
private flushingAnnouncements;
|
|
44
74
|
protected rawJwt: string;
|
|
45
75
|
protected sessionId?: string;
|
|
46
76
|
eventBusService: EventBusService;
|
|
@@ -71,7 +101,7 @@ export declare class AgentGatewayWSAsync {
|
|
|
71
101
|
static readonly HALT_TURN_MESSAGE: Record<HaltReason, string>;
|
|
72
102
|
/** Publishes the live message to the store; see ThrottledEmitter for the cadence rules. */
|
|
73
103
|
private readonly liveMessage;
|
|
74
|
-
constructor(user: User, eventBusService: EventBusService, artifactService: IArtifactService, baseUrl: string, config: AgentContext, sessionStore: AiChatStore, notificationPort: INotificationPort, ws: IWebSocketConnection, storageService: IStorageService, sessionId?: string);
|
|
104
|
+
constructor(user: User, eventBusService: EventBusService, artifactService: IArtifactService, baseUrl: string, config: AgentContext, sessionStore: AiChatStore, notificationPort: INotificationPort, ws: IWebSocketConnection, storageService: IStorageService, sessionId?: string, options?: AgentGatewayOptions);
|
|
75
105
|
/**
|
|
76
106
|
* The turn the user is waiting on will not continue: close it from the client side with an error
|
|
77
107
|
* part, the same way a server error would. No-op when no turn is open.
|
|
@@ -112,25 +142,48 @@ export declare class AgentGatewayWSAsync {
|
|
|
112
142
|
getSessionId(): string | undefined;
|
|
113
143
|
setSession(sessionId: string, _toolSessionId?: string): void;
|
|
114
144
|
startInteraction(interactionQuestion: string, wasSuspended?: boolean | undefined, idOverrideForTests?: string): Interaction;
|
|
145
|
+
/** A new interaction and its merge service, in the maps. Who becomes current is the caller's decision. */
|
|
146
|
+
private registerInteraction;
|
|
147
|
+
/** The current interaction's turn is still open — it owns the live message, and must stay current. */
|
|
148
|
+
private currentTurnIsOpen;
|
|
149
|
+
/**
|
|
150
|
+
* A turn this tab did not send (AIA Issue 1548): a WhatsApp message, a platform wake turn, another tab's turn, a
|
|
151
|
+
* detached run's briefing. It becomes the current interaction only when no open turn holds that place — a local
|
|
152
|
+
* turn mid-stream keeps it, and with it the resume cursor, suspend and the client-side close; the remote turn
|
|
153
|
+
* streams into its own interaction and takes over the live message when that turn ends.
|
|
154
|
+
*/
|
|
155
|
+
private openRemoteInteraction;
|
|
156
|
+
/**
|
|
157
|
+
* An `InteractionStarted` frame. Opens a turn this tab did not send, with the text that started it as its
|
|
158
|
+
* question; ignores one this tab sent (its interaction already exists) and one already known or committed.
|
|
159
|
+
* Outside {@link AgentGatewayOptions.transcriptOfDetachedRun}, a detached run's turn is ignored too: it runs on
|
|
160
|
+
* the run's own session, and its box — not this transcript — shows it.
|
|
161
|
+
*/
|
|
162
|
+
interactionStarted(start: InteractionStart): void;
|
|
115
163
|
getInteractions(): Interaction[];
|
|
116
164
|
getCurrentInteractionId(): string | null;
|
|
117
165
|
getCurrentInteraction(): Interaction | null;
|
|
118
166
|
protected updateMap(serverEvent: ServerEvent): Interaction | undefined;
|
|
119
167
|
protected getNewInteractionId(): string;
|
|
120
168
|
Message(event: MessageEvent | ServerEvent): Promise<void>;
|
|
121
|
-
protected
|
|
122
|
-
protected
|
|
123
|
-
protected
|
|
169
|
+
protected detachedRunInteractions: Map<string, Interaction>;
|
|
170
|
+
protected detachedRunInteractionServices: Map<string, InteractionService>;
|
|
171
|
+
protected getOrCreateDetachedRunInteraction(detachedRunId: string, interactionId: string, detachedRunName?: string): {
|
|
124
172
|
interaction: Interaction;
|
|
125
173
|
service: InteractionService;
|
|
126
174
|
};
|
|
127
|
-
protected
|
|
175
|
+
protected handleDetachedRunEvent(serverEvent: ServerEvent): void;
|
|
128
176
|
protected localEmitToolEvent(toolDetails: ToolEventDetails): void;
|
|
129
177
|
protected registerInteractionCallId(interactionId: string, options?: GatewaySendMessageOptions): void;
|
|
130
178
|
protected localEmitFirstToken(interactionId: string): void;
|
|
131
179
|
protected localEmitMessage(message: Interaction): void;
|
|
132
180
|
protected localOpen(interactionId: string, _author: string): void;
|
|
133
|
-
protected turnComplete(interactionId: string, agentInteraction: Interaction, _author: string,
|
|
181
|
+
protected turnComplete(interactionId: string, agentInteraction: Interaction, _author: string, detachedRunId?: string): Promise<void>;
|
|
182
|
+
/**
|
|
183
|
+
* The current turn ended while another is still open (a remote turn that started under it): that one becomes
|
|
184
|
+
* current and its progress so far goes live at once.
|
|
185
|
+
*/
|
|
186
|
+
private handOverLiveMessage;
|
|
134
187
|
runningRequests: Map<string, Promise<Artifact | null>>;
|
|
135
188
|
asyncLoadArtifact(artifactId: string): Promise<Artifact | null>;
|
|
136
189
|
/**
|
|
@@ -169,6 +222,19 @@ export declare class AgentGatewayWSAsync {
|
|
|
169
222
|
* thrown from a click handler — with the answer lost either way.
|
|
170
223
|
*/
|
|
171
224
|
answerHumanTool(toolCallId: string, answer: string): 'sent' | 'queued';
|
|
225
|
+
/**
|
|
226
|
+
* Ask the server to tell this conversation about a detached run of it that settled (AIA Issue 1548 §5): the
|
|
227
|
+
* `AnnounceDetachedRun` socket action. The server claims every settled-and-unannounced run of the session at once
|
|
228
|
+
* (two tabs asking, one wins) and starts an ordinary turn on this socket, `origin: platform`, in the host's words —
|
|
229
|
+
* which arrives as any remote turn does (`InteractionStarted`).
|
|
230
|
+
*
|
|
231
|
+
* <p>Never over a turn: while one is open in this tab the request waits, and goes out when the chat is idle (and
|
|
232
|
+
* the socket up). `settleKey` — the run's `settledAt` — scopes the dedupe: a repeated request for the same settle
|
|
233
|
+
* is a no-op, a resumed run that settles anew is announced again.</p>
|
|
234
|
+
*/
|
|
235
|
+
announceDetachedRun(runId: string, settleKey?: string | null): Promise<AnnounceDetachedRunResult>;
|
|
236
|
+
/** Send the queued announcements, oldest first, while the chat is idle and the socket is open. */
|
|
237
|
+
private flushAnnouncements;
|
|
172
238
|
suspend(): Promise<boolean>;
|
|
173
239
|
sleep(ms: number): Promise<unknown>;
|
|
174
240
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { LlmEvent, StreamingResponse, PartialLlmEvent } from '../../models/semanticKernelModel/models';
|
|
1
|
+
import { InteractionStart, LlmEvent, StreamingResponse, PartialLlmEvent } from '../../models/semanticKernelModel/models';
|
|
2
2
|
/**
|
|
3
3
|
* The server narrows a delta-only frame to `pe` (PartialEvent.cs): no envelope
|
|
4
4
|
* fields beyond the interaction id, and one of `pt` (text, or the ARGUMENTS
|
|
@@ -13,9 +13,14 @@ export declare function llmEventFromPartial(pe: PartialLlmEvent): LlmEvent;
|
|
|
13
13
|
/**
|
|
14
14
|
* The LlmEvent carried by a frame, whichever form it took — the full `event`,
|
|
15
15
|
* or the narrowed `pe` widened back. Control frames (Pong, Suspended,
|
|
16
|
-
* RewindLost without a payload) yield nothing. The envelope's
|
|
16
|
+
* RewindLost without a payload) yield nothing. The envelope's detached run identity
|
|
17
17
|
* is stamped onto the event so the gateway can route it.
|
|
18
18
|
*/
|
|
19
19
|
export declare function llmEventFromFrame(frame: StreamingResponse): LlmEvent | undefined;
|
|
20
20
|
/** True when the event carries any content item or streaming part — what counts as a first token. */
|
|
21
21
|
export declare function carriesContent(event: LlmEvent): boolean;
|
|
22
|
+
/**
|
|
23
|
+
* The turn an `InteractionStarted` frame announces (AIA Issue 1548), with the envelope's detached run id carried
|
|
24
|
+
* onto it when the payload has none; undefined for any other frame, or one with no interaction id.
|
|
25
|
+
*/
|
|
26
|
+
export declare function interactionStartFromFrame(frame: StreamingResponse): InteractionStart | undefined;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ServerEvent } from '../../src/models/ServerEvent';
|
|
2
|
-
import { IMessage, IWebSocketConnection } from '../../src/services/WebSocketConnection/webSocketConnection';
|
|
3
|
-
import { InteractionStatistics } from '../../src/models/semanticKernelModel/models';
|
|
2
|
+
import { IMessage, IMessageBase, IWebSocketConnection } from '../../src/services/WebSocketConnection/webSocketConnection';
|
|
3
|
+
import { InteractionStart, InteractionStatistics } from '../../src/models/semanticKernelModel/models';
|
|
4
4
|
export declare class FakeWebSocketConnection implements IWebSocketConnection {
|
|
5
5
|
onEvent?: (event: MessageEvent | ServerEvent) => Promise<void>;
|
|
6
6
|
onError?: (error: string) => void;
|
|
@@ -10,6 +10,7 @@ export declare class FakeWebSocketConnection implements IWebSocketConnection {
|
|
|
10
10
|
onClose?: (code: number, reason: string) => void;
|
|
11
11
|
onNewPacket?: (stats: InteractionStatistics) => void;
|
|
12
12
|
onRewindLost?: never;
|
|
13
|
+
onInteractionStarted?: (start: InteractionStart) => void;
|
|
13
14
|
readonly recordedSends: IMessage[];
|
|
14
15
|
sessionIdToReturn: string;
|
|
15
16
|
/** Every `connect()` call — the id and options the gateway dialled with, in order. */
|
|
@@ -25,6 +26,9 @@ export declare class FakeWebSocketConnection implements IWebSocketConnection {
|
|
|
25
26
|
resume?: boolean;
|
|
26
27
|
openInteractionId?: string;
|
|
27
28
|
}): Promise<string>;
|
|
29
|
+
/** Every non-turn frame (`AnnounceDetachedRun`) sent through `sendBaseMessage`. */
|
|
30
|
+
readonly recordedBaseSends: IMessageBase[];
|
|
31
|
+
sendBaseMessage(message: IMessageBase): void;
|
|
28
32
|
sendMessage(message: IMessage): void;
|
|
29
33
|
suspendStream(): void;
|
|
30
34
|
disconnect(): void;
|
|
@@ -44,5 +48,7 @@ export declare class FakeWebSocketConnection implements IWebSocketConnection {
|
|
|
44
48
|
* merge path is fully synchronous after the await, but if onEvent
|
|
45
49
|
* ever grows an internal async hop the test stays correct).
|
|
46
50
|
*/
|
|
51
|
+
/** Drive an `InteractionStarted` announcement, as the real transport does for that frame type. */
|
|
52
|
+
announce(start: InteractionStart): void;
|
|
47
53
|
deliver(event: ServerEvent): Promise<void>;
|
|
48
54
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { AiChatStore } from '../../src/components/AiChat/stateConfiguration';
|
|
2
2
|
import { EventBusService } from '../../src/services/eventBusService';
|
|
3
|
-
import { AgentGatewayWSAsync } from '../../src/services/servers/AgentGatewayWSAsync';
|
|
3
|
+
import { AgentGatewayWSAsync, AgentGatewayOptions } from '../../src/services/servers/AgentGatewayWSAsync';
|
|
4
4
|
import { AgentContext } from '../../src/models/contexts';
|
|
5
5
|
import { BasicNotification } from '../../src/models/Notification';
|
|
6
6
|
import { INotificationPort } from '../../src/interfaces/INotificationPort';
|
|
@@ -43,6 +43,8 @@ export interface MakeGatewayOptions {
|
|
|
43
43
|
* against the real wire code. `handle.ws` is then that object, typed as the fake.
|
|
44
44
|
*/
|
|
45
45
|
ws?: IWebSocketConnection;
|
|
46
|
+
/** Construction-time gateway switches (e.g. `transcriptOfDetachedRun`). */
|
|
47
|
+
gatewayOptions?: AgentGatewayOptions;
|
|
46
48
|
}
|
|
47
49
|
/**
|
|
48
50
|
* Build a fully-wired AgentGatewayWSAsync for tests. The `ws` field is
|
package/dist/tests/fixtures.d.ts
CHANGED
|
@@ -35,17 +35,17 @@ export declare function serverEvent(opts: {
|
|
|
35
35
|
asyncFinalResponse?: boolean;
|
|
36
36
|
author?: 'main' | 'tool' | 'system';
|
|
37
37
|
llmArtifacts?: LlmArtifact[];
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
detachedRunId?: string;
|
|
39
|
+
detachedRunName?: string;
|
|
40
40
|
}): ServerEventType;
|
|
41
41
|
/**
|
|
42
|
-
* A
|
|
43
|
-
* the `
|
|
44
|
-
* `
|
|
42
|
+
* A detached run text event. Same shape as `partialTextEvent` but carries
|
|
43
|
+
* the `detachedRunId` / `detachedRunName` that routes the event through
|
|
44
|
+
* `handleDetachedRunEvent` (separate Interaction tree from the main turn).
|
|
45
45
|
*/
|
|
46
|
-
export declare function
|
|
47
|
-
|
|
48
|
-
|
|
46
|
+
export declare function detachedRunTextEvent(interactionId: string, opts: {
|
|
47
|
+
detachedRunId: string;
|
|
48
|
+
detachedRunName?: string;
|
|
49
49
|
text: string;
|
|
50
50
|
partial?: boolean;
|
|
51
51
|
turn_complete?: boolean;
|
|
@@ -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-
|
|
4
|
+
import { H } from "./httpSessionService-Ckb9Cxia.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-
|
|
107
|
+
//# sourceMappingURL=useChatSessions-aTjNcj8q.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useChatSessions-C6sYF4U6.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,EAAE,QAAA,CAAS,IAAI,SAAYA;AACnD;AALSC,EAAAH,GAAA;AAOT,SAASI,EAAgBC,GAAgC;AACrD,MAAI,CAACA,EAAM,QAAO;AAClB,QA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AAM,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-aTjNcj8q.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;AAC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AkB,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,34 +0,0 @@
|
|
|
1
|
-
var m = Object.defineProperty;
|
|
2
|
-
var c = (a, s, i) => s in a ? m(a, s, { enumerable: !0, configurable: !0, writable: !0, value: i }) : a[s] = i;
|
|
3
|
-
var r = (a, s) => m(a, "name", { value: s, configurable: !0 });
|
|
4
|
-
var e = (a, s, i) => c(a, typeof s != "symbol" ? s + "" : s, i);
|
|
5
|
-
const t = class t {
|
|
6
|
-
constructor(s, i, d, f, y) {
|
|
7
|
-
e(this, "mimeType");
|
|
8
|
-
e(this, "data");
|
|
9
|
-
e(this, "friendlyMessage");
|
|
10
|
-
e(this, "fake");
|
|
11
|
-
/**
|
|
12
|
-
* Optional image attachments that travel as a structured payload
|
|
13
|
-
* on the WS frame (see `IMessage.Images`). Kept separate from
|
|
14
|
-
* `data` so we don't have to encode them into the text body — the
|
|
15
|
-
* server adds them as `ImageContent` entries on the user turn.
|
|
16
|
-
*/
|
|
17
|
-
e(this, "images");
|
|
18
|
-
/**
|
|
19
|
-
* Optional client-only UI representation for this user turn. Carried to the
|
|
20
|
-
* server as a `UserUiContent` sibling (persisted + replayed) but stripped from
|
|
21
|
-
* every model request — `data` stays the only model-facing text. `args` is a
|
|
22
|
-
* serialized JSON string. The gateway also injects a matching `UserAnswer` part
|
|
23
|
-
* on the live interaction so the component renders immediately.
|
|
24
|
-
*/
|
|
25
|
-
e(this, "userUi");
|
|
26
|
-
this.data = s, this.mimeType = i, this.friendlyMessage = f, this.fake = d, this.images = y;
|
|
27
|
-
}
|
|
28
|
-
};
|
|
29
|
-
r(t, "ClientMessage");
|
|
30
|
-
let h = t;
|
|
31
|
-
export {
|
|
32
|
-
h as C
|
|
33
|
-
};
|
|
34
|
-
//# sourceMappingURL=ClientMessage-DUby3KyC.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ClientMessage-DUby3KyC.js","sources":["../src/models/ClientMessage.ts"],"sourcesContent":["/**\n * A single image attachment carried alongside a ClientMessage. `data`\n * is the raw base64 payload (no `data:<mime>;base64,` prefix) so the\n * server can `Convert.FromBase64String` directly into bytes.\n */\nexport interface ClientMessageImage {\n mimeType: string;\n data: string;\n}\n\nexport class ClientMessage {\n mimeType: string;\n data: string;\n friendlyMessage?: string;\n fake?: boolean;\n /**\n * Optional image attachments that travel as a structured payload\n * on the WS frame (see `IMessage.Images`). Kept separate from\n * `data` so we don't have to encode them into the text body — the\n * server adds them as `ImageContent` entries on the user turn.\n */\n images?: ClientMessageImage[];\n\n /**\n * Optional client-only UI representation for this user turn. Carried to the\n * server as a `UserUiContent` sibling (persisted + replayed) but stripped from\n * every model request — `data` stays the only model-facing text. `args` is a\n * serialized JSON string. The gateway also injects a matching `UserAnswer` part\n * on the live interaction so the component renders immediately.\n */\n userUi?: { name: string; args?: string };\n\n constructor(data: string, mimeType: string, fake?: boolean, friendlyMessage?: string, images?: ClientMessageImage[]) {\n this.data = data;\n this.mimeType = mimeType;\n this.friendlyMessage = friendlyMessage;\n this.fake = fake;\n this.images = images;\n }\n}"],"names":["_ClientMessage","data","mimeType","fake","friendlyMessage","images","__publicField","__name","ClientMessage"],"mappings":";;;;AAUO,MAAMA,IAAN,MAAMA,EAAc;AAAA,EAsBzB,YAAYC,GAAcC,GAAkBC,GAAgBC,GAA0BC,GAA+B;AArBrH,IAAAC,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AACA,IAAAA,EAAA;AAOA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,EAAA;AASA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,EAAA;AAGE,SAAK,OAAOL,GACZ,KAAK,WAAWC,GAChB,KAAK,kBAAkBE,GACvB,KAAK,OAAOD,GACZ,KAAK,SAASE;AAAA,EAChB;AACF;AA7B2BE,EAAAP,GAAA;AAApB,IAAMQ,IAANR;"}
|
package/dist/Memory-CjrYSkzB.js
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
var b = Object.defineProperty;
|
|
2
|
-
var g = (a, i, r) => i in a ? b(a, i, { enumerable: !0, configurable: !0, writable: !0, value: r }) : a[i] = r;
|
|
3
|
-
var s = (a, i) => b(a, "name", { value: i, configurable: !0 });
|
|
4
|
-
var e = (a, i, r) => g(a, typeof i != "symbol" ? i + "" : i, r);
|
|
5
|
-
const n = class n {
|
|
6
|
-
constructor(i, r) {
|
|
7
|
-
e(this, "id");
|
|
8
|
-
e(this, "biName");
|
|
9
|
-
this.id = i, this.biName = r;
|
|
10
|
-
}
|
|
11
|
-
getBiName() {
|
|
12
|
-
return `BI_${this.biName}`;
|
|
13
|
-
}
|
|
14
|
-
};
|
|
15
|
-
s(n, "Account");
|
|
16
|
-
let l = n;
|
|
17
|
-
const t = {
|
|
18
|
-
ExplorerAgent: "ExplorerAgent",
|
|
19
|
-
DashboardAgent: "DashboardAgent",
|
|
20
|
-
Unknown: "Unknown"
|
|
21
|
-
}, d = [
|
|
22
|
-
"Completed",
|
|
23
|
-
"Failed",
|
|
24
|
-
"Cancelled"
|
|
25
|
-
];
|
|
26
|
-
function u(a) {
|
|
27
|
-
return a ? d.includes(a) : !1;
|
|
28
|
-
}
|
|
29
|
-
s(u, "isSubAgentTerminalStatus");
|
|
30
|
-
var h = /* @__PURE__ */ ((a) => (a[a.Table = 0] = "Table", a[a.Metric = 1] = "Metric", a[a.Chart = 2] = "Chart", a[a.Dashboards = 3] = "Dashboards", a[a.Suggestions = 4] = "Suggestions", a[a.Memory = 5] = "Memory", a))(h || {});
|
|
31
|
-
const c = {
|
|
32
|
-
0: "Table",
|
|
33
|
-
1: "Metric",
|
|
34
|
-
2: "Chart",
|
|
35
|
-
3: "Dashboards",
|
|
36
|
-
4: "Suggestions",
|
|
37
|
-
5: "Memory"
|
|
38
|
-
};
|
|
39
|
-
export {
|
|
40
|
-
l as A,
|
|
41
|
-
c as M,
|
|
42
|
-
d as S,
|
|
43
|
-
t as a,
|
|
44
|
-
h as b,
|
|
45
|
-
u as i
|
|
46
|
-
};
|
|
47
|
-
//# sourceMappingURL=Memory-CjrYSkzB.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Memory-CjrYSkzB.js","sources":["../src/models/contexts.ts","../src/models/Agent.ts","../src/models/subAgentModel.ts","../src/models/Memory.ts"],"sourcesContent":["import type { Customer } from \"./Customer\";\nimport type { Agent } from \"./Agent\";\nimport { type IDBStorable } from \"./IDBStorable\";\n\nexport class Account {\n id: string;\n biName: string;\n\n constructor(id: string, biName: string) {\n this.id = id;\n this.biName = biName;\n }\n\n getBiName() {\n return `BI_${this.biName}`;\n }\n}\n\nexport interface User extends IDBStorable {\n email: string;\n family_name: string;\n given_name: string;\n name: string;\n hd: string;\n picture: string;\n access_token: string;\n previous_access_token?: string;\n refresh_token?: string;\n account?: Account;\n}\n\nexport interface AuthState {\n isAuthenticated: boolean;\n isLoading: boolean;\n login: (userData: User) => void;\n logout: () => void;\n errorMessage: string | null;\n}\n\nexport interface AgentContext {\n agentConfig: Partial<Agent>;\n customer?: Customer;\n model?: string;\n}\n","export type AgentKind = 'ExplorerAgent' | 'DashboardAgent' | 'Unknown';\nexport const AgentKind = {\n ExplorerAgent: 'ExplorerAgent' as AgentKind,\n DashboardAgent: 'DashboardAgent' as AgentKind,\n Unknown: 'Unknown' as AgentKind,\n} as const;\n\n/**\n * Agent model - represents an AI agent configuration\n * Mirrors the .NET Agent entity in Envision.SemanticKernel.Models.Agent\n */\nexport interface Agent {\n id: string;\n name: string;\n type?: AgentKind;\n defaultModelId?: string;\n defaultQuickModelId?: string;\n description?: string;\n muiIconName?: string;\n embeddingConfigurationId: string;\n agentImplementation?: string;\n agentBootStrapImplementation?: string;\n parameters?: Record<string, string>;\n plugins: string[];\n /** List of additional main instruction IDs (Category: Main or Generic) for this agent */\n mainInstructionIds?: string[];\n lastUpdated?: Date;\n created?: Date;\n}\n\n/**\n * Partial agent for listing purposes (only essential fields)\n */\nexport type AgentSummary = Pick<Agent, 'id' | 'name' | 'description' | 'muiIconName' | 'type'>;\n","import type { TodoList } from './todoListModel';\n\n/**\n * Mirrors `Envision.SemanticKernel.Core.SubAgent.SubAgentStatus` enum on the\n * server. Values come back as plain strings (the controller uses `Status.ToString()`).\n */\nexport type SubAgentStatus =\n | 'Pending'\n | 'Running'\n | 'Completed'\n | 'Failed'\n | 'Cancelled'\n | 'Unknown';\n\n/**\n * Lightweight representation of a chat message embedded in the SubAgentDto.\n * The server-side `Message` type carries more fields, but only the basics are\n * needed for status polling on the client.\n */\nexport interface SubAgentMessage {\n id?: string;\n role?: string;\n content?: string;\n [key: string]: unknown;\n}\n\n/**\n * TypeScript counterpart of `Envision.SemanticKernel.Core.SubAgent.SubAgentDto`.\n *\n * This is the payload returned by `GET /SubAgent/{sessionId}/{id}`.\n *\n * `TodoList.percentComplete` is serialized by the server as a fraction in the\n * range `[0, 1]` (i.e. `completedItems / totalItems`). It can be `NaN` when the\n * todo list is empty, so consumers should guard against non-finite values.\n */\nexport interface SubAgentDto {\n id?: string;\n subAgentId: string;\n name: string;\n sessionId?: string;\n dashboardId?: string | null;\n todoList?: TodoList | null;\n generalInstructions?: string | null;\n dashboardInstructions?: string | null;\n detailedStatus?: string | null;\n status: SubAgentStatus | string;\n error?: string | null;\n hasResult?: boolean | null;\n finalSummary?: string | null;\n parameters?: Record<string, string> | null;\n updatedAt?: string | Date | null;\n created?: string | Date | null;\n message?: SubAgentMessage | null;\n}\n\n/** Status values that indicate the sub-agent is no longer making progress. */\nexport const SUB_AGENT_TERMINAL_STATUSES: ReadonlyArray<SubAgentStatus> = [\n 'Completed',\n 'Failed',\n 'Cancelled',\n];\n\nexport function isSubAgentTerminalStatus(status: string | undefined | null): boolean {\n if (!status) return false;\n return (SUB_AGENT_TERMINAL_STATUSES as readonly string[]).includes(status);\n}\n","/**\n * Memory model - represents a semantic memory stored in MongoDB and Qdrant\n * Mirrors the .NET Memory entity in Envision.SemanticKernel.Core/Memory/Memory.cs\n */\n\n/**\n * Context types for memories - determines how they're filtered in semantic search\n */\nexport enum MemoryContexts {\n Table = 0, // Table schema information\n Metric = 1, // Business metrics and KPIs\n Chart = 2, // Chart/visualization descriptions\n Dashboards = 3, // Dashboard information\n Suggestions = 4, // Business recommendations\n Memory = 5 // General memories (no filter applied in search)\n}\n\n/**\n * Human-readable labels for each context type\n */\nexport const MemoryContextLabels: Record<MemoryContexts, string> = {\n [MemoryContexts.Table]: 'Table',\n [MemoryContexts.Metric]: 'Metric',\n [MemoryContexts.Chart]: 'Chart',\n [MemoryContexts.Dashboards]: 'Dashboards',\n [MemoryContexts.Suggestions]: 'Suggestions',\n [MemoryContexts.Memory]: 'Memory',\n};\n\n/**\n * Full Memory entity as stored in the database\n */\nexport interface SemanticMemory {\n id: string;\n memoryText: string;\n relatedTags?: string;\n created?: string;\n updatedAt?: string;\n // Runtime properties (populated by search results only)\n runtimeScore?: number;\n runtimeRank?: number;\n}\n\n/**\n * Input model for creating/updating memories\n * Does not include id, created, or runtime properties\n */\nexport interface SemanticMemoryInput {\n memoryText: string;\n relatedTags?: string;\n}\n\n/**\n * Options for semantic search\n */\nexport interface SemanticMemorySearchOptions {\n relatedTable?: string;\n relatedContext?: MemoryContexts;\n relatedTags?: string;\n limit?: number;\n}\n"],"names":["_Account","id","biName","__publicField","__name","Account","AgentKind","SUB_AGENT_TERMINAL_STATUSES","isSubAgentTerminalStatus","status","MemoryContexts","MemoryContextLabels"],"mappings":";;;;AAIO,MAAMA,IAAN,MAAMA,EAAQ;AAAA,EAIjB,YAAYC,GAAYC,GAAgB;AAHxC,IAAAC,EAAA;AACA,IAAAA,EAAA;AAGI,SAAK,KAAKF,GACV,KAAK,SAASC;AAAA,EAClB;AAAA,EAEA,YAAY;AACR,WAAO,MAAM,KAAK,MAAM;AAAA,EAC5B;AACJ;AAZqBE,EAAAJ,GAAA;AAAd,IAAMK,IAANL;ACHA,MAAMM,IAAY;AAAA,EACrB,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,SAAS;AACb,GCmDaC,IAA6D;AAAA,EACtE;AAAA,EACA;AAAA,EACA;AACJ;AAEO,SAASC,EAAyBC,GAA4C;AACjF,SAAKA,IACGF,EAAkD,SAASE,CAAM,IADrD;AAExB;AAHgBL,EAAAI,GAAA;ACtDT,IAAKE,sBAAAA,OACRA,EAAAA,EAAA,QAAQ,CAAA,IAAR,SACAA,EAAAA,EAAA,SAAS,CAAA,IAAT,UACAA,EAAAA,EAAA,QAAQ,CAAA,IAAR,SACAA,EAAAA,EAAA,aAAa,CAAA,IAAb,cACAA,EAAAA,EAAA,cAAc,CAAA,IAAd,eACAA,EAAAA,EAAA,SAAS,CAAA,IAAT,UANQA,IAAAA,KAAA,CAAA,CAAA;AAYL,MAAMC,IAAsD;AAAA,EAC9D,GAAuB;AAAA,EACvB,GAAwB;AAAA,EACxB,GAAuB;AAAA,EACvB,GAA4B;AAAA,EAC5B,GAA6B;AAAA,EAC7B,GAAwB;AAC7B;"}
|