UNPKG

@squidcloud/client

Version:

A typescript implementation of the Squid client

1,164 lines (1,163 loc) 47 kB
import { JSONSchema } from 'json-schema-typed'; import { AiAudioCreateSpeechModelName, AiAudioTranscriptionModelName, AiChatModelName, AiImageModelName, AiProviderType, AiRerankProvider, AnthropicChatModelName, GeminiChatModelName, GrokChatModelName, ModelIdSpec, OpenAiAudioCreateSpeechModelName, OpenAiAudioTranscriptionModelName, OpenAiChatModelName, OpenAiCreateSpeechFormat, OpenAiImageModelName } from './ai-common.public-types'; import { AiContextMetadata, AiContextMetadataFilter, AiKnowledgeBaseContextType, AiRagType } from './ai-knowledge-base.public-types'; import { AiFunctionId, AiFunctionIdWithContext, UserAiChatModelName } from './backend.public-types'; import { AiAgentId, AiContextId, AiKnowledgeBaseId, AppId, IntegrationId } from './communication.public-types'; import { DocumentExtractionMethod } from './extraction.public-types'; import { IntegrationType } from './integration.public-types'; import { JobId } from './job.public-types'; import { SecretKey } from './secret.public-types'; /** * @category AI */ export type AiGenerateImageOptions = GptImageOptions | StableDiffusionCoreOptions | FluxOptions; /** * @category AI */ export type OpenAiAudioTranscribeOptions = WhisperTranscribeOptions | Gpt4oTranscribeOptions; /** * @category AI */ export type AiAudioTranscribeOptions = OpenAiAudioTranscribeOptions; /** * @category AI */ export type AiAudioCreateSpeechOptions = OpenAiCreateSpeechOptions; /** * Base options for generating images with an AI model. * @category AI */ export interface BaseAiGenerateImageOptions { /** The name of the AI model to use for image generation. */ modelName: AiImageModelName; } /** * Base options for transcribing audio with an AI model. * @category AI */ export interface BaseAiAudioTranscribeOptions { /** The name of the AI model to use for audio transcription. */ modelName: AiAudioTranscriptionModelName; } /** * Base options for creating speech with an AI model. * @category AI */ export interface BaseAiAudioCreateSpeechOptions { /** The name of the AI model to use for speech creation. */ modelName: AiAudioCreateSpeechModelName; } /** * Options for generating images using OpenAI's gpt-image-* family of models. * @category AI */ export interface GptImageOptions extends BaseAiGenerateImageOptions { /** Specifies the OpenAI image model to use. */ modelName: OpenAiImageModelName; /** The quality of the generated image; defaults to 'auto'. */ quality?: 'auto' | 'high' | 'medium' | 'low'; /** The size of the generated image; defaults to '1024x1024'. */ size?: '1024x1024' | '1024x1536' | '1536x1024' | 'auto'; /** The number of images to generate; defaults to 1. */ numberOfImagesToGenerate?: number; } interface BaseOpenAiAudioTranscribeOptions extends BaseAiAudioTranscribeOptions { /** Specifies the model for audio transcription. */ modelName: OpenAiAudioTranscriptionModelName; /** The temperature for sampling during transcription; defaults to model-specific value. */ temperature?: number; /** An optional prompt to guide the transcription process. */ prompt?: string; } /** * Options for transcribing audio using the Whisper model. * @category AI */ export interface WhisperTranscribeOptions extends BaseOpenAiAudioTranscribeOptions { /** Specifies the Whisper-1 model for audio transcription. */ modelName: 'whisper-1'; /** The format of the transcription response; defaults to 'json'. */ responseFormat?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt'; } /** * Options for transcribing audio using the GPT-4o model. * @category AI */ export interface Gpt4oTranscribeOptions extends BaseOpenAiAudioTranscribeOptions { /** Specifies the Whisper-1 model for audio transcription. */ modelName: 'gpt-4o-transcribe' | 'gpt-4o-mini-transcribe'; /** The format of the transcription response; defaults to 'json'. */ responseFormat?: 'json'; } /** * Options for creating speech using OpenAI's text-to-speech models. * @category AI */ export interface OpenAiCreateSpeechOptions extends BaseAiAudioCreateSpeechOptions { /** The OpenAI model to use for speech creation (e.g., 'tts-1' or 'tts-1-hd'). */ modelName: OpenAiAudioCreateSpeechModelName; /** The voice to use for speech synthesis; defaults to model-specific value. */ voice?: 'alloy' | 'ash' | 'ballad' | 'coral' | 'echo' | 'fable' | 'onyx' | 'nova' | 'sage' | 'shimmer' | 'verse'; /** The format of the audio output; defaults to 'mp3'. */ responseFormat?: OpenAiCreateSpeechFormat; /** An optional prompt to guide the speech synthesis process. */ instructions?: string; /** The speed of the speech; defaults to 1.0. */ speed?: number; } /** * Options for generating images using the Flux model. * @category AI */ export interface FluxOptions extends BaseAiGenerateImageOptions { /** Specifies the Flux Pro 1.1 model for image generation. */ modelName: 'flux-pro-1.1' | 'flux-kontext-pro'; /** The width of the generated image, must be a multiple of 32, min 256, max 1440; defaults to 1024. */ width?: number; /** The height of the generated image, must be a multiple of 32, min 256, max 1440; defaults to 768. */ height?: number; /** Whether to enhance the prompt for more creative output; defaults to false. */ prompt_upsampling?: boolean; /** A random seed for reproducible generation, if specified. */ seed?: number; /** The safety tolerance level, from 1 (strict) to 5 (permissive). */ safety_tolerance?: number; } /** * Options for generating images using the Stable Diffusion Core model. * @category AI */ export interface StableDiffusionCoreOptions extends BaseAiGenerateImageOptions { /** Specifies the Stable Diffusion Core model for image generation. */ modelName: 'stable-diffusion-core'; /** The aspect ratio of the generated image; defaults to '1:1'. */ aspectRatio?: '16:9' | '1:1' | '21:9' | '2:3' | '3:2' | '4:5' | '5:4' | '9:16' | '9:21'; /** An optional negative prompt to guide what to exclude from the image. */ negativePrompt?: string; /** A random seed for reproducible generation, if specified. */ seed?: number; /** A style preset to apply to the generated image, if specified. */ stylePreset?: 'analog-film' | 'anime' | 'cinematic' | 'comic-book' | 'digital-art' | 'enhance' | 'fantasy-art' | 'isometric' | 'line-art' | 'low-poly' | 'modeling-compound' | 'neon-punk' | 'origami' | 'photographic' | 'pixel-art' | 'tile-texture'; /** The format of the output image; defaults to 'png'. */ outputFormat?: 'jpeg' | 'png' | 'webp'; } /** * The possible sources for the LLM provider API key. * @category AI */ export type ApiKeySource = 'user' | 'system'; /** * Structured output format configuration for AI models that support schema-constrained responses. * * When used with supported models, * this guarantees that responses will strictly conform to the provided JSON schema through * constrained decoding - the model cannot generate tokens that violate the schema. * * If the model does not support structured output, the response format will default to 'json_object'. * **Example:** * ```typescript * { * type: 'json_schema', * schema: { * type: 'object', * properties: { * name: { type: 'string' }, * age: { type: 'number' } * }, * required: ['name', 'age'], * additionalProperties: false * } * } * ``` * * @see https://docs.anthropic.com/en/docs/build-with-claude/structured-outputs * @category AI */ export interface AiStructuredOutputFormat { /** * The type of structured output. * Currently only 'json_schema' is supported by Anthropic models. */ type: 'json_schema'; /** * The JSON schema that the AI response must strictly conform to. * Uses constrained decoding to guarantee schema compliance. */ schema: JSONSchema; } /** * Response format for AI agent responses. * * **Available formats:** * - `'text'`: Plain text response (default) - standard conversational output * - `'json_object'`: JSON response - model attempts to return valid JSON, but without strict schema validation * - `AiStructuredOutputFormat`: Structured output with schema (Anthropic only) - guarantees JSON conforms exactly to provided schema * * **Structured outputs (Anthropic-specific):** * For Anthropic models that support structured outputs, you can pass an object with `type: 'json_schema'` * and a JSON schema. This uses constrained decoding to guarantee the response matches your schema perfectly, * eliminating parsing errors and validation issues. * * **Example with structured output:** * ```typescript * { * responseFormat: { * type: 'json_schema', * schema: { * type: 'object', * properties: { * sentiment: { type: 'string', enum: ['positive', 'negative', 'neutral'] }, * confidence: { type: 'number', minimum: 0, maximum: 1 } * }, * required: ['sentiment', 'confidence'] * } * } * } * ``` * * @category AI */ export type AiAgentResponseFormat = 'text' | 'json_object' | AiStructuredOutputFormat; /** * @category AI */ export type AiFileUrlType = 'image' | 'document'; /** * Represents a URL reference to an AI-processed file, such as an image. * @category AI */ export interface AiFileUrl { /** The unique identifier for the file URL for the current request. */ id: string; /** The type of file referenced by the URL (e.g., 'image'). */ type: AiFileUrlType; /** The purpose of the file, indicating how it will be used in AI processing. */ purpose: AiFilePurpose; /** The URL pointing to the file. */ url: string; /** An optional description of the file's content or purpose - sent to the AI. */ description?: string; /** The file name, can be used in the prompt to reference the file. */ fileName?: string; } /** * The purpose of the AI file, used to determine how the file should be processed or utilized. * * - `'context'` - The file is included directly in the AI prompt as contextual content (e.g., images, PDFs). * Use this for files that the AI should reference when generating a response. * - `'tools'` - The file is returned as part of a tool/function call result (e.g., query results, generated documents). * Use this for files produced by AI tools or integrations that should be delivered to the caller alongside the response. */ export type AiFilePurpose = 'context' | 'tools'; /** * Metadata for an AI agent connected to an integration. * @category AI */ export interface AiConnectedIntegrationMetadata<AiConnectedIntegrationOptionsType = unknown> { /** The ID of the connected integration. */ integrationId: IntegrationId; /** The type of the connected integration (e.g., API, database). */ integrationType: IntegrationType; /** An optional description of the integration for the parent agent context, used as AI function description. */ description?: string; /** Optional instructions for the connected integration agent, overriding the default if provided. */ instructions?: string; /** * A list of AI function IDs that the AI agent can use from this integration. * * - When `undefined` (not provided), the AI agent has access to all AI functions for this integration type. * - When an empty array `[]`, the AI agent has access to no AI functions. * - When an array with function IDs, the AI agent only has access to those specific functions. * * Example function IDs: 'jiraService__searchJiraIssues', 'confluenceService__searchInConfluence' */ functionsToUse?: AiFunctionId[]; /** * Additional options for the connected integration. * Squid Core or AI functions in connector packages may use these options to adjust behavior of the integration agent. */ options?: AiConnectedIntegrationOptionsType; /** * Indicates that this integration should be treated as an MCP server. * When true, API integrations with exposeAsMcpServer will be handled through the MCP protocol. */ connectedAsMcp?: boolean; } /** * Metadata for a connected AI agent callable by the current agent. * @category AI */ export interface AiConnectedAgentMetadata { /** The ID of the connected AI agent. */ agentId: AiAgentId; /** A description of the connected agent for the parent agent context, used as AI function description. */ description: string; } /** * Metadata for a connected AI Knowledge Base callable by the current agent. * @category AI */ export interface AiConnectedKnowledgeBaseMetadata { /** The ID of the connected AI KnowledgeBase */ knowledgeBaseId: AiKnowledgeBaseId; /** A description of when to use this AiKnowledgeBase */ description: string; /** Whether to include document metadata when providing KB search results to the agent. Defaults to false. */ includeMetadata?: boolean; /** * When true, the chat agent gets a tool to enumerate/search this KB's metadata field values on * demand. Off by default. (Chat surface only for now; MCP/CLI is not wired.) */ enableMetadataInspection?: boolean; } /** * Quotas for a single AI chat prompt (`ask()` method call). * @category AI */ export interface AiChatPromptQuotas { /** * Maximum depth of AI call recursion allowed. * Recursion occurs when one AI agent calls another. * Note that, for simplicity of implementation, this option guarantees only the maximum recursion depth, * not the total number of nested AI calls. * Default: 5. */ maxAiCallStackSize: number; /** * Maximum wall-clock runtime, in seconds, of a single prompt for CLI-agent models * (Claude Code, Codex). Optional override of the per-call self-kill deadline — mainly to * tighten it for stricter runaway protection — clamped to [30, 1800]. Ignored for * non-CLI-agent models. Default: the platform maximum (30 minutes). */ maxRuntimeSeconds?: number; } /** * Options for AI agent execution plan, allowing the agent to plan what functionality to use (connected agents, * connected, integrations, or functions). */ export interface AiAgentExecutionPlanOptions { /** Whether to enable an execution plan for the agent. */ enabled: boolean; /** The model to use for the execution plan - defaults to the model used by the agent. */ model?: AiChatModelSelection; /** In case the model supports reasoning, this will control the level of effort - defaults to `high`. */ reasoningEffort?: AiReasoningEffort; /** * Whether the agent is allowed to ask follow-up or clarification questions. * If true, the agent can respond with questions to gather more information before completing the task. * Defaults to false. */ allowClarificationQuestions?: boolean; } /** * The memory mode for an AI agent: * - 'none': No memory is used, the agent does not remember past interactions. * - 'read-only': The agent can read from memory but cannot write to it. * - 'read-write': The agent can both read from and write to memory. * @category AI */ export type AiAgentMemoryMode = 'none' | 'read-only' | 'read-write'; /** * Options for AI agent memory management. * @category AI */ export interface AiAgentMemoryOptions { /** * The memory mode for an AI agent. * * Note: Squid persists chat history in its own store only for models whose provider does NOT manage memory * itself. For provider-managed-memory models (e.g. Claude Code, which keeps its own CLI session), this mode * still controls whether the conversation resumes, but Squid never reads or writes its own history DB. */ memoryMode: AiAgentMemoryMode; /** * A unique ID to store the chat memory. * * The full chat memory key is constructed as a combination of 'appId', 'agentId', and 'memoryId'. * If not provided the Squid client instance ID used as a memoryId. * * Important: the memory ID should be treated with the same security measures as Access Token because it unblocks * direct access to the agent chat history. A good practice is to use a non-trivial and a unique value. */ memoryId?: string; /** * Overrides the expiration for the whole chat history. * If not provided, the expiration will not be changed. * * Default: the last provided expiration by user or 1 day if * the user didn't provide any expiration. */ expirationMinutes?: number; } /** * Model specification for integration-based LLM providers like Ollama. * @category AI */ export interface IntegrationModelSpec { /** The integration ID that provides the LLM */ integrationId: IntegrationId; /** The model name within that integration */ model: string; } /** * Type for specifying which LLM model to use. * Can be either a vendor model name (string) or an integration-based model (object). * @category AI */ export type AiChatModelSelection = AiChatModelName | IntegrationModelSpec; /** * The base AI agent chat options, should not be used directly. * @category AI */ export interface BaseAiChatOptions { /** * The maximum number of input tokens that Squid can use when making the request to the AI model. * Defaults to the max tokens the model can accept. */ maxTokens?: number; /** * The maximum number of tokens the model should output. * Passed directly to the AI model. Can be used to control the output verbosity. */ maxOutputTokens?: number; /** The context ID to use for the request. If not provided, the agent's default context will be used. */ memoryOptions?: AiAgentMemoryOptions; /** * Names a shared working directory for CLI-backed agents (`claude-code`, `codex`). When set, the agent * runs in `/data/workspaces/<sharedWorkspaceId>` on the app's shared storage, so files created in * one ask persist and are visible to later asks reusing the same id — including across providers. * * Pass the same id consistently for a conversation; changing it points the agent at a different * directory (and, for Claude Code, starts a fresh transcript). Must match `[A-Za-z0-9_-]` (1-200 chars). * Ignored by non-CLI agents and when shared storage is unavailable (falls back to an ephemeral dir). */ sharedWorkspaceId?: string; /** Whether to disable the whole context for the request. Default to false. */ disableContext?: boolean; /** * Whether to use the legacy knowledge base context mode, where KB results are fetched upfront * and appended directly to the prompt. When false (default), the KB is exposed as a callable * tool that the LLM can invoke on demand. */ legacyKnowledgeBaseContext?: boolean; /** Rewrite prompt for RAG - defaults to false */ enablePromptRewriteForRag?: boolean; /** Whether to include references from the source context in the response. Default to false. */ includeReference?: boolean; /** The format of the response from the AI model. Note that not all models support JSON format. Default to 'text'. */ responseFormat?: AiAgentResponseFormat; /** Whether to response in a "smooth typing" way, beneficial when the chat result is displayed in a UI. Default to true. */ smoothTyping?: boolean; /** Global context passed to the agent and all AI functions of the agent. */ agentContext?: Record<string, unknown>; /** * Functions to expose to the AI. * Either a function name or a name with an extra function context passed only to this function. * The parameter values must be valid serializable JSON values. * Overrides the stored value. */ functions?: Array<AiFunctionId | AiFunctionIdWithContext>; /** Instructions to include with the prompt. */ instructions?: string; /** A set of filters that will limit the context the AI can access. * @deprecated use `contextMetadataFilterForKnowledgeBase` instead. */ contextMetadataFilter?: AiContextMetadataFilter; /** A set of filters that will limit the context the AI can access. */ contextMetadataFilterForKnowledgeBase?: Record<AiKnowledgeBaseId, AiContextMetadataFilter>; /** The options to use for the response in voice. */ voiceOptions?: AiAudioCreateSpeechOptions; /** List of connected AI agents can be called by the current agent. Overrides the stored value. */ connectedAgents?: Array<AiConnectedAgentMetadata>; /** List of connected AI agents can be called by the current agent. Overrides the stored value. */ connectedIntegrations?: Array<AiConnectedIntegrationMetadata>; /** List of connected AiKnowlegeBases that can be called by the current agent */ connectedKnowledgeBases?: Array<AiConnectedKnowledgeBaseMetadata>; /** Current budget for nested or recursive AI chat calls per single prompt. */ quotas?: AiChatPromptQuotas; /** * Include metadata in the context. * @deprecated Use `includeMetadata` on individual `AiConnectedKnowledgeBaseMetadata` entries in `connectedKnowledgeBases` instead. */ includeMetadata?: boolean; /** The temperature to use when sampling from the model. Default to 0.5. */ temperature?: number; /** Preset instruction options that can be toggled on */ guardrails?: GuardrailsOptions; /** The LLM model to use. Can be a vendor model name (string) or an integration-based model (object). */ model?: AiChatModelSelection; /** Which provider's reranker to use for reranking the context. Defaults to 'cohere'. */ rerankProvider?: AiRerankProvider; /** * Options for AI agent execution plan, allowing the agent to perform an execution plan before invoking * connected agents, connected integrations, or functions. */ executionPlanOptions?: AiAgentExecutionPlanOptions; /** An array of file URLs to include in the chat context. */ fileUrls?: Array<AiFileUrl>; /** * Arbitrary client-defined annotations attached to this AI call for usage tracking. * Reported as `annotation.<key>` tags on Squid AI usage metrics, so token usage can later be * filtered and grouped by these values (e.g. `{ feature: 'support-bot', requestSource: 'mobile' }`). * Inherited by nested calls to connected agents made while serving this call. * Limits: at most 10 entries, keys up to 64 characters, values up to 256 characters; * entries beyond the limits are dropped or truncated. */ metricAnnotations?: Record<string, string>; /** * The level of reasoning effort to apply; defaults to model-specific value. * Effective only for models with reasoning. */ reasoningEffort?: AiReasoningEffort; /** * Controls response length and detail level. * Use `low` for brief responses, `medium` for balanced detail, or `high` for comprehensive explanations. * Default: 'medium'. * * Note: this parameter is only supported by OpenAI plain text responses and is ignored for others. * For other providers ask about verbosity in prompt and using `maxOutputTokens`. */ verbosity?: AiVerbosityLevel; /** * Enable LLMs built-in code interpreter for executing Python code. * - 'none': Code interpreter is disabled (default). * - 'llm': Use LLM's native code interpreter to run Python code. * * Note: Only supported by OpenAI, Anthropic and Gemini models. Ignored for other providers. */ useCodeInterpreter?: 'none' | 'llm'; /** * File IDs to include in the chat context. * These are IDs returned from the AI provider's Files API after uploading files. * Files are attached to the conversation and can be read/analyzed by the AI. */ fileIds?: string[]; /** Timeout in milliseconds for the entire chat request. Defaults to 240,000 (4 minutes). */ timeoutMs?: number; /** Maximum number of tool-call iterations the model may perform in a single chat turn. Defaults to 50. */ maxToolIterations?: number; } /** * Chat options specific to Gemini models, extending base options. * @category AI */ export interface GeminiChatOptions extends BaseAiChatOptions { /** The Gemini model to use for the chat. */ model?: GeminiChatModelName; /** Enables grounding with web search for more informed responses; defaults to false. */ groundingWithWebSearch?: boolean; } /** * Chat options specific to Grok models, extending base options. * @category AI */ export interface GrokChatOptions extends BaseAiChatOptions { /** The Grok model to use for the chat. */ model?: GrokChatModelName; } /** * Chat options specific to OpenAI models, extending base options. * @category AI */ export interface OpenAiChatOptions extends BaseAiChatOptions { /** The OpenAI model to use for the chat. */ model?: OpenAiChatModelName; } /** * Canonical reasoning-effort levels, ordered from least to most effort. These are the values that * have a defined position on the effort axis and therefore participate in clamping when a model does * not support the exact requested level. * @category AI */ export type CanonicalReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'; /** * AI reasoning effort. Pass one of the canonical levels for portable, autocomplete-friendly usage, or * a raw provider-native string when a model exposes a level outside the canonical set. * * Resolution against the selected model (see {@link ReasoningCapability}): * - exact match with the model's capability -> used as-is (1:1); * - canonical level the model lacks -> clamped to the nearest supported level (ties resolve downward); * - unknown string the model cannot place on the axis -> dropped, so the model's own default applies, * with a warning; * - model without a reasoning knob -> ignored, with a warning. * @category AI */ export type AiReasoningEffort = CanonicalReasoningEffort | (string & {}); /** * Declares how a model exposes reasoning effort. Used as the single source of truth for resolving a * requested {@link AiReasoningEffort} onto what the model natively accepts. When a request cannot be * matched or clamped, no reasoning parameter is emitted and the model applies its own native default. * * - `none`: the model has no reasoning knob (e.g. it always reasons). * - `levels`: the model accepts a fixed set of named levels (emitted as a string). * - `budget`: the model accepts a token budget; each canonical level maps to a concrete integer. * @category AI */ export type ReasoningCapability = { kind: 'none'; } | { kind: 'levels'; supported: AiReasoningEffort[]; } | { kind: 'budget'; perLevel: Partial<Record<CanonicalReasoningEffort, number>>; }; /** * Controls response length and detail level. * Use `low` for brief responses,`medium` for balanced detail, or `high` for comprehensive explanations. * Default: 'medium'. */ export type AiVerbosityLevel = 'low' | 'medium' | 'high'; /** * Chat options specific to Anthropic models, extending base options. * * **Structured Outputs:** * Anthropic models support structured outputs * through the `responseFormat` field. Pass an object with `type: 'json_schema'` and a JSON schema * to guarantee the response conforms exactly to your schema. * * **Example:** * ```typescript * { * model: 'claude-sonnet-5', * responseFormat: { * type: 'json_schema', * schema: { * type: 'object', * properties: { * name: { type: 'string' }, * age: { type: 'number' } * }, * required: ['name', 'age'], * additionalProperties: false * } * } * } * ``` * * @see https://docs.anthropic.com/en/docs/build-with-claude/structured-outputs * @category AI */ export interface AnthropicChatOptions extends BaseAiChatOptions { /** The Anthropic model to use for the chat. */ model?: AnthropicChatModelName; } /** * The generic options type. When no generic is provided, * the type is inferred from the provided overrideModel (or falls back to BaseAiAgentChatOptions). * @category AI */ export type AiChatOptions<T extends AiChatModelSelection | undefined = undefined> = T extends undefined ? BaseAiChatOptions | GeminiChatOptions | OpenAiChatOptions | AnthropicChatOptions : T extends GeminiChatModelName ? GeminiChatOptions : T extends OpenAiChatModelName ? OpenAiChatOptions : T extends AnthropicChatModelName ? AnthropicChatOptions : T extends GrokChatModelName ? GrokChatOptions : BaseAiChatOptions; /** * @category AI */ export type AllAiAgentChatOptions = { [K in keyof BaseAiChatOptions | keyof GeminiChatOptions | keyof GrokChatOptions | keyof OpenAiChatOptions | keyof AnthropicChatOptions]?: (K extends keyof BaseAiChatOptions ? BaseAiChatOptions[K] : never) | (K extends keyof GeminiChatOptions ? GeminiChatOptions[K] : never) | (K extends keyof GrokChatOptions ? GrokChatOptions[K] : never) | (K extends keyof OpenAiChatOptions ? OpenAiChatOptions[K] : never) | (K extends keyof AnthropicChatOptions ? AnthropicChatOptions[K] : never); }; /** * A definition of an AI agent with its properties and default chat options. * @category AI */ export interface AiAgent<T extends AiChatModelSelection | undefined = undefined> { /** The unique identifier of the AI agent. */ id: AiAgentId; /** The date and time the agent was created. */ createdAt: Date; /** The date and time the agent was last updated. */ updatedAt: Date; /** An optional description of the agent's purpose or capabilities. */ description?: string; /** Indicates whether the agent is publicly accessible; defaults to false. */ isPublic?: boolean; /** Enables audit logging for the agent's activities if true; defaults to false. */ auditLog?: boolean; /** The default chat options for the agent, overridable by the user during use. */ options: AiChatOptions<T>; /** Optional api key used specifically for operations on this agent */ apiKey?: string; } /** * @category AI */ export type UpsertAgentRequest = Omit<AiAgent, 'createdAt' | 'updatedAt' | 'options'> & { options?: AiChatOptions; }; /** * Status update title broadcast when the agent finishes producing a response, * either successfully or with an error. Emitted exactly once per `ask` job and * is the last status event for that job. * @category AI */ export declare const AGENT_STATUS_TITLE_AGENT_RESPONSE = "Agent Response"; /** * Status update title broadcast when the agent invokes a knowledge-base * callable. A matching invocation produces a single event with this title. * @category AI */ export declare const AGENT_STATUS_TITLE_ACCESSING_KB = "Accessing Knowledge Base"; /** * Status update title broadcast when the agent invokes an AI function callable * (a backend `@aiFunction`). Lets a caller detect that a function was actually * called, independent of how the model renders the result in its final answer. * @category AI */ export declare const AGENT_STATUS_TITLE_CALLING_AI_FUNCTION = "Calling AI Function"; /** * Status update title broadcast when the agent invokes a knowledge-base metadata-inspection callable * (the opt-in `enableMetadataInspection` tool). Distinct from {@link AGENT_STATUS_TITLE_ACCESSING_KB} * so a caller can tell a metadata-value inspection apart from an ordinary KB search. * @category AI */ export declare const AGENT_STATUS_TITLE_INSPECTING_KB_METADATA = "Inspecting Knowledge Base Metadata"; /** * Status update title broadcast when the agent queries a spreadsheet file callable. * @category AI */ export declare const AGENT_STATUS_TITLE_QUERYING_SPREADSHEET = "Querying Spreadsheet"; /** * A status message from an AI agent operation. * @category AI */ export interface AiStatusMessage { /** ID of the status update message. */ messageId: string; /** The ID of the agent generating the status message. */ agentId?: AiAgentId; /** An optional chat ID associated with the status message. */ chatId?: string; /** The title or summary of the status message. */ title: string; /** Markdown body content for the status update. */ body: string; /** ID of the parent status update for nested display. */ parentStatusUpdateId?: string; /** The Job ID associated with the status message. */ jobId: JobId; /** Optional tags providing additional metadata about the status. */ tags?: Record<string, any>; } /** List of all chat history (memory) sources. */ export declare const AI_CHAT_MESSAGE_SOURCE: readonly ["user", "ai"]; /** Source of the chat history entry: either an AI response or a user. */ export type AiChatMessageSource = (typeof AI_CHAT_MESSAGE_SOURCE)[number]; /** A history entry for a chat. */ export interface AiChatMessage { /** ID of the entry. Unique per agent. */ id: string; /** Agent's application. */ appId: AppId; /** The ID of the agent that owns the history. */ agentId: AiAgentId; /** A memory (history) ID associated with the chat conversation. */ memoryId: string; /** The source of the message: a user or an AI. */ source: AiChatMessageSource; /** The text of the entry: a user's prompt or an AI-generated response. */ message: string; /** Time the entry is created. Unix time millis. */ timestamp: number; } /** * A single chunk of data returned from an AI search operation. * @category AI */ export interface AiSearchResultChunk { /** The data content of the search result chunk. */ data: string; /** Optional metadata associated with the chunk. */ metadata?: AiContextMetadata; /** The relevance score of the chunk, indicating match quality. */ score: number; } /** * Represents an AI agent's context entry with metadata and content. * @category AI */ export interface AiAgentContext { /** The unique identifier of the context entry. */ id: AiContextId; /** The date and time the context was created. */ createdAt: Date; /** The date and time the context was last updated. */ updatedAt: Date; /** The ID of the agent owning this context. */ agentId: AiAgentId; /** The type of context (e.g., 'text' or 'file'). */ type: AiKnowledgeBaseContextType; /** A title describing the context content. */ title: string; /** The text content of the context. */ text: string; /** Indicates whether the context is a preview; defaults to false. */ preview: boolean; /** The size of the context content in bytes. */ sizeBytes: number; /** Metadata associated with the context. */ metadata: AiContextMetadata; } /** * @category AI */ export type AgentContextRequest = TextContextRequest | FileContextRequest; interface BaseContextRequest { contextId: string; type: AiKnowledgeBaseContextType; metadata?: AiContextMetadata; } /** * Status of an individual context item after successfully upserting it. * @category AI */ export interface BaseUpsertContextStatus { /** Whether the context upsert was successful, otherwise, what occurred. */ status: 'success' | 'error'; /** The unique identifier of the context item. */ contextId: string; /** The name of the context item, typically the title or filename. */ name: string; } /** * Status of an individual context item after successfully upserting it. * @category AI */ export interface UpsertContextStatusSuccess extends BaseUpsertContextStatus { /** Whether the context upsert was successful or got an error. */ status: 'success'; } /** * Status of an individual context item after it failed to upsert. * * Contains the error message for why the upsert failed. * @category AI */ export interface UpsertContextStatusError extends BaseUpsertContextStatus { /** Whether the context upsert was successful or got an error. */ status: 'error'; /** Reason the upsert failed. */ errorMessage: string; } /** * Status of an individual context item after attempting to upsert it. * @category AI */ export type UpsertContextStatus = UpsertContextStatusSuccess | UpsertContextStatusError; /** * Response structure for upserting context. * @category AI */ export interface UpsertAgentContextResponse { /** Upsert failure that occurred for the items sent in the request. */ failure?: UpsertContextStatusError; } /** * Response structure for upserting contexts. * @category AI */ export interface UpsertAgentContextsResponse { /** List of the upsert failures that occurred for the items sent in the request. */ failures: Array<UpsertContextStatusError>; } /** * Base options for upserting text content into the AI agent's context. * @category AI */ export interface AiContextTextOptions extends BaseAiContextOptions { } /** * Base options for upserting file content into the AI agent's context. * @category AI */ export interface AiContextFileOptions extends BaseAiContextOptions { } /** * Request structure for adding text-based context to an AI agent. * @category AI */ export interface TextContextRequest extends BaseContextRequest { /** Specifies the context type as 'text'. */ type: 'text'; /** A title for the text context. */ title: string; /** The text content to add to the context. */ text: string; /** General options for how to process the text. */ options?: AiContextTextOptions; } /** * Request structure for adding file-based context to an AI agent. * @category AI */ export interface FileContextRequest extends BaseContextRequest { /** Specifies the context type as 'file'. */ type: 'file'; /** Whether to extract images from the file; defaults to false. */ extractImages?: boolean; /** The minimum size for extracted images, if applicable. */ imageMinSizePixels?: number; /** The AI model to use for extraction, if specified. */ extractionModel?: AiChatModelSelection; /** General options for how to process the file. */ options?: AiContextFileOptions; /** The preferred method for extracting data from the document. */ preferredExtractionMethod?: DocumentExtractionMethod; /** * Whether Squid keeps or discards the original file. * * Keeping the original file allows reprocessing and the ability for the user to download it later. * * Defaults to false. */ discardOriginalFile?: boolean; } /** * Base options for how to deal with the content being upserted. * @category AI */ export type BaseAiContextOptions = { /** The type of RAG to use for the content. */ ragType?: AiRagType; /** Amount of chunk overlap, in characters. */ chunkOverlap?: number; }; /** * @category AI */ export type GuardrailKeysType = 'disableProfanity' | 'offTopicAnswers' | 'professionalTone' | 'disablePii'; /** * Options for applying guardrails to AI responses to enforce specific constraints. * @category AI */ export type GuardrailsOptions = { /** Disables profanity in the AI response if true; defaults to false. */ disableProfanity?: boolean; /** Prevents off-topic answers if true; defaults to false. */ offTopicAnswers?: boolean; /** Enforces a professional tone in the response if true; defaults to false. */ professionalTone?: boolean; /** Disables inclusion of personally identifiable information if true; defaults to false. */ disablePii?: boolean; /** A custom guardrail instruction, if specified. */ custom?: string; }; /** * Response structure for transcribing audio and asking an AI agent a question. * @category AI */ export interface AiTranscribeAndAskResponse { /** The AI agent's response to the transcribed prompt. */ responseString: string; /** The transcribed text from the audio input. */ transcribedPrompt: string; /** The annotations associated with the AI response, if any. */ annotations?: Record<string, AiAnnotation>; } /** Per application AI settings. */ export interface ApplicationAiSettings { /** Maps AI provider name to API key secret name that must be used for any request made by the application. */ apiKeys: Partial<Record<AiProviderType, SecretKey>>; } /** * Options for user-provided LLM models. * @category AI */ export interface UserAiChatOptions extends BaseAiChatOptions { /** LLM Model to use for the chat query. */ model: UserAiChatModelName; } /** * Response structure for asking a user LLM a question. * @category AI */ export interface UserAiAskResponse { /** The response from the AI agent. */ response?: string; /** The number of input tokens used in the request. */ inputTokens?: number; /** The number of output tokens generated by the AI agent. */ outputTokens?: number; /** Cached input tokens read from the prompt cache. Only set by providers that report it (e.g. claude-code). */ cacheReadInputTokens?: number; /** Input tokens written to the prompt cache. Only set by providers that report it (e.g. claude-code). */ cacheWriteInputTokens?: number; /** Total request cost in USD as reported by the provider. Only set by providers that compute it (e.g. claude-code). */ totalCostUsd?: number; } /** Represents an annotation in the AI response. */ export type AiAnnotation = AiFileAnnotation; /** Represents an annotation for a file in the AI response. */ export interface AiFileAnnotation { /** The type of the annotation, always 'file'. */ type: 'file'; /** The AI file with the URL to the file */ aiFileUrl: AiFileUrl; } /** * Context for an AI session */ export type AiSessionContext = { /** The ID of the client initiating the session. */ clientId: string; /** The ID of the AI agent involved in the session. */ agentId: string; /** The ID of the job associated with the session. */ jobId: JobId; /** * The effective chat timeout (in milliseconds) of the session that initiated this AI work. * Present only when the root chat request explicitly set `timeoutMs`. Nested AI operations * (e.g. AI-query stages spawned by a tool call) use it as a fallback budget so a long-running * parent chat is not silently capped by the nested defaults. */ timeoutMs?: number; }; /** * API request to delete an AI agent * @category AI */ export interface DeleteAgentRequest { /** The ID of the agent to delete */ agentId: string; } /** * API response from agent ask methods * @category AI */ export interface AiAskResponse { /** The response string from the agent */ responseString: string; /** Optional annotations (e.g., file references) in the response */ annotations?: Record<string, AiAnnotation>; } /** * API request to create speech from text * @category AI */ export interface AiAudioCreateSpeechRequest { /** The text input to convert to speech */ input: string; /** Options for speech generation */ options: AiAudioCreateSpeechOptions; } /** * API request to generate an image * @category AI */ export interface AiGenerateImageRequest { /** The prompt describing the image to generate */ prompt: string; /** Options for image generation */ options?: AiGenerateImageOptions; } /** * Revision action types for agent history tracking. * @category AI */ export type AiAgentRevisionAction = 'created' | 'updated' | 'deleted'; /** * Represents a single agent revision entry. * @category AI */ export interface AiAgentRevision { /** The ID of the agent this revision belongs to. */ agentId: AiAgentId; /** The revision number, incremented for each change to the agent. */ revisionNumber: number; /** The action that triggered this revision (created, updated, or deleted). */ action: AiAgentRevisionAction; /** Timestamp when this revision was created. */ createdAt: Date; /** Snapshot of the agent data at the time of the revision. */ agentSnapshot: AiAgent; } /** * Request to list all revisions for an agent. * @category AI */ export interface ListAgentRevisionsRequest { /** The ID of the agent to list revisions for. */ agentId: AiAgentId; } /** * Response containing the list of agent revisions. * @category AI */ export interface ListAgentRevisionsResponse { /** The list of revisions for the agent, sorted by revision number descending. */ revisions: Array<AiAgentRevision>; } /** * Request to get a specific agent revision. * @category AI */ export interface GetAgentRevisionRequest { /** The ID of the agent to get the revision for. */ agentId: AiAgentId; /** The revision number to retrieve. */ revisionNumber: number; } /** * Response containing a specific agent revision. * @category AI */ export interface GetAgentRevisionResponse { /** The requested revision, or undefined if not found. */ revision: AiAgentRevision | undefined; } /** * Request to restore an agent to a specific revision. * @category AI */ export interface RestoreAgentRevisionRequest { /** The ID of the agent to restore. */ agentId: AiAgentId; /** The revision number to restore the agent to. */ revisionNumber: number; } /** * Request to delete a specific agent revision. * @category AI */ export interface DeleteAgentRevisionRequest { /** The ID of the agent whose revision should be deleted. */ agentId: AiAgentId; /** The revision number to delete. */ revisionNumber: number; } /** * Options for the agent builder. * @category AI */ export interface BuildAgentOptions { /** Whether the caller has permission to create or update integrations. Defaults to false. */ canManageIntegrations?: boolean; } /** * Response containing the list of AI agents in an application. * @category AI */ export interface ListAgentsResponse { /** All AI agents defined for the application. */ agents: Array<AiAgent>; } /** * Request options for listing the chat models available to an application. * @category AI */ export interface ListChatModelsRequest { /** * When true, deprecated vendor models (those with `replacedBy`) are included. * Defaults to false (only active models are returned). */ includeDeprecated?: boolean; } /** * Response containing the list of chat models available to an application. * Includes both Squid-provided vendor models and any custom integration models. * Vendor models carry a human-readable `description`. Deprecated vendor models are * included only when requested via `includeDeprecated` and are marked with `replacedBy`. * @category AI */ export interface ListChatModelsResponse { /** All chat models available to the application. */ models: Array<ModelIdSpec>; } export {};