Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chore(dcs): Kill dcs websocket server (#1599)
Eric Hayes367cfad1da6c
diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.tsindex 0844e91863..ed26b8dc46 100644--- a/js/app/packages/service-clients/service-cognition/generated/client.ts+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts@@ -1136,49 +1136,6 @@ export const getBatchPreview = async (} as getBatchPreviewResponse;};-export type wsHandlerResponse200 = {- data: void;- status: 200;-};--export type wsHandlerResponse500 = {- data: string;- status: 500;-};--export type wsHandlerResponseSuccess = wsHandlerResponse200 & {- headers: Headers;-};-export type wsHandlerResponseError = wsHandlerResponse500 & {- headers: Headers;-};--export type wsHandlerResponse =- | wsHandlerResponseSuccess- | wsHandlerResponseError;--export const getWsHandlerUrl = () => {- return `/stream`;-};--export const wsHandler = async (- options?: RequestInit-): Promise<wsHandlerResponse> => {- const res = await fetch(getWsHandlerUrl(), {- ...options,- method: 'GET',- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: wsHandlerResponse['data'] = body ? JSON.parse(body) : {};- return {- data,- status: res.status,- headers: res.headers,- } as wsHandlerResponse;-};-/*** This endpoint initiates a chat message and streams the response via the stream service.The client should subscribe to the returned stream_id via connection_gateway to receive chunks.diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStream.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStream.tsindex 83c0fc78eb..916fb92799 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStream.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStream.ts@@ -13,7 +13,6 @@ import type { ChatStreamOneOfOneseven } from './chatStreamOneOfOneseven';import type { ChatStreamOneOfOnetwo } from './chatStreamOneOfOnetwo';import type { ChatStreamOneOfOnezero } from './chatStreamOneOfOnezero';import type { ChatStreamOneOfSix } from './chatStreamOneOfSix';-import type { ChatStreamOneOfThreeone } from './chatStreamOneOfThreeone';import type { ChatStreamOneOfTwofive } from './chatStreamOneOfTwofive';import type { ChatStreamOneOfTwonine } from './chatStreamOneOfTwonine';import type { ChatStreamOneOfTwoone } from './chatStreamOneOfTwoone';@@ -34,5 +33,4 @@ export type ChatStream =| ChatStreamOneOfTwothree| ChatStreamOneOfTwofive| ChatStreamOneOfTwoseven- | ChatStreamOneOfTwonine- | ChatStreamOneOfThreeone;+ | ChatStreamOneOfTwonine;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOf.tsindex d1b5d346f4..e72a32cbc6 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOf.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOf.ts@@ -6,9 +6,9 @@*/import type { ChatStreamOneOfAllOf } from './chatStreamOneOfAllOf';-import type { WebSocketError } from './webSocketError';+import type { StreamError } from './streamError';/*** Misc error*/-export type ChatStreamOneOf = WebSocketError & ChatStreamOneOfAllOf;+export type ChatStreamOneOf = StreamError & ChatStreamOneOfAllOf;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfThreeone.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfThreeone.tsdeleted file mode 100644index 33d69b175d..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfThreeone.ts+++ /dev/null@@ -1,12 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { ChatStreamOneOfThreeoneType } from './chatStreamOneOfThreeoneType';--export type ChatStreamOneOfThreeone = {- stream_id: string;- type: ChatStreamOneOfThreeoneType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfThreeoneType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfThreeoneType.tsdeleted file mode 100644index 92c4a09d9d..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfThreeoneType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type ChatStreamOneOfThreeoneType =- (typeof ChatStreamOneOfThreeoneType)[keyof typeof ChatStreamOneOfThreeoneType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const ChatStreamOneOfThreeoneType = {- stream_end: 'stream_end',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofive.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofive.tsindex 32d336055c..449c4f7fde 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofive.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofive.ts@@ -6,6 +6,12 @@*/import type { ChatStreamOneOfTwofiveType } from './chatStreamOneOfTwofiveType';+/**+ * pdf completion+ */export type ChatStreamOneOfTwofive = {+ completion_id: string;+ content: string;+ done: boolean;type: ChatStreamOneOfTwofiveType;};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofiveType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofiveType.tsindex 12ca4baf4a..75fbc8061f 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofiveType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofiveType.ts@@ -10,5 +10,5 @@ export type ChatStreamOneOfTwofiveType =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const ChatStreamOneOfTwofiveType = {- pong: 'pong',+ completion_response: 'completion_response',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonine.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonine.tsindex 0a02433a8f..31b0de618d 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonine.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonine.ts@@ -7,8 +7,6 @@import type { ChatStreamOneOfTwonineType } from './chatStreamOneOfTwonineType';export type ChatStreamOneOfTwonine = {- completion_id: string;- content: string;- done: boolean;+ stream_id: string;type: ChatStreamOneOfTwonineType;};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonineType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonineType.tsindex 35705a75c8..cd751d9bb2 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonineType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonineType.ts@@ -10,5 +10,5 @@ export type ChatStreamOneOfTwonineType =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const ChatStreamOneOfTwonineType = {- completion_stream_chunk: 'completion_stream_chunk',+ stream_end: 'stream_end',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwoseven.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwoseven.tsindex 0073f7e68b..71c2cce606 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwoseven.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwoseven.ts@@ -6,9 +6,6 @@*/import type { ChatStreamOneOfTwosevenType } from './chatStreamOneOfTwosevenType';-/**- * pdf completion- */export type ChatStreamOneOfTwoseven = {completion_id: string;content: string;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwosevenType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwosevenType.tsindex 0a062ac784..b1ccd9869d 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwosevenType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwosevenType.ts@@ -10,5 +10,5 @@ export type ChatStreamOneOfTwosevenType =// eslint-disable-next-line @typescript-eslint/no-redeclareexport const ChatStreamOneOfTwosevenType = {- completion_response: 'completion_response',+ completion_stream_chunk: 'completion_stream_chunk',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/extractionStatusPayload.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/extractionStatusPayload.tsdeleted file mode 100644index 381fba6792..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/extractionStatusPayload.ts+++ /dev/null@@ -1,10 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export interface ExtractionStatusPayload {- attachment_id: string;-}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/index.tsindex 766d5a20da..f2fa0d5267 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts@@ -92,8 +92,6 @@ export * from './chatStreamOneOfOnezero';export * from './chatStreamOneOfOnezeroType';export * from './chatStreamOneOfSix';export * from './chatStreamOneOfSixType';-export * from './chatStreamOneOfThreeone';-export * from './chatStreamOneOfThreeoneType';export * from './chatStreamOneOfTwofive';export * from './chatStreamOneOfTwofiveType';export * from './chatStreamOneOfTwonine';@@ -133,7 +131,6 @@ export * from './extractionStatusEnumOneOfSevenType';export * from './extractionStatusEnumOneOfThree';export * from './extractionStatusEnumOneOfThreeType';export * from './extractionStatusEnumOneOfType';-export * from './extractionStatusPayload';export * from './fileType';export * from './genericErrorResponse';export * from './genericSuccessResponse';@@ -181,31 +178,21 @@ export * from './patchChatRequestV2ProjectId';export * from './patchChatRequestV2SharePermission';export * from './provider';export * from './role';-export * from './selectModelPayload';export * from './sendChatMessagePayload';export * from './sendChatMessagePayloadAllOf';export * from './sendChatMessagePayloadAllOfAdditionalInstructions';export * from './sendChatMessagePayloadAllOfAttachments';export * from './sendChatMessageResponse';-export * from './sendCompletionPayload';-export * from './sendCompletionPayloadAttachmentId';-export * from './sendCompletionPayloadCompletionId';-export * from './sendCompletionPayloadSelectedText';export * from './sharePermissionV2';export * from './sharePermissionV2ChannelSharePermissions';export * from './sharePermissionV2PublicAccessLevel';export * from './simpleCompletionError';export * from './simpleCompletionErrorCompletionId';export * from './simpleCompletionResponse';-export * from './stopChatMessagePayload';export * from './streamError';export * from './streamErrorOneOf';export * from './streamErrorOneOfFive';export * from './streamErrorOneOfFiveStreamError';-export * from './streamErrorOneOfNine';-export * from './streamErrorOneOfNineStreamError';-export * from './streamErrorOneOfSeven';-export * from './streamErrorOneOfSevenStreamError';export * from './streamErrorOneOfStreamError';export * from './streamErrorOneOfThree';export * from './streamErrorOneOfThreeStreamError';@@ -220,28 +207,6 @@ export * from './toolSetOneOf';export * from './toolSetOneOfThree';export * from './toolSetOneOfThreeType';export * from './toolSetOneOfType';-export * from './toWebSocketMessage';-export * from './toWebSocketMessageOneOf';-export * from './toWebSocketMessageOneOfAllOf';-export * from './toWebSocketMessageOneOfAllOfType';-export * from './toWebSocketMessageOneOfFour';-export * from './toWebSocketMessageOneOfFourAllOf';-export * from './toWebSocketMessageOneOfFourAllOfType';-export * from './toWebSocketMessageOneOfOnenine';-export * from './toWebSocketMessageOneOfOnenineAllOf';-export * from './toWebSocketMessageOneOfOnenineAllOfType';-export * from './toWebSocketMessageOneOfOnesix';-export * from './toWebSocketMessageOneOfOnesixAllOf';-export * from './toWebSocketMessageOneOfOnesixAllOfType';-export * from './toWebSocketMessageOneOfOnethree';-export * from './toWebSocketMessageOneOfOnethreeAllOf';-export * from './toWebSocketMessageOneOfOnethreeAllOfType';-export * from './toWebSocketMessageOneOfOnezero';-export * from './toWebSocketMessageOneOfOnezeroAllOf';-export * from './toWebSocketMessageOneOfOnezeroAllOfType';-export * from './toWebSocketMessageOneOfSeven';-export * from './toWebSocketMessageOneOfSevenAllOf';-export * from './toWebSocketMessageOneOfSevenAllOfType';export * from './updateChannelSharePermission';export * from './updateChannelSharePermissionAccessLevel';export * from './updateOperation';@@ -252,38 +217,4 @@ export * from './updateSharePermissionRequestV2PublicAccessLevel';export * from './userPdfRect';export * from './verifyAttachmentsRequest';export * from './verifyAttachmentsResponse';-export * from './webSocketError';-export * from './webSocketErrorOneOf';-export * from './webSocketErrorOneOfAllOf';-export * from './webSocketErrorOneOfAllOfErrorType';-export * from './webSocketErrorOneOfFour';-export * from './webSocketErrorOneOfFourDetails';-export * from './webSocketErrorOneOfFourErrorType';-export * from './webSocketErrorOneOfOnenine';-export * from './webSocketErrorOneOfOnenineDetails';-export * from './webSocketErrorOneOfOnenineErrorType';-export * from './webSocketErrorOneOfOnesix';-export * from './webSocketErrorOneOfOnesixAllOf';-export * from './webSocketErrorOneOfOnesixAllOfErrorType';-export * from './webSocketErrorOneOfOnethree';-export * from './webSocketErrorOneOfOnethreeDetails';-export * from './webSocketErrorOneOfOnethreeErrorType';-export * from './webSocketErrorOneOfOnezero';-export * from './webSocketErrorOneOfOnezeroDetails';-export * from './webSocketErrorOneOfOnezeroErrorType';-export * from './webSocketErrorOneOfSeven';-export * from './webSocketErrorOneOfSevenDetails';-export * from './webSocketErrorOneOfSevenErrorType';-export * from './webSocketErrorOneOfThreetwo';-export * from './webSocketErrorOneOfThreetwoErrorType';-export * from './webSocketErrorOneOfThreezero';-export * from './webSocketErrorOneOfThreezeroErrorType';-export * from './webSocketErrorOneOfTwoeight';-export * from './webSocketErrorOneOfTwoeightErrorType';-export * from './webSocketErrorOneOfTwofive';-export * from './webSocketErrorOneOfTwofiveDetails';-export * from './webSocketErrorOneOfTwofiveErrorType';-export * from './webSocketErrorOneOfTwotwo';-export * from './webSocketErrorOneOfTwotwoDetails';-export * from './webSocketErrorOneOfTwotwoErrorType';export * from './withChatId';diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/selectModelPayload.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/selectModelPayload.tsdeleted file mode 100644index d9de2a3842..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/selectModelPayload.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export interface SelectModelPayload {- chat_id: string;- model: string;-}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/sendCompletionPayload.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/sendCompletionPayload.tsdeleted file mode 100644index 221d12edc2..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/sendCompletionPayload.ts+++ /dev/null@@ -1,21 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { SendCompletionPayloadAttachmentId } from './sendCompletionPayloadAttachmentId';-import type { SendCompletionPayloadCompletionId } from './sendCompletionPayloadCompletionId';-import type { SendCompletionPayloadSelectedText } from './sendCompletionPayloadSelectedText';--export interface SendCompletionPayload {- /** Optional attachment id for the completion */- attachment_id?: SendCompletionPayloadAttachmentId;- /** Optional completion id to keep track of the completion-if non is provided, one will be generated */- completion_id?: SendCompletionPayloadCompletionId;- /** the prompt of the completion */- prompt: string;- /** The selected text for the completion, */- selected_text?: SendCompletionPayloadSelectedText;-}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/sendCompletionPayloadAttachmentId.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/sendCompletionPayloadAttachmentId.tsdeleted file mode 100644index c59b3aa754..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/sendCompletionPayloadAttachmentId.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--/**- * Optional attachment id for the completion- */-export type SendCompletionPayloadAttachmentId = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/sendCompletionPayloadCompletionId.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/sendCompletionPayloadCompletionId.tsdeleted file mode 100644index e074b0ba55..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/sendCompletionPayloadCompletionId.ts+++ /dev/null@@ -1,12 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--/**- * Optional completion id to keep track of the completion-if non is provided, one will be generated- */-export type SendCompletionPayloadCompletionId = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/sendCompletionPayloadSelectedText.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/sendCompletionPayloadSelectedText.tsdeleted file mode 100644index 7158e30a64..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/sendCompletionPayloadSelectedText.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--/**- * The selected text for the completion,- */-export type SendCompletionPayloadSelectedText = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/stopChatMessagePayload.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/stopChatMessagePayload.tsdeleted file mode 100644index 11988261a1..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/stopChatMessagePayload.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export interface StopChatMessagePayload {- /** stream id */- stream_id: string;-}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/streamError.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/streamError.tsindex f8a643aa1e..8f41bac7ce 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/streamError.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/streamError.ts@@ -6,13 +6,9 @@*/import type { StreamErrorOneOf } from './streamErrorOneOf';import type { StreamErrorOneOfFive } from './streamErrorOneOfFive';-import type { StreamErrorOneOfNine } from './streamErrorOneOfNine';-import type { StreamErrorOneOfSeven } from './streamErrorOneOfSeven';import type { StreamErrorOneOfThree } from './streamErrorOneOfThree';export type StreamError =| StreamErrorOneOf| StreamErrorOneOfThree- | StreamErrorOneOfFive- | StreamErrorOneOfSeven- | StreamErrorOneOfNine;+ | StreamErrorOneOfFive;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOfNine.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOfNine.tsdeleted file mode 100644index 74c80c00a3..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOfNine.ts+++ /dev/null@@ -1,12 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { StreamErrorOneOfNineStreamError } from './streamErrorOneOfNineStreamError';--export type StreamErrorOneOfNine = {- stream_error: StreamErrorOneOfNineStreamError;- stream_id: string;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOfNineStreamError.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOfNineStreamError.tsdeleted file mode 100644index eaf9c87839..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOfNineStreamError.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type StreamErrorOneOfNineStreamError =- (typeof StreamErrorOneOfNineStreamError)[keyof typeof StreamErrorOneOfNineStreamError];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const StreamErrorOneOfNineStreamError = {- payment_required: 'payment_required',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOfSeven.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOfSeven.tsdeleted file mode 100644index 1f9a6c9ae7..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOfSeven.ts+++ /dev/null@@ -1,12 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { StreamErrorOneOfSevenStreamError } from './streamErrorOneOfSevenStreamError';--export type StreamErrorOneOfSeven = {- stream_error: StreamErrorOneOfSevenStreamError;- stream_id: string;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOfSevenStreamError.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOfSevenStreamError.tsdeleted file mode 100644index 0899b997cd..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/streamErrorOneOfSevenStreamError.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type StreamErrorOneOfSevenStreamError =- (typeof StreamErrorOneOfSevenStreamError)[keyof typeof StreamErrorOneOfSevenStreamError];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const StreamErrorOneOfSevenStreamError = {- unauthorized: 'unauthorized',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessage.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessage.tsdeleted file mode 100644index 654948045b..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessage.ts+++ /dev/null@@ -1,22 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { ToWebSocketMessageOneOf } from './toWebSocketMessageOneOf';-import type { ToWebSocketMessageOneOfFour } from './toWebSocketMessageOneOfFour';-import type { ToWebSocketMessageOneOfOnenine } from './toWebSocketMessageOneOfOnenine';-import type { ToWebSocketMessageOneOfOnesix } from './toWebSocketMessageOneOfOnesix';-import type { ToWebSocketMessageOneOfOnethree } from './toWebSocketMessageOneOfOnethree';-import type { ToWebSocketMessageOneOfOnezero } from './toWebSocketMessageOneOfOnezero';-import type { ToWebSocketMessageOneOfSeven } from './toWebSocketMessageOneOfSeven';--export type ToWebSocketMessage =- | ToWebSocketMessageOneOf- | ToWebSocketMessageOneOfFour- | ToWebSocketMessageOneOfSeven- | ToWebSocketMessageOneOfOnezero- | ToWebSocketMessageOneOfOnethree- | ToWebSocketMessageOneOfOnesix- | ToWebSocketMessageOneOfOnenine;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOf.tsdeleted file mode 100644index 023f8bcdc7..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOf.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { SendChatMessagePayload } from './sendChatMessagePayload';-import type { ToWebSocketMessageOneOfAllOf } from './toWebSocketMessageOneOfAllOf';--/**- * Initializes a new message in a chat for streaming- */-export type ToWebSocketMessageOneOf = SendChatMessagePayload &- ToWebSocketMessageOneOfAllOf;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfAllOf.tsdeleted file mode 100644index 4ada460847..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfAllOf.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { ToWebSocketMessageOneOfAllOfType } from './toWebSocketMessageOneOfAllOfType';--export type ToWebSocketMessageOneOfAllOf = {- type: ToWebSocketMessageOneOfAllOfType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfAllOfType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfAllOfType.tsdeleted file mode 100644index 0a08423343..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfAllOfType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type ToWebSocketMessageOneOfAllOfType =- (typeof ToWebSocketMessageOneOfAllOfType)[keyof typeof ToWebSocketMessageOneOfAllOfType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const ToWebSocketMessageOneOfAllOfType = {- send_chat_message: 'send_chat_message',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfFour.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfFour.tsdeleted file mode 100644index a36db3ae76..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfFour.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { SendChatMessagePayload } from './sendChatMessagePayload';-import type { ToWebSocketMessageOneOfFourAllOf } from './toWebSocketMessageOneOfFourAllOf';--/**- * Replace user message and restream response- */-export type ToWebSocketMessageOneOfFour = SendChatMessagePayload &- ToWebSocketMessageOneOfFourAllOf;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfFourAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfFourAllOf.tsdeleted file mode 100644index 55f4375751..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfFourAllOf.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { ToWebSocketMessageOneOfFourAllOfType } from './toWebSocketMessageOneOfFourAllOfType';--export type ToWebSocketMessageOneOfFourAllOf = {- type: ToWebSocketMessageOneOfFourAllOfType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfFourAllOfType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfFourAllOfType.tsdeleted file mode 100644index 60423d36a0..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfFourAllOfType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type ToWebSocketMessageOneOfFourAllOfType =- (typeof ToWebSocketMessageOneOfFourAllOfType)[keyof typeof ToWebSocketMessageOneOfFourAllOfType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const ToWebSocketMessageOneOfFourAllOfType = {- edit_chat_message: 'edit_chat_message',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnenine.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnenine.tsdeleted file mode 100644index b7c1046aa1..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnenine.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { GetSimpleCompletionStreamPayload } from './getSimpleCompletionStreamPayload';-import type { ToWebSocketMessageOneOfOnenineAllOf } from './toWebSocketMessageOneOfOnenineAllOf';--/**- * stream a simple completion- */-export type ToWebSocketMessageOneOfOnenine = GetSimpleCompletionStreamPayload &- ToWebSocketMessageOneOfOnenineAllOf;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnenineAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnenineAllOf.tsdeleted file mode 100644index 600fcd50fe..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnenineAllOf.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { ToWebSocketMessageOneOfOnenineAllOfType } from './toWebSocketMessageOneOfOnenineAllOfType';--export type ToWebSocketMessageOneOfOnenineAllOf = {- type: ToWebSocketMessageOneOfOnenineAllOfType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnenineAllOfType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnenineAllOfType.tsdeleted file mode 100644index 20964cb070..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnenineAllOfType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type ToWebSocketMessageOneOfOnenineAllOfType =- (typeof ToWebSocketMessageOneOfOnenineAllOfType)[keyof typeof ToWebSocketMessageOneOfOnenineAllOfType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const ToWebSocketMessageOneOfOnenineAllOfType = {- get_simple_completion_stream: 'get_simple_completion_stream',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnesix.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnesix.tsdeleted file mode 100644index b9e2bf3d86..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnesix.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { SendCompletionPayload } from './sendCompletionPayload';-import type { ToWebSocketMessageOneOfOnesixAllOf } from './toWebSocketMessageOneOfOnesixAllOf';--/**- * pdf completion- */-export type ToWebSocketMessageOneOfOnesix = SendCompletionPayload &- ToWebSocketMessageOneOfOnesixAllOf;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnesixAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnesixAllOf.tsdeleted file mode 100644index 5f2a8710c5..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnesixAllOf.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { ToWebSocketMessageOneOfOnesixAllOfType } from './toWebSocketMessageOneOfOnesixAllOfType';--export type ToWebSocketMessageOneOfOnesixAllOf = {- type: ToWebSocketMessageOneOfOnesixAllOfType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnesixAllOfType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnesixAllOfType.tsdeleted file mode 100644index 3ac6df7898..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnesixAllOfType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type ToWebSocketMessageOneOfOnesixAllOfType =- (typeof ToWebSocketMessageOneOfOnesixAllOfType)[keyof typeof ToWebSocketMessageOneOfOnesixAllOfType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const ToWebSocketMessageOneOfOnesixAllOfType = {- send_completion: 'send_completion',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnethree.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnethree.tsdeleted file mode 100644index ba6cdcc56b..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnethree.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { ExtractionStatusPayload } from './extractionStatusPayload';-import type { ToWebSocketMessageOneOfOnethreeAllOf } from './toWebSocketMessageOneOfOnethreeAllOf';--/**- * Get extraction status for a given attachment- */-export type ToWebSocketMessageOneOfOnethree = ExtractionStatusPayload &- ToWebSocketMessageOneOfOnethreeAllOf;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnethreeAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnethreeAllOf.tsdeleted file mode 100644index 0f744e502e..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnethreeAllOf.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { ToWebSocketMessageOneOfOnethreeAllOfType } from './toWebSocketMessageOneOfOnethreeAllOfType';--export type ToWebSocketMessageOneOfOnethreeAllOf = {- type: ToWebSocketMessageOneOfOnethreeAllOfType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnethreeAllOfType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnethreeAllOfType.tsdeleted file mode 100644index 8128e871fb..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnethreeAllOfType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type ToWebSocketMessageOneOfOnethreeAllOfType =- (typeof ToWebSocketMessageOneOfOnethreeAllOfType)[keyof typeof ToWebSocketMessageOneOfOnethreeAllOfType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const ToWebSocketMessageOneOfOnethreeAllOfType = {- extraction_status: 'extraction_status',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnezero.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnezero.tsdeleted file mode 100644index feca0323a7..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnezero.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { SelectModelPayload } from './selectModelPayload';-import type { ToWebSocketMessageOneOfOnezeroAllOf } from './toWebSocketMessageOneOfOnezeroAllOf';--/**- * Select model for a given chat- */-export type ToWebSocketMessageOneOfOnezero = SelectModelPayload &- ToWebSocketMessageOneOfOnezeroAllOf;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnezeroAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnezeroAllOf.tsdeleted file mode 100644index b7c9ab3021..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnezeroAllOf.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { ToWebSocketMessageOneOfOnezeroAllOfType } from './toWebSocketMessageOneOfOnezeroAllOfType';--export type ToWebSocketMessageOneOfOnezeroAllOf = {- type: ToWebSocketMessageOneOfOnezeroAllOfType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnezeroAllOfType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnezeroAllOfType.tsdeleted file mode 100644index dd4a96dd97..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfOnezeroAllOfType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type ToWebSocketMessageOneOfOnezeroAllOfType =- (typeof ToWebSocketMessageOneOfOnezeroAllOfType)[keyof typeof ToWebSocketMessageOneOfOnezeroAllOfType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const ToWebSocketMessageOneOfOnezeroAllOfType = {- select_model_for_chat: 'select_model_for_chat',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfSeven.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfSeven.tsdeleted file mode 100644index 7101c83b00..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfSeven.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { StopChatMessagePayload } from './stopChatMessagePayload';-import type { ToWebSocketMessageOneOfSevenAllOf } from './toWebSocketMessageOneOfSevenAllOf';--/**- * Stop streaming for a given message- */-export type ToWebSocketMessageOneOfSeven = StopChatMessagePayload &- ToWebSocketMessageOneOfSevenAllOf;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfSevenAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfSevenAllOf.tsdeleted file mode 100644index 27ee063695..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfSevenAllOf.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { ToWebSocketMessageOneOfSevenAllOfType } from './toWebSocketMessageOneOfSevenAllOfType';--export type ToWebSocketMessageOneOfSevenAllOf = {- type: ToWebSocketMessageOneOfSevenAllOfType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfSevenAllOfType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfSevenAllOfType.tsdeleted file mode 100644index c3c6d87f39..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/toWebSocketMessageOneOfSevenAllOfType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type ToWebSocketMessageOneOfSevenAllOfType =- (typeof ToWebSocketMessageOneOfSevenAllOfType)[keyof typeof ToWebSocketMessageOneOfSevenAllOfType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const ToWebSocketMessageOneOfSevenAllOfType = {- stop_chat_message: 'stop_chat_message',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketError.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketError.tsdeleted file mode 100644index 38b4e30d54..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketError.ts+++ /dev/null@@ -1,32 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOf } from './webSocketErrorOneOf';-import type { WebSocketErrorOneOfFour } from './webSocketErrorOneOfFour';-import type { WebSocketErrorOneOfOnenine } from './webSocketErrorOneOfOnenine';-import type { WebSocketErrorOneOfOnesix } from './webSocketErrorOneOfOnesix';-import type { WebSocketErrorOneOfOnethree } from './webSocketErrorOneOfOnethree';-import type { WebSocketErrorOneOfOnezero } from './webSocketErrorOneOfOnezero';-import type { WebSocketErrorOneOfSeven } from './webSocketErrorOneOfSeven';-import type { WebSocketErrorOneOfThreetwo } from './webSocketErrorOneOfThreetwo';-import type { WebSocketErrorOneOfThreezero } from './webSocketErrorOneOfThreezero';-import type { WebSocketErrorOneOfTwoeight } from './webSocketErrorOneOfTwoeight';-import type { WebSocketErrorOneOfTwofive } from './webSocketErrorOneOfTwofive';-import type { WebSocketErrorOneOfTwotwo } from './webSocketErrorOneOfTwotwo';--export type WebSocketError =- | WebSocketErrorOneOf- | WebSocketErrorOneOfFour- | WebSocketErrorOneOfSeven- | WebSocketErrorOneOfOnezero- | WebSocketErrorOneOfOnethree- | WebSocketErrorOneOfOnesix- | WebSocketErrorOneOfOnenine- | WebSocketErrorOneOfTwotwo- | WebSocketErrorOneOfTwofive- | WebSocketErrorOneOfTwoeight- | WebSocketErrorOneOfThreezero- | WebSocketErrorOneOfThreetwo;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOf.tsdeleted file mode 100644index 608c17177b..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOf.ts+++ /dev/null@@ -1,10 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { StreamError } from './streamError';-import type { WebSocketErrorOneOfAllOf } from './webSocketErrorOneOfAllOf';--export type WebSocketErrorOneOf = StreamError & WebSocketErrorOneOfAllOf;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfAllOf.tsdeleted file mode 100644index a226c6a150..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfAllOf.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOfAllOfErrorType } from './webSocketErrorOneOfAllOfErrorType';--export type WebSocketErrorOneOfAllOf = {- error_type: WebSocketErrorOneOfAllOfErrorType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfAllOfErrorType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfAllOfErrorType.tsdeleted file mode 100644index 6c3b7f457b..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfAllOfErrorType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfAllOfErrorType =- (typeof WebSocketErrorOneOfAllOfErrorType)[keyof typeof WebSocketErrorOneOfAllOfErrorType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const WebSocketErrorOneOfAllOfErrorType = {- stream_error: 'stream_error',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfFour.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfFour.tsdeleted file mode 100644index 32eba964d2..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfFour.ts+++ /dev/null@@ -1,16 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOfFourDetails } from './webSocketErrorOneOfFourDetails';-import type { WebSocketErrorOneOfFourErrorType } from './webSocketErrorOneOfFourErrorType';--export type WebSocketErrorOneOfFour = {- chat_id: string;- details?: WebSocketErrorOneOfFourDetails;- error_type: WebSocketErrorOneOfFourErrorType;- message_id: string;- stream_id: string;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfFourDetails.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfFourDetails.tsdeleted file mode 100644index b993628a92..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfFourDetails.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfFourDetails = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfFourErrorType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfFourErrorType.tsdeleted file mode 100644index 871f3f40ad..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfFourErrorType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfFourErrorType =- (typeof WebSocketErrorOneOfFourErrorType)[keyof typeof WebSocketErrorOneOfFourErrorType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const WebSocketErrorOneOfFourErrorType = {- failed_to_send_chat_message: 'failed_to_send_chat_message',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnenine.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnenine.tsdeleted file mode 100644index 460abc74b9..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnenine.ts+++ /dev/null@@ -1,13 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOfOnenineDetails } from './webSocketErrorOneOfOnenineDetails';-import type { WebSocketErrorOneOfOnenineErrorType } from './webSocketErrorOneOfOnenineErrorType';--export type WebSocketErrorOneOfOnenine = {- details?: WebSocketErrorOneOfOnenineDetails;- error_type: WebSocketErrorOneOfOnenineErrorType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnenineDetails.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnenineDetails.tsdeleted file mode 100644index ecf18f4abd..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnenineDetails.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfOnenineDetails = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnenineErrorType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnenineErrorType.tsdeleted file mode 100644index bee6b7cae2..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnenineErrorType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfOnenineErrorType =- (typeof WebSocketErrorOneOfOnenineErrorType)[keyof typeof WebSocketErrorOneOfOnenineErrorType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const WebSocketErrorOneOfOnenineErrorType = {- failed_to_send_websocket_message: 'failed_to_send_websocket_message',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnesix.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnesix.tsdeleted file mode 100644index c23c5cb7d2..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnesix.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { GenericErrorResponse } from './genericErrorResponse';-import type { WebSocketErrorOneOfOnesixAllOf } from './webSocketErrorOneOfOnesixAllOf';--export type WebSocketErrorOneOfOnesix = GenericErrorResponse &- WebSocketErrorOneOfOnesixAllOf;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnesixAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnesixAllOf.tsdeleted file mode 100644index 083020af80..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnesixAllOf.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOfOnesixAllOfErrorType } from './webSocketErrorOneOfOnesixAllOfErrorType';--export type WebSocketErrorOneOfOnesixAllOf = {- error_type: WebSocketErrorOneOfOnesixAllOfErrorType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnesixAllOfErrorType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnesixAllOfErrorType.tsdeleted file mode 100644index 0275d6db7a..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnesixAllOfErrorType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfOnesixAllOfErrorType =- (typeof WebSocketErrorOneOfOnesixAllOfErrorType)[keyof typeof WebSocketErrorOneOfOnesixAllOfErrorType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const WebSocketErrorOneOfOnesixAllOfErrorType = {- generic: 'generic',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnethree.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnethree.tsdeleted file mode 100644index ca15a62ca5..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnethree.ts+++ /dev/null@@ -1,15 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOfOnethreeDetails } from './webSocketErrorOneOfOnethreeDetails';-import type { WebSocketErrorOneOfOnethreeErrorType } from './webSocketErrorOneOfOnethreeErrorType';--export type WebSocketErrorOneOfOnethree = {- chat_id: string;- details?: WebSocketErrorOneOfOnethreeDetails;- error_type: WebSocketErrorOneOfOnethreeErrorType;- stream_id: string;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnethreeDetails.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnethreeDetails.tsdeleted file mode 100644index e774f656ad..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnethreeDetails.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfOnethreeDetails = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnethreeErrorType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnethreeErrorType.tsdeleted file mode 100644index 3d33d80679..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnethreeErrorType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfOnethreeErrorType =- (typeof WebSocketErrorOneOfOnethreeErrorType)[keyof typeof WebSocketErrorOneOfOnethreeErrorType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const WebSocketErrorOneOfOnethreeErrorType = {- failed_to_store_chat: 'failed_to_store_chat',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnezero.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnezero.tsdeleted file mode 100644index ca411e460e..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnezero.ts+++ /dev/null@@ -1,13 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOfOnezeroDetails } from './webSocketErrorOneOfOnezeroDetails';-import type { WebSocketErrorOneOfOnezeroErrorType } from './webSocketErrorOneOfOnezeroErrorType';--export type WebSocketErrorOneOfOnezero = {- details?: WebSocketErrorOneOfOnezeroDetails;- error_type: WebSocketErrorOneOfOnezeroErrorType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnezeroDetails.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnezeroDetails.tsdeleted file mode 100644index 7bb08c2aec..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnezeroDetails.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfOnezeroDetails = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnezeroErrorType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnezeroErrorType.tsdeleted file mode 100644index f3dec2be0a..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfOnezeroErrorType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfOnezeroErrorType =- (typeof WebSocketErrorOneOfOnezeroErrorType)[keyof typeof WebSocketErrorOneOfOnezeroErrorType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const WebSocketErrorOneOfOnezeroErrorType = {- failed_to_send_error_message: 'failed_to_send_error_message',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfSeven.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfSeven.tsdeleted file mode 100644index d7eae2f471..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfSeven.ts+++ /dev/null@@ -1,15 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOfSevenDetails } from './webSocketErrorOneOfSevenDetails';-import type { WebSocketErrorOneOfSevenErrorType } from './webSocketErrorOneOfSevenErrorType';--export type WebSocketErrorOneOfSeven = {- chat_id: string;- details?: WebSocketErrorOneOfSevenDetails;- error_type: WebSocketErrorOneOfSevenErrorType;- stream_id: string;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfSevenDetails.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfSevenDetails.tsdeleted file mode 100644index 39c9426289..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfSevenDetails.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfSevenDetails = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfSevenErrorType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfSevenErrorType.tsdeleted file mode 100644index ec9209839e..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfSevenErrorType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfSevenErrorType =- (typeof WebSocketErrorOneOfSevenErrorType)[keyof typeof WebSocketErrorOneOfSevenErrorType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const WebSocketErrorOneOfSevenErrorType = {- failed_to_rename_chat: 'failed_to_rename_chat',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfThreetwo.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfThreetwo.tsdeleted file mode 100644index f73df335f3..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfThreetwo.ts+++ /dev/null@@ -1,13 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOfThreetwoErrorType } from './webSocketErrorOneOfThreetwoErrorType';--export type WebSocketErrorOneOfThreetwo = {- error_type: WebSocketErrorOneOfThreetwoErrorType;- reason: string;- stream_id: string;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfThreetwoErrorType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfThreetwoErrorType.tsdeleted file mode 100644index 4f0792cba0..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfThreetwoErrorType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfThreetwoErrorType =- (typeof WebSocketErrorOneOfThreetwoErrorType)[keyof typeof WebSocketErrorOneOfThreetwoErrorType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const WebSocketErrorOneOfThreetwoErrorType = {- failed_to_edit_message: 'failed_to_edit_message',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfThreezero.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfThreezero.tsdeleted file mode 100644index 326c0cd5e1..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfThreezero.ts+++ /dev/null@@ -1,12 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOfThreezeroErrorType } from './webSocketErrorOneOfThreezeroErrorType';--export type WebSocketErrorOneOfThreezero = {- attachment_ids: string[];- error_type: WebSocketErrorOneOfThreezeroErrorType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfThreezeroErrorType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfThreezeroErrorType.tsdeleted file mode 100644index 4c2ea35bf9..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfThreezeroErrorType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfThreezeroErrorType =- (typeof WebSocketErrorOneOfThreezeroErrorType)[keyof typeof WebSocketErrorOneOfThreezeroErrorType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const WebSocketErrorOneOfThreezeroErrorType = {- attachment_permission_error: 'attachment_permission_error',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwoeight.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwoeight.tsdeleted file mode 100644index 98192389ac..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwoeight.ts+++ /dev/null@@ -1,12 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOfTwoeightErrorType } from './webSocketErrorOneOfTwoeightErrorType';--export type WebSocketErrorOneOfTwoeight = {- attachment_id: string;- error_type: WebSocketErrorOneOfTwoeightErrorType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwoeightErrorType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwoeightErrorType.tsdeleted file mode 100644index 8288f523f8..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwoeightErrorType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfTwoeightErrorType =- (typeof WebSocketErrorOneOfTwoeightErrorType)[keyof typeof WebSocketErrorOneOfTwoeightErrorType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const WebSocketErrorOneOfTwoeightErrorType = {- extraction_status_failed: 'extraction_status_failed',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwofive.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwofive.tsdeleted file mode 100644index b7f96174a0..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwofive.ts+++ /dev/null@@ -1,16 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOfTwofiveDetails } from './webSocketErrorOneOfTwofiveDetails';-import type { WebSocketErrorOneOfTwofiveErrorType } from './webSocketErrorOneOfTwofiveErrorType';--export type WebSocketErrorOneOfTwofive = {- chat_id: string;- details?: WebSocketErrorOneOfTwofiveDetails;- error_type: WebSocketErrorOneOfTwofiveErrorType;- message_id: string;- stream_id: string;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwofiveDetails.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwofiveDetails.tsdeleted file mode 100644index 078dfdac3f..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwofiveDetails.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfTwofiveDetails = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwofiveErrorType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwofiveErrorType.tsdeleted file mode 100644index 59e5f8bb94..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwofiveErrorType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfTwofiveErrorType =- (typeof WebSocketErrorOneOfTwofiveErrorType)[keyof typeof WebSocketErrorOneOfTwofiveErrorType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const WebSocketErrorOneOfTwofiveErrorType = {- failed_to_update_token_count: 'failed_to_update_token_count',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwotwo.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwotwo.tsdeleted file mode 100644index 8292818e2e..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwotwo.ts+++ /dev/null@@ -1,13 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { WebSocketErrorOneOfTwotwoDetails } from './webSocketErrorOneOfTwotwoDetails';-import type { WebSocketErrorOneOfTwotwoErrorType } from './webSocketErrorOneOfTwotwoErrorType';--export type WebSocketErrorOneOfTwotwo = {- details?: WebSocketErrorOneOfTwotwoDetails;- error_type: WebSocketErrorOneOfTwotwoErrorType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwotwoDetails.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwotwoDetails.tsdeleted file mode 100644index 5ab38402fd..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwotwoDetails.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfTwotwoDetails = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwotwoErrorType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwotwoErrorType.tsdeleted file mode 100644index 55a5a92f47..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/webSocketErrorOneOfTwotwoErrorType.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type WebSocketErrorOneOfTwotwoErrorType =- (typeof WebSocketErrorOneOfTwotwoErrorType)[keyof typeof WebSocketErrorOneOfTwotwoErrorType];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const WebSocketErrorOneOfTwotwoErrorType = {- failed_to_select_model: 'failed_to_select_model',-} as const;diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.jsonindex f36331bf67..cdc5dfbad5 100644--- a/js/app/packages/service-clients/service-cognition/openapi.json+++ b/js/app/packages/service-clients/service-cognition/openapi.json@@ -1020,27 +1020,6 @@}}},- "/stream": {- "get": {- "tags": ["ws::connection"],- "operationId": "ws_handler",- "responses": {- "200": {- "description": "Sucessfully conntect to streaming websocket"- },- "500": {- "description": "Failed to connect to streaming websocket",- "content": {- "text/plain": {- "schema": {- "type": "string"- }- }- }- }- }- }- },"/stream/chat/message": {"post": {"tags": ["chat_message"],@@ -1782,7 +1761,7 @@{"allOf": [{- "$ref": "#/components/schemas/WebSocketError",+ "$ref": "#/components/schemas/StreamError","description": "Misc error"},{@@ -2021,16 +2000,6 @@}}},- {- "type": "object",- "required": ["type"],- "properties": {- "type": {- "type": "string",- "enum": ["pong"]- }- }- },{"type": "object","description": "pdf completion",@@ -2260,15 +2229,6 @@}]},- "ExtractionStatusPayload": {- "type": "object",- "required": ["attachment_id"],- "properties": {- "attachment_id": {- "type": "string"- }- }- },"FileType": {"type": "string","description": "Generates a FileType enum and associated ContentType enum with their implementations.\n\nThis macro takes a list of tuples in the format:\n(Variant, \"extension\", \"mime_type\", CONTENT_TYPE_VARIANT)\n\nFor each tuple it generates:\n- A variant in the FileType enum\n- A variant in the ContentType enum\n- Implementations for:\n - FileType::to_str() - Converts FileType to extension string\n - FileType::from_str() - Converts extension string to FileType\n - From<FileType> for ContentType - Maps FileType to ContentType\n - ContentType::mime_type() - Gets MIME type for ContentType\n",@@ -2757,18 +2717,6 @@"type": "string","enum": ["user", "assistant", "system"]},- "SelectModelPayload": {- "type": "object",- "required": ["chat_id", "model"],- "properties": {- "chat_id": {- "type": "string"- },- "model": {- "type": "string"- }- }- },"SendChatMessagePayload": {"allOf": [{@@ -2832,28 +2780,6 @@}}},- "SendCompletionPayload": {- "type": "object",- "required": ["prompt"],- "properties": {- "attachment_id": {- "type": ["string", "null"],- "description": "Optional attachment id for the completion"- },- "completion_id": {- "type": ["string", "null"],- "description": "Optional completion id to keep track of the completion\nif non is provided, one will be generated"- },- "prompt": {- "type": "string",- "description": "the prompt of the completion"- },- "selected_text": {- "type": ["string", "null"],- "description": "The selected text for the completion,"- }- }- },"SharePermissionV2": {"type": "object","required": ["id", "isPublic", "owner"],@@ -2914,16 +2840,6 @@}}},- "StopChatMessagePayload": {- "type": "object",- "required": ["stream_id"],- "properties": {- "stream_id": {- "type": "string",- "description": "stream id"- }- }- },"StreamError": {"oneOf": [{@@ -2967,32 +2883,6 @@"type": "string"}}- },- {- "type": "object",- "required": ["stream_id", "stream_error"],- "properties": {- "stream_error": {- "type": "string",- "enum": ["unauthorized"]- },- "stream_id": {- "type": "string"- }- }- },- {- "type": "object",- "required": ["stream_id", "stream_error"],- "properties": {- "stream_error": {- "type": "string",- "enum": ["payment_required"]- },- "stream_id": {- "type": "string"- }- }}]},@@ -3039,143 +2929,6 @@}}},- "ToWebSocketMessage": {- "oneOf": [- {- "allOf": [- {- "$ref": "#/components/schemas/SendChatMessagePayload",- "description": "Initializes a new message in a chat for streaming"- },- {- "type": "object",- "required": ["type"],- "properties": {- "type": {- "type": "string",- "enum": ["send_chat_message"]- }- }- }- ],- "description": "Initializes a new message in a chat for streaming"- },- {- "allOf": [- {- "$ref": "#/components/schemas/SendChatMessagePayload",- "description": "Replace user message and restream response"- },- {- "type": "object",- "required": ["type"],- "properties": {- "type": {- "type": "string",- "enum": ["edit_chat_message"]- }- }- }- ],- "description": "Replace user message and restream response"- },- {- "allOf": [- {- "$ref": "#/components/schemas/StopChatMessagePayload",- "description": "Stop streaming for a given message"- },- {- "type": "object",- "required": ["type"],- "properties": {- "type": {- "type": "string",- "enum": ["stop_chat_message"]- }- }- }- ],- "description": "Stop streaming for a given message"- },- {- "allOf": [- {- "$ref": "#/components/schemas/SelectModelPayload",- "description": "Select model for a given chat"- },- {- "type": "object",- "required": ["type"],- "properties": {- "type": {- "type": "string",- "enum": ["select_model_for_chat"]- }- }- }- ],- "description": "Select model for a given chat"- },- {- "allOf": [- {- "$ref": "#/components/schemas/ExtractionStatusPayload",- "description": "Get extraction status for a given attachment"- },- {- "type": "object",- "required": ["type"],- "properties": {- "type": {- "type": "string",- "enum": ["extraction_status"]- }- }- }- ],- "description": "Get extraction status for a given attachment"- },- {- "allOf": [- {- "$ref": "#/components/schemas/SendCompletionPayload",- "description": "pdf completion"- },- {- "type": "object",- "required": ["type"],- "properties": {- "type": {- "type": "string",- "enum": ["send_completion"]- }- }- }- ],- "description": "pdf completion"- },- {- "allOf": [- {- "$ref": "#/components/schemas/GetSimpleCompletionStreamPayload",- "description": "stream a simple completion"- },- {- "type": "object",- "required": ["type"],- "properties": {- "type": {- "type": "string",- "enum": ["get_simple_completion_stream"]- }- }- }- ],- "description": "stream a simple completion"- }- ]- },"ToolSchema": {"type": "object","description": "Schema information for a single tool, serializable for API responses.",@@ -3339,210 +3092,6 @@}}},- "WebSocketError": {- "oneOf": [- {- "allOf": [- {- "$ref": "#/components/schemas/StreamError"- },- {- "type": "object",- "required": ["error_type"],- "properties": {- "error_type": {- "type": "string",- "enum": ["stream_error"]- }- }- }- ]- },- {- "type": "object",- "required": ["chat_id", "message_id", "stream_id", "error_type"],- "properties": {- "chat_id": {- "type": "string"- },- "details": {- "type": ["string", "null"]- },- "error_type": {- "type": "string",- "enum": ["failed_to_send_chat_message"]- },- "message_id": {- "type": "string"- },- "stream_id": {- "type": "string"- }- }- },- {- "type": "object",- "required": ["chat_id", "stream_id", "error_type"],- "properties": {- "chat_id": {- "type": "string"- },- "details": {- "type": ["string", "null"]- },- "error_type": {- "type": "string",- "enum": ["failed_to_rename_chat"]- },- "stream_id": {- "type": "string"- }- }- },- {- "type": "object",- "required": ["error_type"],- "properties": {- "details": {- "type": ["string", "null"]- },- "error_type": {- "type": "string",- "enum": ["failed_to_send_error_message"]- }- }- },- {- "type": "object",- "required": ["chat_id", "stream_id", "error_type"],- "properties": {- "chat_id": {- "type": "string"- },- "details": {- "type": ["string", "null"]- },- "error_type": {- "type": "string",- "enum": ["failed_to_store_chat"]- },- "stream_id": {- "type": "string"- }- }- },- {- "allOf": [- {- "$ref": "#/components/schemas/GenericErrorResponse"- },- {- "type": "object",- "required": ["error_type"],- "properties": {- "error_type": {- "type": "string",- "enum": ["generic"]- }- }- }- ]- },- {- "type": "object",- "required": ["error_type"],- "properties": {- "details": {- "type": ["string", "null"]- },- "error_type": {- "type": "string",- "enum": ["failed_to_send_websocket_message"]- }- }- },- {- "type": "object",- "required": ["error_type"],- "properties": {- "details": {- "type": ["string", "null"]- },- "error_type": {- "type": "string",- "enum": ["failed_to_select_model"]- }- }- },- {- "type": "object",- "required": ["chat_id", "message_id", "stream_id", "error_type"],- "properties": {- "chat_id": {- "type": "string"- },- "details": {- "type": ["string", "null"]- },- "error_type": {- "type": "string",- "enum": ["failed_to_update_token_count"]- },- "message_id": {- "type": "string"- },- "stream_id": {- "type": "string"- }- }- },- {- "type": "object",- "required": ["attachment_id", "error_type"],- "properties": {- "attachment_id": {- "type": "string"- },- "error_type": {- "type": "string",- "enum": ["extraction_status_failed"]- }- }- },- {- "type": "object",- "required": ["attachment_ids", "error_type"],- "properties": {- "attachment_ids": {- "type": "array",- "items": {- "type": "string"- }- },- "error_type": {- "type": "string",- "enum": ["attachment_permission_error"]- }- }- },- {- "type": "object",- "required": ["reason", "stream_id", "error_type"],- "properties": {- "error_type": {- "type": "string",- "enum": ["failed_to_edit_message"]- },- "reason": {- "type": "string"- },- "stream_id": {- "type": "string"- }- }- }- ]- },"WithChatId": {"type": "object","required": ["chat_id"],diff --git a/js/app/packages/service-clients/service-connection/websocket.ts b/js/app/packages/service-clients/service-connection/websocket.tsindex 7d12a5109b..33a6a11686 100644--- a/js/app/packages/service-clients/service-connection/websocket.ts+++ b/js/app/packages/service-clients/service-connection/websocket.ts@@ -57,7 +57,6 @@ export const ws = new WebsocketBuilder(resolveWsUrl).build();export const state = createWebsocketStateSignal(ws);-// TODO: add type mapping on the websocket eventexport function createConnectionBlockWebsocketEffect(callback: (data: FromWebsocketMessage) => voiddiff --git a/rust/cloud-storage/connection_gateway/Cargo.toml b/rust/cloud-storage/connection_gateway/Cargo.tomlindex 84811e670b..8efe53e30e 100644--- a/rust/cloud-storage/connection_gateway/Cargo.toml+++ b/rust/cloud-storage/connection_gateway/Cargo.toml@@ -4,9 +4,6 @@ name = "connection_gateway"publish = falseversion = "0.1.0"-[features]-local_auth = []-[lib]name = "connection_gateway_client"path = "src/lib.rs"diff --git a/rust/cloud-storage/connection_gateway/justfile b/rust/cloud-storage/connection_gateway/justfileindex 1b8b49e6d2..b9b8f9ed4e 100644--- a/rust/cloud-storage/connection_gateway/justfile+++ b/rust/cloud-storage/connection_gateway/justfile@@ -21,7 +21,7 @@ deploy-dev:just ci::deploy-dev connection-gatewayrun *FLAGS: ensure::ensure_dynamodb ensure::ensure_redis- cargo run --bin connection_gateway_service {{ FLAGS }}+ cargo run --bin connection_gateway_service --features macro_middleware/local_auth {{ FLAGS }}run_cleanup:cargo run --bin stale_connectionsdiff --git a/rust/cloud-storage/document_cognition_service/src/api/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/mod.rsindex 06e9bef9b6..13fad30856 100644--- a/rust/cloud-storage/document_cognition_service/src/api/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/mod.rs@@ -23,7 +23,6 @@ mod preview;pub mod stream;pub(crate) mod swagger;pub mod utils;-mod ws;mod attachments;mod chats;@@ -75,7 +74,6 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {fn api_router(api_context: ApiContext) -> Router {let internal_router = Router::new().nest("/chats", chats::router(api_context.clone()))- .nest("/", ws::router(api_context.clone())).nest("/stream", stream::router(api_context.clone())).nest("/internal",diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rsindex f5024d0bf2..3135ba0e68 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs@@ -1,15 +1,13 @@//! HTTP endpoint for sending chat messages with streaming responses.-+use super::util::chat_message::ai_request::build_chat_completion_request;+use super::util::chat_message::toolset::choose_toolset;+use super::util::chat_message::{store_conversation_messages, store_incoming_message};+use super::util::chat_permissions;use crate::api::context::ApiContext;use crate::api::utils::log;-use crate::api::ws::chat_message::ai_request::build_chat_completion_request;-use crate::api::ws::chat_message::toolset::choose_toolset;-use crate::api::ws::chat_message::{store_conversation_messages, store_incoming_message};-use crate::api::ws::chat_permissions;-use crate::api::ws::connection::MESSAGE_ABORT_MAP;use crate::core::constants::DEFAULT_CHAT_NAME;use crate::core::model::FALLBACK_MODEL;-use crate::model::ws::{ChatStream, JwtPayload, SendChatMessagePayload, StreamError, ToolSet};+use crate::model::stream::{ChatStream, JwtPayload, SendChatMessagePayload, StreamError, ToolSet};use crate::service::ai::name::maybe_rename_chat;use crate::service::get_chat::get_chat;use ai::tool::ToolLoop;@@ -343,12 +341,6 @@ fn stream_and_save_message(durable_stream_id: StreamId,is_first_message: bool,) {- // Check for abort before starting- if MESSAGE_ABORT_MAP.contains_key(&stream_id) {- MESSAGE_ABORT_MAP.remove(&stream_id);- return;- }-tracing::trace!(request=?request, "streaming chat request");let tool_context = ToolServiceContext {@@ -399,10 +391,7 @@ fn stream_and_save_message(stream_id: stream_id.clone(),},};- let error_msg = ChatStream::Error(- crate::model::ws::WebSocketError::StreamError(stream_error),- );- if let Ok(json) = serde_json::to_value(&error_msg) {+ if let Ok(json) = serde_json::to_value(&stream_error) {yield json;}return;@@ -420,12 +409,6 @@ fn stream_and_save_message(log::log_timing(log::LatencyMetric::TimeToFirstToken, model, now.elapsed());}- // Check for abort during streaming- if MESSAGE_ABORT_MAP.contains_key(&stream_id) {- MESSAGE_ABORT_MAP.remove(&stream_id);- return;- }-match response {Ok(response_chunk) => {let message_part = match response_chunk {@@ -484,10 +467,7 @@ fn stream_and_save_message(stream_id: stream_id.clone(),},};- let error_msg = ChatStream::Error(- crate::model::ws::WebSocketError::StreamError(stream_error),- );- if let Ok(json) = serde_json::to_value(&error_msg) {+ if let Ok(json) = serde_json::to_value(&stream_error) {yield json;}return;diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/mod.rsindex 8c996eca4b..56be1a50f1 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/mod.rs@@ -5,6 +5,7 @@pub mod chat_message;pub mod simple_completion;+mod util;use axum::{Router, routing::post};use tower::ServiceBuilder;diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/simple_completion.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/simple_completion.rsindex 2c42e7737b..96f8f7904f 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/simple_completion.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/simple_completion.rs@@ -2,7 +2,7 @@use crate::api::context::ApiContext;use crate::core::constants::DEFAULT_MAX_TOKENS;-use crate::model::ws::{ChatStream, GetSimpleCompletionStreamPayload};+use crate::model::stream::{ChatStream, GetSimpleCompletionStreamPayload};use crate::service::attachment::document::get_document_plaintext_content;use ai::chat_stream::get_chat_stream;use ai::types::{ChatStreamCompletionResponse, MessageBuilder, Model, RequestBuilder};diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/ai_request.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rssimilarity index 95%rename from rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/ai_request.rsrename to rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rsindex 75572fb1ef..5536cb46d0 100644--- a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/ai_request.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rs@@ -1,6 +1,6 @@use crate::{api::context::ApiContext, core::constants::DEFAULT_MAX_TOKENS,- model::ws::SendChatMessagePayload, service::attachment::fetch,+ model::stream::SendChatMessagePayload, service::attachment::fetch,};use crate::model::chats::ChatResponse;diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/mod.rsnew file mode 100644index 0000000000..19991821a5--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/mod.rs@@ -0,0 +1,124 @@+pub mod ai_request;+pub mod toolset;++use crate::model::chats::ChatResponse;+use crate::{+ api::{context::ApiContext, utils::search},+ model::stream::SendChatMessagePayload,+};++use macro_db_client::dcs::create_chat_message::create_chat_message;++use ai::types::Model;+use ai::types::Role;+use ai::types::{ChatMessage, ChatMessageContent};+use anyhow::{Context, Result};+use model::chat::{NewAttachment, NewChatMessage};+use std::sync::Arc;++// Stores the incoming user message in the database+#[tracing::instrument(err, skip(ctx, chat, incoming_message), fields(chat_id=?incoming_message.chat_id))]+pub async fn store_incoming_message(+ ctx: Arc<ApiContext>,+ user_id: &str,+ chat: &ChatResponse,+ model: Model,+ incoming_message: &SendChatMessagePayload,+) -> Result<String> {+ let created_at = chrono::Utc::now();+ let new_chat_message = NewChatMessage {+ id: None,+ content: ChatMessageContent::Text(incoming_message.content.clone()),+ role: Role::User,+ // Attach the current chat attachments to the user message+ attachments: incoming_message.attachments.as_ref().map(|attachments| {+ attachments+ .iter()+ .cloned()+ .map(|attachment| NewAttachment {+ attachment_id: attachment.attachment_id,+ attachment_type: attachment.attachment_type,+ })+ .collect()+ }),+ created_at,+ updated_at: created_at,+ model,+ };++ let user_message_id =+ create_chat_message(ctx.db.clone(), &incoming_message.chat_id, new_chat_message)+ .await+ .context("failed to create chat message")?;++ // Send chat message for search processing+ search::send_chat_message_to_search(+ &ctx,+ &chat.id,+ &user_message_id,+ user_id,+ created_at,+ created_at, // updated_at = created_at+ );++ Ok(user_message_id)+}++/// Stores multiple conversation messages to the database.+/// If `first_message_id` is provided, the first assistant message will use that ID.+#[tracing::instrument(err, skip(ctx, messages), fields(chat_id=?chat_id, message_count=messages.len()))]+pub async fn store_conversation_messages(+ ctx: Arc<ApiContext>,+ user_id: &str,+ chat_id: &str,+ messages: Vec<ChatMessage>,+ model: Model,+ first_message_id: Option<String>,+) -> Result<Vec<String>> {+ if messages.is_empty() {+ return Ok(vec![]);+ }++ let mut message_ids = Vec::new();+ let mut first_id_used = false;++ let created_at = chrono::Utc::now();++ for message in messages {+ // Use the pre-generated ID for the first assistant message+ let id = if !first_id_used && message.role == Role::Assistant {+ first_id_used = true;+ first_message_id.clone()+ } else {+ None+ };++ let new_chat_message = model::chat::NewChatMessage {+ id,+ content: message.content,+ role: message.role,+ attachments: None, // New messages from streaming don't have attachments (they are asssistant messages)+ model,+ created_at,+ updated_at: created_at,+ };++ let message_id = create_chat_message(ctx.db.clone(), chat_id, new_chat_message)+ .await+ .context("failed to create chat message")?;++ message_ids.push(message_id.clone());++ // Send each message for search processing+ search::send_chat_message_to_search(+ &ctx,+ chat_id,+ &message_id,+ user_id,+ created_at,+ created_at, // updated_at = created_at+ );+ }++ Ok(message_ids)+}diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/toolset.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/toolset.rssimilarity index 74%rename from rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/toolset.rsrename to rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/toolset.rsindex e6fb8e2e42..6b3fbf1f91 100644--- a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/toolset.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/toolset.rs@@ -1,7 +1,7 @@-use crate::model::ws::ToolSet;+use crate::model::stream::ToolSet;use ai_tools::{ToolSetWithPrompt, all_tools, no_tools};-use crate::model::ws::SendChatMessagePayload;+use crate::model::stream::SendChatMessagePayload;pub fn choose_toolset(request: &SendChatMessagePayload) -> ToolSetWithPrompt {match request.toolset {diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_permissions.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_permissions.rssimilarity index 53%rename from rust/cloud-storage/document_cognition_service/src/api/ws/chat_permissions.rsrename to rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_permissions.rsindex 14d7250473..5ae5009a19 100644--- a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_permissions.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_permissions.rs@@ -1,5 +1,4 @@use crate::api::context::ApiContext;-use crate::model::ws::{StreamError, WebSocketError};use anyhow::Result;use macro_middleware::cloud_storage::ensure_access::get_users_access_level_v2;use model::user::UserContext;@@ -19,25 +18,12 @@ pub async fn chat_access(user_ctx: &UserContext,chat_id: &str,stream_id: String,-) -> Result<AccessLevel, WebSocketError> {+) -> Result<AccessLevel> {get_users_access_level_v2(&ctx.db, &user_ctx.user_id, chat_id, "chat").await- .map_err(|e| {- tracing::error!(- error = ?e,- "Failed to get user access level"- );- WebSocketError::StreamError(StreamError::Unauthorized {- stream_id: stream_id.clone(),- })- })+ .map_err(|e| anyhow::anyhow!(e.1)).and_then(|access| match access {Some(access) => Ok(access),- None => {- tracing::error!("User has no access to chat");- Err(WebSocketError::StreamError(StreamError::Unauthorized {- stream_id,- }))- }+ None => Err(anyhow::anyhow!("No Access")),})}diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/util/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/util/mod.rsnew file mode 100644index 0000000000..71a19392c8--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/util/mod.rs@@ -0,0 +1,3 @@+//! this is the remnents of the WS server and is very messy+pub mod chat_message;+pub mod chat_permissions;diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rsindex 3a75c16997..698d961605 100644--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs@@ -24,7 +24,6 @@ use crate::{self, ChatMessageError, HttpSendChatMessageRequest, SendChatMessageResponse,},stream::simple_completion::{self, SimpleCompletionError, SimpleCompletionResponse},- ws::{self},},model::{request::{@@ -39,10 +38,9 @@ use crate::{chats::{GetChatPermissionsResponseV2, GetChatResponse, GetModelsResponse},models::AIModel,},- ws::{- ChatStream, ExtractionStatusPayload, GetSimpleCompletionStreamPayload,- SelectModelPayload, SendChatMessagePayload, SendCompletionPayload,- StopChatMessagePayload, StreamError, ToWebSocketMessage, ToolSet, WebSocketError,+ stream::{+ ChatStream, GetSimpleCompletionStreamPayload, SendChatMessagePayload, StreamError,+ ToolSet,},},};@@ -80,7 +78,6 @@ use utoipa::OpenApi;paths(health::health_handler,get_chat::get_chat_handler,- ws::connection::ws_handler,create_user_chat::create_chat_handler,copy_chat::copy_chat_handler,get_chat_permissions::get_chat_permissions_handler_v2,@@ -157,15 +154,10 @@ use utoipa::OpenApi;// Share PermissionUpdateOperation,- // WebSocket- ToWebSocketMessage,+ //streamChatStream,SendChatMessagePayload,- StopChatMessagePayload,- WebSocketError,- SelectModelPayload,- ExtractionStatusPayload,- SendCompletionPayload,+ StreamError,// AttachmentsGetChatsForAttachmentResponse,diff --git a/rust/cloud-storage/document_cognition_service/src/api/utils/search.rs b/rust/cloud-storage/document_cognition_service/src/api/utils/search.rsindex c061901e05..38bfa1bff1 100644--- a/rust/cloud-storage/document_cognition_service/src/api/utils/search.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/utils/search.rs@@ -2,7 +2,9 @@ use crate::api::context::ApiContext;use chrono::{DateTime, Utc};use sqs_client::search::SearchQueueMessage;-/// Spawns a tokio task to send a remove chat message to the search text extractor+/// Spawns a tokio task to send a remove chat message from the search text extractor+// used in edit_message which is dead for now+#[allow(dead_code)]pub fn send_remove_chat_message_to_search(ctx: &ApiContext, chat_id: &str, message_id: &str) {let chat_id = chat_id.to_string();let message_id = message_id.to_string();diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/attachment_permissions.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/attachment_permissions.rsdeleted file mode 100644index 7447325976..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/ws/attachment_permissions.rs+++ /dev/null@@ -1,60 +0,0 @@-use crate::api::context::ApiContext;-use crate::model::ws::{GenericErrorResponse, WebSocketError};-use anyhow::Result;-use macro_middleware::cloud_storage::ensure_access::get_users_access_level_v2;-use model::{chat::AttachmentType, user::UserContext};--#[tracing::instrument(skip(ctx, attachments))]-pub async fn ensure_user_attachment_access(- ctx: &ApiContext,- user_ctx: UserContext,- attachments: Vec<(String, Option<AttachmentType>)>,-) -> Result<(), WebSocketError> {- let permissions = attachments- .into_iter()- .map(|(attachment_id, attachment_type)| {- let ctx = &ctx;- let user_ctx = &user_ctx;- async move {- get_users_access_level_v2(- &ctx.db,- &user_ctx.user_id,- attachment_id.as_str(),- &attachment_type- .map(|kind| {- // balls ass decision to make images their own attachment type- if kind == AttachmentType::Image {- AttachmentType::Document- } else {- kind- }- })- .unwrap_or(AttachmentType::Document)- .to_string(),- )- .await- .map_err(|e| {- tracing::error!(- error = ?e,- user_id = %user_ctx.user_id,- attachment_id = %attachment_id,- "Failed to check attachment access level"- );- WebSocketError::Generic(GenericErrorResponse { message: e.1 })- })- .and_then(|permissions| {- if permissions.is_none() {- tracing::warn!(user_id=?user_ctx.user_id, attachment_id=?attachment_id, "no permission to access attachment");- Err(WebSocketError::Generic(GenericErrorResponse {- message: "No Permission".into(),- }))- } else {- Ok(permissions)- }- })- }- });-- let _ = futures::future::try_join_all(permissions).await?;- Ok(())-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rsdeleted file mode 100644index bcbd128f7e..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs+++ /dev/null@@ -1,416 +0,0 @@-pub mod ai_request;-pub mod toolset;--use crate::api::ws::connection::{MESSAGE_ABORT_MAP, ws_send};-use crate::core::model::FALLBACK_MODEL;-use crate::model::chats::ChatResponse;-use crate::model::ws::{StreamError, StreamWebSocketError};-use crate::{- api::{- context::ApiContext,- utils::{log, search},- },- model::ws::{ChatStream, SendChatMessagePayload},- service::{ai::name::maybe_rename_chat, get_chat::get_chat},-};--use macro_db_client::dcs::create_chat_message::create_chat_message;--use ai::tool::ToolLoop;-use ai::tool::types::StreamPart;-use ai::types::Role;-use ai::types::{AssistantMessagePart, ChatCompletionRequest, Model};-use ai::types::{ChatMessage, ChatMessageContent};-use ai_request::build_chat_completion_request;-use ai_tools::{AiToolSet, RequestContext, ToolServiceContext};-use anyhow::{Context, Result};-use futures::stream::StreamExt;-use macro_user_id::user_id::MacroUserIdStr;-use model::chat::{NewAttachment, NewChatMessage};-use std::sync::Arc;-use tokio;-use tokio::sync::mpsc::UnboundedSender;--// Stores the incoming user message in the database-#[tracing::instrument(err, skip(ctx, chat, incoming_message), fields(chat_id=?incoming_message.chat_id))]-pub async fn store_incoming_message(- ctx: Arc<ApiContext>,- user_id: &str,- chat: &ChatResponse,- model: Model,- incoming_message: &SendChatMessagePayload,-) -> Result<String> {- let created_at = chrono::Utc::now();- let new_chat_message = NewChatMessage {- id: None,- content: ChatMessageContent::Text(incoming_message.content.clone()),- role: Role::User,- // Attach the current chat attachments to the user message- attachments: incoming_message.attachments.as_ref().map(|attachments| {- attachments- .iter()- .cloned()- .map(|attachment| NewAttachment {- attachment_id: attachment.attachment_id,- attachment_type: attachment.attachment_type,- })- .collect()- }),- created_at,- updated_at: created_at,- model,- };-- let user_message_id =- create_chat_message(ctx.db.clone(), &incoming_message.chat_id, new_chat_message)- .await- .context("failed to create chat message")?;-- // Send chat message for search processing- search::send_chat_message_to_search(- &ctx,- &chat.id,- &user_message_id,- user_id,- created_at,- created_at, // updated_at = created_at- );-- Ok(user_message_id)-}--pub struct StreamChatResponse {- pub new_messages: Vec<ChatMessage>,-}--#[tracing::instrument(err, skip(context, user_id, request, sender, jwt_token, toolset), fields(chat_id=?chat_id, message_id=?message_id))]-#[expect(clippy::too_many_arguments, reason = "too annoying to fix")]-// Handles streaming the response from the provider back to the-// client over the websocket connection. Returns the response string-pub async fn stream_chat_response(- context: Arc<ApiContext>,- user_id: Arc<MacroUserIdStr<'static>>,- request: ChatCompletionRequest,- toolset: AiToolSet,- sender: &UnboundedSender<ChatStream>,- chat_id: &str,- message_id: &str,- connection_id: &str,- stream_id: &str,- jwt_token: &str,-) -> Result<StreamChatResponse, ai::types::AiError> {- if MESSAGE_ABORT_MAP.contains_key(stream_id) {- MESSAGE_ABORT_MAP.remove(stream_id);- return Ok(StreamChatResponse {- new_messages: Vec::new(), // Return empty for aborted streams- });- }- tracing::trace!(request=?request, "streaming chat request");- let model = request.model();-- let tool_context = ToolServiceContext {- email_service_client: context.email_service_client_external.clone(),- search_service_client: context.search_service_client.clone(),- scribe: context.scribe.clone(),- soup_service: context.soup_service.clone(),- };-- #[expect(deprecated)]- let request_context = RequestContext {- user_id: user_id.clone(),- jwt: Arc::new(jwt_token.to_string()),- };-- let client = ToolLoop::new(toolset, tool_context);- let mut chat = client.chat();- let now = std::time::Instant::now();- let mut stream = chat- .send_message(request, request_context, user_id.as_ref().to_string())- .await?;-- // Process the stream completely- let mut is_first_token = false;- while let Some(response) = stream.next().await {- tracing::trace!("{:#?}", response);- if !is_first_token {- is_first_token = true;- log::log_timing(log::LatencyMetric::TimeToFirstToken, model, now.elapsed());- }- let response_chunk = response?;- // Abort streaming for a message if it has been stopped- if MESSAGE_ABORT_MAP.contains_key(stream_id) {- MESSAGE_ABORT_MAP.remove(stream_id);- return Ok(StreamChatResponse {- new_messages: Vec::new(), // Return empty for aborted streams- });- }-- // We need this in the near future- match response_chunk {- StreamPart::Content(content) => {- if content.is_empty() {- continue;- }-- let message_part = AssistantMessagePart::Text { text: content };-- // Send to websocket- let response = ChatStream::ChatMessageResponse {- stream_id: stream_id.to_string(),- chat_id: chat_id.to_string(),- message_id: message_id.to_string(),- content: message_part,- };- ws_send(sender, response)?;- }- StreamPart::ToolCall(call) => {- let message_part = AssistantMessagePart::ToolCall {- name: call.name,- json: call.json,- id: call.id,- };-- let response = ChatStream::ChatMessageResponse {- stream_id: stream_id.to_string(),- chat_id: chat_id.to_string(),- message_id: message_id.to_string(),- content: message_part,- };- ws_send(sender, response)?;- }- StreamPart::Usage(usage) => {- tracing::debug!(record=?usage, "usage");- }- StreamPart::ToolResponse(ai::tool::types::ToolResponse::Json { id, json, name }) => {- let message_part = AssistantMessagePart::ToolCallResponseJson { name, json, id };-- ws_send(- sender,- ChatStream::ChatMessageResponse {- stream_id: stream_id.to_string(),- message_id: message_id.to_string(),- chat_id: chat_id.to_string(),- content: message_part,- },- )?;- }- StreamPart::ToolResponse(ai::tool::types::ToolResponse::Err {- id,- name,- description,- }) => {- let message_part = AssistantMessagePart::ToolCallErr {- name,- description,- id,- };-- ws_send(- sender,- ChatStream::ChatMessageResponse {- stream_id: stream_id.to_string(),- message_id: message_id.to_string(),- chat_id: chat_id.to_string(),- content: message_part,- },- )?;- }- }- }-- // Explicitly drop the stream to release the mutable borrow- drop(stream);-- // Get new messages - no finalization needed since we only save on disconnect- let new_messages = chat.get_new_conversation_messages();-- Ok(StreamChatResponse { new_messages })-}--/// Stores multiple conversation messages to the database.-/// If `first_message_id` is provided, the first assistant message will use that ID.-#[tracing::instrument(err, skip(ctx, messages), fields(chat_id=?chat_id, message_count=messages.len()))]-pub async fn store_conversation_messages(- ctx: Arc<ApiContext>,- user_id: &str,- chat_id: &str,- messages: Vec<ChatMessage>,- model: Model,- first_message_id: Option<String>,-) -> Result<Vec<String>> {- if messages.is_empty() {- return Ok(vec![]);- }-- let mut message_ids = Vec::new();- let mut first_id_used = false;-- let created_at = chrono::Utc::now();-- for message in messages {- // Use the pre-generated ID for the first assistant message- let id = if !first_id_used && message.role == Role::Assistant {- first_id_used = true;- first_message_id.clone()- } else {- None- };-- let new_chat_message = model::chat::NewChatMessage {- id,- content: message.content,- role: message.role,- attachments: None, // New messages from streaming don't have attachments (they are asssistant messages)- model,- created_at,- updated_at: created_at,- };-- let message_id = create_chat_message(ctx.db.clone(), chat_id, new_chat_message)- .await- .context("failed to create chat message")?;-- message_ids.push(message_id.clone());-- // Send each message for search processing- search::send_chat_message_to_search(- &ctx,- chat_id,- &message_id,- user_id,- created_at,- created_at, // updated_at = created_at- );- }-- Ok(message_ids)-}--/// Handles incoming messages of type `send_message`-#[tracing::instrument(skip(ctx, sender, incoming_message, jwt_token, user_id), fields(chat_id=?incoming_message.chat_id, stream_id=?incoming_message.stream_id))]-pub async fn handle_send_chat_message(- sender: &UnboundedSender<ChatStream>,- ctx: Arc<ApiContext>,- message_id: String,- incoming_message: SendChatMessagePayload,- user_id: Arc<MacroUserIdStr<'static>>,- connection_id: &str,- jwt_token: &str,-) -> Result<(), StreamWebSocketError> {- let now = std::time::Instant::now();- let chat = get_chat(&ctx, &incoming_message.chat_id, user_id.0.as_ref())- .await- .map_err(|err| {- tracing::error!(error=?err, "failed to get chat");- StreamError::InternalError {- stream_id: incoming_message.stream_id.clone(),- }- })?;- let is_first_message = chat.messages.is_empty();- let model = if incoming_message.model == Model::Claude46Opus {- Model::Claude46Opus- } else {- FALLBACK_MODEL- };-- let _user_message_id = store_incoming_message(- ctx.clone(),- user_id.0.as_ref(),- &chat,- model,- &incoming_message,- )- .await- .map_err(|err| {- tracing::error!(error=?err, "failed to store incoming message");- StreamError::InternalError {- stream_id: incoming_message.stream_id.clone(),- }- })?;-- let toolset = toolset::choose_toolset(&incoming_message);- let request = build_chat_completion_request(- ctx.clone(),- &chat,- &incoming_message,- toolset.prompt,- jwt_token,- )- .await- .map_err(|err| {- tracing::error!(error=?err, "failed to build chat completion request");- StreamError::InternalError {- stream_id: incoming_message.stream_id.clone(),- }- })?;-- log::log_timing(log::LatencyMetric::TimeToSendRequest, model, now.elapsed());- let StreamChatResponse { new_messages } = stream_chat_response(- ctx.clone(),- user_id.clone(),- request,- toolset.toolset,- sender,- incoming_message.chat_id.as_str(),- message_id.as_str(),- connection_id,- incoming_message.stream_id.as_str(),- jwt_token,- )- .await- .map_err(|err| {- tracing::error!(error=?err, "failed to stream chat response");- match err {- ai::types::AiError::ContextWindowExceeded => StreamError::ModelContextOverflow {- stream_id: incoming_message.stream_id.clone(),- },- ai::types::AiError::Generic(_) => StreamError::InternalError {- stream_id: incoming_message.stream_id.clone(),- },- }- })?;-- ws_send(- sender,- ChatStream::StreamEnd {- stream_id: incoming_message.stream_id.clone(),- },- )- .map_err(|_| StreamError::InternalError {- stream_id: incoming_message.stream_id.clone(),- })?;-- store_conversation_messages(- ctx.clone(),- user_id.0.as_ref(),- &incoming_message.chat_id,- new_messages,- model,- None,- )- .await- .map_err(|err| {- tracing::error!(error=?err, "failed to store conversation messages");- StreamError::InternalError {- stream_id: incoming_message.stream_id.clone(),- }- })?;-- // The chat is empty and we want to auto generate a name for the chat- if is_first_message- && let Ok(new_name) = maybe_rename_chat(&incoming_message.chat_id, &ctx, user_id.0.as_ref())- .await- .inspect_err(|err| tracing::error!(error=?err, "failed to rename chat"))- {- ws_send(- sender,- ChatStream::ChatRenamed {- chat_id: incoming_message.chat_id.clone(),- stream_id: incoming_message.stream_id.clone(),- name: new_name,- },- )- .ok();- }- Ok(())-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rsdeleted file mode 100644index 8e0eb4e15c..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs+++ /dev/null@@ -1,223 +0,0 @@-/* This is misnamed - this is a pdf completion only for the "generalized popup" */-use aho_corasick::AhoCorasick;-use anyhow::{Context, Result};-use model::document::FileType;-use regex::Regex;-use std::{str::FromStr, sync::Arc};-use tracing::instrument;-use uuid::Uuid;--use ai::{- chat_stream::get_chat_stream,- types::{ChatCompletionRequest, ChatMessage, ChatStreamCompletionResponse},-};-use tokio::sync::mpsc::UnboundedSender;--use futures::stream::StreamExt;--use crate::{- api::context::ApiContext,- core::constants::DEFAULT_MAX_TOKENS,- core::model::{COMPLETION_CONTEXT_WINDOW, COMPLETION_MODEL},- model::ws::{ChatStream, SendCompletionPayload, WebSocketError},- service::attachment::document::get_document_plaintext_content,-};--use macro_db_client::dcs::{- get_document::get_document, get_document_text::get_pdf_docx_document_text,-};--use ai_format::document::Document;--use super::connection::ws_send;--pub fn normalize_text(text: &str) -> String {- Regex::new(r"\[\[.*?\]\]")- .map_or_else(- |_| text.to_string(),- |pattern| pattern.replace_all(text, "").to_string(),- )- .split_whitespace()- .collect::<Vec<_>>()- .join(" ")- .to_lowercase()- .replace("\n", " ")- .replace("\t", " ")- .replace("\r", " ")-}--#[tracing::instrument(err, skip(document))]-fn find_text_context(document: &str, selected_text: &str) -> Result<Option<String>> {- let normalized_content = normalize_text(document);- let normalized_pattern = normalize_text(selected_text);-- let ac = AhoCorasick::builder()- .ascii_case_insensitive(true)- .match_kind(aho_corasick::MatchKind::Standard)- .build(vec![&normalized_pattern])?;-- Ok(ac.find_iter(&normalized_content).next().map(|m| {- // UTF-8 encoded special characters (like the minus sign '−') can span multiple bytes- let bytes = normalized_content.as_bytes();- let start = (m.start() as i32 - (COMPLETION_CONTEXT_WINDOW / 2)).max(0) as usize;- let end = (m.end() + (COMPLETION_CONTEXT_WINDOW / 2) as usize).min(bytes.len());-- String::from_utf8_lossy(&bytes[start..end]).into_owned()- }))-}--#[tracing::instrument(err, skip(ctx, payload))]-async fn build_completion_request(- ctx: Arc<ApiContext>,- payload: &SendCompletionPayload,-) -> Result<ChatCompletionRequest> {- let mut prompt_attachments = vec![];-- if let (Some(attachment_id), Some(selected_text)) = (- payload.attachment_id.as_ref(),- payload.selected_text.as_ref(),- ) {- let document = get_document(&ctx.db, attachment_id)- .await- .context("failed to get document")?;-- match document {- Some(document) => {- let file_type = FileType::from_str(&document.file_type);-- match file_type {- Err(_) => {- tracing::warn!(document_id=%attachment_id, "document type is missing");- }- Ok(f @ FileType::Pdf) | Ok(f @ FileType::Docx) => {- let document_text =- get_pdf_docx_document_text(ctx.db.clone(), attachment_id).await?;- if let Some(context) =- find_text_context(&document_text.content, selected_text)?- {- prompt_attachments.push(- Document {- id: attachment_id.to_string(),- file_type: f.as_str().to_string(),- name: document.name,- content: context,- properties: None,- }- .boxed(),- );- } else {- tracing::warn!(- document_id=%attachment_id,- selected_text = selected_text,- "could not find matches for completion"- );- }- }- Ok(file_type) => {- let content = get_document_plaintext_content(&ctx, attachment_id)- .await?- .text_content()?;- if content.chars().filter(|c| !c.is_whitespace()).count() == 0 {- tracing::warn!(- document_id=%attachment_id,- "document content is empty"- );- } else {- prompt_attachments.push(- Document {- id: attachment_id.to_string(),- file_type: file_type.as_str().to_string(),- name: document.name,- content,- properties: None,- }- .boxed(),- );- }- }- }- }- None => {- tracing::warn!(document_id=%attachment_id, "document does not exist");- }- }- }-- let messages: Vec<ChatMessage> = vec![ChatMessage {- role: ai::types::Role::User,- content: ai::types::ChatMessageContent::Text(payload.prompt.clone()),- image_urls: None,- }];- let request = ai::types::RequestBuilder::new()- .system_prompt(ai_tools::prompts::BASE_PROMPT)- .attachments(prompt_attachments)- .messages(messages)- .max_tokens(DEFAULT_MAX_TOKENS)- .model(COMPLETION_MODEL)- .build();-- Ok(request)-}--#[instrument(skip(sender), err)]-async fn stream_completion(- request: ChatCompletionRequest,- sender: &UnboundedSender<ChatStream>,- completion_id: &str,- user_id: &str,-) -> Result<()> {- tracing::debug!("stream_completion get chat stream {:#?}", request);- let mut stream = get_chat_stream(request)- .await- .context("failed to get chat stream")?;- let mut response_message = String::new();- while let Some(response) = stream.next().await {- let parts = response.context("failed to get response message")?;- for part in parts {- let ChatStreamCompletionResponse::Content(content) = part;- response_message.push_str(&content.content);-- let response = ChatStream::CompletionResponse {- completion_id: completion_id.to_string(),- content: response_message.clone(),- done: false,- };-- ws_send(sender, response)?;- }- }-- ws_send(- sender,- ChatStream::CompletionResponse {- completion_id: completion_id.to_string(),- content: response_message,- done: true,- },- )?;-- Ok(())-}--#[tracing::instrument(skip_all, fields(user_id, completion_id=?payload.completion_id), err)]-pub async fn send_completion_handler(- ctx: Arc<ApiContext>,- sender: &UnboundedSender<ChatStream>,- payload: &SendCompletionPayload,- user_id: &str,-) -> Result<(), WebSocketError> {- let completion_id = payload- .completion_id- .clone()- .unwrap_or_else(|| Uuid::new_v4().to_string());- tracing::debug!("build completion request for send_completion_handler");- let request = build_completion_request(ctx.clone(), payload)- .await- .context("build completion request")?;-- stream_completion(request, sender, &completion_id, user_id)- .await- .context("failed to stream completion")?;-- Ok(())-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rsdeleted file mode 100644index eb26776110..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs+++ /dev/null@@ -1,499 +0,0 @@-use super::chat_permissions;-use ai::types::AiError;-use anyhow::Result;-use axum::extract::State;-use axum::{- extract::{- Extension,- ws::{Message, WebSocket, WebSocketUpgrade},- },- response::IntoResponse,-};-use dashmap::DashMap;-use macro_user_id::user_id::{MacroUserId, MacroUserIdStr};-use model::{chat::AttachmentType, user::UserContext};-use models_permissions::share_permission::access_level::AccessLevel;-use std::sync::Arc;-use std::sync::LazyLock;-use tokio::sync::mpsc::{self, UnboundedSender, WeakUnboundedSender};-use tokio_util::sync::CancellationToken;-use uuid::Uuid;--use crate::{- api::{- context::ApiContext,- ws::{- chat_message::handle_send_chat_message, completion::send_completion_handler,- edit_message::handle_edit_last_user_message,- extraction_status::extraction_status_handler, select_model::select_model_handler,- simple_completion::handle_simple_completion,- },- },- model::ws::{ChatStream, StreamError, ToWebSocketMessage, WebSocketError},-};--use super::attachment_permissions::ensure_user_attachment_access;--use futures::{sink::SinkExt, stream::StreamExt};--/// Maps a stream id to a boolean indicating if the message should be aborted-pub static MESSAGE_ABORT_MAP: LazyLock<DashMap<String, bool>> =- std::sync::LazyLock::new(DashMap::new);--/// Maps a connection id to a websocket sender-pub static CONNECTION_MAP: LazyLock<DashMap<String, WeakUnboundedSender<ChatStream>>> =- std::sync::LazyLock::new(DashMap::new);--#[utoipa::path(- get,- path = "/stream",- responses(- (status = 200, description="Sucessfully conntect to streaming websocket"),- (status = 500, body=String, description="Failed to connect to streaming websocket"),- )- )]-#[tracing::instrument(skip(ws, state, user_context))]-pub async fn ws_handler(- ws: WebSocketUpgrade,- State(state): State<ApiContext>,- user_context: Extension<UserContext>,-) -> impl IntoResponse {- ws.on_upgrade(move |socket| handle_websocket_connection(socket, state, user_context.0))-}--/// Determines if the incoming message is processable-/// [Err(err)] means there was something wrong with the message... ie not supported-/// [Ok(None)] means the message was ok, but there is nothing for us to process-#[tracing::instrument()]-async fn process_incoming_message(- msg: &Message,- message_sender: &UnboundedSender<ChatStream>,-) -> Result<Option<ToWebSocketMessage>> {- // Need to make sure we properly handle Control Frames like Close, Ping, Pong- match msg {- // Supported will continue to be handled if properly formatted- Message::Text(text) => {- // Handle heartbeat ping messages- if text == "ping" {- ws_send(message_sender, ChatStream::Pong)?;- return Ok(None);- }-- // Existing JSON parsing code...- match msg.to_owned().try_into() {- Ok(msg) => Ok(Some(msg)),- Err(err) => {- tracing::error!(error = %err, "failed to parse websocket message");- Ok(None)- }- }- }- // Unsupported message type- Message::Binary(_) => {- tracing::error!("unsupported binary websocket message");- Ok(None)- }- // Should break the loop if the connection is closed- Message::Close(_) => Ok(None),- // [Message::Ping] and [Message::Pong] are automatically handled by axum- _ => Ok(None),- }-}--#[tracing::instrument(skip(socket, ctx, user_context), fields(user_id=?user_context.user_id))]-async fn handle_websocket_connection(- socket: WebSocket,- ctx: ApiContext,- user_context: UserContext,-) {- tracing::info!(abort_map_size=?MESSAGE_ABORT_MAP.len(), connection_map_size=?CONNECTION_MAP.len(), "new connection");- let connection_id = Uuid::new_v4().to_string();-- // ws_sender handles sending messages over the websocket- // ws_receiver handles receiving messages over the websocket- let (mut ws_sender, mut ws_receiver) = socket.split();-- // message_sender handles sending messages between threads which are forwarded to the websocket- // message_receiver handles receiving messages between threads which are forwarded to the websocket- let (message_sender, mut message_receiver) = mpsc::unbounded_channel::<ChatStream>();-- // store a WeakUnboundedSender in the map- // this ensures that the sender is not kept alive by the map- (*CONNECTION_MAP).insert(connection_id.clone(), message_sender.clone().downgrade());-- let ctx = Arc::new(ctx);- // Ability to cancel the receiver task from any subtask- let receiver_cancel_token = CancellationToken::new();- let cancel_token = receiver_cancel_token.clone();- let connection_id_clone = connection_id.clone();-- // the sender task listens on messages to the message_receiver, and then- // forwards them over the ws_sender- let mut sender_task = tokio::spawn(async move {- while let Some(message) = message_receiver.recv().await {- if let Err(err) = ws_sender.send(message.clone().into()).await {- tracing::error!(message=?message, error=%err, "failed to send websocket message");- }- }- });-- let mut receiver_task = tokio::spawn(async move {- let cancel_token = cancel_token.clone();-- while let Some(Ok(msg)) = ws_receiver.next().await {- tracing::debug!("message recieved");- // kill the task if the connection is closed- if cancel_token.is_cancelled() {- continue;- }-- let incoming_message = match process_incoming_message(&msg, &message_sender).await {- Ok(Some(msg)) => msg,- Ok(None) => continue,- Err(err) => {- tracing::error!(error = %err, "failed to process incoming websocket message");- continue;- }- };- tracing::debug!("{:#?}", incoming_message);-- let span =- tracing::span!(tracing::Level::TRACE, "websocket message received", message=?msg);- let _span_gaurd = span.enter();-- let message_id = Uuid::new_v4().to_string();- let ctx_clone = ctx.clone();- let user_context_clone = user_context.clone();- let message_sender_clone = message_sender.clone();- let connection_id = connection_id.clone();-- let attachments: Vec<(String, Option<AttachmentType>)> = match incoming_message {- ToWebSocketMessage::ExtractionStatus(ref extract) => {- vec![(extract.attachment_id.clone(), None)]- }- ToWebSocketMessage::GetSimpleCompletionStream(ref stream) => {- let attachments = stream- .content_document_ids- .clone()- .unwrap_or_else(std::vec::Vec::new)- .clone();- attachments- .iter()- .map(|attachment| (attachment.clone(), None))- .collect()- }- ToWebSocketMessage::SendCompletion(ref completion) => completion- .attachment_id- .clone()- .map(|id| vec![(id, None)])- .unwrap_or_else(std::vec::Vec::new),- _ => vec![],- };-- if let Err(err) =- ensure_user_attachment_access(&ctx, user_context.clone(), attachments).await- {- ws_send(&message_sender_clone, ChatStream::Error(err)).ok();- continue;- }-- match incoming_message {- ToWebSocketMessage::SendChatMessage(payload) => {- if let Err(e) = check_user_quota(&ctx, &user_context).await {- match e {- UserQuotaError::InvalidMacroUserId- | UserQuotaError::UnableToGetUserPermissions- | UserQuotaError::UnableToGetUserQuota => ws_send(- &message_sender_clone,- ChatStream::Error(WebSocketError::StreamError(- StreamError::InternalError {- stream_id: payload.stream_id,- },- )),- ),- UserQuotaError::ExceededMaxChatMessages => ws_send(- &message_sender_clone,- ChatStream::Error(WebSocketError::StreamError(- StreamError::PaymentRequired {- stream_id: payload.stream_id,- },- )),- ),- }- .ok();- continue;- }-- let user_id = match MacroUserIdStr::try_from(user_context_clone.user_id.clone())- {- Ok(id) => Arc::new(id),- Err(_) => {- ws_send(- &message_sender_clone,- ChatStream::Error(WebSocketError::StreamError(- StreamError::InternalError {- stream_id: payload.stream_id.clone(),- },- )),- )- .ok();- continue;- }- };- let jwt_token = payload.jwt.token.clone();- let cancel_token = cancel_token.clone();- tracing::debug!(user_id=?user_id.as_ref(), chat_id=?payload.chat_id, "handling chat message");- let ctx = ctx.clone();- match chat_permissions::chat_access(- &ctx,- &user_context,- &payload.chat_id,- payload.stream_id.clone(),- )- .await- {- Err(e) => {- ws_send(&message_sender_clone, ChatStream::Error(e)).ok();- continue;- }- Ok(access) => match access {- AccessLevel::View | AccessLevel::Comment => {- ws_send(- &message_sender_clone,- ChatStream::Error(WebSocketError::StreamError(- StreamError::Unauthorized {- stream_id: payload.stream_id,- },- )),- )- .ok();- continue;- }- _ => (),- },- };-- tokio::spawn(async move {- tokio::select! {- _ = cancel_token.cancelled() => {},- result = Box::pin(handle_send_chat_message(- &message_sender_clone,- ctx,- message_id,- payload,- user_id,- &connection_id,- &jwt_token- )) => {- if let Err(err) = result {- ws_send(&message_sender_clone, ChatStream::Error(err.into())).ok();- }- }- }- });- }- ToWebSocketMessage::EditChatMessage(payload) => {- let user_id = match MacroUserIdStr::try_from(user_context_clone.user_id.clone())- {- Ok(id) => Arc::new(id),- Err(_) => {- ws_send(- &message_sender_clone,- ChatStream::Error(WebSocketError::StreamError(- StreamError::InternalError {- stream_id: payload.stream_id.clone(),- },- )),- )- .ok();- continue;- }- };- let jwt_token = payload.jwt.token.clone();- tracing::debug!(user_id=?user_id.as_ref(), chat_id=?payload.chat_id, "handling edit message");- let ctx = ctx.clone();-- match chat_permissions::chat_access(- &ctx,- &user_context,- &payload.chat_id,- payload.stream_id.clone(),- )- .await- {- Err(e) => {- ws_send(&message_sender_clone, ChatStream::Error(e)).ok();- continue;- }- Ok(access) => match access {- AccessLevel::View | AccessLevel::Comment => {- ws_send(- &message_sender_clone,- ChatStream::Error(WebSocketError::StreamError(- StreamError::Unauthorized {- stream_id: payload.stream_id,- },- )),- )- .ok();- continue;- }- _ => (),- },- };- tokio::spawn(async move {- if let Err(err) = handle_edit_last_user_message(- ctx,- &message_sender_clone,- payload,- user_id,- &connection_id,- &jwt_token,- )- .await- {- ws_send(&message_sender_clone, ChatStream::Error(err.into())).ok();- }- });- }- ToWebSocketMessage::StopChatMessage(payload) => {- // Insert the stream id into the abort map- MESSAGE_ABORT_MAP.insert(payload.stream_id.clone(), true);- }- ToWebSocketMessage::SelectModelForChat(payload) => {- if let Err(err) =- select_model_handler(&ctx_clone.db, payload)- .await- .map_err(|err| WebSocketError::FailedToSelectModel {- details: Some(err.to_string()),- })- {- ws_send(&message_sender_clone, ChatStream::Error(err)).ok();- }- }- ToWebSocketMessage::ExtractionStatus(payload) => {- let attachment_id = payload.attachment_id.clone();- if let Err(err) = extraction_status_handler(- &message_sender_clone,- ctx_clone,- &connection_id,- payload,- )- .await- .map_err(|_err| WebSocketError::ExtractionStatusFailed { attachment_id })- {- ws_send(&message_sender_clone, ChatStream::Error(err)).ok();- }- }- ToWebSocketMessage::SendCompletion(payload) => {- let user_id = &user_context_clone.user_id;- if let Err(err) = send_completion_handler(- ctx.clone(),- &message_sender_clone,- &payload,- user_id,- )- .await- {- ws_send(&message_sender_clone, ChatStream::Error(err)).ok();- }- }- ToWebSocketMessage::GetSimpleCompletionStream(payload) => {- let user_id = &user_context_clone.user_id;- if let Err(err) = handle_simple_completion(- ctx_clone.clone(),- &message_sender_clone,- &payload,- user_id,- )- .await- {- ws_send(&message_sender_clone, ChatStream::Error(err)).ok();- }- }- };- }- });-- let connection_id = connection_id_clone.clone();-- // If either task finishes, abort the other task- tokio::select! {- _ = (&mut sender_task) => {- receiver_task.abort();- tracing::trace!("sender task aborted");- receiver_cancel_token.cancel();- },- _ = (&mut receiver_task) => {- sender_task.abort();- tracing::trace!("receiver task aborted");- receiver_cancel_token.cancel();- },-- };- CONNECTION_MAP.remove(&connection_id);-}--/// Error returned when failing to send a websocket message-#[derive(Debug, thiserror::Error)]-#[error("failed to send websocket message: channel closed")]-pub struct WsSendError;--impl From<WsSendError> for AiError {- fn from(err: WsSendError) -> Self {- AiError::Generic(err.into())- }-}--/// Sends a message over the websocket channel-#[tracing::instrument(skip(sender), err)]-pub fn ws_send(- sender: &UnboundedSender<ChatStream>,- message: ChatStream,-) -> Result<(), WsSendError> {- sender.send(message).map_err(|_| WsSendError)-}--/// Errors that can occur when checking the user quota-#[derive(Debug, thiserror::Error)]-enum UserQuotaError {- #[error("invalid macro user id")]- InvalidMacroUserId,- #[error("failed to get user permissions")]- UnableToGetUserPermissions,- #[error("failed to get user quota")]- UnableToGetUserQuota,- #[error("exceeded max chat messages")]- ExceededMaxChatMessages,-}--/// Checks if the user has paid features and if they have not exceeded their max chat messages-#[tracing::instrument(skip(ctx, user_context), ret, err, fields(user_id=?user_context.user_id))]-async fn check_user_quota(- ctx: &ApiContext,- user_context: &UserContext,-) -> Result<(), UserQuotaError> {- let is_paid_user = if let Some(permissions) = user_context.permissions.as_ref() {- permissions.contains("read:professional_features")- } else {- return Err(UserQuotaError::UnableToGetUserPermissions);- };-- if is_paid_user {- return Ok(());- }-- let user_id = MacroUserId::parse_from_str(&user_context.user_id)- .map(|u| u.lowercase())- .map_err(|_| UserQuotaError::InvalidMacroUserId)?;-- let user_quota = macro_db_client::user_quota::get_user_quota(&ctx.db, &user_id)- .await- .map_err(|_| UserQuotaError::UnableToGetUserQuota)?;-- if user_quota.ai_chat_messages + 1 > user_quota.max_ai_chat_messages.into() {- Err(UserQuotaError::ExceededMaxChatMessages)- } else {- Ok(())- }-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/edit_message.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/edit_message.rsdeleted file mode 100644index ba424003ed..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/ws/edit_message.rs+++ /dev/null@@ -1,150 +0,0 @@-use crate::{- api::{context::ApiContext, utils::search},- model::ws::{ChatStream, SendChatMessagePayload, StreamWebSocketError},- service::get_chat::get_chat,-};--use macro_db_client::dcs::delete_chat_message::delete_chat_message;-use macro_user_id::user_id::MacroUserIdStr;--use super::chat_message::handle_send_chat_message;-use super::connection::ws_send;-use ai::types::Role;-use anyhow::Result;-use std::sync::Arc;-use tokio;-use tokio::sync::mpsc::UnboundedSender;--#[tracing::instrument(skip(ctx, sender, jwt_token, incoming_message, user_id))]-pub async fn handle_edit_last_user_message(- ctx: Arc<ApiContext>,- sender: &UnboundedSender<ChatStream>,- incoming_message: SendChatMessagePayload,- user_id: Arc<MacroUserIdStr<'static>>,- connection_id: &str,- jwt_token: &str,-) -> Result<(), StreamWebSocketError> {- let chat = get_chat(&ctx, &incoming_message.chat_id, user_id.0.as_ref())- .await- .map_err(|err| {- tracing::error!(- chat_id = %incoming_message.chat_id,- user_id = %user_id,- error = %err,- "failed to get chat"- );- StreamWebSocketError::FailedToEditMessage {- reason: "internal error".to_string(),- stream_id: incoming_message.stream_id.clone(),- }- })?;- let message_id = macro_uuid::generate_uuid_v7().to_string();-- let edited_message = chat- .messages- .iter()- .rev()- .take(2)- .find(|message| message.role == Role::User);-- // check that message is valid- // currently only the last user message can be edited- if edited_message.is_none() {- return Err(StreamWebSocketError::FailedToEditMessage {- reason: "Message could not be found or is not supported".to_string(),- stream_id: incoming_message.stream_id.clone(),- });- }-- ws_send(- sender,- ChatStream::ChatMessageAck {- message_id: message_id.clone(),- chat_id: incoming_message.chat_id.clone(),- },- )- .map_err(|_| StreamWebSocketError::FailedToEditMessage {- reason: "failed to send message".to_string(),- stream_id: incoming_message.stream_id.clone(),- })?;-- // delete last messages and message after if it exists- let mut last = chat.messages.iter().rev().take(2).collect::<Vec<_>>();- last.reverse();- let mut tsx = ctx.db.begin().await.map_err(|err| {- tracing::error!(- chat_id = %incoming_message.chat_id,- user_id = %user_id,- error = %err,- "error creating transaction"- );- StreamWebSocketError::FailedToEditMessage {- reason: "internal error".to_string(),- stream_id: incoming_message.stream_id.clone(),- }- })?;-- if let Some(first) = last.first()- && first.role == Role::User- {- delete_chat_message(&mut *tsx, &first.id)- .await- .map_err(|err| {- tracing::error!(- chat_id = %incoming_message.chat_id,- message_id = %first.id,- user_id = %user_id,- error = %err,- "failed to delete message (i)"- );- StreamWebSocketError::FailedToEditMessage {- reason: "internal error".to_string(),- stream_id: incoming_message.stream_id.clone(),- }- })?;- search::send_remove_chat_message_to_search(&ctx, &chat.id, &first.id);- }-- if let Some(last) = last.last() {- delete_chat_message(&mut *tsx, &last.id)- .await- .map_err(|err| {- tracing::error!(- chat_id = %incoming_message.chat_id,- message_id = %last.id,- user_id = %user_id,- error = %err,- "failed to delete message (ii)"- );- StreamWebSocketError::FailedToEditMessage {- reason: "internal error".to_string(),- stream_id: incoming_message.stream_id.clone(),- }- })?;- search::send_remove_chat_message_to_search(&ctx, &chat.id, &last.id);- }-- tsx.commit().await.map_err(|err| {- tracing::error!(- chat_id = %incoming_message.chat_id,- user_id = %user_id,- error = %err,- "error committing transaction"- );- StreamWebSocketError::FailedToEditMessage {- reason: "internal error".to_string(),- stream_id: incoming_message.stream_id.clone(),- }- })?;-- handle_send_chat_message(- sender,- ctx,- message_id,- incoming_message,- user_id,- connection_id,- jwt_token,- )- .await-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/error.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/error.rsdeleted file mode 100644index 98cc799bfc..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/ws/error.rs+++ /dev/null@@ -1,15 +0,0 @@-use crate::model::ws::{GenericErrorResponse, WebSocketError};--impl From<anyhow::Error> for GenericErrorResponse {- fn from(err: anyhow::Error) -> Self {- Self {- message: err.to_string(),- }- }-}--impl From<anyhow::Error> for WebSocketError {- fn from(err: anyhow::Error) -> Self {- WebSocketError::Generic(GenericErrorResponse::from(err))- }-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/extraction_status.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/extraction_status.rsdeleted file mode 100644index 1b24af81e1..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/ws/extraction_status.rs+++ /dev/null@@ -1,251 +0,0 @@-use anyhow::{Context, Result};-use std::{- collections::HashMap,- sync::{- Arc,- atomic::{AtomicBool, Ordering},- },- time::Instant,-};--use dashmap::DashMap;-use tokio::sync::mpsc::UnboundedSender;--use crate::{- api::context::{ApiContext, GLOBAL_CONTEXT},- model::ws::{ChatStream, ExtractionStatusPayload, WebSocketError},- service::attachment::document::get_document_plaintext_content,-};--use macro_db_client::dcs::get_document::get_document;-use macro_db_client::dcs::get_document_text::{- ExtractionStatusEnum, batch_document_text_extraction_status, document_text_extraction_status,- status_of_extracted_text,-};--use std::time::Duration;--use std::sync::LazyLock;--use super::connection::{CONNECTION_MAP, ws_send};--/// Max time to check for extraction status is 6 minutes-const MAX_POLL_TIME: Duration = Duration::from_secs(360);--/// Poll interval is 500 milliseconds-const POLL_INTERVAL: Duration = Duration::from_millis(500);--// RwLock allows shared read access but exclusive write access-/// single handle for the task running the poller-static HANDLE: AtomicBool = AtomicBool::new(false);--/// map of polling key to connections lisening to that key-static ATTACHMENT_POLLING_MAP: LazyLock<DashMap<String, DashMap<String, Instant>>> =- LazyLock::new(DashMap::new);--#[tracing::instrument(skip(sender, ctx), fields(attachment_id=?payload.attachment_id, connection_id=connection_id))]-pub async fn extraction_status_handler(- sender: &UnboundedSender<ChatStream>,- ctx: Arc<ApiContext>,- connection_id: &str,- payload: ExtractionStatusPayload,-) -> Result<(), WebSocketError> {- // Ensure the attachment in question exists- let document_id = payload.attachment_id.as_str();- let document_metadata_opt = get_document(&ctx.db, payload.attachment_id.as_str())- .await- .context("failed to get document")?;- let document_metadata = document_metadata_opt.unwrap();- let extraction_status = if ["pdf", "docx"].contains(&document_metadata.file_type.as_str()) {- document_text_extraction_status(ctx.db.clone(), document_id)- .await- .map_err(|e| {- tracing::error!(error = %e, "failed to get document text extraction status");- WebSocketError::ExtractionStatusFailed {- attachment_id: payload.attachment_id.clone(),- }- })?- } else {- let document_text = get_document_plaintext_content(&ctx, document_id)- .await- .map_err(|e| {- tracing::error!(error = %e, "failed to get document plaintext content");- WebSocketError::ExtractionStatusFailed {- attachment_id: payload.attachment_id.clone(),- }- })?- .text_content()?;- status_of_extracted_text(&document_text)- };-- ws_send(- sender,- ChatStream::ExtractionStatusAck {- attachment_id: payload.attachment_id.clone(),- status: extraction_status.into(),- },- )- .map_err(|err| {- tracing::error!(error=?err, "failed to send extraction status ack");- WebSocketError::ExtractionStatusFailed {- attachment_id: payload.attachment_id.clone(),- }- })?;-- if extraction_status != ExtractionStatusEnum::Incomplete {- return Ok(());- }-- // non-[pdf/docx] should not be added to this poll- if ["pdf", "docx"].contains(&document_metadata.file_type.as_str()) {- push_attachment_to_poll(payload.attachment_id.as_str(), connection_id).await;- }- Ok(())-}--/// Pushes an attachment id and a connection id into the poller map-/// if a poller is not already running, we start a new poller-pub async fn push_attachment_to_poll(attachment_id: &str, connection_id: &str) {- // Insert the attachment id and connection id into the poller map- let map = &*ATTACHMENT_POLLING_MAP;- map.entry(attachment_id.to_string())- .or_default()- .insert(connection_id.to_string(), Instant::now());-- // Start the poller back up if it's not already running- if !HANDLE.load(Ordering::SeqCst) {- spawn_poller();- }-}--/// returns a snapshot of the current attachment polling map-/// this is used to ensure consistency between a single poller iteration-/// and void deadlocks-pub fn get_attachments_snapshot() -> HashMap<String, HashMap<String, Instant>> {- ATTACHMENT_POLLING_MAP- .iter()- .map(|entry| {- let outer_key = entry.key().clone();- let inner_map: HashMap<String, Instant> = entry- .value()- .iter()- .map(|inner_entry| (inner_entry.key().clone(), *inner_entry.value()))- .collect();- (outer_key, inner_map)- })- .collect()-}--/// removes a connection from the attachment polling map-pub fn remove_polling_connection(attachment_id: &str, connection_id: &str) {- if let Some(attachment) = ATTACHMENT_POLLING_MAP.get_mut(attachment_id) {- attachment.remove(connection_id);- }-}--/// Spawns a new poller task-/// there should only ever be one poller running at a time-/// poller will poll all attachments that are currently being listened to-pub fn spawn_poller() {- tokio::spawn(async move {- HANDLE.store(true, Ordering::SeqCst);- tracing::trace!("starting poller");- let context = match GLOBAL_CONTEXT.get() {- Some(context) => context.clone(),- None => {- tracing::error!("GLOBAL_CONTEXT is not set");- return;- }- };-- loop {- let attachment_map = get_attachments_snapshot();-- let attachment_ids = attachment_map- .iter()- .filter_map(|a| {- if a.1.is_empty() {- return None;- }- Some(a.0.to_string())- })- .collect::<Vec<_>>();-- if attachment_ids.is_empty() {- tracing::trace!("stopping poller, no attachments to poll");- break;- }-- let res = match batch_document_text_extraction_status(- context.db.clone(),- &attachment_ids,- )- .await- {- Ok(res) => res,- Err(err) => {- tracing::error!(error = %err, "failed to check document text extraction status");- continue;- }- };-- let connection_map = &*CONNECTION_MAP;-- for (attachment_id, extraction_status) in res.into_iter() {- let connections = match attachment_map.get(&attachment_id) {- Some(attachment_entry) => attachment_entry,- None => {- continue;- }- };-- if connections.is_empty() {- continue;- }-- for (connection_id, start_time) in connections {- let sender = match connection_map- .get(connection_id)- .and_then(|sender| sender.upgrade())- {- Some(sender) => sender,- None => {- continue;- }- };-- if extraction_status != ExtractionStatusEnum::Incomplete {- ws_send(- &sender,- ChatStream::ExtractionStatusUpdate {- attachment_id: attachment_id.clone(),- status: extraction_status.into(),- },- )- .ok();- remove_polling_connection(&attachment_id, connection_id);- } else {- if *start_time + MAX_POLL_TIME > Instant::now() {- continue;- }-- // We have been polling this attachment for too long, so we should stop- // polling it.- ws_send(- &sender,- ChatStream::Error(WebSocketError::ExtractionStatusFailed {- attachment_id: attachment_id.to_string(),- }),- )- .ok();- remove_polling_connection(&attachment_id, connection_id)- }- }- }-- tokio::time::sleep(POLL_INTERVAL).await;- }- tracing::trace!("poller stopped");- HANDLE.store(false, Ordering::SeqCst);- });-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/mod.rsdeleted file mode 100644index 8879f7edd5..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/ws/mod.rs+++ /dev/null@@ -1,31 +0,0 @@-mod attachment_permissions;-pub mod chat_message;-pub mod chat_permissions;-pub mod completion;-pub mod connection;-pub mod edit_message;-pub mod error;-pub mod extraction_status;-pub mod select_model;-pub mod simple_completion;--use axum::{Router, routing::get};-use tower::ServiceBuilder;--use crate::api::context::ApiContext;--pub fn router(state: ApiContext) -> Router<ApiContext> {- Router::new().route(- "/",- get(connection::ws_handler).layer(- ServiceBuilder::new()- .layer(axum::middleware::from_fn(- macro_middleware::auth::ensure_user_exists::handler,- ))- .layer(axum::middleware::from_fn_with_state(- state,- macro_middleware::user_permissions::attach_user_permissions::handler,- )),- ),- )-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/select_model.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/select_model.rsdeleted file mode 100644index 9f264b491a..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/ws/select_model.rs+++ /dev/null@@ -1,24 +0,0 @@-use crate::model::ws::SelectModelPayload;-use ai::types::Model;-use anyhow::{Context as _, Result};-use macro_db_client::dcs::patch_chat::patch_chat;-use sqlx::PgPool;-use std::str::FromStr as _;--#[tracing::instrument(err, skip(db), fields(model=payload.model, chat_id=payload.chat_id))]-pub async fn select_model_handler(db: &PgPool, payload: SelectModelPayload) -> Result<()> {- let new_model = Model::from_str(&payload.model).context("failed to parse model string")?;-- patch_chat(- db,- &payload.chat_id,- None,- None,- Some(new_model.to_string().as_str()),- None,- )- .await- .context("failed to patch chat")?;-- Ok(())-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/simple_completion.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/simple_completion.rsdeleted file mode 100644index affab17acd..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/ws/simple_completion.rs+++ /dev/null@@ -1,112 +0,0 @@-/* A completion without a chat or attachments */-use crate::api::context::ApiContext;-use crate::core::constants::DEFAULT_MAX_TOKENS;-use crate::model::ws::{ChatStream, GetSimpleCompletionStreamPayload, WebSocketError};-use crate::service::attachment::document::get_document_plaintext_content;-use ai::chat_stream::get_chat_stream;-use ai::types::{ChatStreamCompletionResponse, MessageBuilder, Model, RequestBuilder};-use anyhow::Result;-use futures::StreamExt;-use std::sync::Arc;-use tokio::sync::mpsc::UnboundedSender;--use macro_db_client::dcs::get_document;-use macro_db_client::dcs::get_document_text;--const SIMPLE_COMPLETION_DEFAULT_MODEL: Model = Model::OpenAIGPT4oMini;--#[tracing::instrument(skip(ctx, payload, sender))]-pub async fn handle_simple_completion(- ctx: Arc<ApiContext>,- sender: &UnboundedSender<ChatStream>,- payload: &GetSimpleCompletionStreamPayload,- user_id: &str,-) -> Result<(), WebSocketError> {- // Fetch document content if document_id is provided- let mut system_prompt: String = payload.prompt.clone();- if let Some(document_ids) = &payload.content_document_ids {- let db = &ctx.db;-- // This might have to be reworked when we have use cases that have multiple attachments- for document_id in document_ids.iter() {- let document = get_document::get_document(db, document_id)- .await- .map_err(|e| {- tracing::error!(error = %e, document_id, "failed to get document metadata");- e- })?;- let document_content =- if ["pdf", "docx"].contains(&document.unwrap().file_type.as_str()) {- get_document_text::get_pdf_docx_document_text(db.clone(), document_id)- .await- .map_err(|e| {- tracing::error!(error = %e, document_id, "failed to get document text");- anyhow::Error::new(e)- })?- .content- } else {- get_document_plaintext_content(&ctx, document_id)- .await?- .text_content()?- };- // check if document content is empty- if document_content- .chars()- .filter(|c| !c.is_whitespace())- .count()- > 0- {- system_prompt = format!(- "{}\n\nDocument Content:\n{}",- system_prompt, document_content- );- }- }- }-- let model = payload.model.unwrap_or(SIMPLE_COMPLETION_DEFAULT_MODEL);- let request = RequestBuilder::new()- .model(model)- .max_tokens(payload.max_tokens.unwrap_or(DEFAULT_MAX_TOKENS))- .messages(vec![- MessageBuilder::new()- .user()- .content(payload.user_request.clone())- .build(),- ])- .system_prompt(system_prompt)- .build();-- let mut stream = get_chat_stream(request).await?;- let mut cumulative_content = String::new();- while let Some(response) = stream.next().await {- let parts = response?;- for part in parts {- let ChatStreamCompletionResponse::Content(content) = part;- cumulative_content.push_str(&content.content);- let message = ChatStream::CompletionStreamChunk {- completion_id: payload.completion_id.clone(),- content: cumulative_content.clone(),- done: false,- };- sender.send(message).map_err(|err| {- tracing::error!(error = %err, "failed to send completion message");- WebSocketError::FailedToSendWebsocketMessage {- details: Some(err.to_string()),- }- })?;- }- }- let message = ChatStream::CompletionStreamChunk {- completion_id: payload.completion_id.clone(),- content: cumulative_content.clone(),- done: true,- };- sender.send(message).map_err(|err| {- tracing::error!(error = %err, "failed to send completion message");- WebSocketError::FailedToSendWebsocketMessage {- details: Some(err.to_string()),- }- })?;- Ok(())-}diff --git a/rust/cloud-storage/document_cognition_service/src/core/model.rs b/rust/cloud-storage/document_cognition_service/src/core/model.rsindex ccfed0685f..0e010eeb4c 100644--- a/rust/cloud-storage/document_cognition_service/src/core/model.rs+++ b/rust/cloud-storage/document_cognition_service/src/core/model.rs@@ -1,7 +1,4 @@use ai::types::Model;pub static CHAT_MODELS: &[Model] = &[Model::Claude45Haiku, Model::Claude46Opus];--pub static COMPLETION_MODEL: Model = Model::OpenAiGpt41;-pub static COMPLETION_CONTEXT_WINDOW: i32 = 80000;pub static FALLBACK_MODEL: Model = Model::Claude45Haiku;diff --git a/rust/cloud-storage/document_cognition_service/src/model/mod.rs b/rust/cloud-storage/document_cognition_service/src/model/mod.rsindex ba24544ddb..e0d27faddf 100644--- a/rust/cloud-storage/document_cognition_service/src/model/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/model/mod.rs@@ -2,4 +2,4 @@ pub mod chats;pub mod internal;pub mod request;pub mod response;-pub mod ws;+pub mod stream;diff --git a/rust/cloud-storage/document_cognition_service/src/model/stream.rs b/rust/cloud-storage/document_cognition_service/src/model/stream.rsnew file mode 100644index 0000000000..8067a0eaab--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/model/stream.rs@@ -0,0 +1,201 @@+use ai::types::AssistantMessagePart;+use ai::types::Model;+use model::chat::ChatAttachmentWithName;+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;++#[derive(Deserialize, Serialize, ToSchema, Debug, Clone)]+pub struct JwtPayload {+ pub token: String,+}++#[derive(Serialize, Deserialize, ToSchema, Debug, Clone, Default)]+#[serde(rename_all = "snake_case", tag = "type")]+pub enum ToolSet {+ #[default]+ All,+ None,+}++#[derive(Deserialize, Serialize, ToSchema, Debug, Clone)]+pub struct SendChatMessagePayload {+ /// Stream ID for tracking the response+ pub stream_id: String,+ /// The content of the message+ pub content: String,+ /// Id of the chat the message belongs to+ pub chat_id: String,+ /// the chate model to respond with+ pub model: Model,+ /// Additional system instructions appended to the base system prompt+ #[serde(skip_serializing_if = "Option::is_none")]+ pub additional_instructions: Option<String>,+ /// Use citation prompt+ #[serde(skip_serializing_if = "Option::is_none")]+ pub attachments: Option<Vec<ChatAttachmentWithName>>,+ /// Which toolset to use. Defaults to `all`+ #[serde(default)]+ pub toolset: ToolSet,+ #[serde(flatten)]+ pub jwt: JwtPayload,+}++#[derive(Deserialize, Serialize, ToSchema, Debug, Clone)]+pub struct GetSimpleCompletionStreamPayload {+ /// system prompt+ pub prompt: String,+ /// user request+ pub user_request: String,+ /// model to use for the completion+ #[schema(value_type = Option<String>)]+ pub model: Option<Model>,+ /// max tokens+ pub max_tokens: Option<u32>,+ /// Optional document ID to provide context+ pub content_document_ids: Option<Vec<String>>,+ /// client provided id, returned in responses+ pub completion_id: String,+}++#[derive(Deserialize, Serialize, ToSchema, Debug, Clone, PartialEq, Copy)]+#[serde(tag = "type", rename_all = "lowercase")]+pub enum ExtractionStatusEnum {+ // Extraction incomplete+ Incomplete,++ // Extraction complete, but text content is empty+ Empty,++ // Extraction complete, but text content is insufficient+ Insufficient,++ // Extraction complete and sufficient+ Complete,+}++// Akkad prospers and we cope+impl From<macro_db_client::dcs::get_document_text::ExtractionStatusEnum> for ExtractionStatusEnum {+ fn from(value: macro_db_client::dcs::get_document_text::ExtractionStatusEnum) -> Self {+ match value {+ macro_db_client::dcs::get_document_text::ExtractionStatusEnum::Complete => {+ Self::Complete+ }+ macro_db_client::dcs::get_document_text::ExtractionStatusEnum::Empty => Self::Empty,+ macro_db_client::dcs::get_document_text::ExtractionStatusEnum::Insufficient => {+ Self::Insufficient+ }+ macro_db_client::dcs::get_document_text::ExtractionStatusEnum::Incomplete => {+ Self::Incomplete+ }+ }+ }+}++#[derive(Serialize, Deserialize, ToSchema, Debug, Clone)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum ChatStream {+ /// Misc error+ Error(StreamError),++ /// Acknowledges that a message has been received for processing+ ChatMessageAck {+ message_id: String,+ chat_id: String,+ },++ /// The user message that initiated this stream, sent as the first item+ /// so other clients can add it to their local chat state.+ ChatUserMessage {+ stream_id: String,+ chat_id: String,+ message_id: String,+ content: String,+ attachments: Vec<ChatAttachmentWithName>,+ },++ /// Indicates a response from the chat completion API for a given message+ ChatMessageResponse {+ stream_id: String,+ message_id: String,+ chat_id: String,+ content: AssistantMessagePart,+ },++ /// Indicates that a message has been finished+ ChatMessageFinished {+ message_id: String,+ chat_id: String,+ user_message_id: String,+ },++ /// Indicates that a chat has been renamed+ ChatRenamed {+ stream_id: String,+ chat_id: String,+ name: String,+ },++ /// Notifies the client that the available models have changed+ ModelSelectionChanged {+ chat_id: String,+ available_models: Vec<Model>,+ new_model: Option<Model>,+ },++ TokenCountChanged {+ chat_id: String,+ token_count: i64,+ },++ /// Status update+ ChatMessageStatusUpdate {+ chat_id: String,+ message_id: String,+ message: String,+ },++ /// Acknowledges the request to get extraction status+ /// if the `status` field is 'incomplete', we need to await the extraction status updates+ /// if the `status` field is 'empty', extraction is complete but text content is empty+ /// if the `status` field is 'complete', the extraction is already complete+ ExtractionStatusAck {+ attachment_id: String,+ status: ExtractionStatusEnum,+ },++ /// Status update for the extraction status+ ExtractionStatusUpdate {+ attachment_id: String,+ status: ExtractionStatusEnum,+ },++ /// pdf completion+ CompletionResponse {+ completion_id: String,+ content: String,+ done: bool,+ },++ CompletionStreamChunk {+ completion_id: String,+ content: String,+ done: bool,+ },++ StreamEnd {+ stream_id: String,+ },+}++#[derive(thiserror::Error, Debug, ToSchema, Serialize, Deserialize, Clone)]+#[serde(rename_all = "snake_case", tag = "stream_error")]+pub enum StreamError {+ #[error("provider error")]+ ProviderError { stream_id: String, model: Model },++ #[error("model context overflow")]+ ModelContextOverflow { stream_id: String },++ #[error("internal error")]+ InternalError { stream_id: String },+}diff --git a/rust/cloud-storage/document_cognition_service/src/model/ws/mod.rs b/rust/cloud-storage/document_cognition_service/src/model/ws/mod.rsdeleted file mode 100644index e5e1503bfc..0000000000--- a/rust/cloud-storage/document_cognition_service/src/model/ws/mod.rs+++ /dev/null@@ -1,396 +0,0 @@-use ai::types::AssistantMessagePart;-use ai::types::Model;-use axum::extract::ws::Message;-use model::chat::ChatAttachmentWithName;-use serde::{Deserialize, Serialize};-use utoipa::ToSchema;--#[derive(Deserialize, Serialize, ToSchema, Debug, Clone)]-pub struct JwtPayload {- pub token: String,-}--#[derive(Serialize, Deserialize, ToSchema, Debug, Clone, Default)]-#[serde(rename_all = "snake_case", tag = "type")]-pub enum ToolSet {- #[default]- All,- None,-}--#[derive(Deserialize, Serialize, ToSchema, Debug, Clone)]-pub struct SendChatMessagePayload {- /// Stream ID for tracking the response- pub stream_id: String,- /// The content of the message- pub content: String,- /// Id of the chat the message belongs to- pub chat_id: String,- /// the chate model to respond with- pub model: Model,- /// Additional system instructions appended to the base system prompt- #[serde(skip_serializing_if = "Option::is_none")]- pub additional_instructions: Option<String>,- /// Use citation prompt- #[serde(skip_serializing_if = "Option::is_none")]- pub attachments: Option<Vec<ChatAttachmentWithName>>,- /// Which toolset to use. Defaults to `all`- #[serde(default)]- pub toolset: ToolSet,- #[serde(flatten)]- pub jwt: JwtPayload,-}--#[derive(Deserialize, Serialize, ToSchema, Debug)]-pub struct StopChatMessagePayload {- /// stream id- pub stream_id: String,-}--#[derive(Deserialize, Serialize, ToSchema, Debug)]-pub struct SelectModelPayload {- pub chat_id: String,- pub model: String,-}--#[derive(Deserialize, Serialize, ToSchema, Debug, Clone)]-pub struct ExtractionStatusPayload {- pub attachment_id: String,-}--#[derive(Deserialize, Serialize, ToSchema, Debug, Clone)]-pub struct SendCompletionPayload {- /// Optional attachment id for the completion- pub attachment_id: Option<String>,- /// the prompt of the completion- pub prompt: String,- /// Optional completion id to keep track of the completion- /// if non is provided, one will be generated- pub completion_id: Option<String>,- /// The selected text for the completion,- pub selected_text: Option<String>,-}--#[derive(Deserialize, Serialize, ToSchema, Debug, Clone)]-pub struct GetSimpleCompletionStreamPayload {- /// system prompt- pub prompt: String,- /// user request- pub user_request: String,- /// model to use for the completion- #[schema(value_type = Option<String>)]- pub model: Option<Model>,- /// max tokens- pub max_tokens: Option<u32>,- /// Optional document ID to provide context- pub content_document_ids: Option<Vec<String>>,- /// client provided id, returned in responses- pub completion_id: String,-}--#[derive(Deserialize, Serialize, ToSchema, Debug)]-#[serde(tag = "type", rename_all = "snake_case")]-pub enum ToWebSocketMessage {- /// Initializes a new message in a chat for streaming- SendChatMessage(SendChatMessagePayload),-- /// Replace user message and restream response- EditChatMessage(SendChatMessagePayload),-- /// Stop streaming for a given message- StopChatMessage(StopChatMessagePayload),-- /// Select model for a given chat- SelectModelForChat(SelectModelPayload),-- /// Get extraction status for a given attachment- ExtractionStatus(ExtractionStatusPayload),-- /// pdf completion- SendCompletion(SendCompletionPayload),- /// stream a simple completion- GetSimpleCompletionStream(GetSimpleCompletionStreamPayload),-}--#[derive(Deserialize, Serialize, ToSchema, Debug, Clone, PartialEq, Copy)]-#[serde(tag = "type", rename_all = "lowercase")]-pub enum ExtractionStatusEnum {- // Extraction incomplete- Incomplete,-- // Extraction complete, but text content is empty- Empty,-- // Extraction complete, but text content is insufficient- Insufficient,-- // Extraction complete and sufficient- Complete,-}--// Akkad prospers and we cope-impl From<macro_db_client::dcs::get_document_text::ExtractionStatusEnum> for ExtractionStatusEnum {- fn from(value: macro_db_client::dcs::get_document_text::ExtractionStatusEnum) -> Self {- match value {- macro_db_client::dcs::get_document_text::ExtractionStatusEnum::Complete => {- Self::Complete- }- macro_db_client::dcs::get_document_text::ExtractionStatusEnum::Empty => Self::Empty,- macro_db_client::dcs::get_document_text::ExtractionStatusEnum::Insufficient => {- Self::Insufficient- }- macro_db_client::dcs::get_document_text::ExtractionStatusEnum::Incomplete => {- Self::Incomplete- }- }- }-}--#[derive(Serialize, Deserialize, ToSchema, Debug, Clone)]-#[serde(tag = "type", rename_all = "snake_case")]-pub enum ChatStream {- /// Misc error- Error(WebSocketError),-- /// Acknowledges that a message has been received for processing- ChatMessageAck {- message_id: String,- chat_id: String,- },-- /// The user message that initiated this stream, sent as the first item- /// so other clients can add it to their local chat state.- ChatUserMessage {- stream_id: String,- chat_id: String,- message_id: String,- content: String,- attachments: Vec<ChatAttachmentWithName>,- },-- /// Indicates a response from the chat completion API for a given message- ChatMessageResponse {- stream_id: String,- message_id: String,- chat_id: String,- content: AssistantMessagePart,- },-- /// Indicates that a message has been finished- ChatMessageFinished {- message_id: String,- chat_id: String,- user_message_id: String,- },-- /// Indicates that a chat has been renamed- ChatRenamed {- stream_id: String,- chat_id: String,- name: String,- },-- /// Notifies the client that the available models have changed- ModelSelectionChanged {- chat_id: String,- available_models: Vec<Model>,- new_model: Option<Model>,- },-- TokenCountChanged {- chat_id: String,- token_count: i64,- },-- /// Status update- ChatMessageStatusUpdate {- chat_id: String,- message_id: String,- message: String,- },-- /// Acknowledges the request to get extraction status- /// if the `status` field is 'incomplete', we need to await the extraction status updates- /// if the `status` field is 'empty', extraction is complete but text content is empty- /// if the `status` field is 'complete', the extraction is already complete- ExtractionStatusAck {- attachment_id: String,- status: ExtractionStatusEnum,- },-- /// Status update for the extraction status- ExtractionStatusUpdate {- attachment_id: String,- status: ExtractionStatusEnum,- },-- Pong,-- /// pdf completion- CompletionResponse {- completion_id: String,- content: String,- done: bool,- },-- CompletionStreamChunk {- completion_id: String,- content: String,- done: bool,- },-- StreamEnd {- stream_id: String,- },-}--impl TryInto<ToWebSocketMessage> for Message {- type Error = serde_json::Error;- fn try_into(self) -> Result<ToWebSocketMessage, Self::Error> {- let payload =- serde_json::from_str::<ToWebSocketMessage>(self.to_text().unwrap_or_default())?;- Ok(payload)- }-}--impl From<ChatStream> for Message {- fn from(val: ChatStream) -> Self {- match val {- ChatStream::Pong => Message::Text("pong".to_string()),- _ => {- let payload = serde_json::to_string(&val).unwrap();- Message::Text(payload)- }- }- }-}--#[derive(Serialize, Debug, ToSchema, Deserialize, Clone)]-pub struct GenericErrorResponse {- pub message: String,-}--#[derive(thiserror::Error, Debug, ToSchema, Serialize, Deserialize, Clone)]-#[serde(rename_all = "snake_case", tag = "stream_error")]-pub enum StreamError {- #[error("provider error")]- ProviderError { stream_id: String, model: Model },-- #[error("model context overflow")]- ModelContextOverflow { stream_id: String },-- #[error("internal error")]- InternalError { stream_id: String },-- #[error("unauthorized")]- Unauthorized { stream_id: String },-- #[error("payment required")]- PaymentRequired { stream_id: String },-}--/// Subset enum containing only WebSocketError variants that have stream_id-#[derive(thiserror::Error, Debug, Clone)]-pub enum StreamWebSocketError {- #[error("edit message error")]- FailedToEditMessage { reason: String, stream_id: String },-- #[error("stream error")]- StreamError(#[from] StreamError),-}--impl StreamWebSocketError {- pub fn stream_id(&self) -> &str {- match self {- StreamWebSocketError::FailedToEditMessage { stream_id, .. } => stream_id,- StreamWebSocketError::StreamError(StreamError::ProviderError { stream_id, .. }) => {- stream_id- }- StreamWebSocketError::StreamError(StreamError::ModelContextOverflow { stream_id }) => {- stream_id- }- StreamWebSocketError::StreamError(StreamError::InternalError { stream_id, .. }) => {- stream_id- }- StreamWebSocketError::StreamError(StreamError::Unauthorized { stream_id }) => stream_id,- StreamWebSocketError::StreamError(StreamError::PaymentRequired { stream_id }) => {- stream_id- }- }- }-}--impl From<StreamWebSocketError> for WebSocketError {- fn from(err: StreamWebSocketError) -> Self {- match err {- StreamWebSocketError::FailedToEditMessage { reason, stream_id } => {- WebSocketError::FailedToEditMessage { reason, stream_id }- }- StreamWebSocketError::StreamError(stream_err) => {- WebSocketError::StreamError(stream_err)- }- }- }-}--#[derive(thiserror::Error, Debug, ToSchema, Serialize, Deserialize, Clone)]-#[serde(rename_all = "snake_case", tag = "error_type")]-pub enum WebSocketError {- #[error("stream error")]- StreamError(StreamError),-- // NOTE: unused- #[error("failed to send chat message for chat {chat_id} : {details:?}")]- FailedToSendChatMessage {- details: Option<String>,- chat_id: String,- message_id: String,- stream_id: String,- },-- // NOTE: unused- #[error("failed to automatically rename chat {chat_id} : {details:?}")]- FailedToRenameChat {- details: Option<String>,- chat_id: String,- stream_id: String,- },-- #[error("failed to send error message : {details:?}")]- FailedToSendErrorMessage { details: Option<String> },-- // NOTE: unused- #[error("failed to store chat {chat_id}: {details:?}")]- FailedToStoreChat {- details: Option<String>,- chat_id: String,- stream_id: String,- },-- #[error("an internal server error occurred")]- Generic(GenericErrorResponse),-- #[error("failed to send a message over the websocket : {details:?}")]- FailedToSendWebsocketMessage { details: Option<String> },-- #[error("failed to select model : {details:?}")]- FailedToSelectModel { details: Option<String> },-- // NOTE: unused- #[error("failed to update token count : {details:?}")]- FailedToUpdateTokenCount {- details: Option<String>,- chat_id: String,- message_id: String,- stream_id: String,- },-- #[error("extraction status has failed")]- ExtractionStatusFailed { attachment_id: String },-- #[error("attachment permission error: {attachment_ids:?}")]- AttachmentPermissionError { attachment_ids: Vec<String> },-- #[error("edit message error")]- FailedToEditMessage { reason: String, stream_id: String },-}