@dremio/js-sdk 0.60.0 → 0.62.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 +28 -1
- package/dist/cloud/ai/AIResource.d.ts +90 -0
- package/dist/cloud/projects/Project.d.ts +5 -0
- package/dist/cloud/projects/projectPropertiesCodec.d.ts +15 -0
- package/dist/cloud/projects/projectPropertiesCodec.js +6 -0
- package/dist/cloud/projects/projectPropertiesCodec.js.map +1 -1
- package/dist/enterprise/ai/AIResource.d.ts +90 -0
- package/dist/enterprise/ai/chat/chatEventSchema.d.ts +33 -0
- package/dist/enterprise/ai/chat/chatEventSchema.js +22 -0
- package/dist/enterprise/ai/chat/chatEventSchema.js.map +1 -1
- package/dist/enterprise/ai/conversations/AgentConversation.d.ts +30 -0
- package/dist/enterprise/ai/conversations/createConversationMachine.d.ts +90 -0
- package/dist/enterprise/ai/conversations/createConversationMachine.js +3 -2
- package/dist/enterprise/ai/conversations/createConversationMachine.js.map +1 -1
- package/dist/enterprise/ai/conversations/methods/retrieveConversationHistory.d.ts +15 -0
- package/dist/enterprise/ai/conversations/reduceChatEvents.d.ts +5 -1
- package/dist/enterprise/ai/conversations/reduceChatEvents.js +93 -0
- package/dist/enterprise/ai/conversations/reduceChatEvents.js.map +1 -1
- package/dist/enterprise/ai/index.d.ts +3 -3
- package/dist/enterprise/ai/index.js.map +1 -1
- package/dist-iife/cloud.js +181 -12
- package/dist-iife/enterprise.js +175 -12
- package/package.json +1 -1
|
@@ -108,6 +108,21 @@ export declare class AgentConversation implements AgentConversationProperties {
|
|
|
108
108
|
result: Record<string, unknown>;
|
|
109
109
|
};
|
|
110
110
|
role: "agent";
|
|
111
|
+
} | {
|
|
112
|
+
conversationId: string;
|
|
113
|
+
modelName: string;
|
|
114
|
+
modelProviderId: string;
|
|
115
|
+
runId: string;
|
|
116
|
+
createdAt: import("temporal-polyfill").Temporal.Instant;
|
|
117
|
+
id: string;
|
|
118
|
+
content: {
|
|
119
|
+
chunkType: "selectedSkills";
|
|
120
|
+
selectedSkills: {
|
|
121
|
+
id: string;
|
|
122
|
+
name: string;
|
|
123
|
+
}[];
|
|
124
|
+
};
|
|
125
|
+
role: "agent";
|
|
111
126
|
} | {
|
|
112
127
|
conversationId: string;
|
|
113
128
|
modelName: string;
|
|
@@ -256,6 +271,21 @@ export declare class AgentConversation implements AgentConversationProperties {
|
|
|
256
271
|
result: Record<string, unknown>;
|
|
257
272
|
};
|
|
258
273
|
role: "agent";
|
|
274
|
+
} | {
|
|
275
|
+
conversationId: string;
|
|
276
|
+
modelName: string;
|
|
277
|
+
modelProviderId: string;
|
|
278
|
+
runId: string;
|
|
279
|
+
createdAt: import("temporal-polyfill").Temporal.Instant;
|
|
280
|
+
id: string;
|
|
281
|
+
content: {
|
|
282
|
+
chunkType: "selectedSkills";
|
|
283
|
+
selectedSkills: {
|
|
284
|
+
id: string;
|
|
285
|
+
name: string;
|
|
286
|
+
}[];
|
|
287
|
+
};
|
|
288
|
+
role: "agent";
|
|
259
289
|
} | {
|
|
260
290
|
conversationId: string;
|
|
261
291
|
modelName: string;
|
|
@@ -147,6 +147,21 @@ export declare const createConversationMachine: (config: SonarV4Config) => impor
|
|
|
147
147
|
result: Record<string, unknown>;
|
|
148
148
|
};
|
|
149
149
|
role: "agent";
|
|
150
|
+
} | {
|
|
151
|
+
conversationId: string;
|
|
152
|
+
modelName: string;
|
|
153
|
+
modelProviderId: string;
|
|
154
|
+
runId: string;
|
|
155
|
+
createdAt: import("temporal-polyfill").Temporal.Instant;
|
|
156
|
+
id: string;
|
|
157
|
+
content: {
|
|
158
|
+
chunkType: "selectedSkills";
|
|
159
|
+
selectedSkills: {
|
|
160
|
+
id: string;
|
|
161
|
+
name: string;
|
|
162
|
+
}[];
|
|
163
|
+
};
|
|
164
|
+
role: "agent";
|
|
150
165
|
} | {
|
|
151
166
|
conversationId: string;
|
|
152
167
|
modelName: string;
|
|
@@ -309,6 +324,21 @@ export declare const createConversationMachine: (config: SonarV4Config) => impor
|
|
|
309
324
|
result: Record<string, unknown>;
|
|
310
325
|
};
|
|
311
326
|
role: "agent";
|
|
327
|
+
} | {
|
|
328
|
+
conversationId: string;
|
|
329
|
+
modelName: string;
|
|
330
|
+
modelProviderId: string;
|
|
331
|
+
runId: string;
|
|
332
|
+
createdAt: import("temporal-polyfill").Temporal.Instant;
|
|
333
|
+
id: string;
|
|
334
|
+
content: {
|
|
335
|
+
chunkType: "selectedSkills";
|
|
336
|
+
selectedSkills: {
|
|
337
|
+
id: string;
|
|
338
|
+
name: string;
|
|
339
|
+
}[];
|
|
340
|
+
};
|
|
341
|
+
role: "agent";
|
|
312
342
|
} | {
|
|
313
343
|
conversationId: string;
|
|
314
344
|
modelName: string;
|
|
@@ -478,6 +508,21 @@ export declare const createConversationMachine: (config: SonarV4Config) => impor
|
|
|
478
508
|
result: Record<string, unknown>;
|
|
479
509
|
};
|
|
480
510
|
role: "agent";
|
|
511
|
+
} | {
|
|
512
|
+
conversationId: string;
|
|
513
|
+
modelName: string;
|
|
514
|
+
modelProviderId: string;
|
|
515
|
+
runId: string;
|
|
516
|
+
createdAt: import("temporal-polyfill").Temporal.Instant;
|
|
517
|
+
id: string;
|
|
518
|
+
content: {
|
|
519
|
+
chunkType: "selectedSkills";
|
|
520
|
+
selectedSkills: {
|
|
521
|
+
id: string;
|
|
522
|
+
name: string;
|
|
523
|
+
}[];
|
|
524
|
+
};
|
|
525
|
+
role: "agent";
|
|
481
526
|
} | {
|
|
482
527
|
conversationId: string;
|
|
483
528
|
modelName: string;
|
|
@@ -664,6 +709,21 @@ export declare const createConversationMachine: (config: SonarV4Config) => impor
|
|
|
664
709
|
result: Record<string, unknown>;
|
|
665
710
|
};
|
|
666
711
|
role: "agent";
|
|
712
|
+
} | {
|
|
713
|
+
conversationId: string;
|
|
714
|
+
modelName: string;
|
|
715
|
+
modelProviderId: string;
|
|
716
|
+
runId: string;
|
|
717
|
+
createdAt: import("temporal-polyfill").Temporal.Instant;
|
|
718
|
+
id: string;
|
|
719
|
+
content: {
|
|
720
|
+
chunkType: "selectedSkills";
|
|
721
|
+
selectedSkills: {
|
|
722
|
+
id: string;
|
|
723
|
+
name: string;
|
|
724
|
+
}[];
|
|
725
|
+
};
|
|
726
|
+
role: "agent";
|
|
667
727
|
} | {
|
|
668
728
|
conversationId: string;
|
|
669
729
|
modelName: string;
|
|
@@ -830,6 +890,21 @@ export declare const createConversationMachine: (config: SonarV4Config) => impor
|
|
|
830
890
|
result: Record<string, unknown>;
|
|
831
891
|
};
|
|
832
892
|
role: "agent";
|
|
893
|
+
} | {
|
|
894
|
+
conversationId: string;
|
|
895
|
+
modelName: string;
|
|
896
|
+
modelProviderId: string;
|
|
897
|
+
runId: string;
|
|
898
|
+
createdAt: import("temporal-polyfill").Temporal.Instant;
|
|
899
|
+
id: string;
|
|
900
|
+
content: {
|
|
901
|
+
chunkType: "selectedSkills";
|
|
902
|
+
selectedSkills: {
|
|
903
|
+
id: string;
|
|
904
|
+
name: string;
|
|
905
|
+
}[];
|
|
906
|
+
};
|
|
907
|
+
role: "agent";
|
|
833
908
|
} | {
|
|
834
909
|
conversationId: string;
|
|
835
910
|
modelName: string;
|
|
@@ -1011,6 +1086,21 @@ export declare const createConversationMachine: (config: SonarV4Config) => impor
|
|
|
1011
1086
|
result: Record<string, unknown>;
|
|
1012
1087
|
};
|
|
1013
1088
|
role: "agent";
|
|
1089
|
+
} | {
|
|
1090
|
+
conversationId: string;
|
|
1091
|
+
modelName: string;
|
|
1092
|
+
modelProviderId: string;
|
|
1093
|
+
runId: string;
|
|
1094
|
+
createdAt: import("temporal-polyfill").Temporal.Instant;
|
|
1095
|
+
id: string;
|
|
1096
|
+
content: {
|
|
1097
|
+
chunkType: "selectedSkills";
|
|
1098
|
+
selectedSkills: {
|
|
1099
|
+
id: string;
|
|
1100
|
+
name: string;
|
|
1101
|
+
}[];
|
|
1102
|
+
};
|
|
1103
|
+
role: "agent";
|
|
1014
1104
|
} | {
|
|
1015
1105
|
conversationId: string;
|
|
1016
1106
|
modelName: string;
|
|
@@ -23,9 +23,10 @@ import { createExchangeRun } from "./methods/createExchangeRun.js";
|
|
|
23
23
|
import { stopExchangeRun } from "./methods/stopExchangeRun.js";
|
|
24
24
|
import { streamRunEvents } from "./methods/streamRunEvents.js";
|
|
25
25
|
import { fromTextEventStream } from "../../../common/fromTextEventStream.js";
|
|
26
|
-
import { map } from "rxjs";
|
|
26
|
+
import { map, timeout } from "rxjs";
|
|
27
27
|
import { chatEventCodec } from "../chat/chatEventSchema.js";
|
|
28
28
|
const RETRIEVE_STATE_TIMEOUT_MS = 10_000;
|
|
29
|
+
const STREAM_IDLE_TIMEOUT_MS = 60_000;
|
|
29
30
|
const STREAM_RETRY_DELAY_MS = 2500;
|
|
30
31
|
export const MAX_STREAM_RETRIES = 5;
|
|
31
32
|
const STREAM_STATE_RESET = {
|
|
@@ -85,7 +86,7 @@ export const createConversationMachine = (config) => setup({
|
|
|
85
86
|
}
|
|
86
87
|
return result.value;
|
|
87
88
|
})),
|
|
88
|
-
streamRun: fromObservable(({ input }) => fromTextEventStream(({ signal }) => streamRunEvents(config)({ conversationId: input.conversationId, runId: input.runId }, { signal })).pipe(map((event) => z.decode(chatEventCodec, JSON.parse(event.data))))),
|
|
89
|
+
streamRun: fromObservable(({ input }) => fromTextEventStream(({ signal }) => streamRunEvents(config)({ conversationId: input.conversationId, runId: input.runId }, { signal })).pipe(map((event) => z.decode(chatEventCodec, JSON.parse(event.data))), timeout({ each: STREAM_IDLE_TIMEOUT_MS }))),
|
|
89
90
|
},
|
|
90
91
|
delays: {
|
|
91
92
|
STREAM_RETRY_DELAY: STREAM_RETRY_DELAY_MS,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createConversationMachine.js","sourceRoot":"","sources":["../../../../src/enterprise/ai/conversations/createConversationMachine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE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,EAAE,UAAU;aAChB;SACF;QACD,yBAAyB,EAAE;YACzB,WAAW,EAAE,0BAA0B;YACvC,EAAE,EAAE;gBACF,eAAe,EAAE;oBACf,OAAO,EAAE,MAAM,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC;oBACzC,MAAM,EAAE,oBAAoB;iBAC7B;gBACD,aAAa,EAAE;oBACb,OAAO,EAAE,MAAM,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC;oBACzC,MAAM,EAAE,oBAAoB;iBAC7B;gBACD,mBAAmB,EAAE;oBACnB,OAAO,EAAE,MAAM,CAAC;wBACd,SAAS,EAAE,SAAS;wBACpB,cAAc,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO;qBAC7C,CAAC;oBACF,MAAM,EAAE,oBAAoB;iBAC7B;aACF;SACF;QACD,aAAa,EAAE;YACb,MAAM,EAAE;gBACN,KAAK,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc;gBAChD,MAAM,EAAE,oBAAoB;aAC7B;YACD,WAAW,EACT,gFAAgF;YAClF,EAAE,EAAE;gBACF,mBAAmB,EAAE;oBACnB,OAAO,EAAE,MAAM,CAAC;wBACd,cAAc,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO;qBAC7C,CAAC;oBACF,MAAM,EAAE,uBAAuB;iBAChC;aACF;SACF;KACF;CACF,CAAC,CAAC","sourcesContent":["/*\n * Copyright (C) 2024-2025 Dremio Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { setup, fromObservable, fromPromise, assign, enqueueActions, emit } from \"xstate\";\nimport type { UserChatMessage } from \"../chat/UserChatMessage.ts\";\nimport { AgentConversation } from \"./AgentConversation.ts\";\nimport type { ConversationExchange } from \"./reduceChatEvents.ts\";\nimport type { SonarV4Config } from \"../../../common/Config.ts\";\nimport { createConversation, createConversationCodec } from \"./methods/createConversation.ts\";\nimport * as z from \"zod/mini\";\nimport { retrieveConversation } from \"./methods/retrieveConversation.ts\";\nimport { retrieveConversationHistory } from \"./methods/retrieveConversationHistory.ts\";\nimport { createExchangeRun } from \"./methods/createExchangeRun.ts\";\nimport { stopExchangeRun } from \"./methods/stopExchangeRun.ts\";\nimport { streamRunEvents } from \"./methods/streamRunEvents.ts\";\nimport { fromTextEventStream } from \"../../../common/fromTextEventStream.ts\";\nimport { map } from \"rxjs\";\nimport { chatEventCodec, type ChatEvent } from \"../chat/chatEventSchema.ts\";\nimport type { HttpError } from \"../../../common/HttpError.ts\";\n\nexport type ConversationMachineInput = {\n conversationId: string | null;\n};\n\nexport type ConversationMachineContext = {\n conversationId: string | null;\n conversationSnapshot?: ConversationExchange[];\n currentRunId?: string | null;\n lastError?: unknown;\n messageAttempt?: UserChatMessage;\n receivedEndOfStream: boolean;\n streamRetryCount: number;\n userRequestedStop: boolean;\n};\nexport type ConversationMachineEvents =\n | { type: \"STOP_RUN\" }\n | { type: \"SUBMIT_USER_MESSAGE\"; message: UserChatMessage }\n | { type: \"RETRY_MESSAGE\" }\n | { type: \"REFRESH_HISTORY\" };\n\nexport type ConversationMachineEmitted =\n | {\n type: \"apiError\";\n error: HttpError;\n }\n | {\n type: \"chatEventReceived\";\n chatEvent: ChatEvent;\n }\n | {\n type: \"conversationCreated\";\n id: string;\n };\n\nconst RETRIEVE_STATE_TIMEOUT_MS = 10_000;\nconst STREAM_RETRY_DELAY_MS = 2500;\nexport const MAX_STREAM_RETRIES = 5;\nconst STREAM_STATE_RESET = {\n receivedEndOfStream: false,\n streamRetryCount: 0,\n userRequestedStop: false,\n};\n\nexport const createConversationMachine = (config: SonarV4Config) =>\n setup({\n actors: {\n createConversation: fromPromise(\n ({ input }: { input: z.input<typeof createConversationCodec> }) =>\n createConversation(config)(input).then((result) => {\n if (result.isErr()) {\n throw result.error;\n }\n return result.value;\n }),\n ),\n retrieveConversation: fromPromise(\n ({ input, signal }: { input: { conversationId: string }; signal: AbortSignal }) =>\n retrieveConversation(config)(input.conversationId, { signal }).then((result) => {\n if (result.isErr()) {\n throw result.error;\n }\n return result.value;\n }),\n ),\n retrieveHistory: fromPromise(\n ({ input, signal }: { input: { conversationId: string }; signal: AbortSignal }) =>\n retrieveConversationHistory(config)(input.conversationId, { signal }).then((result) => {\n if (result.isErr()) {\n throw result.error;\n }\n return result.value;\n }),\n ),\n retrieveState: fromPromise(\n async ({ input, signal }: { input: { conversationId: string }; signal: AbortSignal }) => {\n const timeoutSignal = AbortSignal.any([\n signal,\n AbortSignal.timeout(RETRIEVE_STATE_TIMEOUT_MS),\n ]);\n const [conversationResult, historyResult] = await Promise.all([\n retrieveConversation(config)(input.conversationId, { signal: timeoutSignal }),\n retrieveConversationHistory(config)(input.conversationId, { signal: timeoutSignal }),\n ]);\n\n if (conversationResult.isErr()) {\n throw conversationResult.error;\n }\n\n if (historyResult.isErr()) {\n throw historyResult.error;\n }\n\n return {\n conversation: conversationResult.value,\n history: historyResult.value,\n };\n },\n ),\n startRun: fromPromise(\n ({ input }: { input: { conversationId: string; message: UserChatMessage } }) =>\n createExchangeRun(config)(input.conversationId, { message: input.message }).then(\n (result) => {\n if (result.isErr()) {\n throw result.error;\n }\n return result.value;\n },\n ),\n ),\n stopRun: fromPromise(({ input }: { input: { conversationId: string; runId: string } }) =>\n stopExchangeRun(config)(input.conversationId, input.runId).then((result) => {\n if (result.isErr()) {\n throw result.error;\n }\n return result.value;\n }),\n ),\n streamRun: fromObservable(({ input }: { input: { conversationId: string; runId: string } }) =>\n fromTextEventStream(({ signal }) =>\n streamRunEvents(config)(\n { conversationId: input.conversationId, runId: input.runId },\n { signal },\n ),\n ).pipe(\n map((event) =>\n z.decode(chatEventCodec, JSON.parse(event.data) as z.input<typeof chatEventCodec>),\n ),\n ),\n ),\n },\n delays: {\n STREAM_RETRY_DELAY: STREAM_RETRY_DELAY_MS,\n },\n types: {\n context: {} as ConversationMachineContext,\n emitted: {} as ConversationMachineEmitted,\n events: {} as ConversationMachineEvents,\n input: {} as ConversationMachineInput,\n },\n }).createMachine({\n context: ({ input }) => ({\n conversationId: input.conversationId,\n conversationSnapshot: undefined,\n currentRunId: undefined,\n messageAttempt: undefined,\n ...STREAM_STATE_RESET,\n }),\n id: \"agentConversation\",\n initial: \"uninitialized\",\n states: {\n creating_conversation: {\n description: \"Creating a new conversation object\",\n invoke: {\n input: ({ context }) => ({\n message: context.messageAttempt!,\n }),\n onDone: [\n {\n actions: [\n assign({\n conversationId: ({ event }) => event.output.id,\n // Add the message attempt into the snapshot manually\n conversationSnapshot: ({ context, event }) => [\n ...(context.conversationSnapshot ?? []),\n {\n id: event.output.currentRunId!,\n messages: new Map(),\n submittedUserMessage: context.messageAttempt,\n toolCalls: new Map(),\n } satisfies ConversationExchange,\n ],\n currentRunId: ({ event }) => event.output.currentRunId,\n messageAttempt: undefined,\n ...STREAM_STATE_RESET,\n }),\n emit(({ event }) => ({\n id: event.output.id,\n type: \"conversationCreated\",\n })),\n ],\n // Don't transition to streaming in a situation where we didn't receive a currentRunId\n guard: ({ event }) => !!event.output.currentRunId,\n target: \"streaming\",\n },\n /**\n * Fall back to the retrieving_history state if we didn't receive a currentRunId\n */\n {\n actions: assign({\n conversationId: ({ event }) => event.output.id,\n currentRunId: ({ event }) => event.output.currentRunId,\n messageAttempt: undefined,\n }),\n target: \"retrieving_history\",\n },\n ],\n onError: {\n actions: emit(({ event }) => ({\n error: event.error as HttpError,\n type: \"apiError\",\n })),\n target: \"uninitialized\",\n },\n src: \"createConversation\",\n },\n },\n idle: {\n description: \"Waiting for user input to start the next reply stream\",\n on: {\n REFRESH_HISTORY: {\n target: \"retrieving_history\",\n },\n SUBMIT_USER_MESSAGE: {\n actions: assign({\n messageAttempt: ({ event }) => event.message,\n }),\n target: \"submitting_message\",\n },\n },\n },\n retrieve_history_failed: {\n on: {\n REFRESH_HISTORY: {\n actions: assign({ lastError: undefined }),\n target: \"retrieving_history\",\n },\n },\n },\n retrieving_history: {\n description: \"Retrieving latest copy of conversation history\",\n invoke: {\n input: ({ context }) => ({ conversationId: context.conversationId! }),\n onDone: [\n {\n actions: assign({\n conversationSnapshot: ({ context, event }) =>\n AgentConversation.reduceChatEvents(\n context.conversationSnapshot,\n event.output.history.data,\n ),\n currentRunId: ({ event }) => event.output.conversation.currentRunId,\n receivedEndOfStream: false,\n }),\n guard: ({ event }) => !!event.output.conversation.currentRunId,\n target: \"streaming\",\n },\n {\n actions: assign({\n conversationSnapshot: ({ context, event }) =>\n AgentConversation.reduceChatEvents(\n context.conversationSnapshot,\n event.output.history.data,\n ),\n currentRunId: ({ event }) => event.output.conversation.currentRunId,\n ...STREAM_STATE_RESET,\n }),\n target: \"idle\",\n },\n ],\n onError: [\n {\n guard: ({ event }) => {\n const e = event.error as Error & { code?: string };\n if (e?.name === \"TimeoutError\") return false;\n return (\n e?.name === \"AbortError\" ||\n e?.message?.includes(\"aborted\") ||\n e?.code === \"ABORT_ERR\"\n );\n },\n target: \"uninitialized\",\n },\n {\n guard: ({ context }) => context.streamRetryCount > 0,\n target: \"stream_interrupted\",\n },\n {\n actions: [\n assign({\n lastError: ({ event }) => event.error,\n }),\n emit(({ event }) => ({\n error: event.error as HttpError,\n type: \"apiError\",\n })),\n ],\n target: \"retrieve_history_failed\",\n },\n ],\n src: \"retrieveState\",\n },\n },\n stream_interrupted: {\n after: {\n STREAM_RETRY_DELAY: [\n {\n actions: assign({\n streamRetryCount: ({ context }) => context.streamRetryCount + 1,\n }),\n guard: ({ context }) => context.streamRetryCount < MAX_STREAM_RETRIES,\n target: \"retrieving_history\",\n },\n {\n target: \"stream_recovery_failed\",\n },\n ],\n },\n },\n stream_recovery_failed: {\n on: {\n REFRESH_HISTORY: {\n actions: assign({ lastError: undefined, streamRetryCount: 0 }),\n target: \"retrieving_history\",\n },\n },\n },\n streaming: {\n description: \"Manages monitoring and canceling the current run\",\n initial: \"monitoring_replies\",\n invoke: {\n input: ({ context }) => {\n if (!context.currentRunId) {\n throw new Error(\"Attempted to stream without a runId\");\n }\n return {\n conversationId: context.conversationId!,\n runId: context.currentRunId,\n };\n },\n onDone: [\n {\n actions: assign({ currentRunId: null, userRequestedStop: false }),\n guard: ({ context }) => !!context.receivedEndOfStream || !!context.userRequestedStop,\n target: \"idle\",\n },\n {\n actions: assign({ currentRunId: null }),\n target: \"stream_interrupted\",\n },\n ],\n onError: [\n {\n actions: assign({ currentRunId: null, userRequestedStop: false }),\n guard: ({ context }) => !!context.receivedEndOfStream || !!context.userRequestedStop,\n target: \"idle\",\n },\n {\n actions: assign({ currentRunId: null }),\n target: \"stream_interrupted\",\n },\n ],\n onSnapshot: {\n actions: enqueueActions(({ context, enqueue, event }) => {\n const chatEvent = event.snapshot.context;\n if (!chatEvent) {\n return;\n }\n\n if (chatEvent.content.chunkType === \"endOfStream\" && !context.receivedEndOfStream) {\n enqueue.assign({ receivedEndOfStream: true });\n }\n\n const nextSnapshot = AgentConversation.reduceChatEvents(\n context.conversationSnapshot,\n [chatEvent],\n );\n\n enqueue.assign({\n conversationSnapshot: nextSnapshot,\n });\n enqueue.emit({\n chatEvent,\n type: \"chatEventReceived\",\n });\n }),\n },\n src: \"streamRun\",\n },\n states: {\n monitoring_replies: {\n description: \"Attached to the run event stream\",\n on: {\n STOP_RUN: {\n actions: assign({ userRequestedStop: true }),\n target: \"stopping\",\n },\n },\n },\n stopping: {\n description: \"Background cancelation of the run stream\",\n invoke: {\n input: ({ context }) => ({\n conversationId: context.conversationId!,\n runId: context.currentRunId!,\n }),\n onDone: {\n actions: assign({ currentRunId: undefined, userRequestedStop: false }),\n target: \"#agentConversation.idle\",\n },\n onError: {\n actions: assign({ userRequestedStop: false }),\n target: \"#agentConversation.retrieving_history\",\n },\n src: \"stopRun\",\n },\n },\n },\n },\n submitting_message: {\n description: \"Submitting message to start a new reply stream\",\n invoke: {\n input: ({ context, event }) => {\n switch (event.type) {\n case \"RETRY_MESSAGE\":\n if (!context.messageAttempt) {\n throw new Error(\"Tried to resubmit nonexistent message\");\n }\n return {\n conversationId: context.conversationId!,\n message: context.messageAttempt,\n };\n case \"SUBMIT_USER_MESSAGE\":\n return {\n conversationId: context.conversationId!,\n message: event.message,\n };\n }\n throw new Error(`Unexpected event type received in submitting_message: ${event.type}`);\n },\n onDone: {\n actions: assign({\n // Add the message attempt into the snapshot manually\n conversationSnapshot: ({ context, event }) => [\n ...(context.conversationSnapshot ?? []),\n {\n id: event.output.currentRunId,\n messages: new Map(),\n submittedUserMessage: context.messageAttempt || undefined,\n toolCalls: new Map(),\n } satisfies ConversationExchange,\n ],\n currentRunId: ({ event }) => event.output.currentRunId,\n messageAttempt: undefined,\n ...STREAM_STATE_RESET,\n }),\n target: \"streaming\",\n },\n onError: {\n actions: [\n assign({\n currentRunId: () => null,\n lastError: ({ event }) => event.error,\n }),\n emit(({ event }) => ({\n error: event.error as HttpError,\n type: \"apiError\",\n })),\n ],\n target: \"submitting_message_failed\",\n },\n src: \"startRun\",\n },\n },\n submitting_message_failed: {\n description: \"Failed to submit message\",\n on: {\n REFRESH_HISTORY: {\n actions: assign({ lastError: undefined }),\n target: \"retrieving_history\",\n },\n RETRY_MESSAGE: {\n actions: assign({ lastError: undefined }),\n target: \"submitting_message\",\n },\n SUBMIT_USER_MESSAGE: {\n actions: assign({\n lastError: undefined,\n messageAttempt: ({ event }) => event.message,\n }),\n target: \"submitting_message\",\n },\n },\n },\n uninitialized: {\n always: {\n guard: ({ context }) => !!context.conversationId,\n target: \"retrieving_history\",\n },\n description:\n \"Entry state that the machine remains in when no conversation has been provided\",\n on: {\n SUBMIT_USER_MESSAGE: {\n actions: assign({\n messageAttempt: ({ event }) => event.message,\n }),\n target: \"creating_conversation\",\n },\n },\n },\n },\n });\n\nexport type AgentConversationMachine = ReturnType<typeof createConversationMachine>;\n"]}
|
|
1
|
+
{"version":3,"file":"createConversationMachine.js","sourceRoot":"","sources":["../../../../src/enterprise/ai/conversations/createConversationMachine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAE1F,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAG3D,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAC9F,OAAO,KAAK,CAAC,MAAM,UAAU,CAAC;AAC9B,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,2BAA2B,EAAE,MAAM,0CAA0C,CAAC;AACvF,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAE,cAAc,EAAkB,MAAM,4BAA4B,CAAC;AAqC5E,MAAM,yBAAyB,GAAG,MAAM,CAAC;AACzC,MAAM,sBAAsB,GAAG,MAAM,CAAC;AACtC,MAAM,qBAAqB,GAAG,IAAI,CAAC;AACnC,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC;AACpC,MAAM,kBAAkB,GAAG;IACzB,mBAAmB,EAAE,KAAK;IAC1B,gBAAgB,EAAE,CAAC;IACnB,iBAAiB,EAAE,KAAK;CACzB,CA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E,EAAE,CAAC,KAAK,CAAC,OAAO;qBAC7C,CAAC;oBACF,MAAM,EAAE,uBAAuB;iBAChC;aACF;SACF;KACF;CACF,CAAC,CAAC","sourcesContent":["/*\n * Copyright (C) 2024-2025 Dremio Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { setup, fromObservable, fromPromise, assign, enqueueActions, emit } from \"xstate\";\nimport type { UserChatMessage } from \"../chat/UserChatMessage.ts\";\nimport { AgentConversation } from \"./AgentConversation.ts\";\nimport type { ConversationExchange } from \"./reduceChatEvents.ts\";\nimport type { SonarV4Config } from \"../../../common/Config.ts\";\nimport { createConversation, createConversationCodec } from \"./methods/createConversation.ts\";\nimport * as z from \"zod/mini\";\nimport { retrieveConversation } from \"./methods/retrieveConversation.ts\";\nimport { retrieveConversationHistory } from \"./methods/retrieveConversationHistory.ts\";\nimport { createExchangeRun } from \"./methods/createExchangeRun.ts\";\nimport { stopExchangeRun } from \"./methods/stopExchangeRun.ts\";\nimport { streamRunEvents } from \"./methods/streamRunEvents.ts\";\nimport { fromTextEventStream } from \"../../../common/fromTextEventStream.ts\";\nimport { map, timeout } from \"rxjs\";\nimport { chatEventCodec, type ChatEvent } from \"../chat/chatEventSchema.ts\";\nimport type { HttpError } from \"../../../common/HttpError.ts\";\n\nexport type ConversationMachineInput = {\n conversationId: string | null;\n};\n\nexport type ConversationMachineContext = {\n conversationId: string | null;\n conversationSnapshot?: ConversationExchange[];\n currentRunId?: string | null;\n lastError?: unknown;\n messageAttempt?: UserChatMessage;\n receivedEndOfStream: boolean;\n streamRetryCount: number;\n userRequestedStop: boolean;\n};\nexport type ConversationMachineEvents =\n | { type: \"STOP_RUN\" }\n | { type: \"SUBMIT_USER_MESSAGE\"; message: UserChatMessage }\n | { type: \"RETRY_MESSAGE\" }\n | { type: \"REFRESH_HISTORY\" };\n\nexport type ConversationMachineEmitted =\n | {\n type: \"apiError\";\n error: HttpError;\n }\n | {\n type: \"chatEventReceived\";\n chatEvent: ChatEvent;\n }\n | {\n type: \"conversationCreated\";\n id: string;\n };\n\nconst RETRIEVE_STATE_TIMEOUT_MS = 10_000;\nconst STREAM_IDLE_TIMEOUT_MS = 60_000;\nconst STREAM_RETRY_DELAY_MS = 2500;\nexport const MAX_STREAM_RETRIES = 5;\nconst STREAM_STATE_RESET = {\n receivedEndOfStream: false,\n streamRetryCount: 0,\n userRequestedStop: false,\n};\n\nexport const createConversationMachine = (config: SonarV4Config) =>\n setup({\n actors: {\n createConversation: fromPromise(\n ({ input }: { input: z.input<typeof createConversationCodec> }) =>\n createConversation(config)(input).then((result) => {\n if (result.isErr()) {\n throw result.error;\n }\n return result.value;\n }),\n ),\n retrieveConversation: fromPromise(\n ({ input, signal }: { input: { conversationId: string }; signal: AbortSignal }) =>\n retrieveConversation(config)(input.conversationId, { signal }).then((result) => {\n if (result.isErr()) {\n throw result.error;\n }\n return result.value;\n }),\n ),\n retrieveHistory: fromPromise(\n ({ input, signal }: { input: { conversationId: string }; signal: AbortSignal }) =>\n retrieveConversationHistory(config)(input.conversationId, { signal }).then((result) => {\n if (result.isErr()) {\n throw result.error;\n }\n return result.value;\n }),\n ),\n retrieveState: fromPromise(\n async ({ input, signal }: { input: { conversationId: string }; signal: AbortSignal }) => {\n const timeoutSignal = AbortSignal.any([\n signal,\n AbortSignal.timeout(RETRIEVE_STATE_TIMEOUT_MS),\n ]);\n const [conversationResult, historyResult] = await Promise.all([\n retrieveConversation(config)(input.conversationId, { signal: timeoutSignal }),\n retrieveConversationHistory(config)(input.conversationId, { signal: timeoutSignal }),\n ]);\n\n if (conversationResult.isErr()) {\n throw conversationResult.error;\n }\n\n if (historyResult.isErr()) {\n throw historyResult.error;\n }\n\n return {\n conversation: conversationResult.value,\n history: historyResult.value,\n };\n },\n ),\n startRun: fromPromise(\n ({ input }: { input: { conversationId: string; message: UserChatMessage } }) =>\n createExchangeRun(config)(input.conversationId, { message: input.message }).then(\n (result) => {\n if (result.isErr()) {\n throw result.error;\n }\n return result.value;\n },\n ),\n ),\n stopRun: fromPromise(({ input }: { input: { conversationId: string; runId: string } }) =>\n stopExchangeRun(config)(input.conversationId, input.runId).then((result) => {\n if (result.isErr()) {\n throw result.error;\n }\n return result.value;\n }),\n ),\n streamRun: fromObservable(({ input }: { input: { conversationId: string; runId: string } }) =>\n fromTextEventStream(({ signal }) =>\n streamRunEvents(config)(\n { conversationId: input.conversationId, runId: input.runId },\n { signal },\n ),\n ).pipe(\n map((event) =>\n z.decode(chatEventCodec, JSON.parse(event.data) as z.input<typeof chatEventCodec>),\n ),\n timeout({ each: STREAM_IDLE_TIMEOUT_MS }),\n ),\n ),\n },\n delays: {\n STREAM_RETRY_DELAY: STREAM_RETRY_DELAY_MS,\n },\n types: {\n context: {} as ConversationMachineContext,\n emitted: {} as ConversationMachineEmitted,\n events: {} as ConversationMachineEvents,\n input: {} as ConversationMachineInput,\n },\n }).createMachine({\n context: ({ input }) => ({\n conversationId: input.conversationId,\n conversationSnapshot: undefined,\n currentRunId: undefined,\n messageAttempt: undefined,\n ...STREAM_STATE_RESET,\n }),\n id: \"agentConversation\",\n initial: \"uninitialized\",\n states: {\n creating_conversation: {\n description: \"Creating a new conversation object\",\n invoke: {\n input: ({ context }) => ({\n message: context.messageAttempt!,\n }),\n onDone: [\n {\n actions: [\n assign({\n conversationId: ({ event }) => event.output.id,\n // Add the message attempt into the snapshot manually\n conversationSnapshot: ({ context, event }) => [\n ...(context.conversationSnapshot ?? []),\n {\n id: event.output.currentRunId!,\n messages: new Map(),\n submittedUserMessage: context.messageAttempt,\n toolCalls: new Map(),\n } satisfies ConversationExchange,\n ],\n currentRunId: ({ event }) => event.output.currentRunId,\n messageAttempt: undefined,\n ...STREAM_STATE_RESET,\n }),\n emit(({ event }) => ({\n id: event.output.id,\n type: \"conversationCreated\",\n })),\n ],\n // Don't transition to streaming in a situation where we didn't receive a currentRunId\n guard: ({ event }) => !!event.output.currentRunId,\n target: \"streaming\",\n },\n /**\n * Fall back to the retrieving_history state if we didn't receive a currentRunId\n */\n {\n actions: assign({\n conversationId: ({ event }) => event.output.id,\n currentRunId: ({ event }) => event.output.currentRunId,\n messageAttempt: undefined,\n }),\n target: \"retrieving_history\",\n },\n ],\n onError: {\n actions: emit(({ event }) => ({\n error: event.error as HttpError,\n type: \"apiError\",\n })),\n target: \"uninitialized\",\n },\n src: \"createConversation\",\n },\n },\n idle: {\n description: \"Waiting for user input to start the next reply stream\",\n on: {\n REFRESH_HISTORY: {\n target: \"retrieving_history\",\n },\n SUBMIT_USER_MESSAGE: {\n actions: assign({\n messageAttempt: ({ event }) => event.message,\n }),\n target: \"submitting_message\",\n },\n },\n },\n retrieve_history_failed: {\n on: {\n REFRESH_HISTORY: {\n actions: assign({ lastError: undefined }),\n target: \"retrieving_history\",\n },\n },\n },\n retrieving_history: {\n description: \"Retrieving latest copy of conversation history\",\n invoke: {\n input: ({ context }) => ({ conversationId: context.conversationId! }),\n onDone: [\n {\n actions: assign({\n conversationSnapshot: ({ context, event }) =>\n AgentConversation.reduceChatEvents(\n context.conversationSnapshot,\n event.output.history.data,\n ),\n currentRunId: ({ event }) => event.output.conversation.currentRunId,\n receivedEndOfStream: false,\n }),\n guard: ({ event }) => !!event.output.conversation.currentRunId,\n target: \"streaming\",\n },\n {\n actions: assign({\n conversationSnapshot: ({ context, event }) =>\n AgentConversation.reduceChatEvents(\n context.conversationSnapshot,\n event.output.history.data,\n ),\n currentRunId: ({ event }) => event.output.conversation.currentRunId,\n ...STREAM_STATE_RESET,\n }),\n target: \"idle\",\n },\n ],\n onError: [\n {\n guard: ({ event }) => {\n const e = event.error as Error & { code?: string };\n if (e?.name === \"TimeoutError\") return false;\n return (\n e?.name === \"AbortError\" ||\n e?.message?.includes(\"aborted\") ||\n e?.code === \"ABORT_ERR\"\n );\n },\n target: \"uninitialized\",\n },\n {\n guard: ({ context }) => context.streamRetryCount > 0,\n target: \"stream_interrupted\",\n },\n {\n actions: [\n assign({\n lastError: ({ event }) => event.error,\n }),\n emit(({ event }) => ({\n error: event.error as HttpError,\n type: \"apiError\",\n })),\n ],\n target: \"retrieve_history_failed\",\n },\n ],\n src: \"retrieveState\",\n },\n },\n stream_interrupted: {\n after: {\n STREAM_RETRY_DELAY: [\n {\n actions: assign({\n streamRetryCount: ({ context }) => context.streamRetryCount + 1,\n }),\n guard: ({ context }) => context.streamRetryCount < MAX_STREAM_RETRIES,\n target: \"retrieving_history\",\n },\n {\n target: \"stream_recovery_failed\",\n },\n ],\n },\n },\n stream_recovery_failed: {\n on: {\n REFRESH_HISTORY: {\n actions: assign({ lastError: undefined, streamRetryCount: 0 }),\n target: \"retrieving_history\",\n },\n },\n },\n streaming: {\n description: \"Manages monitoring and canceling the current run\",\n initial: \"monitoring_replies\",\n invoke: {\n input: ({ context }) => {\n if (!context.currentRunId) {\n throw new Error(\"Attempted to stream without a runId\");\n }\n return {\n conversationId: context.conversationId!,\n runId: context.currentRunId,\n };\n },\n onDone: [\n {\n actions: assign({ currentRunId: null, userRequestedStop: false }),\n guard: ({ context }) => !!context.receivedEndOfStream || !!context.userRequestedStop,\n target: \"idle\",\n },\n {\n actions: assign({ currentRunId: null }),\n target: \"stream_interrupted\",\n },\n ],\n onError: [\n {\n actions: assign({ currentRunId: null, userRequestedStop: false }),\n guard: ({ context }) => !!context.receivedEndOfStream || !!context.userRequestedStop,\n target: \"idle\",\n },\n {\n actions: assign({ currentRunId: null }),\n target: \"stream_interrupted\",\n },\n ],\n onSnapshot: {\n actions: enqueueActions(({ context, enqueue, event }) => {\n const chatEvent = event.snapshot.context;\n if (!chatEvent) {\n return;\n }\n\n if (chatEvent.content.chunkType === \"endOfStream\" && !context.receivedEndOfStream) {\n enqueue.assign({ receivedEndOfStream: true });\n }\n\n const nextSnapshot = AgentConversation.reduceChatEvents(\n context.conversationSnapshot,\n [chatEvent],\n );\n\n enqueue.assign({\n conversationSnapshot: nextSnapshot,\n });\n enqueue.emit({\n chatEvent,\n type: \"chatEventReceived\",\n });\n }),\n },\n src: \"streamRun\",\n },\n states: {\n monitoring_replies: {\n description: \"Attached to the run event stream\",\n on: {\n STOP_RUN: {\n actions: assign({ userRequestedStop: true }),\n target: \"stopping\",\n },\n },\n },\n stopping: {\n description: \"Background cancelation of the run stream\",\n invoke: {\n input: ({ context }) => ({\n conversationId: context.conversationId!,\n runId: context.currentRunId!,\n }),\n onDone: {\n actions: assign({ currentRunId: undefined, userRequestedStop: false }),\n target: \"#agentConversation.idle\",\n },\n onError: {\n actions: assign({ userRequestedStop: false }),\n target: \"#agentConversation.retrieving_history\",\n },\n src: \"stopRun\",\n },\n },\n },\n },\n submitting_message: {\n description: \"Submitting message to start a new reply stream\",\n invoke: {\n input: ({ context, event }) => {\n switch (event.type) {\n case \"RETRY_MESSAGE\":\n if (!context.messageAttempt) {\n throw new Error(\"Tried to resubmit nonexistent message\");\n }\n return {\n conversationId: context.conversationId!,\n message: context.messageAttempt,\n };\n case \"SUBMIT_USER_MESSAGE\":\n return {\n conversationId: context.conversationId!,\n message: event.message,\n };\n }\n throw new Error(`Unexpected event type received in submitting_message: ${event.type}`);\n },\n onDone: {\n actions: assign({\n // Add the message attempt into the snapshot manually\n conversationSnapshot: ({ context, event }) => [\n ...(context.conversationSnapshot ?? []),\n {\n id: event.output.currentRunId,\n messages: new Map(),\n submittedUserMessage: context.messageAttempt || undefined,\n toolCalls: new Map(),\n } satisfies ConversationExchange,\n ],\n currentRunId: ({ event }) => event.output.currentRunId,\n messageAttempt: undefined,\n ...STREAM_STATE_RESET,\n }),\n target: \"streaming\",\n },\n onError: {\n actions: [\n assign({\n currentRunId: () => null,\n lastError: ({ event }) => event.error,\n }),\n emit(({ event }) => ({\n error: event.error as HttpError,\n type: \"apiError\",\n })),\n ],\n target: \"submitting_message_failed\",\n },\n src: \"startRun\",\n },\n },\n submitting_message_failed: {\n description: \"Failed to submit message\",\n on: {\n REFRESH_HISTORY: {\n actions: assign({ lastError: undefined }),\n target: \"retrieving_history\",\n },\n RETRY_MESSAGE: {\n actions: assign({ lastError: undefined }),\n target: \"submitting_message\",\n },\n SUBMIT_USER_MESSAGE: {\n actions: assign({\n lastError: undefined,\n messageAttempt: ({ event }) => event.message,\n }),\n target: \"submitting_message\",\n },\n },\n },\n uninitialized: {\n always: {\n guard: ({ context }) => !!context.conversationId,\n target: \"retrieving_history\",\n },\n description:\n \"Entry state that the machine remains in when no conversation has been provided\",\n on: {\n SUBMIT_USER_MESSAGE: {\n actions: assign({\n messageAttempt: ({ event }) => event.message,\n }),\n target: \"creating_conversation\",\n },\n },\n },\n },\n });\n\nexport type AgentConversationMachine = ReturnType<typeof createConversationMachine>;\n"]}
|
|
@@ -80,6 +80,21 @@ export declare const retrieveConversationHistory: (config: SonarV4Config) => (id
|
|
|
80
80
|
result: Record<string, unknown>;
|
|
81
81
|
};
|
|
82
82
|
role: "agent";
|
|
83
|
+
} | {
|
|
84
|
+
conversationId: string;
|
|
85
|
+
modelName: string;
|
|
86
|
+
modelProviderId: string;
|
|
87
|
+
runId: string;
|
|
88
|
+
createdAt: import("temporal-polyfill").Temporal.Instant;
|
|
89
|
+
id: string;
|
|
90
|
+
content: {
|
|
91
|
+
chunkType: "selectedSkills";
|
|
92
|
+
selectedSkills: {
|
|
93
|
+
id: string;
|
|
94
|
+
name: string;
|
|
95
|
+
}[];
|
|
96
|
+
};
|
|
97
|
+
role: "agent";
|
|
83
98
|
} | {
|
|
84
99
|
conversationId: string;
|
|
85
100
|
modelName: string;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ChatEvent, ChatEventWithChunkType } from "../chat/chatEventSchema.ts";
|
|
1
|
+
import type { ChatEvent, ChatEventWithChunkType, SelectedSkillInfo } from "../chat/chatEventSchema.ts";
|
|
2
2
|
import type { UserChatMessage } from "../chat/UserChatMessage.ts";
|
|
3
3
|
export type AgentToolCall = {
|
|
4
4
|
id: string;
|
|
@@ -7,9 +7,13 @@ export type AgentToolCall = {
|
|
|
7
7
|
result: ChatEventWithChunkType<"toolResponse"> | undefined;
|
|
8
8
|
};
|
|
9
9
|
export type ConversationExchangeMessage = ChatEventWithChunkType<"error"> | ChatEventWithChunkType<"model"> | ChatEventWithChunkType<"sandboxProgress"> | ChatEventWithChunkType<"sandboxStdout"> | ChatEventWithChunkType<"userMessage">;
|
|
10
|
+
export type ConversationExchangeRunMetadata = {
|
|
11
|
+
selectedSkills?: SelectedSkillInfo[];
|
|
12
|
+
};
|
|
10
13
|
export type ConversationExchange = {
|
|
11
14
|
id: string;
|
|
12
15
|
messages: Map<string, ConversationExchangeMessage>;
|
|
16
|
+
runMetadata?: ConversationExchangeRunMetadata;
|
|
13
17
|
submittedUserMessage?: UserChatMessage;
|
|
14
18
|
toolCalls: Map<string, AgentToolCall>;
|
|
15
19
|
};
|
|
@@ -14,6 +14,10 @@
|
|
|
14
14
|
* limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
import { create } from "mutative";
|
|
17
|
+
import { Temporal } from "temporal-polyfill";
|
|
18
|
+
// Mutative array drafts do not handle symbol-key reads reliably, so use a non-enumerable
|
|
19
|
+
// string key for reducer bookkeeping while keeping JSON/deep equality output clean.
|
|
20
|
+
const selectedSkillsCursorKey = "__dremioSelectedSkillsCursor";
|
|
17
21
|
function applyChatEventToConversation(draft, chatEvent) {
|
|
18
22
|
let conversationExchange = draft.findLast((exchange) => exchange.id === chatEvent.runId);
|
|
19
23
|
if (!conversationExchange) {
|
|
@@ -37,6 +41,10 @@ function applyChatEventToConversationExchange(conversationExchange, chatEvent) {
|
|
|
37
41
|
}
|
|
38
42
|
break;
|
|
39
43
|
}
|
|
44
|
+
case "selectedSkills": {
|
|
45
|
+
applySelectedSkillsMetadata(conversationExchange, chatEvent);
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
40
48
|
case "error":
|
|
41
49
|
case "model":
|
|
42
50
|
case "sandboxProgress":
|
|
@@ -76,6 +84,91 @@ function applyChatEventToConversationExchange(conversationExchange, chatEvent) {
|
|
|
76
84
|
}
|
|
77
85
|
}
|
|
78
86
|
}
|
|
87
|
+
function applySelectedSkillsMetadata(conversationExchange, chatEvent) {
|
|
88
|
+
if (!isSelectedSkillsEventNewer(conversationExchange.runMetadata, chatEvent)) {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
conversationExchange.runMetadata ??= {};
|
|
92
|
+
// Clone before attaching reducer bookkeeping so the input event payload stays immutable.
|
|
93
|
+
const selectedSkills = [...chatEvent.content.selectedSkills];
|
|
94
|
+
setSelectedSkillsCursor(selectedSkills, {
|
|
95
|
+
messagePosition: parseMessagePosition(chatEvent.id),
|
|
96
|
+
updatedAt: chatEvent.createdAt,
|
|
97
|
+
});
|
|
98
|
+
conversationExchange.runMetadata.selectedSkills = selectedSkills;
|
|
99
|
+
}
|
|
100
|
+
function isSelectedSkillsEventNewer(runMetadata, chatEvent) {
|
|
101
|
+
// selectedSkills is singleton run metadata, so unlike messages and tool calls it is not keyed by
|
|
102
|
+
// event id. Keep newer live-stream metadata when an older history replay is reduced later.
|
|
103
|
+
const cursor = getSelectedSkillsCursor(runMetadata);
|
|
104
|
+
if (!cursor) {
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
const timestampComparison = Temporal.Instant.compare(chatEvent.createdAt, cursor.updatedAt);
|
|
108
|
+
if (timestampComparison !== 0) {
|
|
109
|
+
return timestampComparison > 0;
|
|
110
|
+
}
|
|
111
|
+
const messagePositionComparison = compareMessagePositions(parseMessagePosition(chatEvent.id), cursor.messagePosition);
|
|
112
|
+
if (messagePositionComparison !== undefined) {
|
|
113
|
+
return messagePositionComparison >= 0;
|
|
114
|
+
}
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
function getSelectedSkillsCursor(runMetadata) {
|
|
118
|
+
return runMetadata?.selectedSkills?.[selectedSkillsCursorKey];
|
|
119
|
+
}
|
|
120
|
+
function setSelectedSkillsCursor(selectedSkills, cursor) {
|
|
121
|
+
Object.defineProperty(selectedSkills, selectedSkillsCursorKey, {
|
|
122
|
+
configurable: true,
|
|
123
|
+
enumerable: false,
|
|
124
|
+
value: cursor,
|
|
125
|
+
writable: true,
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
// Run-events message ids are chunkId:messageSubId; split message parts append :partId.
|
|
129
|
+
function parseMessagePosition(messageId) {
|
|
130
|
+
const parts = messageId.split(":");
|
|
131
|
+
if (parts.length < 2 || parts.length > 3) {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
const [chunkId, messageSubId, partId] = parts;
|
|
135
|
+
if (!chunkId) {
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
const parsedMessageSubId = parseNonNegativeInteger(messageSubId);
|
|
139
|
+
if (parsedMessageSubId === undefined) {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
const parsedPartId = partId === undefined ? undefined : parseNonNegativeInteger(partId);
|
|
143
|
+
if (partId !== undefined && parsedPartId === undefined) {
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
chunkId,
|
|
148
|
+
messageSubId: parsedMessageSubId,
|
|
149
|
+
partId: parsedPartId,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function parseNonNegativeInteger(value) {
|
|
153
|
+
if (value === undefined || !/^\d+$/.test(value)) {
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
const parsedValue = Number(value);
|
|
157
|
+
if (!Number.isSafeInteger(parsedValue)) {
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
return parsedValue;
|
|
161
|
+
}
|
|
162
|
+
function compareMessagePositions(incoming, current) {
|
|
163
|
+
if (!incoming || !current || incoming.chunkId !== current.chunkId) {
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
const messageSubIdComparison = incoming.messageSubId - current.messageSubId;
|
|
167
|
+
if (messageSubIdComparison !== 0) {
|
|
168
|
+
return messageSubIdComparison;
|
|
169
|
+
}
|
|
170
|
+
return (incoming.partId ?? 0) - (current.partId ?? 0);
|
|
171
|
+
}
|
|
79
172
|
export function reduceChatEvents(state = [], chatEvents) {
|
|
80
173
|
return create(state, (draft) => {
|
|
81
174
|
for (const chatEvent of chatEvents) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reduceChatEvents.js","sourceRoot":"","sources":["../../../../src/enterprise/ai/conversations/reduceChatEvents.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,MAAM,EAAc,MAAM,UAAU,CAAC;AA2B9C,SAAS,4BAA4B,CACnC,KAAmC,EACnC,SAAoB;IAEpB,IAAI,oBAAoB,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,KAAK,SAAS,CAAC,KAAK,CAAC,CAAC;IAEzF,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAC1B,oBAAoB,GAAG;YACrB,EAAE,EAAE,SAAS,CAAC,KAAK;YACnB,QAAQ,EAAE,IAAI,GAAG,EAAE;YACnB,SAAS,EAAE,IAAI,GAAG,EAAE;SACrB,CAAC;QACF,KAAK,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;QACjC,oBAAoB,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACjD,CAAC;IAED,oCAAoC,CAAC,oBAAqB,EAAE,SAAS,CAAC,CAAC;AACzE,CAAC;AAED,SAAS,oCAAoC,CAC3C,oBAAiD,EACjD,SAAoB;IAEpB,QAAQ,SAAS,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC;QACpC,KAAK,aAAa,CAAC,CAAC,C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AAM,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;wBACrD,QAAQ,CAAC,KAAK,GAAG,OAAO,CAAC;oBAC3B,CAAC;yBAAM,CAAC;wBACN,QAAQ,CAAC,KAAK,GAAG,SAAS,CAAC;oBAC7B,CAAC;oBACD,MAAM;YACV,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,QAA+B,EAAE,EAAE,UAAuB;IACzF,OAAO,MAAM,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE;QAC7B,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;YACnC,4BAA4B,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;QAChE,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/*\n * Copyright (C) 2024-2025 Dremio Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { create, type Draft } from \"mutative\";\nimport type { ChatEvent, ChatEventWithChunkType } from \"../chat/chatEventSchema.ts\";\nimport type { UserChatMessage } from \"../chat/UserChatMessage.ts\";\n\nexport type AgentToolCall = {\n id: string;\n state: \"canceled\" | \"error\" | \"pending\" | \"success\";\n request: ChatEventWithChunkType<\"toolRequest\"> | undefined;\n result: ChatEventWithChunkType<\"toolResponse\"> | undefined;\n};\n\nexport type ConversationExchangeMessage =\n | ChatEventWithChunkType<\"error\">\n | ChatEventWithChunkType<\"model\">\n | ChatEventWithChunkType<\"sandboxProgress\">\n | ChatEventWithChunkType<\"sandboxStdout\">\n | ChatEventWithChunkType<\"userMessage\">;\n\nexport type ConversationExchange = {\n id: string;\n messages: Map<string, ConversationExchangeMessage>;\n submittedUserMessage?: UserChatMessage;\n toolCalls: Map<string, AgentToolCall>;\n};\n\nexport type ChatEventReducerState = ConversationExchange[];\n\nfunction applyChatEventToConversation(\n draft: Draft<ChatEventReducerState>,\n chatEvent: ChatEvent,\n): void {\n let conversationExchange = draft.findLast((exchange) => exchange.id === chatEvent.runId);\n\n if (!conversationExchange) {\n conversationExchange = {\n id: chatEvent.runId,\n messages: new Map(),\n toolCalls: new Map(),\n };\n draft.push(conversationExchange);\n conversationExchange = draft[draft.length - 1];\n }\n\n applyChatEventToConversationExchange(conversationExchange!, chatEvent);\n}\n\nfunction applyChatEventToConversationExchange(\n conversationExchange: Draft<ConversationExchange>,\n chatEvent: ChatEvent,\n): void {\n switch (chatEvent.content.chunkType) {\n case \"endOfStream\": {\n for (const [, toolCall] of conversationExchange.toolCalls) {\n if (!toolCall.result) {\n toolCall.state = \"canceled\";\n }\n }\n break;\n }\n case \"error\":\n case \"model\":\n case \"sandboxProgress\":\n case \"sandboxStdout\":\n case \"userMessage\": {\n // TypeScript doesn't narrow outer union via nested content.chunkType; cast is sound here\n const event = chatEvent as Extract<ChatEvent, { id: string }>;\n conversationExchange.messages.set(event.id, event as Draft<ConversationExchangeMessage>);\n break;\n }\n case \"toolRequest\":\n case \"toolResponse\": {\n const callId = chatEvent.content.callId;\n\n if (!conversationExchange.toolCalls.has(callId)) {\n conversationExchange.toolCalls.set(callId, {\n id: callId,\n request: undefined,\n result: undefined,\n state: \"pending\",\n });\n }\n\n const toolCall = conversationExchange.toolCalls.get(callId)!;\n\n switch (chatEvent.content.chunkType) {\n case \"toolRequest\":\n toolCall.request = chatEvent as unknown as Draft<ChatEventWithChunkType<\"toolRequest\">>;\n break;\n case \"toolResponse\":\n toolCall.result = chatEvent as unknown as Draft<ChatEventWithChunkType<\"toolResponse\">>;\n if (\"errorMessage\" in toolCall.result.content.result) {\n toolCall.state = \"error\";\n } else {\n toolCall.state = \"success\";\n }\n break;\n }\n }\n }\n}\n\nexport function reduceChatEvents(state: ChatEventReducerState = [], chatEvents: ChatEvent[]) {\n return create(state, (draft) => {\n for (const chatEvent of chatEvents) {\n applyChatEventToConversation(draft, Object.freeze(chatEvent));\n }\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"reduceChatEvents.js","sourceRoot":"","sources":["../../../../src/enterprise/ai/conversations/reduceChatEvents.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,MAAM,EAAc,MAAM,UAAU,CAAC;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAsB7C,yFAAyF;AACzF,oFAAoF;AACpF,MAAM,uBAAuB,GAAG,8BAA8B,CAAC;AA+B/D,SAAS,4BAA4B,CACnC,KAAmC,EACnC,SAAoB;IAEpB,IAAI,oBAAoB,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,KAAK,SAAS,CAAC,KAAK,CAAC,CAAC;IAEzF,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAC1B,oBAAoB,GAAG;YACrB,EAAE,EAAE,SAAS,CAAC,KAAK;YACnB,QAAQ,EAAE,IAAI,GAAG,EAAE;YACnB,SAAS,EAAE,IAAI,GAAG,EAAE;SACrB,CAAC;QACF,KAAK,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;QACjC,oBAAoB,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACjD,CAAC;IAED,oCAAoC,CAAC,oBAAqB,EAAE,SAAS,CAAC,CAAC;AACzE,CAAC;AAED,SAAS,oCAAoC,CAC3C,oBAAiD,EACjD,SAAoB;IAEpB,QAAQ,SAAS,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC;QACpC,KAAK,aAAa,CAAC,CAAC,CAAC;YACnB,KAAK,MAAM,CAAC,E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AS,CAAC,CAAC,CAAC;QAChE,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/*\n * Copyright (C) 2024-2025 Dremio Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { create, type Draft } from \"mutative\";\nimport { Temporal } from \"temporal-polyfill\";\nimport type {\n ChatEvent,\n ChatEventWithChunkType,\n SelectedSkillInfo,\n} from \"../chat/chatEventSchema.ts\";\nimport type { UserChatMessage } from \"../chat/UserChatMessage.ts\";\n\nexport type AgentToolCall = {\n id: string;\n state: \"canceled\" | \"error\" | \"pending\" | \"success\";\n request: ChatEventWithChunkType<\"toolRequest\"> | undefined;\n result: ChatEventWithChunkType<\"toolResponse\"> | undefined;\n};\n\nexport type ConversationExchangeMessage =\n | ChatEventWithChunkType<\"error\">\n | ChatEventWithChunkType<\"model\">\n | ChatEventWithChunkType<\"sandboxProgress\">\n | ChatEventWithChunkType<\"sandboxStdout\">\n | ChatEventWithChunkType<\"userMessage\">;\n\n// Mutative array drafts do not handle symbol-key reads reliably, so use a non-enumerable\n// string key for reducer bookkeeping while keeping JSON/deep equality output clean.\nconst selectedSkillsCursorKey = \"__dremioSelectedSkillsCursor\";\n\ntype SelectedSkillsCursor = {\n messagePosition: MessagePosition | undefined;\n updatedAt: Temporal.Instant;\n};\n\ntype SelectedSkillsWithCursor = SelectedSkillInfo[] & {\n [selectedSkillsCursorKey]?: SelectedSkillsCursor;\n};\n\ntype MessagePosition = {\n chunkId: string;\n messageSubId: number;\n partId: number | undefined;\n};\n\nexport type ConversationExchangeRunMetadata = {\n selectedSkills?: SelectedSkillInfo[];\n};\n\nexport type ConversationExchange = {\n id: string;\n messages: Map<string, ConversationExchangeMessage>;\n runMetadata?: ConversationExchangeRunMetadata;\n submittedUserMessage?: UserChatMessage;\n toolCalls: Map<string, AgentToolCall>;\n};\n\nexport type ChatEventReducerState = ConversationExchange[];\n\nfunction applyChatEventToConversation(\n draft: Draft<ChatEventReducerState>,\n chatEvent: ChatEvent,\n): void {\n let conversationExchange = draft.findLast((exchange) => exchange.id === chatEvent.runId);\n\n if (!conversationExchange) {\n conversationExchange = {\n id: chatEvent.runId,\n messages: new Map(),\n toolCalls: new Map(),\n };\n draft.push(conversationExchange);\n conversationExchange = draft[draft.length - 1];\n }\n\n applyChatEventToConversationExchange(conversationExchange!, chatEvent);\n}\n\nfunction applyChatEventToConversationExchange(\n conversationExchange: Draft<ConversationExchange>,\n chatEvent: ChatEvent,\n): void {\n switch (chatEvent.content.chunkType) {\n case \"endOfStream\": {\n for (const [, toolCall] of conversationExchange.toolCalls) {\n if (!toolCall.result) {\n toolCall.state = \"canceled\";\n }\n }\n break;\n }\n case \"selectedSkills\": {\n applySelectedSkillsMetadata(\n conversationExchange,\n chatEvent as ChatEventWithChunkType<\"selectedSkills\">,\n );\n break;\n }\n case \"error\":\n case \"model\":\n case \"sandboxProgress\":\n case \"sandboxStdout\":\n case \"userMessage\": {\n // TypeScript doesn't narrow outer union via nested content.chunkType; cast is sound here\n const event = chatEvent as Extract<ChatEvent, { id: string }>;\n conversationExchange.messages.set(event.id, event as Draft<ConversationExchangeMessage>);\n break;\n }\n case \"toolRequest\":\n case \"toolResponse\": {\n const callId = chatEvent.content.callId;\n\n if (!conversationExchange.toolCalls.has(callId)) {\n conversationExchange.toolCalls.set(callId, {\n id: callId,\n request: undefined,\n result: undefined,\n state: \"pending\",\n });\n }\n\n const toolCall = conversationExchange.toolCalls.get(callId)!;\n\n switch (chatEvent.content.chunkType) {\n case \"toolRequest\":\n toolCall.request = chatEvent as unknown as Draft<ChatEventWithChunkType<\"toolRequest\">>;\n break;\n case \"toolResponse\":\n toolCall.result = chatEvent as unknown as Draft<ChatEventWithChunkType<\"toolResponse\">>;\n if (\"errorMessage\" in toolCall.result.content.result) {\n toolCall.state = \"error\";\n } else {\n toolCall.state = \"success\";\n }\n break;\n }\n }\n }\n}\n\nfunction applySelectedSkillsMetadata(\n conversationExchange: Draft<ConversationExchange>,\n chatEvent: ChatEventWithChunkType<\"selectedSkills\">,\n): void {\n if (!isSelectedSkillsEventNewer(conversationExchange.runMetadata, chatEvent)) {\n return;\n }\n\n conversationExchange.runMetadata ??= {};\n // Clone before attaching reducer bookkeeping so the input event payload stays immutable.\n const selectedSkills = [...chatEvent.content.selectedSkills];\n setSelectedSkillsCursor(selectedSkills, {\n messagePosition: parseMessagePosition(chatEvent.id),\n updatedAt: chatEvent.createdAt,\n });\n conversationExchange.runMetadata.selectedSkills = selectedSkills;\n}\n\nfunction isSelectedSkillsEventNewer(\n runMetadata: Draft<ConversationExchangeRunMetadata> | undefined,\n chatEvent: ChatEventWithChunkType<\"selectedSkills\">,\n): boolean {\n // selectedSkills is singleton run metadata, so unlike messages and tool calls it is not keyed by\n // event id. Keep newer live-stream metadata when an older history replay is reduced later.\n const cursor = getSelectedSkillsCursor(runMetadata);\n if (!cursor) {\n return true;\n }\n\n const timestampComparison = Temporal.Instant.compare(chatEvent.createdAt, cursor.updatedAt);\n if (timestampComparison !== 0) {\n return timestampComparison > 0;\n }\n\n const messagePositionComparison = compareMessagePositions(\n parseMessagePosition(chatEvent.id),\n cursor.messagePosition,\n );\n if (messagePositionComparison !== undefined) {\n return messagePositionComparison >= 0;\n }\n\n return true;\n}\n\nfunction getSelectedSkillsCursor(\n runMetadata: Draft<ConversationExchangeRunMetadata> | undefined,\n): Draft<SelectedSkillsCursor> | undefined {\n return (runMetadata?.selectedSkills as Draft<SelectedSkillsWithCursor> | undefined)?.[\n selectedSkillsCursorKey\n ];\n}\n\nfunction setSelectedSkillsCursor(\n selectedSkills: SelectedSkillInfo[],\n cursor: SelectedSkillsCursor,\n): void {\n Object.defineProperty(selectedSkills, selectedSkillsCursorKey, {\n configurable: true,\n enumerable: false,\n value: cursor,\n writable: true,\n });\n}\n\n// Run-events message ids are chunkId:messageSubId; split message parts append :partId.\nfunction parseMessagePosition(messageId: string): MessagePosition | undefined {\n const parts = messageId.split(\":\");\n if (parts.length < 2 || parts.length > 3) {\n return undefined;\n }\n\n const [chunkId, messageSubId, partId] = parts;\n if (!chunkId) {\n return undefined;\n }\n\n const parsedMessageSubId = parseNonNegativeInteger(messageSubId);\n if (parsedMessageSubId === undefined) {\n return undefined;\n }\n\n const parsedPartId = partId === undefined ? undefined : parseNonNegativeInteger(partId);\n if (partId !== undefined && parsedPartId === undefined) {\n return undefined;\n }\n\n return {\n chunkId,\n messageSubId: parsedMessageSubId,\n partId: parsedPartId,\n };\n}\n\nfunction parseNonNegativeInteger(value: string | undefined): number | undefined {\n if (value === undefined || !/^\\d+$/.test(value)) {\n return undefined;\n }\n\n const parsedValue = Number(value);\n if (!Number.isSafeInteger(parsedValue)) {\n return undefined;\n }\n\n return parsedValue;\n}\n\nfunction compareMessagePositions(\n incoming: MessagePosition | undefined,\n current: Draft<MessagePosition> | undefined,\n): number | undefined {\n if (!incoming || !current || incoming.chunkId !== current.chunkId) {\n return undefined;\n }\n\n const messageSubIdComparison = incoming.messageSubId - current.messageSubId;\n if (messageSubIdComparison !== 0) {\n return messageSubIdComparison;\n }\n\n return (incoming.partId ?? 0) - (current.partId ?? 0);\n}\n\nexport function reduceChatEvents(state: ChatEventReducerState = [], chatEvents: ChatEvent[]) {\n return create(state, (draft) => {\n for (const chatEvent of chatEvents) {\n applyChatEventToConversation(draft, Object.freeze(chatEvent));\n }\n });\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AgentConversation } from "./conversations/AgentConversation.ts";
|
|
2
2
|
import { ModelProvider } from "./modelProvider/ModelProvider.ts";
|
|
3
|
-
import { type ChatEvent, type ChatEventWithChunkType } from "./chat/chatEventSchema.ts";
|
|
4
|
-
import type { ConversationExchange, ConversationExchangeMessage, AgentToolCall } from "./conversations/reduceChatEvents.ts";
|
|
3
|
+
import { type ChatEvent, type ChatEventWithChunkType, type SelectedSkillInfo } from "./chat/chatEventSchema.ts";
|
|
4
|
+
import type { ConversationExchange, ConversationExchangeMessage, ConversationExchangeRunMetadata, AgentToolCall } from "./conversations/reduceChatEvents.ts";
|
|
5
5
|
import { type AgentConversationMachine } from "./conversations/createConversationMachine.ts";
|
|
6
6
|
export * from "./chat/index.ts";
|
|
7
|
-
export { AgentConversation, ModelProvider, type ChatEvent, type ChatEventWithChunkType, type ConversationExchange, type ConversationExchangeMessage, type AgentToolCall, type AgentConversationMachine, };
|
|
7
|
+
export { AgentConversation, ModelProvider, type ChatEvent, type ChatEventWithChunkType, type SelectedSkillInfo, type ConversationExchange, type ConversationExchangeMessage, type ConversationExchangeRunMetadata, type AgentToolCall, type AgentConversationMachine, };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/enterprise/ai/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAC;AACzE,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAC;AACjE,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/enterprise/ai/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAC;AACzE,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAC;AACjE,OAAO,EAIN,MAAM,2BAA2B,CAAC;AAOnC,OAAO,EAAiC,MAAM,8CAA8C,CAAC;AAC7F,cAAc,iBAAiB,CAAC;AAChC,OAAO,EACL,iBAAiB,EACjB,aAAa,GASd,CAAC","sourcesContent":["/*\n * Copyright (C) 2024-2025 Dremio Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AgentConversation } from \"./conversations/AgentConversation.ts\";\nimport { ModelProvider } from \"./modelProvider/ModelProvider.ts\";\nimport {\n type ChatEvent,\n type ChatEventWithChunkType,\n type SelectedSkillInfo,\n} from \"./chat/chatEventSchema.ts\";\nimport type {\n ConversationExchange,\n ConversationExchangeMessage,\n ConversationExchangeRunMetadata,\n AgentToolCall,\n} from \"./conversations/reduceChatEvents.ts\";\nimport { type AgentConversationMachine } from \"./conversations/createConversationMachine.ts\";\nexport * from \"./chat/index.ts\";\nexport {\n AgentConversation,\n ModelProvider,\n type ChatEvent,\n type ChatEventWithChunkType,\n type SelectedSkillInfo,\n type ConversationExchange,\n type ConversationExchangeMessage,\n type ConversationExchangeRunMetadata,\n type AgentToolCall,\n type AgentConversationMachine,\n};\n"]}
|