/* auto-generated by NAPI-RS */
/* eslint-disable */
/** Handle to a running agent runtime (TypeScript wrapper). */
export declare class JsAgentHandle {
  /**
   * Wait for and return the next mesh event.
   *
   * This is an async method that blocks until an event is available.
   * Returns a JsMeshEvent with eventType "shutdown" when the runtime has shut down.
   */
  nextEvent(): Promise<JsMeshEvent>
  /**
   * Get current dependency endpoints.
   *
   * Returns an object mapping capability names to endpoint URLs.
   */
  getDependencies(): Promise<Record<string, string>>
  /** Get current agent health status. */
  getStatus(): Promise<string>
  /** Get the agent ID assigned by the registry. */
  getAgentId(): Promise<string | null>
  /** Check if shutdown has been requested. */
  isShutdownRequested(): Promise<boolean>
  /** Request graceful shutdown of the agent runtime. */
  shutdown(): Promise<void>
  /**
   * Update the tools/routes registered with the registry.
   *
   * Uses smart diffing - only triggers a heartbeat if tools have changed.
   * Call this after Express route introspection to update route names
   * from placeholders (e.g., "route_0_UNKNOWN:UNKNOWN") to proper names
   * (e.g., "GET:/time").
   *
   * @param tools - Array of tool specifications with updated function names
   * @returns true if the update was sent successfully
   */
  updateTools(tools: Array<JsToolSpec>): Promise<boolean>
  /**
   * Update the HTTP port (e.g., after auto-detection from Express).
   *
   * @param port - The detected HTTP port
   * @returns true if the update was sent successfully
   */
  updatePort(port: number): Promise<boolean>
}

/**
 * Add tool execution results to the agentic loop.
 *
 * @param stateJson - Serialized loop state from a previous call
 * @param toolResultsJson - Array of {tool_call_id, content} objects
 * @returns Action JSON: call_llm or max_iterations
 */
export declare function addToolResults(stateJson: string, toolResultsJson: string): string

/**
 * Auto-detect external IP address.
 *
 * Uses UDP socket trick to find the IP that would route to external networks.
 * Falls back to "localhost" if detection fails.
 */
export declare function autoDetectIp(): string

/**
 * Build a JSON-RPC 2.0 request envelope.
 *
 * @param method - JSON-RPC method name (e.g., "tools/call")
 * @param paramsJson - JSON string to embed as params
 * @param requestId - Unique request identifier
 * @returns Full JSON-RPC request string
 */
export declare function buildJsonrpcRequest(method: string, paramsJson: string, requestId: string): string

/**
 * Build the `response_format` JSON object for structured output.
 *
 * Returns null for vendors that do not support response_format.
 *
 * @param provider - Vendor name
 * @param schemaJson - JSON schema string
 * @param schemaName - Schema name for the response_format
 * @param hasTools - Whether tools are present
 * @returns JSON string with response_format, or null
 */
export declare function buildResponseFormat(provider: string, schemaJson: string, schemaName: string, hasTools: boolean): string | null

/**
 * Call a remote MCP tool via HTTP POST with retry.
 *
 * @param endpoint - MCP endpoint URL
 * @param toolName - Name of the tool to call
 * @param argsJson - Optional JSON string of tool arguments
 * @param headersJson - Optional JSON object of extra headers
 * @param timeoutMs - Request timeout in milliseconds
 * @param maxRetries - Maximum number of retries on network error
 * @returns Result content string
 */
export declare function callTool(endpoint: string, toolName: string, argsJson: string | undefined | null, headersJson: string | undefined | null, timeoutMs: number, maxRetries: number): Promise<string>

/**
 * Clean up temporary TLS credential files.
 *
 * Call during agent shutdown. Safe to call multiple times.
 */
export declare function cleanupTls(): void

/**
 * Create initial agentic loop state.
 *
 * @param configJson - JSON config with `messages` array and optional `maxIterations`
 * @returns Action JSON with `action: "call_llm"` and serialized state
 */
export declare function createAgenticLoop(configJson: string): string

/** Check if any tool schema property contains x-media-type. */
export declare function detectMediaParams(schemaJson: string): boolean

/**
 * Determine output mode for a vendor given the context.
 *
 * @param provider - Vendor name (e.g., "anthropic", "openai", "gemini")
 * @param isStringType - Whether the output schema is a plain string type
 * @param hasTools - Whether tools are present in the request
 * @param overrideMode - Optional override mode
 * @returns Output mode: "text", "hint", or "strict"
 */
export declare function determineOutputMode(provider: string, isStringType: boolean, hasTools: boolean, overrideMode?: string | undefined | null): string

/**
 * Extract text content from MCP CallToolResult JSON.
 *
 * @param resultJson - JSON string of the MCP result
 * @returns Extracted content string
 */
export declare function extractContent(resultJson: string): string

/**
 * Extract JSON from LLM response text.
 *
 * Strategies: code fences -> progressive object parse -> progressive array parse.
 * Returns null if no JSON found.
 */
export declare function extractJson(text: string): string | null

/** Extract trace context from HTTP headers with body fallback. */
export declare function extractTraceContext(headersJson: string, bodyJson?: string | undefined | null): string

/** Filter headers by propagation allowlist with prefix matching. */
export declare function filterPropagationHeaders(headersJson: string, allowlistCsv: string): string

/**
 * Build the complete system prompt with vendor-specific additions.
 *
 * @param provider - Vendor name
 * @param basePrompt - Base system prompt text
 * @param hasTools - Whether tools are present
 * @param hasMediaParams - Whether media parameters are present
 * @param schemaJson - Optional JSON schema string
 * @param schemaName - Optional schema name
 * @param outputMode - Output mode: "text", "hint", or "strict"
 * @returns Complete system prompt string
 */
export declare function formatSystemPrompt(provider: string, basePrompt: string, hasTools: boolean, hasMediaParams: boolean, schemaJson: string | undefined | null, schemaName: string | undefined | null, outputMode: string): string

/** Generate a unique request ID (format: req_{millis}_{hex6}). */
export declare function generateRequestId(): string

/** Generate OpenTelemetry-compliant span ID (16-char hex, 64-bit). */
export declare function generateSpanId(): string

/** Generate OpenTelemetry-compliant trace ID (32-char hex, 128-bit). */
export declare function generateTraceId(): string

/**
 * Get the default value for a configuration key.
 *
 * This allows SDKs to retrieve default values without doing full resolution,
 * useful for documentation, type hints, and avoiding duplicate default definitions.
 *
 * @param keyName - Config key (e.g., "registry_url", "namespace", "health_interval")
 * @returns Default value if the key is known and has a default, null otherwise.
 */
export declare function getDefault(keyName: string): string | null

/**
 * Get the environment variable name for a configuration key.
 *
 * @param keyName - Config key (e.g., "registry_url", "namespace")
 * @returns Environment variable name if the key is known, null otherwise.
 */
export declare function getEnvVar(keyName: string): string | null

/**
 * Get a read-only view of the agentic loop state.
 *
 * @param stateJson - Serialized loop state
 * @returns State info JSON with iteration, token counts, message_count
 */
export declare function getLoopState(stateJson: string): string

/** Get Redis URL with fallback to default (redis://localhost:6379). */
export declare function getRedisUrl(): string

/**
 * Get TLS configuration resolved from environment variables.
 *
 * Returns JSON string with TLS config including mode, cert paths, and enabled status.
 * SDKs should call this instead of reading TLS env vars directly.
 * If prepare_tls() was called first, returns the cached resolved config
 * (including temp file paths from Vault provider).
 */
export declare function getTlsConfig(): string

/**
 * Get vendor capabilities as JSON.
 *
 * @param provider - Vendor name
 * @returns JSON string with vendor capabilities
 */
export declare function getVendorCapabilities(provider: string): string

/**
 * Initialize the trace publisher.
 *
 * Must be called before publishing spans. Checks if tracing is enabled
 * and initializes Redis connection.
 *
 * @returns true if tracing is enabled and Redis is available, false otherwise.
 */
export declare function initTracePublisher(): Promise<boolean>

/** Inject trace context into JSON-RPC arguments. */
export declare function injectTraceContext(argsJson: string, traceId: string, spanId: string, propagatedHeadersJson?: string | undefined | null): string

/** Check if a JSON schema is simple enough for hint mode. */
export declare function isSimpleSchema(schemaJson: string): boolean

/**
 * Check if trace publishing is available.
 *
 * @returns true if tracing is enabled and Redis is connected.
 */
export declare function isTracePublisherAvailable(): Promise<boolean>

/**
 * Check if distributed tracing is enabled.
 *
 * Checks MCP_MESH_DISTRIBUTED_TRACING_ENABLED environment variable.
 */
export declare function isTracingEnabled(): boolean

/** Agent specification for TypeScript. */
export interface JsAgentSpec {
  /** Unique agent name/identifier */
  name: string
  /** Agent version (semver) */
  version: string
  /** Human-readable description */
  description: string
  /** Registry URL (e.g., "http://localhost:8100") */
  registryUrl: string
  /** HTTP port for this agent */
  httpPort: number
  /** HTTP host announced to registry */
  httpHost: string
  /** Namespace for isolation */
  namespace: string
  /**
   * Agent type: "mcp_agent" (provides capabilities) or "api" (only consumes)
   * Defaults to "mcp_agent" if not specified
   */
  agentType?: string
  /**
   * SDK runtime type: "python" or "typescript"
   * Defaults to "typescript" for TypeScript SDK
   */
  runtime?: string
  /** Tools/capabilities provided by this agent */
  tools: Array<JsToolSpec>
  /** LLM agent specifications for tools using mesh.llm() */
  llmAgents?: Array<JsLlmAgentSpec>
  /** Heartbeat interval in seconds */
  heartbeatInterval: number
}

/** Dependency specification for TypeScript. */
export interface JsDependencySpec {
  /** Capability name to depend on */
  capability: string
  /**
   * Tags for filtering - JSON string to support nested arrays for OR alternatives
   * e.g., '["addition", ["python", "typescript"]]' means addition AND (python OR typescript)
   */
  tags: string
  /** Version constraint (e.g., ">=2.0.0") */
  version?: string
}

/**
 * LLM agent specification for TypeScript.
 * Used to register LLM-powered tools with the mesh.
 */
export interface JsLlmAgentSpec {
  /** Unique identifier for this LLM function (matches the tool's function_name) */
  functionId: string
  /**
   * Provider selector - serialized JSON string
   * e.g., '{"capability": "llm", "tags": ["+claude"]}'
   */
  provider: string
  /**
   * Tool filter specification - serialized JSON string
   * e.g., '[{"capability": "calculator"}, {"tags": ["tools"]}]'
   */
  filter?: string
  /** Filter mode: "all", "best_match", or "*" */
  filterMode: string
  /** Maximum agentic loop iterations */
  maxIterations: number
}

/** LLM provider information returned in llm_provider_available events. */
export interface JsLlmProviderInfo {
  /** Function ID of the LLM function that requested this provider */
  functionId: string
  /** Agent ID providing this capability */
  agentId: string
  /** Endpoint URL to call */
  endpoint: string
  /** Function name to call */
  functionName: string
  /** Model name (optional) */
  model?: string
  /** Vendor name for handler selection (e.g., "gemini", "anthropic") */
  vendor?: string
}

/**
 * LLM tool information returned in llm_tools_updated events.
 * Contains resolved tool metadata for LLM agents to use.
 */
export interface JsLlmToolInfo {
  /** Function name of the tool */
  functionName: string
  /** Capability name */
  capability: string
  /** Tool description for LLM prompting */
  description?: string
  /** Endpoint URL to call */
  endpoint: string
  /** Agent ID providing this tool */
  agentId: string
  /** Input schema (serialized JSON string) */
  inputSchema?: string
}

/** Mesh event for TypeScript. */
export interface JsMeshEvent {
  /** Event type (e.g., "dependency_available", "agent_registered", "llm_tools_updated") */
  eventType: string
  /** Capability name (for dependency events) */
  capability?: string
  /** Endpoint URL (for dependency_available) */
  endpoint?: string
  /** Function name to call (for dependency_available) */
  functionName?: string
  /** Agent ID (for dependency events) */
  agentId?: string
  /**
   * Function that requested this dependency (for dependency events)
   * This is the tool/function that declared the dependency.
   */
  requestingFunction?: string
  /**
   * Dependency index within the requesting function (for dependency events)
   * This allows SDKs to inject the resolved dependency at the correct position.
   */
  depIndex?: number
  /** Function ID of the LLM agent (for llm_tools_updated, llm_provider_available) */
  functionId?: string
  /** List of available tools (for llm_tools_updated event) */
  tools?: Array<JsLlmToolInfo>
  /** Provider info (for llm_provider_available event) */
  providerInfo?: JsLlmProviderInfo
  /** Error message (for error events) */
  error?: string
  /** Reason for event (for disconnect events) */
  reason?: string
}

/** Tool specification for TypeScript. */
export interface JsToolSpec {
  /** Function name in the code */
  functionName: string
  /** Capability name for discovery */
  capability: string
  /** Version of this capability */
  version: string
  /** Tags for filtering */
  tags: Array<string>
  /** Human-readable description */
  description: string
  /** Dependencies required by this tool */
  dependencies: Array<JsDependencySpec>
  /** JSON Schema for input parameters (MCP format) - serialized JSON string */
  inputSchema?: string
  /** LLM filter specification (for @mesh.llm decorated functions) - serialized JSON string */
  llmFilter?: string
  /** LLM provider specification (for mesh delegation) - serialized JSON string */
  llmProvider?: string
}

/**
 * Make a JSON schema strict for structured output.
 *
 * Adds additionalProperties: false to all object types.
 * If addAllRequired is true, sets required to include all property keys.
 */
export declare function makeSchemaStrict(schemaJson: string, addAllRequired?: boolean | undefined | null): string

/** Check if a header matches the propagation allowlist. */
export declare function matchesPropagateHeader(headerName: string, allowlistCsv: string): boolean

/**
 * Parse SSE or plain JSON response and extract JSON data.
 *
 * @param responseText - Raw response body (SSE or plain JSON)
 * @returns Extracted JSON string
 */
export declare function parseSseResponse(responseText: string): string

/**
 * Parse SSE or plain JSON response and return a JS object directly.
 *
 * Avoids the double-parse overhead of `parseSseResponse` (which returns
 * a JSON string that TypeScript must then `JSON.parse`).
 *
 * @param responseText - Raw response body (SSE or plain JSON)
 * @returns Parsed JavaScript object
 */
export declare function parseSseResponseToObject(responseText: string): any

/**
 * Prepare TLS credentials (fetch from provider, write secure temp files).
 *
 * Must be called early in agent startup, before HTTP server starts.
 * Results are cached globally -- subsequent calls to get_tls_config()
 * will return the resolved config with temp file paths.
 *
 * @param agentName - Agent name for certificate CN
 * @returns JSON string with TLS config
 */
export declare function prepareTls(agentName: string): string

/**
 * Process an LLM response in the agentic loop.
 *
 * @param stateJson - Serialized loop state from a previous call
 * @param llmResponseJson - LLM response with optional tool_calls, content, usage
 * @returns Action JSON: execute_tools, done, max_iterations, or error
 */
export declare function processLlmResponse(stateJson: string, llmResponseJson: string): string

/**
 * Publish a trace span to Redis.
 *
 * Publishes span data to the `mesh:trace` Redis stream.
 * Non-blocking - silently handles failures to never break agent operations.
 *
 * @param spanData - Map of span data (all values must be strings)
 * @returns true if published successfully, false otherwise.
 */
export declare function publishSpan(spanData: Record<string, string>): Promise<boolean>

/**
 * Resolve configuration value with priority: ENV > param > default.
 *
 * @param keyName - Config key (e.g., "registry_url", "http_host", "namespace")
 * @param paramValue - Optional value from code/config
 * @returns Resolved value or empty string if unknown key
 */
export declare function resolveConfig(keyName: string, paramValue?: string | undefined | null): string

/**
 * Resolve boolean configuration value with priority: ENV > param > default.
 *
 * @param keyName - Config key (e.g., "distributed_tracing_enabled")
 * @param paramValue - Optional value from code/config
 * @returns Resolved boolean value
 */
export declare function resolveConfigBool(keyName: string, paramValue?: boolean | undefined | null): boolean

/**
 * Resolve integer configuration value with priority: ENV > param > default.
 *
 * @param keyName - Config key (e.g., "http_port", "health_interval")
 * @param paramValue - Optional value from code/config
 * @returns Resolved integer value or null if unknown key
 */
export declare function resolveConfigInt(keyName: string, paramValue?: number | undefined | null): number | null

/** Sanitize a JSON schema by removing unsupported validation keywords. */
export declare function sanitizeSchema(schemaJson: string): string

/**
 * Start an agent runtime with the given specification.
 *
 * This spawns a background Tokio runtime that handles:
 * - Registration with the mesh registry
 * - Periodic heartbeats
 * - Topology change detection
 * - Event streaming
 */
export declare function startAgent(spec: JsAgentSpec): JsAgentHandle

/** Strip markdown code fences from content. */
export declare function stripCodeFences(text: string): string
