import { ResolvedRef } from "../validation/dolt-schemas.js";
import { AgentScopeConfig, ProjectScopeConfig, SubAgentScopeConfig, TenantScopeConfig } from "../db/manage/scope-definitions.js";
import "../index.js";
import { ApiConfigSchema, AppConfigSchema, ChannelAccessModeSchema, ChannelIdsSchema, EvaluationJobFilterCriteriaSchema, McpTransportConfigSchema, ModelSchema, ProjectModelSchema, PublicKeyAlgorithmSchema, PublicKeyConfigSchema, StatusComponentSchema, StatusUpdateSchema, SupportCopilotConfigSchema, WebClientConfigSchema, WorkAppGitHubAccountTypeSchema, WorkAppGitHubInstallationStatusSchema } from "../validation/schemas.js";
import { ApiKeySelect, FullProjectSelectWithRelationIds } from "./entities.js";
import { z } from "@hono/zod-openapi";

//#region src/types/utility.d.ts
type MessageVisibility = 'user-facing' | 'internal' | 'system' | 'external';
type MessageType = 'chat' | 'a2a-request' | 'a2a-response' | 'task-update' | 'tool-call' | 'tool-result';
type MessageRole = 'user' | 'agent' | 'system';
type MessageMode = 'full' | 'scoped' | 'none';
type Models = z.infer<typeof ModelSchema>;
type ProjectModels = z.infer<typeof ProjectModelSchema>;
type StatusUpdateSettings = z.infer<typeof StatusUpdateSchema>;
type StatusComponent = z.infer<typeof StatusComponentSchema>;
type PaginationConfig = {
  page?: number;
  limit?: number;
};
type PaginationResult = {
  page: number;
  limit: number;
  total: number;
  pages: number;
};
interface ConversationScopeOptions {
  taskId?: string;
  subAgentId?: string;
  delegationId?: string;
  isDelegated?: boolean;
}
type ConversationHistoryConfig = {
  mode?: 'full' | 'scoped' | 'none';
  limit?: number;
  maxOutputTokens?: number;
  includeInternal?: boolean;
  messageTypes?: MessageType[];
};
interface AgentConversationHistoryConfig extends ConversationHistoryConfig {
  mode: 'full' | 'scoped' | 'none';
}
type ConversationMetadata = {
  userContext?: Record<string, unknown>;
  verifiedClaims?: Record<string, unknown>;
  preferences?: Record<string, unknown>;
  sessionData?: Record<string, unknown>;
  apiKeyId?: string;
  externalUserId?: string;
  initiatedBy?: {
    type: 'user' | 'api_key';
    id: string;
  };
};
type MessageContent = {
  text?: string;
  parts?: Array<{
    kind: string;
    text?: string;
    data?: string | Record<string, unknown>;
    metadata?: Record<string, unknown>;
  }>;
  tool_calls?: Array<{
    id: string;
    type: string;
    function: {
      name: string;
      arguments: string;
    };
  }>;
  tool_call_id?: string;
  name?: string;
};
type MessageMetadata = {
  openai_model?: string;
  finish_reason?: string;
  usage?: {
    prompt_tokens?: number;
    completion_tokens?: number;
    total_tokens?: number;
  };
  compressionType?: string;
  a2a_metadata?: Record<string, unknown>;
  processing_time_ms?: number;
  error_details?: Record<string, unknown>;
};
type ContextFetchDefinition = {
  id: string;
  name?: string;
  trigger: 'initialization' | 'invocation';
  fetchConfig: {
    url: string;
    method?: string;
    headers?: Record<string, string>;
    body?: Record<string, unknown>;
    transform?: string;
    timeout?: number;
    requiredToFetch?: Array<string>;
  };
  responseSchema?: Record<string, unknown>;
  defaultValue?: unknown;
  credentialReferenceId?: string;
};
type ContextCacheEntry = {
  id: string;
  tenantId: string;
  projectId: string;
  conversationId: string;
  contextConfigId: string;
  contextVariableKey: string;
  value: unknown;
  requestHash?: string;
  fetchedAt: Date;
  fetchSource?: string;
  fetchDurationMs?: number;
  createdAt: Date;
  updatedAt: Date;
};
type McpAuthType = 'bearer' | 'basic' | 'api_key' | 'none';
type McpServerAuth = {
  type: McpAuthType;
  token?: string;
  username?: string;
  password?: string;
  apiKey?: string;
  headerName?: string;
};
type McpTransportConfig = z.infer<typeof McpTransportConfigSchema>;
type McpServerCapabilities = {
  tools?: boolean;
  resources?: boolean;
  prompts?: boolean;
  logging?: boolean;
};
type McpToolDefinition = {
  name: string;
  description?: string;
  inputSchema?: Record<string, unknown>;
};
type ToolSimplifyConfig = {
  displayName?: string;
  description?: string;
  schema?: any;
  transformation?: Record<string, string> | string;
};
type ToolMcpConfig = {
  server: {
    url: string;
    timeout?: number;
    headers?: Record<string, string>;
  };
  transport?: McpTransportConfig;
  activeTools?: string[];
  toolOverrides?: Record<string, ToolSimplifyConfig>;
  prompt?: string;
};
type ToolServerCapabilities = {
  tools?: boolean;
  resources?: boolean;
  prompts?: boolean;
  logging?: boolean;
  streaming?: boolean;
  serverInstructions?: string;
};
type TaskMetadataConfig = {
  conversation_id: string;
  message_id: string;
  created_at: string;
  updated_at: string;
  root_sub_agent_id?: string;
  sub_agent_id?: string;
  tool_id?: string;
  agent_id?: string;
  stream_request_id?: string;
};
interface ProjectInfo {
  projectId: string;
}
interface ProjectResourceCounts {
  subAgents: number;
  agents: number;
  tools: number;
  contextConfigs: number;
  externalAgents: number;
}
declare const TOOL_STATUS_VALUES: readonly ["healthy", "unhealthy", "unknown", "needs_auth", "unavailable"];
declare const VALID_RELATION_TYPES: readonly ["transfer", "delegate"];
declare const MCPTransportType: {
  readonly streamableHttp: "streamable_http";
  readonly sse: "sse";
};
declare const MCPServerType: {
  readonly nango: "nango";
  readonly generic: "generic";
};
declare const CredentialStoreType: {
  readonly memory: "memory";
  readonly keychain: "keychain";
  readonly nango: "nango";
  readonly composio: "composio";
};
interface CreateApiKeyParams {
  tenantId: string;
  projectId: string;
  agentId: string;
  name: string;
  expiresAt?: string;
}
interface ApiKeyCreateResult {
  apiKey: ApiKeySelect;
  key: string;
}
/**
 * Execution context that gets propagated through agent calls
 * Contains authentication and routing information for internal API calls
 */
interface BaseExecutionContext {
  /** The original API key from the client request */
  apiKey: string;
  /** Tenant ID extracted from API key */
  tenantId: string;
  /** Project ID extracted from API key */
  projectId: string;
  /** Agent ID extracted from API key */
  agentId: string;
  /** Base URL for internal API calls */
  baseUrl: string;
  /** API key ID for tracking */
  apiKeyId: string;
  /** Ref extracted from query params */
  ref?: string;
  /** Sub Agent ID extracted from request headers (only for internal A2A calls) */
  subAgentId?: string;
  /** Metadata for the execution context */
  metadata?: {
    teamDelegation?: boolean;
    originAgentId?: string;
    initiatedBy?: {
      type: 'user' | 'api_key';
      id: string;
    };
    slack?: {
      authorized: true;
      authSource: 'channel' | 'workspace';
      channelId?: string;
      teamId: string;
    };
    endUserId?: string;
    verifiedClaims?: Record<string, unknown>;
    authMethod?: 'app_credential_web_client' | 'app_credential_api' | 'app_credential_web_client_authenticated' | 'app_credential_support_copilot';
    appId?: string;
    appPrompt?: string;
    oauthClientId?: string;
  };
}
interface FullExecutionContext extends BaseExecutionContext {
  resolvedRef: ResolvedRef;
  project: FullProjectSelectWithRelationIds;
}
/**
 * Reusable filter type that supports and/or operations
 *
 * Allows composition of filters using:
 * - Direct filter criteria (e.g., { agentIds: ['id1', 'id2'] })
 * - AND operation: { and: [filter1, filter2, ...] }
 * - OR operation: { or: [filter1, filter2, ...] }
 *
 * @template T - The base filter criteria type (e.g., { agentIds?: string[] })
 *
 * @example
 * // Simple filter
 * const filter: Filter<{ agentIds?: string[] }> = { agentIds: ['id1'] };
 *
 * @example
 * // AND operation
 * const filter: Filter<{ agentIds?: string[] }> = {
 *   and: [
 *     { agentIds: ['id1'] },
 *     { agentIds: ['id2'] }
 *   ]
 * };
 *
 * @example
 * // OR operation
 * const filter: Filter<{ agentIds?: string[] }> = {
 *   or: [
 *     { agentIds: ['id1'] },
 *     { agentIds: ['id2'] }
 *   ]
 * };
 *
 * @example
 * // Complex nested operations
 * const filter: Filter<{ agentIds?: string[] }> = {
 *   and: [
 *     { agentIds: ['id1'] },
 *     {
 *       or: [
 *         { agentIds: ['id2'] },
 *         { agentIds: ['id3'] }
 *       ]
 *     }
 *   ]
 * };
 */
type Filter<T extends Record<string, unknown>> = T | {
  and: Array<Filter<T>>;
} | {
  or: Array<Filter<T>>;
};
type PassCriteriaNumericOperator = '>' | '<' | '>=' | '<=' | '=' | '!=';
type PassCriteriaBooleanOperator = '=' | '!=';
type PassCriteriaNumericCondition = {
  field: string;
  operator: PassCriteriaNumericOperator;
  value: number;
};
type PassCriteriaBooleanCondition = {
  field: string;
  operator: PassCriteriaBooleanOperator;
  value: boolean;
};
type PassCriteriaCondition = PassCriteriaNumericCondition | PassCriteriaBooleanCondition;
type PassCriteria = {
  operator: 'and' | 'or';
  conditions: Array<PassCriteriaCondition | PassCriteria>;
};
declare const MAX_PASS_CRITERIA_DEPTH = 5;
type EvaluationJobFilterCriteria = z.infer<typeof EvaluationJobFilterCriteriaSchema>;
type EvaluationSuiteFilterCriteria = {
  agentIds?: string[];
  [key: string]: unknown;
};
type DatasetMessageRole = 'user' | 'assistant' | 'system';
type DatasetItemInput = {
  messages: Array<{
    role: DatasetMessageRole;
    content: MessageContent;
  }>;
};
type DatasetItemExpectedOutput = Array<{
  role: DatasetMessageRole;
  content: MessageContent;
}>;
/**
 * GitHub App installation status.
 * - 'pending': Installation request awaiting org admin approval
 * - 'active': Installation is active and functional
 * - 'suspended': Installation suspended by GitHub or org admin
 * - 'disconnected': Installation has been disconnected by the user (soft delete)
 */
type WorkAppGitHubInstallationStatus = z.infer<typeof WorkAppGitHubInstallationStatusSchema>;
/**
 * GitHub account type for the installation target.
 * - 'Organization': Installed on a GitHub organization
 * - 'User': Installed on a personal GitHub account
 */
type WorkAppGitHubAccountType = z.infer<typeof WorkAppGitHubAccountTypeSchema>;
/**
 * Channel access mode for the slack MCP tool.
 * - 'all': Tool has access to all channels
 * - 'selected': Tool only has access to channels listed in work_app_slack_mcp_tool_access_config
 */
type ChannelAccessMode = z.infer<typeof ChannelAccessModeSchema>;
type ChannelIds = z.infer<typeof ChannelIdsSchema>;
type AppType = 'web_client' | 'api' | 'support_copilot';
type PublicKeyAlgorithm = z.infer<typeof PublicKeyAlgorithmSchema>;
type PublicKeyConfig = z.infer<typeof PublicKeyConfigSchema>;
type WebClientConfig = z.infer<typeof WebClientConfigSchema>;
type ApiConfig = z.infer<typeof ApiConfigSchema>;
type SupportCopilotConfig = z.infer<typeof SupportCopilotConfigSchema>;
type AppConfig = z.infer<typeof AppConfigSchema>;
//#endregion
export { AgentConversationHistoryConfig, type AgentScopeConfig, ApiConfig, ApiKeyCreateResult, AppConfig, AppType, BaseExecutionContext, ChannelAccessMode, ChannelIds, ContextCacheEntry, ContextFetchDefinition, ConversationHistoryConfig, ConversationMetadata, ConversationScopeOptions, CreateApiKeyParams, CredentialStoreType, DatasetItemExpectedOutput, DatasetItemInput, DatasetMessageRole, EvaluationJobFilterCriteria, EvaluationSuiteFilterCriteria, Filter, FullExecutionContext, MAX_PASS_CRITERIA_DEPTH, MCPServerType, MCPTransportType, McpAuthType, McpServerAuth, McpServerCapabilities, McpToolDefinition, McpTransportConfig, MessageContent, MessageMetadata, MessageMode, MessageRole, MessageType, MessageVisibility, Models, PaginationConfig, PaginationResult, PassCriteria, PassCriteriaBooleanCondition, PassCriteriaBooleanOperator, PassCriteriaCondition, PassCriteriaNumericCondition, PassCriteriaNumericOperator, ProjectInfo, ProjectModels, ProjectResourceCounts, type ProjectScopeConfig, PublicKeyAlgorithm, PublicKeyConfig, StatusComponent, StatusUpdateSettings, type SubAgentScopeConfig, SupportCopilotConfig, TOOL_STATUS_VALUES, TaskMetadataConfig, type TenantScopeConfig, ToolMcpConfig, ToolServerCapabilities, ToolSimplifyConfig, VALID_RELATION_TYPES, WebClientConfig, WorkAppGitHubAccountType, WorkAppGitHubInstallationStatus };