import { SupportedIconsSuggestions } from '@c8y/ngx-components/icon-selector/icons';
import * as i0 from '@angular/core';
import { Type } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { FetchClient } from '@c8y/client';
import { Observable } from 'rxjs';

/**
 * A message exchanged between the user and the AI assistant.
 */
type AIMessage = AIAssistantMessage | AIUserMessage | AISystemMessage;
/**
 * A message entered by the user.
 */
type AIUserMessage = {
    role: 'user';
    content: string;
    timestamp?: string;
};
/** A hidden "system" message (like a system prompt, but later in the message stream). */
type AISystemMessage = {
    role: 'system';
    content: string;
    timestamp?: string;
};
/** A message from the AI assistant. */
interface AIAssistantMessage {
    role: 'assistant';
    content: AIMessagePart[];
    timestamp?: string;
    finishReason?: string;
    usage?: {
        inputTokens: number | undefined;
        outputTokens: number | undefined;
        totalTokens: number | undefined;
    };
}
/** The part of an AI message representing a call to a tool (which may or may not have completed and a result is available). */
interface ToolCallPart<TInput extends Record<string, any> = Record<string, unknown>, TOutput = unknown> {
    /** The status of the tool call - whether it is currently streaming its input, in progress, or has completed and a result (output or error) is available */
    type: 'tool-input-streaming' | 'tool-executing' | 'tool-result';
    /** Unique identifier for the tool, as specified in the MCP server and agent definition. */
    toolName: string;
    /** Unique identifier for this invocation of the tool, used to match calls with results. */
    toolCallId: string;
    /**
     * An object representing the input arguments given to the tool.
     * This field is set once it is available, and is complete once the type changes to `tool-executing`.
     */
    input?: TInput;
    /**
     * The output generated by the tool. This field is set once the type is `tool-result`. It can also be updated by the UI client.
     *
     * This can be a string, a JSON-serializable object, or (for multi-part outputs) an array of content parts.
     */
    output?: TOutput;
    /**
     * If the output was not a string or a JSON object, records the format it was received in to support accurate round-tripping
     * when the tool output is included in future requests.
     * For example, "content" indicates the output is a multi-part content array.
     */
    outputType?: 'content' | string;
    /** Set to true for a tool-result where an error occurred. The error message or JSON is in the output field. */
    error?: boolean;
}
/** Parts that make up the content of a message (typically an assistant message). */
type AIMessagePart = {
    type: 'text' | 'reasoning';
    text: string;
} | {
    type: 'object';
    jsonContent: string;
} | {
    type: 'step-start';
} | ToolCallPart;
/** Additional data received while streaming a response that is not part of AIMessage itself. */
type ResponseMetadataPart = {
    type: 'response-metadata';
    /** The identifier of the model being used. */
    model?: string;
    /** The system prompt(s) in use. */
    systemPrompt?: Array<{
        text: string;
        type: string;
    }>;
};
/** The values returned by the observer for an AI response stream.
 *
 * This can be either an updated assistant message, or response metadata that isn't part of the AIMessage.
 */
type AIStreamResponse = {
    message: AIAssistantMessage;
    /**
     * Specifies which message part was changed.
     *
     * Some part types will be repeatedly modified as results stream in (e.g. executing tool calls) but for others
     * (e.g. tool results) the changedPart will be sent just one, allowing this to be used for invoking callbacks etc.
     *
     * This is also used for metadata updates (that do not affect AIMessage).
     */
    changedPart?: AIMessagePart | ResponseMetadataPart;
};
interface ClientAgentDefinition {
    /**
     * Usually this is false (production mode).
     * If set to true, the agent will use the test endpoint to generate responses (requires admin permissions for the agent manager).
     * This is useful for development and testing purposes, but requires agent admin privileges.
     */
    snapshot: boolean;
    /**
     * The label of the agent that is shown to the user.
     */
    label: string;
    /**
     * The definition of the agent to use
     */
    definition: AgentDefinition;
}
/**
 * Configuration for creating/updating an AI agent including its unique name, the system prompt,
 * and the tools and MCP servers available to it.
 */
interface AgentDefinition {
    /** The unique identifier for this agent. Always include an application/plugin-specific prefix, for example "my-plugin-name". */
    name: string;
    /**
     * Specifies the agent's interaction type.
     * `'text'` indicates this is a text-based conversational agent. You can use a `object` agent to build a agent that only returns structural data such as JSON.
     */
    type: 'object' | 'text';
    agent: {
        /** The system prompt */
        system: string;
        /** Custom provider-specific configuration properties. */
        [key: string]: any;
    };
    /** The tools this agent can use from the configured MCP servers. */
    mcp?: Array<{
        serverName: string;
        tools: string[];
    }>;
}
/** Configuration for the `ai-chat` component. */
interface ChatConfig {
    /** A small title to display under the headline */
    title: string;
    /** Text to display in a heading at the top of the welcome message, and to use for ARIA */
    headline: string;
    /** Welcome text, in markdown format */
    welcomeText: string;
    /** The position of the welcome area in the chat window */
    welcomePosition: 'top' | 'bottom' | 'center';
    /** The message displayed in the input box before the user types their message */
    placeholder: string;
    /** Default is horizontal */
    suggestionsLayout?: 'vertical' | 'horizontal';
    /** Hide scrollbar except when hovering over the chat conversation (default: false) */
    scrollbarOnlyOnHover?: boolean;
    /** By default a framed appearance is used; use this to choose a flat appearance with no shading instead. */
    appearance?: 'framed' | 'flat';
    sendButtonText: string;
    cancelButtonText: string;
    disclaimerText: string;
    userInterfaceIcons: {
        send: string;
        cancel: string;
    };
}
/** Configuration for the `c8y-agent-chat` component. */
interface AgentChatConfig extends ChatConfig {
    /** When true, shows cumulative token usage for the entire conversation. Default: false. */
    showCumulativeUsage?: boolean;
    /** When true, shows per-message token usage. Default: false. */
    showUsagePerMessage?: boolean;
    /** When true, shows a delete button on the last completed assistant message to remove the last exchange. Default: false. */
    showDeleteAction?: boolean;
}
/** Configuration for how the `<ai-chat-assistant-message>` displays a calls for a specific tool name to the user. */
type ToolCallConfig = {
    /**
     * Whether this tool should be promoted to a more prominent positions alongside the main answer
     * rather than kept in the thinking area with tool calls that are of less interest.
     * For example a tool that produces user-visible artifacts/outputs would be shown by the main answer
     * so that the user can look at the change, whereas a tool that just looks up some information for the
     * AI agent would be displayed in its normal position.
     */
    isShownWithMainAnswer?: boolean;
} & ({
    /** The label to use when the tool has completed e.g. "Read the documentation". */
    completedLabel?: string;
    /** The label to use while the tool is in progress e.g. "Reading documentation". */
    executingLabel?: string;
    /** Dynamically provides a translated label for the tool based on its current state. Return undefined for a default label.
     * The returned string can either be a `gettext` that will be passed through the translate pipe, or a fully translated string (in case interpolation is required).
     */
    labelProvider?: (toolCallPart: ToolCallPart, translateService: TranslateService) => string | undefined;
    /** Whether this tool should be hidden from the UI entirely (e.g. because it's only used for internal purposes). */
    isHidden?: boolean;
    component?: never;
} | {
    /**
     * A custom Angular component to render the details of this tool call.
     *
     * This allows you to provide rich rendering for "artifact" tools that produce some kind of user-visible output (e.g. a code diff), or for error cases where there is some useful content to display.
     */
    component: Type<unknown>;
    completedLabel?: never;
    executingLabel?: never;
    labelProvider?: never;
    isHidden?: never;
});
/** Configuration for how the `<ai-chat-assistant-message>` displays messages from the AI assistant. */
interface AssistantMessageDisplayConfig {
    /**
     * Optional configuration that controls how tool calls are displayed.
     * It can be used to provide localized display names, and to identify tools that should be hidden,
     * and tools that require additional prominence in the user interface because they produce user-visible
     * artifacts/outputs such as code changes.
     *
     * It is recommended to define your `toolCallConfig` in the same place you define `ClientAgentDefinition`,
     * and to use the keys from toolCallConfig in the `ClientAgentDefinition` tools list.
     */
    toolCallConfig?: Record<string, ToolCallConfig>;
    /**
     * Provides an Angular component to display details about a tool call, which can be rendered in a collapsible panel in the UI.
     *
     * This function allows you to provide rendering for "artifact" tools that produce some kind of user-visible output
     * (e.g. a code diff) that you wish to display,or for error cases where there is some useful content to display.
     *
     * Often tools with a custom rendering component will also be have the `ToolCallConfig.isShownWithMainAnswer`
     * flag set to ensure they are prominently displayed alongside the main answer.
     *
     * Return undefined for tools where there is no detail to show; you may also wish to return undefined if the
     * tool has not yet finished and returned a result.
     */
    toolDetailsComponent?: (toolCallPart: ToolCallPart) => Type<any> | undefined;
    /**
     * Controls whether a JSON representation of the tool details (inputs and outputs) is shown,
     * for tools that do not have a dedicated `toolDetailsComponent`.
     */
    showDefaultToolDetails?: 'none' | 'all';
    /**
     * The text in the last step that contains the main answer from the agent; this configuration
     * parameter decides how content from intermediate steps while the agent was thinking gets displayed.
     *
     * Options are:
     * - 'collapsible-thinking-block': intermediate steps are shown in a separate collapsible "thinking" block,
     *    which is visually separated from the main answer text.
     *    This helps the user focus on the final answer and not get distracted by the agent's internal thought process,
     *    which can be long and not so relevant to the user.
     *    It also makes it clearer what the final answer is, especially if the agent goes through a long thought process with many steps.
     *
     * - 'main-answer': intermediate step text is shown as part of the main answer.
     *    This can be useful if the intermediate step text is actually important for the user to see and you don't want it to be hidden in a collapsible block.
     *    However, it can also make it harder for the user to identify the final answer, especially if there are many steps.
     *
     * - 'muted-main-answer': same as 'main-answer', but with muted styling (e.g. lighter color).
     *    This is a middle ground between the other two options, where the intermediate step text is still shown as part of the main answer, but with less visual emphasis than the final step text.
     *    This can help the user distinguish between the final answer and the intermediate steps, while still keeping all the information visible.
     */
    experimental_nonFinalStepTextDisplay?: 'collapsible-thinking-block' | 'main-answer' | 'muted-main-answer';
    /**
     * By default we assume that most responses will require one round of tool calls which means we expect `2` steps.
     * Therefore as the first step streams in we render it as "thinking" content rather than as the main answer from the agent.
     *
     * For applications where it's likely most answers are a single step (no tool calls), set this flag to `1` to treat the
     * initial step as the main answer (unless other step content comes in).
     *
     * Setting this expectation for your application heuristically minimizes the need to transition text between the
     * main answer and step thinking styles.
     */
    experimental_expectedStepCount?: number;
}
/** Type for a function that prunes the message history to remove large or unnecessary messages and message parts. */
type pruneMessagesFunction = (messages: AIMessage[]) => AIMessage[];
/**
 * Configuration for the widget agent chat component.
 * These correspond to inputs of the same name on `AgentChatComponent`.
 */
interface WidgetAiChatSectionComponentConfig {
    assistantMessageDisplayConfig?: AssistantMessageDisplayConfig;
    preprocessAgentMessage?: (message: AIAssistantMessage, changedPart: AIStreamResponse['changedPart']) => AIMessage;
    pruneMessagesForAgent?: pruneMessagesFunction;
}
type JsonValue = string | number | boolean | null | JsonValue[] | {
    [key: string]: JsonValue;
};
/** Opaque snapshot of chat history that can be safely serialized to JSON. */
type ChatHistory = JsonValue;
/** Configuration for controlling what gets saved in chat history by the `agent-chat`. */
interface ChatHistoryConfig {
    /** Maximum total number of recent messages to keep when saving. Default: unlimited */
    maxMessages?: number;
    /** A list of tool names whose results should never be persisted to the history (due to being low value, or excessively large). */
    transientToolNames?: string[];
}
/** Suggested prompts that can be selected by the user. */
type Suggestion = {
    label?: string;
    prompt: string;
    icon?: SupportedIconsSuggestions;
};
/**
 * Response from the non-streaming debug/test endpoint for object-type agents.
 * Contains the structured JSON output plus usage information.
 */
interface ObjectAgentResponse {
    /** The structured JSON object returned by the agent. */
    object: Record<string, unknown>;
    /** Token usage for this response. */
    totalUsage?: {
        inputTokens: number;
        outputTokens: number;
        totalTokens: number;
    };
}
interface AgentHealthCheckResponse {
    /** This field indicates summarizes the most serious current health problem with the agent, or "ok" if none.
     * This can be used to generate useful error messages in the front-end.
     *
     */
    status?: 'missing-microservice' | 'missing-permissions' | 'missing-provider' | 'missing-agent' | 'ready';
    /**
     * Indicates if the agent exists and can be used.
     * If false, the agent was not found.
     */
    exists: boolean;
    /**
     * Indicates if the user can create the agent, and if a global provider is configured.
     */
    canCreate: boolean;
    /**
     * Indicates if the provider is configured.
     * If false, the agent cannot be created as the provider is not configured.
     */
    isProviderConfigured: boolean;
    /**
     * If canCreate or exist is false, this array contains messages from the backend
     * that explain why the agent cannot be used or created.
     * These messages may not be translated.
     */
    messages?: string[];
}

declare enum DataStreamType {
    TEXT_DELTA = "text-delta",
    TOOL_CALL = "tool-call",
    TOOL_INPUT_START = "tool-input-start",
    TOOL_INPUT_DELTA = "tool-input-delta",
    TOOL_CALL_STREAMING = "tool-call-streaming",
    TOOL_CALL_DELTA = "tool-call-delta",
    TOOL_RESULT = "tool-result",
    REASONING = "reasoning",
    REASONING_DELTA = "reasoning-delta",
    REDACTED_REASONING = "redacted-reasoning",
    REASONING_SIGNATURE = "reasoning-signature",
    FINISH_REASONING = "finish-reasoning",
    FINISH = "finish",
    FINISH_STEP = "finish-step",
    ERROR = "error",
    DATA = "data",
    MESSAGE_ANNOTATIONS = "message-annotations",
    SOURCE = "source",
    FILE = "file",
    STEP_START = "start-step",
    STEP_FINISH = "finish-step"
}
/** This service manages communication with the AI Agent Manager microservice, supporting
 * management of agents, and sending requests to the agents.
 */
declare class AIService {
    private baseUrl;
    private client;
    constructor(client?: FetchClient);
    /**
     * Creates or updates an agent.
     * @param def The agent definition
     */
    createOrUpdateAgent(def: AgentDefinition): Promise<void>;
    /**
     * Check if an agent exists and is ready for use.
     * @param name Agent name (optional)
     * @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).
     * @returns Agent health check response.
     */
    getAgentHealth(name?: string, fromApp?: string): Promise<AgentHealthCheckResponse>;
    /**
     * Send a text message to the agent.
     * @param name Agent name
     * @param messages The message to send, including any previous message history.
     * Typically you should use `defaultPruneMessagesForAgent` or a custom function to prepare the message history
     * by removing unnecessary content such as large/old tool inputs/outputs.
     * @param variables Variables to include
     * @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).
     * @returns Text response from the agent.
     */
    text(name: string, messages: AIMessage[], variables: Record<string, unknown>, fromApp?: string): Promise<string>;
    /**
     * Send messages to an object-type agent via the non-streaming test endpoint.
     * Object agents return a single structured JSON response rather than a stream.
     *
     * @param agent A ClientAgentDefinition with `snapshot: true` (required for test endpoint).
     * @param messages Messages to send
     * @param variables Variables to include
     * @param abortController An AbortController to cancel the request.
     * @returns The full response including the structured object and usage information.
     */
    callObjectAgent(agent: string | ClientAgentDefinition, messages: AIMessage[], variables: Record<string, unknown>, abortController: AbortController): Promise<ObjectAgentResponse>;
    /**
     * Stream a text message to the agent.
     * @param agent Agent name or an agent definition.
     * @param messages The message to send, including any previous message history.
     * Typically you should use `defaultPruneMessagesForAgent` or a custom function to prepare the message history
     * by removing unnecessary content such as large/old tool inputs/outputs.
     * @param variables Variables to include
     * @param abortController An AbortController to cancel the request.
     * @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).
     * @returns An observable that emits AIStreamResponse including partial `AIMessage` objects as they are received.
     * When additional useful metadata is available, this will be streamed with type indicating it is metadata.
     * The observable can be cancelled using the provided AbortController.
     * The observable will emit an error if the request fails or is aborted.
     * The observable will complete when the stream is finished.
     *
     * The messages sent to the agent can include special options:
     * - `hiddenContent`: If set, this content will be sent to the agent instead of the `content` field.
     * - `skipToLLM`: If set to true, this message will be skipped when sending to the agent.
     *
     * Example usage:
     * ```typescript
     * const abortController = new AbortController();
     * const messages: AIMessage[] = [
     *   { role: 'user', content: 'Hello' },
     *   { role: 'assistant', content: 'Hi there!' },
     *   { role: 'user', content: 'Tell me a joke.', options: { hiddenContent: 'Tell me a joke about cats.' } }
     * ];
     * const observable = aiService.stream$('my-agent', messages, {}, abortController);
     * const subscription = observable.subscribe({
     *   next: (response) => { console.log('Received message update:', response.message); },
     *   error: (err) => console.error('Error:', err),
     *   complete: () => console.log('Stream complete')
     * });
     *
     * // To cancel the request:
     * abortController.abort();
     * subscription.unsubscribe();
     * ```
     */
    stream$(agent: string | ClientAgentDefinition, messages: AIMessage[], variables: {
        [key: string]: any;
    }, abortController: AbortController, fromApp?: string): Promise<Observable<AIStreamResponse>>;
    protected convertToAgentMessageFormat(messages: AIMessage[]): object[];
    /**
     * Convert a tool output from the MCP/wire format (which is different/more compact than LanguageModelV3ToolResultOutput)
     * into our own standard representation, which can be roundtripped to the format we need to provide when making future requests.
     *
     * Handles different data types from Vercel's streaming API:
     * - Text: stored as simple string in output field
     * - JSON objects: stored as-is in output field
     * - Content arrays: stored in output field with outputType="content" to enable roundtripping
     * - Single text in content array: unwrapped to simple string for simpler handling (and easier truncation)
     * - Errors: error flag set to true
     */
    protected convertStreamingToolOutputToToolCallPart(output: any, target: ToolCallPart): void;
    /** Add the specified tool call info to the current step. If this toolCallId is already known,
     * updates it rather than adding a new one, since for UI rendering and compactness of data it's
     * easiest to just have one item per tool call.
     *
     * Returns the changed item.
     */
    private addToolCallInfo;
    /** Unpacks data from the Vercel Data Stream Protocol (sent by the Agent Manager over SSE) to update the message
     *
     * See streamText().fullStream() from https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#data-stream-protocol
     *
     * This is similar to what the Vercel `toUIMessageStreamResponse` API does (though it'd need the agent manager to publish the
     * UIMessageStream which has a bit more - useful - data than what is included here).
     *
     * We always use the same parts object, to make it easier for consumers (eg. agent-chat)
     * to add items to the list and have them still there on the next update from this service.
     */
    private processLine;
    static ɵfac: i0.ɵɵFactoryDeclaration<AIService, never>;
    static ɵprov: i0.ɵɵInjectableDeclaration<AIService>;
}
/**
 * The default implementation of for reducing the size of the message history so it is ready to be sent to the LLM agent.
 *
 * This is important since old tool inputs and outputs can be very large and fill up the agent's context window.
 *
 * Implements `pruneMessagesFunction`.
 *
 * When sending an AI request you can provide your own function instead of using this one,
 * or you can write your own function that calls this and adds extra logic,
 * for example to suppress specific tools from the AIMessage, or
 * retain only the final step text in multi-step responses, etc.
 *
 * The current default implementation preserves text content, but does not include any tool calls.
 * This may change in future releases.
 */
declare function defaultPruneMessagesForAgent(messages: AIMessage[]): AIMessage[];

export { AIService, DataStreamType, defaultPruneMessagesForAgent };
export type { AIAssistantMessage, AIMessage, AIMessagePart, AIStreamResponse, AISystemMessage, AIUserMessage, AgentChatConfig, AgentDefinition, AgentHealthCheckResponse, AssistantMessageDisplayConfig, ChatConfig, ChatHistory, ChatHistoryConfig, ClientAgentDefinition, ObjectAgentResponse, ResponseMetadataPart, Suggestion, ToolCallConfig, ToolCallPart, WidgetAiChatSectionComponentConfig, pruneMessagesFunction };
//# sourceMappingURL=index.d.ts.map
