@c8y/ngx-components 1023.79.1 → 1023.80.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/ai/agent-chat/index.d.ts +22 -11
  2. package/ai/agent-chat/index.d.ts.map +1 -1
  3. package/ai/ai-chat/index.d.ts +30 -9
  4. package/ai/ai-chat/index.d.ts.map +1 -1
  5. package/ai/index.d.ts +64 -49
  6. package/ai/index.d.ts.map +1 -1
  7. package/fesm2022/c8y-ngx-components-ai-agent-chat.mjs +235 -127
  8. package/fesm2022/c8y-ngx-components-ai-agent-chat.mjs.map +1 -1
  9. package/fesm2022/c8y-ngx-components-ai-ai-chat.mjs +104 -44
  10. package/fesm2022/c8y-ngx-components-ai-ai-chat.mjs.map +1 -1
  11. package/fesm2022/c8y-ngx-components-ai.mjs +92 -61
  12. package/fesm2022/c8y-ngx-components-ai.mjs.map +1 -1
  13. package/fesm2022/c8y-ngx-components-global-context.mjs +23 -3
  14. package/fesm2022/c8y-ngx-components-global-context.mjs.map +1 -1
  15. package/fesm2022/c8y-ngx-components-widgets-definitions-html-widget-ai-config.mjs +31 -29
  16. package/fesm2022/c8y-ngx-components-widgets-definitions-html-widget-ai-config.mjs.map +1 -1
  17. package/fesm2022/c8y-ngx-components-widgets-implementations-datapoints-list.mjs +47 -8
  18. package/fesm2022/c8y-ngx-components-widgets-implementations-datapoints-list.mjs.map +1 -1
  19. package/global-context/index.d.ts +17 -2
  20. package/global-context/index.d.ts.map +1 -1
  21. package/locales/de.po +3 -0
  22. package/locales/es.po +3 -0
  23. package/locales/fr.po +3 -0
  24. package/locales/ja_JP.po +3 -0
  25. package/locales/ko.po +3 -0
  26. package/locales/locales.pot +3 -0
  27. package/locales/nl.po +3 -0
  28. package/locales/pl.po +3 -0
  29. package/locales/pt_BR.po +3 -0
  30. package/locales/zh_CN.po +3 -0
  31. package/locales/zh_TW.po +3 -0
  32. package/package.json +1 -1
  33. package/widgets/implementations/datapoints-list/index.d.ts +5 -0
  34. package/widgets/implementations/datapoints-list/index.d.ts.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"c8y-ngx-components-ai.mjs","sources":["../../ai/ai.service.ts","../../ai/c8y-ngx-components-ai.ts"],"sourcesContent":["import { inject, Injectable } from '@angular/core';\nimport { FetchClient } from '@c8y/client';\nimport { Observable, Subscriber } from 'rxjs';\nimport {\n AgentDefinition,\n AgentHealthCheckResponse,\n AgentStep,\n AIMessage,\n AIStreamResponse,\n ClientAgentDefinition,\n ToolCallPart\n} from './ai.model';\n\n// Internal implementation detail; maybe we don't even need this enum since\nexport enum DataStreamType {\n TEXT_DELTA = 'text-delta',\n TOOL_CALL = 'tool-call',\n TOOL_INPUT_START = 'tool-input-start',\n TOOL_INPUT_DELTA = 'tool-input-delta',\n TOOL_CALL_STREAMING = 'tool-call-streaming',\n TOOL_CALL_DELTA = 'tool-call-delta',\n TOOL_RESULT = 'tool-result',\n REASONING = 'reasoning',\n REASONING_DELTA = 'reasoning-delta',\n REDACTED_REASONING = 'redacted-reasoning',\n REASONING_SIGNATURE = 'reasoning-signature',\n FINISH_REASONING = 'finish-reasoning',\n FINISH = 'finish',\n FINISH_STEP = 'finish-step',\n ERROR = 'error',\n DATA = 'data',\n MESSAGE_ANNOTATIONS = 'message-annotations',\n SOURCE = 'source',\n FILE = 'file',\n STEP_START = 'start-step',\n STEP_FINISH = 'finish-step'\n}\n\n/** This service manages communication with the AI Agent Manager microservice, supporting\n * management of agents, and sending requests to the agents.\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class AIService {\n private baseUrl = '/service/ai';\n private client: FetchClient;\n\n // nb: allowing the client to be passed in the constructor allows efficient unit testing without setting up the Angular TestBed\n constructor(client?: FetchClient) {\n this.client = client ?? inject(FetchClient);\n }\n\n /**\n * Creates or updates an agent.\n * @param def The agent definition\n */\n async createOrUpdateAgent(def: AgentDefinition): Promise<void> {\n const health = await this.getAgentHealth(def.name);\n let resource = `${this.baseUrl}/agent/${def.type}`;\n let method = 'POST';\n if (health.exists) {\n resource = `${this.baseUrl}/agent/${def.type}/${def.name}`;\n method = 'PUT';\n }\n const response = await this.client.fetch(resource, {\n body: JSON.stringify(def),\n method,\n headers: { 'Content-Type': 'application/json' }\n });\n\n if (!response.ok) {\n throw new Error(`Failed to create agent: ${response.statusText}`);\n }\n }\n\n /**\n * Check if an agent exists and is ready for use.\n * @param name Agent name (optional)\n * @param fromApp The app context path to check for an agent. This can be used, if the agent should get distributed by the plugin (optional).\n * @returns Agent health check response.\n */\n async getAgentHealth(name = '', fromApp?: string): Promise<AgentHealthCheckResponse> {\n const response = await this.client.fetch(\n `${this.baseUrl}/agent/test/${name || crypto.randomUUID()}${fromApp ? `?fromApp=${fromApp}` : ''}`,\n {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' }\n }\n );\n\n if (!response.ok) {\n return {\n status: response.status === 403 ? 'missing-permissions' : 'missing-microservice',\n exists: false,\n canCreate: false,\n isProviderConfigured: false,\n messages: response.status === 403 ? [] : [response.statusText]\n };\n }\n const json: AgentHealthCheckResponse = await response.json();\n if (!json.isProviderConfigured) {\n json.status = 'missing-provider';\n } else if (!json.exists) {\n json.status = 'missing-agent';\n } else {\n json.status = 'ready';\n }\n return json;\n }\n\n /**\n * Send a text message to the agent.\n * @param name Agent name\n * @param messages The message to send, including any previous message history.\n * Typically you should use `defaultPruneMessagesForAgent` or a custom function to prepare the message history\n * by removing unnecessary content such as large/old tool inputs/outputs.\n * @param variables Variables to include\n * @param fromApp The app context path to check for an agent. This can be used, if the agent should get distributed by the plugin (optional).\n * @returns Text response from the agent.\n */\n async text(\n name: string,\n messages: AIMessage[],\n variables: { [key: string]: any },\n fromApp?: string\n ): Promise<string> {\n const parsedMessages = this.convertToAgentMessageFormat(messages);\n\n const data = this.client.fetch(\n `${this.baseUrl}/agent/text/${name}${fromApp ? `?fromApp=${fromApp}` : ''}`,\n {\n body: JSON.stringify({ messages: parsedMessages, variables }),\n method: 'POST',\n headers: { 'Content-Type': 'application/json' }\n }\n );\n\n const response = await data;\n if (!response.ok) {\n throw new Error(`Failed to talk with agent: ${response.statusText}`);\n }\n const text = await response.text();\n return text;\n }\n\n /**\n * Stream a text message to the agent.\n * @param agent Agent name or an agent definition.\n * @param messages The message to send, including any previous message history.\n * Typically you should use `defaultPruneMessagesForAgent` or a custom function to prepare the message history\n * by removing unnecessary content such as large/old tool inputs/outputs.\n * @param variables Variables to include\n * @param abortController An AbortController to cancel the request.\n * @param fromApp The app context path to check for an agent. This can be used, if the agent should get distributed by the plugin (optional).\n * @returns An observable that emits AIStreamResponse including partial `AIMessage` objects as they are received.\n * When additional useful metadata is available, this will be streamed with type indicating it is metadata.\n * The observable can be cancelled using the provided AbortController.\n * The observable will emit an error if the request fails or is aborted.\n * The observable will complete when the stream is finished.\n *\n * The messages sent to the agent can include special options:\n * - `hiddenContent`: If set, this content will be sent to the agent instead of the `content` field.\n * - `skipToLLM`: If set to true, this message will be skipped when sending to the agent.\n *\n * Example usage:\n * ```typescript\n * const abortController = new AbortController();\n * const messages: AIMessage[] = [\n * { role: 'user', content: 'Hello' },\n * { role: 'assistant', content: 'Hi there!' },\n * { role: 'user', content: 'Tell me a joke.', options: { hiddenContent: 'Tell me a joke about cats.' } }\n * ];\n * const observable = aiService.stream$('my-agent', messages, {}, abortController);\n * const subscription = observable.subscribe({\n * next: (response) => { console.log('Received message update:', response.message); },\n * error: (err) => console.error('Error:', err),\n * complete: () => console.log('Stream complete')\n * });\n *\n * // To cancel the request:\n * abortController.abort();\n * subscription.unsubscribe();\n * ```\n */\n async stream$(\n agent: string | ClientAgentDefinition,\n messages: AIMessage[],\n variables: { [key: string]: any },\n abortController: AbortController,\n fromApp?: string\n ): Promise<Observable<AIStreamResponse>> {\n const parsedMessages = this.convertToAgentMessageFormat(messages);\n\n const agentName = typeof agent === 'string' ? agent : agent.definition.name;\n const useTest = typeof agent !== 'string' && agent.snapshot;\n const baseUrl = useTest\n ? `${this.baseUrl}/agent/test/text`\n : `${this.baseUrl}/agent/text/${agentName}`;\n let body = JSON.stringify({ messages: parsedMessages, variables });\n if (useTest) {\n const agentCopy = {\n ...agent.definition\n };\n agentCopy.agent['messages'] = parsedMessages;\n agentCopy.agent['variables'] = variables;\n body = JSON.stringify(agentCopy);\n }\n\n const response = await this.client.fetch(\n `${baseUrl}?fullResponse=true${fromApp ? `&fromApp=${fromApp}` : ''}`,\n {\n method: 'POST',\n body,\n headers: {\n ...this.client.defaultHeaders,\n 'content-type': 'application/json',\n accept: 'text/event-stream'\n },\n signal: abortController.signal\n }\n );\n\n const stream = response.body;\n const decoder = new TextDecoder();\n\n return new Observable<AIStreamResponse>(observer => {\n if (response.status > 300) {\n response\n .json()\n .then(data => {\n observer.error(`Error communicating with server: ${JSON.stringify(data, null, 2)}`);\n })\n .catch(err => {\n observer.error(\n `Error communicating with server: HTTP ${response.status}: ${response.statusText}; ${err}`\n );\n });\n return;\n }\n\n if (!stream) {\n observer.error('Server error - no response body');\n return;\n }\n\n const reader = stream.getReader();\n const message: AIMessage = {\n role: 'assistant',\n content: '',\n steps: []\n };\n\n const abortHandler = () => {\n reader.cancel();\n observer.error(new DOMException('Aborted', 'AbortError'));\n };\n\n abortController.signal.addEventListener('abort', abortHandler);\n\n let buffer = '';\n\n const read = () => {\n reader.read().then(({ done, value }) => {\n if (done) {\n if (buffer.trim()) this.processLine(buffer, observer, message); // process any remaining data\n observer.complete();\n return;\n }\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n\\n');\n buffer = lines.pop() || '';\n for (const line of lines) {\n if (line.trim()) this.processLine(line, observer, message);\n }\n read();\n });\n };\n\n read();\n return () => {\n abortController.signal.removeEventListener('abort', abortHandler);\n reader.cancel();\n };\n });\n }\n\n protected convertToAgentMessageFormat(messages: AIMessage[]): object[] {\n // We will need to rewrite this to include tool outputs soon (effectively this means targetting LanguageModelV*ToolResultOutput).\n // Once we have more fields than just role and content, we will need to convert between our format and\n // the Vercel format expected by the agent manager (e.g. steps->content parts)\n return messages\n .filter(m => m)\n .map(m => ({\n role: m.role,\n content: m.content\n }));\n }\n\n /**\n * Convert a tool output from the wire format (which is different/more compact than LanguageModelV3ToolResultOutput)\n * into our own standard representation.\n */\n protected convertStreamingToolOutputToToolCallPart(output: any, target: ToolCallPart) {\n // So far we just pass the data through unchanged from the streaming API but that's pretty hard to work with since it's neither\n // in the format returned by the tool nor in the LanguageModelV3ToolResultOutput format that we have to use\n // when passing it back for the next request\n target.output = output;\n\n if (output?.type?.startsWith('error-') || output?.isError) target.error = true;\n }\n\n /** Add the specified tool call info to the current step. If this toolCallId is already known,\n * updates it rather than adding a new one, since for UI rendering and compactness of data it's\n * easiest to just have one item per tool call.\n */\n private addToolCallInfo(\n type: ToolCallPart['type'],\n rawInfo: any,\n addTo: AgentStep\n ): ToolCallPart {\n // Vercel v4 seems to set this to \"id\" not \"toolCallId\" in some places despite doc to the contrary, so normalize it here\n if (!rawInfo.toolCallId) rawInfo.toolCallId = rawInfo.id;\n\n // We can simplify this logic once we have AIMessage as a list of parts instead of separate lists for these\n let existing: ToolCallPart | undefined = addTo.toolCalls?.find(\n tc => tc.toolCallId === rawInfo.toolCallId\n );\n if (!existing) existing = addTo.toolResults?.find(tc => tc.toolCallId === rawInfo.toolCallId);\n\n // Move from toolCalls to toolResults when transitioning to tool-result\n if (existing && type === 'tool-result' && existing.type !== 'tool-result') {\n addTo.toolCalls = addTo.toolCalls?.filter(tc => tc.toolCallId !== existing?.toolCallId);\n existing.type = type;\n addTo.toolResults = [...(addTo.toolResults || []), existing];\n } else if (existing && existing.type !== type) {\n // Just update the type in place for other transitions\n existing.type = type;\n }\n\n if (!existing) {\n existing = { type: type, toolName: rawInfo.toolName, toolCallId: rawInfo.toolCallId };\n if (type !== 'tool-result') addTo.toolCalls = [...(addTo.toolCalls || []), existing];\n else addTo.toolResults = [...(addTo.toolResults || []), existing];\n }\n if (rawInfo?.input) existing.input = rawInfo.input;\n if (rawInfo?.output) this.convertStreamingToolOutputToToolCallPart(rawInfo.output, existing);\n\n return existing;\n }\n\n /** Unpacks data from the Vercel Data Stream Protocol (sent by the Agent Manager over SSE) to update the message\n *\n * See streamText().fullStream() from https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#data-stream-protocol\n *\n * This is similar to what the Vercel `toUIMessageStreamResponse` API does (though it'd need the agent manager to publish the\n * UIMessageStream which has a bit more - useful - data than what is included here).\n *\n * We always use the same steps (or in future, parts) object, to make it easier for consumers (eg. agent-chat)\n * to add items to the list and have them still there on the next update from this service.\n */\n private processLine(line: string, observer: Subscriber<AIStreamResponse>, message: AIMessage) {\n if (!line.trim()) {\n return;\n }\n\n try {\n let data: any = {};\n let type = '';\n try {\n data = JSON.parse(line.replace('data: ', ''));\n type = data.type;\n } catch (e) {\n console.error('Error parsing line from AI response: ', line, e);\n return;\n }\n\n // Ensure there's a step into which we can store everything\n if (!message.steps || message.steps.length === 0) {\n message.steps = [{ type: 'text', text: '' }];\n }\n const lastStep = message.steps[message.steps.length - 1];\n\n switch (type) {\n case DataStreamType.STEP_START:\n if (data.request && data.request.body) {\n observer.next({\n message: message,\n changedPart: {\n type: 'response-metadata',\n model: data.request.body.model,\n systemPrompt: data.request.body.systemPrompt\n }\n });\n }\n\n // Create a step, unless we already have an empty one from the initialization section above\n if (lastStep.text || lastStep.reasoning || lastStep.toolCalls || lastStep.toolResults) {\n message.steps.push({\n type: 'text',\n text: ''\n });\n }\n return;\n\n case DataStreamType.REASONING:\n if (lastStep.reasoning === undefined) {\n lastStep!.reasoning = '';\n }\n lastStep.reasoning += data.text || data.textDelta;\n observer.next({ message, changedPart: undefined });\n return;\n\n case DataStreamType.TEXT_DELTA:\n lastStep.text += data.text || data.textDelta;\n\n // FUTURE: this setting the same value to message.content is probably not correct;\n // duplicating the same text wastes space so not necessary given it's already in steps, and\n // the Vercel SDK sets message.content to the text of the LAST step only (the summarizing step)\n message.content += data.text || data.textDelta;\n\n observer.next({ message, changedPart: undefined });\n return;\n\n case DataStreamType.TOOL_INPUT_START:\n observer.next({\n message,\n changedPart: this.addToolCallInfo('tool-input-streaming', data, lastStep)\n });\n return;\n\n case DataStreamType.TOOL_CALL:\n observer.next({\n message,\n changedPart: this.addToolCallInfo('tool-executing', data, lastStep)\n });\n return;\n\n case DataStreamType.TOOL_RESULT:\n observer.next({\n message,\n changedPart: this.addToolCallInfo('tool-result', data, lastStep)\n });\n return;\n\n case DataStreamType.FINISH:\n message.finishReason = data.finishReason; // FUTURE could be anything, may not match the options in AIMessage\n observer.next({ message, changedPart: undefined });\n observer.complete();\n return;\n\n case DataStreamType.ERROR:\n message.finishReason = 'error';\n observer.next({ message, changedPart: undefined });\n observer.error(data?.message || data?.errorText || data);\n // Error is instead of completing the stream\n return;\n\n // Should we also handle other types such as \"abort\"?\n }\n } catch (e) {\n observer.error(e);\n }\n }\n}\n\n/**\n * The default method for reducing the size of the message history so it is ready to be sent to the LLM agent.\n *\n * This is important since old tool inputs and outputs can be very large and fill up the agent's context window.\n *\n * When sending an AI request you can provide your own function instead of using this one,\n * or you can write your own function that calls this and adds extra logic,\n * for example to suppress specific tools from the AIMessage, or\n * retain only the final step text in multi-step responses, etc.\n *\n * The current default implementation preserves text content, but does not include any tool calls.\n * This may change in future releases.\n */\nexport function defaultPruneMessagesForAgent(messages: AIMessage[]): AIMessage[] {\n // When we change this to include tool calls, we should remove large inputs and truncate large and/or old outputs\n // to avoid too many tokens and context window consumption.\n // Some applications will want to entirely remove specific tool calls that have only transient use,\n // which can be done by providing their own pruneMessagesForAgent function.\n return messages.map(m => ({\n role: m.role,\n content: m.content\n }));\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":";;;;;;AAaA;IACY;AAAZ,CAAA,UAAY,cAAc,EAAA;AACxB,IAAA,cAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,cAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvB,IAAA,cAAA,CAAA,kBAAA,CAAA,GAAA,kBAAq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AAE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,CAAC;AAClD,oBAAA,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,IAAI,IAAI,EAAE,SAAS,IAAI,IAAI,CAAC;;oBAExD;;;QAIN;QAAE,OAAO,CAAC,EAAE;AACV,YAAA,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;QACnB;IACF;+GAnaW,SAAS,EAAA,IAAA,EAAA,CAAA,EAAA,KAAA,EAAA,EAAA,CAAA,WAAA,EAAA,CAAA,EAAA,MAAA,EAAA,EAAA,CAAA,eAAA,CAAA,UAAA,EAAA,CAAA,CAAA;AAAT,IAAA,SAAA,IAAA,CAAA,KAAA,GAAA,EAAA,CAAA,qBAAA,CAAA,EAAA,UAAA,EAAA,QAAA,EAAA,OAAA,EAAA,SAAA,EAAA,QAAA,EAAA,EAAA,EAAA,IAAA,EAAA,SAAS,cAFR,MAAM,EAAA,CAAA,CAAA;;4FAEP,SAAS,EAAA,UAAA,EAAA,CAAA;kBAHrB,UAAU;AAAC,YAAA,IAAA,EAAA,CAAA;AACV,oBAAA,UAAU,EAAE;AACb,iBAAA;;AAuaD;;;;;;;;;;;;AAYG;AACG,SAAU,4BAA4B,CAAC,QAAqB,EAAA;;;;;IAKhE,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,KAAK;QACxB,IAAI,EAAE,CAAC,CAAC,IAAI;QACZ,OAAO,EAAE,CAAC,CAAC;AACZ,KAAA,CAAC,CAAC;AACL;;ACxeA;;AAEG;;;;"}
1
+ {"version":3,"file":"c8y-ngx-components-ai.mjs","sources":["../../ai/ai.service.ts","../../ai/c8y-ngx-components-ai.ts"],"sourcesContent":["import { inject, Injectable } from '@angular/core';\nimport { FetchClient } from '@c8y/client';\nimport { Observable, Subscriber } from 'rxjs';\nimport {\n AgentDefinition,\n AgentHealthCheckResponse,\n AIAssistantMessage,\n AIMessage,\n AIMessagePart,\n AIStreamResponse,\n ClientAgentDefinition,\n ToolCallPart\n} from './ai.model';\n\n// Internal implementation detail; maybe we don't even need this enum since\nexport enum DataStreamType {\n TEXT_DELTA = 'text-delta',\n TOOL_CALL = 'tool-call',\n TOOL_INPUT_START = 'tool-input-start',\n TOOL_INPUT_DELTA = 'tool-input-delta',\n TOOL_CALL_STREAMING = 'tool-call-streaming',\n TOOL_CALL_DELTA = 'tool-call-delta',\n TOOL_RESULT = 'tool-result',\n REASONING = 'reasoning',\n REASONING_DELTA = 'reasoning-delta',\n REDACTED_REASONING = 'redacted-reasoning',\n REASONING_SIGNATURE = 'reasoning-signature',\n FINISH_REASONING = 'finish-reasoning',\n FINISH = 'finish',\n FINISH_STEP = 'finish-step',\n ERROR = 'error',\n DATA = 'data',\n MESSAGE_ANNOTATIONS = 'message-annotations',\n SOURCE = 'source',\n FILE = 'file',\n STEP_START = 'start-step',\n STEP_FINISH = 'finish-step'\n}\n\n/** This service manages communication with the AI Agent Manager microservice, supporting\n * management of agents, and sending requests to the agents.\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class AIService {\n private baseUrl = '/service/ai';\n private client: FetchClient;\n\n // nb: allowing the client to be passed in the constructor allows efficient unit testing without setting up the Angular TestBed\n constructor(client?: FetchClient) {\n this.client = client ?? inject(FetchClient);\n }\n\n /**\n * Creates or updates an agent.\n * @param def The agent definition\n */\n async createOrUpdateAgent(def: AgentDefinition): Promise<void> {\n const health = await this.getAgentHealth(def.name);\n let resource = `${this.baseUrl}/agent/${def.type}`;\n let method = 'POST';\n if (health.exists) {\n resource = `${this.baseUrl}/agent/${def.type}/${def.name}`;\n method = 'PUT';\n }\n const response = await this.client.fetch(resource, {\n body: JSON.stringify(def),\n method,\n headers: { 'Content-Type': 'application/json' }\n });\n\n if (!response.ok) {\n throw new Error(`Failed to create agent: ${response.statusText}`);\n }\n }\n\n /**\n * Check if an agent exists and is ready for use.\n * @param name Agent name (optional)\n * @param fromApp The app context path to check for an agent. This can be used, if the agent should get distributed by the plugin (optional).\n * @returns Agent health check response.\n */\n async getAgentHealth(name = '', fromApp?: string): Promise<AgentHealthCheckResponse> {\n const response = await this.client.fetch(\n `${this.baseUrl}/agent/test/${name || crypto.randomUUID()}${fromApp ? `?fromApp=${fromApp}` : ''}`,\n {\n method: 'GET',\n headers: { 'Content-Type': 'application/json' }\n }\n );\n\n if (!response.ok) {\n return {\n status: response.status === 403 ? 'missing-permissions' : 'missing-microservice',\n exists: false,\n canCreate: false,\n isProviderConfigured: false,\n messages: response.status === 403 ? [] : [response.statusText]\n };\n }\n const json: AgentHealthCheckResponse = await response.json();\n if (!json.isProviderConfigured) {\n json.status = 'missing-provider';\n } else if (!json.exists) {\n json.status = 'missing-agent';\n } else {\n json.status = 'ready';\n }\n return json;\n }\n\n /**\n * Send a text message to the agent.\n * @param name Agent name\n * @param messages The message to send, including any previous message history.\n * Typically you should use `defaultPruneMessagesForAgent` or a custom function to prepare the message history\n * by removing unnecessary content such as large/old tool inputs/outputs.\n * @param variables Variables to include\n * @param fromApp The app context path to check for an agent. This can be used, if the agent should get distributed by the plugin (optional).\n * @returns Text response from the agent.\n */\n async text(\n name: string,\n messages: AIMessage[],\n variables: { [key: string]: any },\n fromApp?: string\n ): Promise<string> {\n const parsedMessages = this.convertToAgentMessageFormat(messages);\n\n const data = this.client.fetch(\n `${this.baseUrl}/agent/text/${name}${fromApp ? `?fromApp=${fromApp}` : ''}`,\n {\n body: JSON.stringify({ messages: parsedMessages, variables }),\n method: 'POST',\n headers: { 'Content-Type': 'application/json' }\n }\n );\n\n const response = await data;\n if (!response.ok) {\n throw new Error(`Failed to talk with agent: ${response.statusText}`);\n }\n const text = await response.text();\n return text;\n }\n\n /**\n * Stream a text message to the agent.\n * @param agent Agent name or an agent definition.\n * @param messages The message to send, including any previous message history.\n * Typically you should use `defaultPruneMessagesForAgent` or a custom function to prepare the message history\n * by removing unnecessary content such as large/old tool inputs/outputs.\n * @param variables Variables to include\n * @param abortController An AbortController to cancel the request.\n * @param fromApp The app context path to check for an agent. This can be used, if the agent should get distributed by the plugin (optional).\n * @returns An observable that emits AIStreamResponse including partial `AIMessage` objects as they are received.\n * When additional useful metadata is available, this will be streamed with type indicating it is metadata.\n * The observable can be cancelled using the provided AbortController.\n * The observable will emit an error if the request fails or is aborted.\n * The observable will complete when the stream is finished.\n *\n * The messages sent to the agent can include special options:\n * - `hiddenContent`: If set, this content will be sent to the agent instead of the `content` field.\n * - `skipToLLM`: If set to true, this message will be skipped when sending to the agent.\n *\n * Example usage:\n * ```typescript\n * const abortController = new AbortController();\n * const messages: AIMessage[] = [\n * { role: 'user', content: 'Hello' },\n * { role: 'assistant', content: 'Hi there!' },\n * { role: 'user', content: 'Tell me a joke.', options: { hiddenContent: 'Tell me a joke about cats.' } }\n * ];\n * const observable = aiService.stream$('my-agent', messages, {}, abortController);\n * const subscription = observable.subscribe({\n * next: (response) => { console.log('Received message update:', response.message); },\n * error: (err) => console.error('Error:', err),\n * complete: () => console.log('Stream complete')\n * });\n *\n * // To cancel the request:\n * abortController.abort();\n * subscription.unsubscribe();\n * ```\n */\n async stream$(\n agent: string | ClientAgentDefinition,\n messages: AIMessage[],\n variables: { [key: string]: any },\n abortController: AbortController,\n fromApp?: string\n ): Promise<Observable<AIStreamResponse>> {\n const parsedMessages = this.convertToAgentMessageFormat(messages);\n\n const agentName = typeof agent === 'string' ? agent : agent.definition.name;\n const useTest = typeof agent !== 'string' && agent.snapshot;\n const baseUrl = useTest\n ? `${this.baseUrl}/agent/test/text`\n : `${this.baseUrl}/agent/text/${agentName}`;\n let body = JSON.stringify({ messages: parsedMessages, variables });\n if (useTest) {\n const agentCopy = {\n ...agent.definition\n };\n agentCopy.agent['messages'] = parsedMessages;\n agentCopy.agent['variables'] = variables;\n body = JSON.stringify(agentCopy);\n }\n\n const response = await this.client.fetch(\n `${baseUrl}?fullResponse=true${fromApp ? `&fromApp=${fromApp}` : ''}`,\n {\n method: 'POST',\n body,\n headers: {\n ...this.client.defaultHeaders,\n 'content-type': 'application/json',\n accept: 'text/event-stream'\n },\n signal: abortController.signal\n }\n );\n\n const stream = response.body;\n const decoder = new TextDecoder();\n\n return new Observable<AIStreamResponse>(observer => {\n if (response.status > 300) {\n response\n .json()\n .then(data => {\n observer.error(`Error communicating with server: ${JSON.stringify(data, null, 2)}`);\n })\n .catch(err => {\n observer.error(\n `Error communicating with server: HTTP ${response.status}: ${response.statusText}; ${err}`\n );\n });\n return;\n }\n\n if (!stream) {\n observer.error('Server error - no response body');\n return;\n }\n\n const reader = stream.getReader();\n const message: AIAssistantMessage = {\n role: 'assistant',\n content: []\n };\n\n const abortHandler = () => {\n reader.cancel();\n observer.error(new DOMException('Aborted', 'AbortError'));\n };\n\n abortController.signal.addEventListener('abort', abortHandler);\n\n let buffer = '';\n\n const read = () => {\n reader.read().then(({ done, value }) => {\n if (done) {\n if (buffer.trim()) this.processLine(buffer, observer, message); // process any remaining data\n observer.complete();\n return;\n }\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n\\n');\n buffer = lines.pop() || '';\n for (const line of lines) {\n if (line.trim()) this.processLine(line, observer, message);\n }\n read();\n });\n };\n\n read();\n return () => {\n abortController.signal.removeEventListener('abort', abortHandler);\n reader.cancel();\n };\n });\n }\n\n protected convertToAgentMessageFormat(messages: AIMessage[]): object[] {\n // We will need to rewrite this to include tool outputs soon (effectively this means targetting LanguageModelV*ToolResultOutput).\n // Once we have more fields than just role and content, we will need to convert between our format and\n // the Vercel format expected by the agent manager (e.g. steps->content parts)\n return messages.map(m => ({\n role: m.role,\n content:\n m.role === 'assistant'\n ? m.content\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map(part => part.text)\n .join('\\n\\n')\n : m.content\n }));\n }\n\n /**\n * Convert a tool output from the MCP/wire format (which is different/more compact than LanguageModelV3ToolResultOutput)\n * into our own standard representation, which can be roundtripped to the format we need to provide when making future requests.\n *\n * Handles different data types from Vercel's streaming API:\n * - Text: stored as simple string in output field\n * - JSON objects: stored as-is in output field\n * - Content arrays: stored in output field with outputType=\"content\" to enable roundtripping\n * - Single text in content array: unwrapped to simple string for simpler handling (and easier truncation)\n * - Errors: error flag set to true\n */\n protected convertStreamingToolOutputToToolCallPart(output: any, target: ToolCallPart) {\n if (!output) {\n return;\n }\n\n if (output.isError || output.type === 'error-text' || output.type === 'error-json')\n target.error = true;\n\n // Handle content array format from streaming API\n if (output.content && Array.isArray(output.content)) {\n // Single text element - unwrap to simple string for simplicity\n if (output.content.length === 1 && output.content[0].type === 'text') {\n target.output = output.content[0].text;\n return;\n }\n\n // Multiple elements or mixed types - preserve as content array\n target.output = output.content;\n target.outputType = 'content'; // Mark as content to enable roundtripping\n return;\n }\n\n // Plain string or structured (JSON-serializable) object - store as-is\n target.output = output;\n }\n\n /** Add the specified tool call info to the current step. If this toolCallId is already known,\n * updates it rather than adding a new one, since for UI rendering and compactness of data it's\n * easiest to just have one item per tool call.\n *\n * Returns the changed item.\n */\n private addToolCallInfo(\n type: ToolCallPart['type'],\n rawInfo: any,\n addTo: AIMessagePart[]\n ): ToolCallPart {\n // Vercel v4 seems to set this to \"id\" not \"toolCallId\" in some places despite doc to the contrary, so normalize it here\n if (!rawInfo.toolCallId) rawInfo.toolCallId = rawInfo.id;\n\n let existing: ToolCallPart | undefined = addTo.find(\n (tc): tc is ToolCallPart =>\n tc.type.startsWith('tool-') && (tc as ToolCallPart).toolCallId === rawInfo.toolCallId\n );\n\n if (existing) {\n existing.type = type;\n } else if (!existing) {\n existing = { type: type, toolName: rawInfo.toolName, toolCallId: rawInfo.toolCallId };\n addTo.push(existing);\n }\n if (rawInfo?.input) existing.input = rawInfo.input;\n if (rawInfo?.output) this.convertStreamingToolOutputToToolCallPart(rawInfo.output, existing);\n\n return existing;\n }\n\n /** Unpacks data from the Vercel Data Stream Protocol (sent by the Agent Manager over SSE) to update the message\n *\n * See streamText().fullStream() from https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#data-stream-protocol\n *\n * This is similar to what the Vercel `toUIMessageStreamResponse` API does (though it'd need the agent manager to publish the\n * UIMessageStream which has a bit more - useful - data than what is included here).\n *\n * We always use the same parts object, to make it easier for consumers (eg. agent-chat)\n * to add items to the list and have them still there on the next update from this service.\n */\n private processLine(\n line: string,\n observer: Subscriber<AIStreamResponse>,\n message: AIAssistantMessage\n ) {\n if (!line.trim()) {\n return;\n }\n\n try {\n let data: any = {};\n let type = '';\n try {\n data = JSON.parse(line.replace('data: ', ''));\n type = data.type;\n } catch (e) {\n console.error('Error parsing line from AI response: ', line, e);\n return;\n }\n\n let lastPart = !message.content ? undefined : message.content[message.content.length - 1];\n\n switch (type) {\n case DataStreamType.STEP_START:\n if (data.request && data.request.body) {\n observer.next({\n message: message,\n changedPart: {\n type: 'response-metadata',\n model: data.request.body.model,\n systemPrompt: data.request.body.systemPrompt\n }\n });\n }\n // Don't add consecutive duplicate step bounaries\n if (!lastPart || lastPart.type !== 'step-start') {\n message.content.push({ type: 'step-start' });\n observer.next({ message, changedPart: message.content[message.content.length - 1] });\n }\n\n return;\n\n case DataStreamType.REASONING_DELTA:\n const reasoning = data.text;\n if (!reasoning) return;\n if (lastPart?.type === 'reasoning') {\n lastPart.text += reasoning;\n } else {\n lastPart = { type: 'reasoning', text: reasoning };\n message.content.push(lastPart);\n }\n observer.next({ message, changedPart: lastPart });\n return;\n\n case DataStreamType.TEXT_DELTA:\n const text = data.textDelta || data.text;\n if (!text) return;\n if (lastPart?.type === 'text') {\n lastPart.text += text;\n } else {\n lastPart = { type: 'text', text: text };\n message.content.push(lastPart);\n }\n observer.next({ message, changedPart: lastPart });\n return;\n\n case DataStreamType.TOOL_INPUT_START:\n observer.next({\n message,\n changedPart: this.addToolCallInfo('tool-input-streaming', data, message.content)\n });\n return;\n\n case DataStreamType.TOOL_CALL:\n observer.next({\n message,\n changedPart: this.addToolCallInfo('tool-executing', data, message.content)\n });\n return;\n\n case DataStreamType.TOOL_RESULT:\n observer.next({\n message,\n changedPart: this.addToolCallInfo('tool-result', data, message.content)\n });\n return;\n\n case DataStreamType.FINISH:\n message.finishReason = data.finishReason; // FUTURE could be anything, may not match the options in AIMessage\n observer.next({ message, changedPart: undefined });\n observer.complete();\n return;\n\n case DataStreamType.ERROR:\n message.finishReason = 'error';\n observer.next({ message, changedPart: undefined });\n observer.error(data?.message || data?.errorText || data);\n // Error is instead of completing the stream\n return;\n\n // Should we also handle other types such as \"abort\"?\n }\n } catch (e) {\n observer.error(e);\n }\n }\n}\n\n/**\n * The default implementation of for reducing the size of the message history so it is ready to be sent to the LLM agent.\n *\n * This is important since old tool inputs and outputs can be very large and fill up the agent's context window.\n *\n * Implements `pruneMessagesFunction`.\n *\n * When sending an AI request you can provide your own function instead of using this one,\n * or you can write your own function that calls this and adds extra logic,\n * for example to suppress specific tools from the AIMessage, or\n * retain only the final step text in multi-step responses, etc.\n *\n * The current default implementation preserves text content, but does not include any tool calls.\n * This may change in future releases.\n */\nexport function defaultPruneMessagesForAgent(messages: AIMessage[]): AIMessage[] {\n // When we change this to include tool calls, we should remove large inputs and truncate large and/or old outputs\n // to avoid too many tokens and context window consumption.\n // Some applications will want to entirely remove specific tool calls that have only transient use,\n // which can be done by providing their own pruneMessagesForAgent function.\n return messages.map(m =>\n m.role !== 'assistant'\n ? {\n role: m.role,\n content: m.content\n }\n : {\n role: m.role,\n content: [\n {\n type: 'text',\n text: m.content\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map(part => part.text)\n .join('\\n\\n')\n }\n ]\n }\n );\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":";;;;;;AAcA;IACY;AAAZ,CAAA,UAAY,cAAc,EAAA;AACxB,IAAA,cAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,cAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvB,IAAA,cAAA,CAAA,kBAAA,CAAA,GAAA,kBAAqC;AACrC,IAAA,cAAA,CAAA,kBAAA,CAAA,GAAA,kBAAqC;AACrC,IAAA,cAAA,CAAA,qBAAA,CAAA,GAAA,qBAA2C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CAAC,CAAC,IAAI,KAA6C,IAAI,CAAC,IAAI,KAAK,MAAM;yBAC7E,GAAG,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI;yBACrB,IAAI,CAAC,MAAM;AACf;AACF;AACF,SAAA,CACN;AACH;;AChhBA;;AAEG;;;;"}
@@ -1560,20 +1560,23 @@ class WidgetConfigMigrationService {
1560
1560
  * // }
1561
1561
  * ```
1562
1562
  */
1563
- migrateWidgetConfig(config) {
1563
+ migrateWidgetConfig(config, options) {
1564
1564
  // Guard: Handle invalid config
1565
1565
  if (!config) {
1566
1566
  return config;
1567
1567
  }
1568
1568
  // Cast to unknown first, then to our working type
1569
- const configObj = config;
1569
+ const rawConfig = config;
1570
+ const configObj = options?.legacyTimeContextDefaults && this.hasNoTimeContextFields(rawConfig)
1571
+ ? { ...rawConfig, ...options.legacyTimeContextDefaults }
1572
+ : rawConfig;
1570
1573
  // Check if already has valid new format (minimal check)
1571
1574
  const hasValidDisplayMode = typeof configObj.displayMode === 'string' && this.isValidDisplayMode(configObj.displayMode);
1572
1575
  const hasValidRefreshOption = typeof configObj.refreshOption === 'string' &&
1573
1576
  this.isValidRefreshOption(configObj.refreshOption);
1574
1577
  // If has basic valid format and no legacy fields needing migration, return as is
1575
1578
  if (hasValidDisplayMode && hasValidRefreshOption && !this.hasLegacyFields(configObj)) {
1576
- return config;
1579
+ return configObj;
1577
1580
  }
1578
1581
  // Extract settings from all levels (including nested) for migration decisions
1579
1582
  const settingsForMigration = this.extractGlobalContextSettings(configObj);
@@ -1583,6 +1586,23 @@ class WidgetConfigMigrationService {
1583
1586
  this.applyGlobalContextProperties(flatConfig, settingsForMigration);
1584
1587
  return flatConfig;
1585
1588
  }
1589
+ /**
1590
+ * True when a config carries neither the new `dateTimeContext` nor any legacy time
1591
+ * field (`dateFrom`, `dateTo`, `dateFilter`, `date`, `interval`). Use to decide
1592
+ * whether widget-specific legacy defaults should be applied.
1593
+ */
1594
+ hasNoTimeContextFields(config) {
1595
+ if (!config) {
1596
+ return false;
1597
+ }
1598
+ const raw = config;
1599
+ return (!raw['dateTimeContext'] &&
1600
+ !raw['dateFrom'] &&
1601
+ !raw['dateTo'] &&
1602
+ !raw['dateFilter'] &&
1603
+ !raw['date'] &&
1604
+ !raw['interval']);
1605
+ }
1586
1606
  /**
1587
1607
  * Creates a flattened configuration by excluding nested configuration objects.
1588
1608
  *