/* auto-generated by NAPI-RS */
/* eslint-disable */
/**
 * Producer-side handle bound to a single job. Application code receives one
 * via DDDI injection (the inbound tool wrapper, next dispatch); the
 * constructor is also exposed for tests and the claim worker dispatch path.
 *
 * Each controller owns a per-instance coalescing queue plus a background
 * batching tick that flushes mid-flight progress deltas to the registry on a
 * fixed cadence. The tick is shut down (with a final flush) when the
 * controller is dropped by JS GC.
 */
export declare class JobController {
  /**
   * Construct a controller bound to `(jobId, instanceId)` against the
   * given `registryUrl`. Spawns a per-controller background batching tick
   * so mid-flight `updateProgress` calls reach the registry on the
   * configured cadence (default 2s); the tick is torn down with a final
   * flush when the controller is dropped.
   */
  constructor(jobId: string, instanceId: string, registryUrl: string)
  /** The job ID this controller is bound to. */
  get jobId(): string
  /**
   * Enqueue a progress update. Coalesces with any prior pending progress
   * for this job — only the latest survives the next batch flush.
   */
  updateProgress(progress: number, message?: string | undefined | null): Promise<void>
  /**
   * Mark the job complete with the given result. Flushes immediately.
   * `result` is any JSON-shaped JS value (object/array/primitive) —
   * mirrors MCP's "results are JSON" contract.
   */
  complete(result: any): Promise<void>
  /** Mark the job failed with the given error reason. Flushes immediately. */
  fail(error: string): Promise<void>
  /**
   * Whether `complete` / `fail` has already been called on this
   * controller. The TS dispatch wrapper uses this to decide whether a
   * returning user function needs an auto-`complete` — users who already
   * `await job.complete(...)` closed out the row, so the wrapper must
   * NOT double-flush.
   *
   * Sync from JS's perspective: returns a Promise<boolean> because the
   * underlying queue read is async, but the call is short.
   */
  isTerminal(): Promise<boolean>
  /**
   * Voluntarily release the lease so a peer replica can re-claim and
   * retry. Used by the TS dispatch wrapper when a handler raises a
   * retryOn-matched exception (issue #894): instead of marking the row
   * terminal=failed, the SDK calls `releaseLease` so the registry resets
   * `owner_instance_id` and a peer replica picks up the row within ~5s
   * via the HEAD-heartbeat path. Note: release does NOT increment
   * `attempt_count` — the claim that picked the row up already counted
   * this attempt; the next claim will count the next attempt.
   *
   * Marks terminal locally before the backend call to fence racing
   * progress updates from the now-defunct attempt (mirror of
   * `JobController::release_lease` in Rust core).
   */
  releaseLease(reason?: string | undefined | null): Promise<void>
}
export type JsJobController = JobController

/**
 * Consumer-side handle: returned by [`submit_job_napi`] and exposes
 * `wait` / `status` / `cancel` for code that wants to await a remote job.
 */
export declare class JobProxy {
  /**
   * Construct a proxy bound to a known `jobId` + `registryUrl`. Normally
   * callers obtain a proxy via [`submit_job_napi`] / DDDI injection
   * rather than constructing one directly.
   */
  constructor(jobId: string, registryUrl: string)
  /** The job ID this proxy is bound to. */
  get jobId(): string
  /**
   * Read the latest job state from the registry (single GET).
   * Returns the full job row as a JSON object.
   */
  status(): Promise<any>
  /**
   * Poll until the job reaches a terminal state. Returns the result
   * payload as a JS value (object/array/primitive) on success;
   * rejects with a "timeout: ..." error on `timeoutSecs`, or
   * "cancelled" / other reason on non-success terminal.
   */
  wait(timeoutSecs?: number | undefined | null): Promise<any>
  /**
   * Request cancellation. The registry forwards the signal to the
   * owner replica when alive. Resolves once the registry has
   * acknowledged.
   */
  cancel(reason?: string | undefined | null): Promise<void>
}
export type JsJobProxy = JobProxy

/** 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>
  /**
   * Update the A2A surfaces and agent_type registered with the registry
   * (issue #938 — mid-flight `mesh.a2a.mount(...)` parity with Python's
   * per-heartbeat `_build_a2a_surfaces`).
   *
   * Uses smart diffing — only triggers a full heartbeat when either the
   * agent_type or the serialized surfaces JSON has actually changed.
   * Empty-string surfaces payloads are treated as `null` so the wire
   * stays clean (matches the constructor-time normalization).
   *
   * Call this from the SDK after each `mesh.a2a.mount(...)` so deferred
   * mounts (mounts registered after `startAgent()` / first heartbeat) are
   * reflected in the next heartbeat envelope rather than silently dropped.
   *
   * @param agentType - New agent_type ("a2a", "api", or "mcp_agent")
   * @param surfaces - JSON-encoded surfaces array (matches `JsAgentSpec.surfaces`),
   *                   or null to clear the field
   * @returns true if the update was sent successfully
   */
  updateSurfaces(agentType: string, surfaces?: string | undefined | null): 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

/**
 * Await the cancel token registered for `jobId` in the process-wide
 * cancel registry. Resolves when the token fires (i.e.
 * [`cancel_active_job_napi`] was called for this `jobId`), or
 * immediately if no token is currently registered (already terminal /
 * never claimed) — callers don't hang on stale jobs.
 *
 * Used by the TS proxy to wire outbound `AbortController`s to the
 * active job's cancel token: when the registry's
 * `POST /jobs/{job_id}/cancel` route fires the token, the proxy aborts
 * in-flight outbound `fetch()` requests so cancel propagates to
 * downstream calls instead of stalling on socket reads. Without this,
 * the producer-side cancel only flips `JobController.is_terminal()`
 * after the outer await returns — outbound HTTP work the handler
 * kicked off keeps running in the background.
 *
 * napi-rs maps `pub async fn -> ()` to `Promise<void>` on the JS side.
 *
 * Resolves on EITHER explicit cancel OR the registry's natural-end
 * signal. Without the latter, futures awaiting a job that finishes
 * without an explicit cancel would hang forever (the snapshot Arc
 * keeps the cancel token alive past `unregister_active_job`), leaking
 * one Rust task + one JS Promise per outbound call. With the `ended`
 * signal, awaiters wake when the registry tears down the entry.
 */
export declare function awaitJobCancel(jobId: string): Promise<void>

/**
 * 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>

/**
 * Fire the cancel token registered for `jobId` in the process-wide
 * cancel registry, if any. Returns `true` iff a token was found and
 * fired (matches [`crate::cancel_registry::cancel_active_job`] semantics).
 *
 * Used by the SDK-owned `POST /jobs/{job_id}/cancel` HTTP route — when the
 * registry forwards a cancel to this replica, the route handler calls this
 * to abort the in-flight job. (Route wiring lands in the next dispatch.)
 */
export declare function cancelActiveJob(jobId: string): boolean

/**
 * 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

/**
 * Snapshot of the active job context on the current Tokio task, or `null`
 * if no job is in scope.
 *
 * Source of truth is the Rust [`crate::job_context`] (set via
 * `with_job` / `run_as_job` by the inbound HTTP wrapper or claim worker).
 * JS code typically reads the AsyncLocalStorage mirror — this binding is
 * for cross-FFI parity / debugging / Rust-originated paths.
 */
export declare function currentJob(): JobContextSnapshot | null

/** 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>

/**
 * Compute the `X-Mesh-Job-Id` / `X-Mesh-Timeout` header values for the
 * active job context, if any.
 *
 * Returns `null` when no job context is active on the current task.
 * The TS outbound HTTP layer (e.g. the proxy `createProxy` factory)
 * merges these into the request headers alongside any existing
 * `X-Trace-Id` propagation.
 *
 * Header *name shape*: this function returns a plain object the SDK can
 * destructure or spread into a request-headers map. We deliberately do NOT
 * reach across into a JS `Headers` instance here — that's TS-runtime
 * territory (Express/Fetch/undici) and varies between transport stacks.
 */
export declare function injectJobHeaders(): JobHeaders | null

/** 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

/**
 * Snapshot of the active job context returned by [`current_job_napi`].
 * Mirrors the TS-side `JobContextSnapshot` interface in `job-context.ts`.
 */
export interface JobContextSnapshot {
  jobId: string
  /** `None` if no deadline is set on the active context. */
  deadlineSecsRemaining?: number
}

/**
 * Headers injected by [`inject_job_headers_napi`].
 *
 * Both fields are optional individually: when an active context has no
 * deadline, `xMeshTimeout` is `None`. When no job context is active at all,
 * the function returns `None` instead of an empty object.
 */
export interface JobHeaders {
  /** `X-Mesh-Job-Id` header value. */
  xMeshJobId: string
  /**
   * `X-Mesh-Timeout` header value (seconds remaining as decimal string),
   * or `None` if the active context has no deadline.
   */
  xMeshTimeout?: string
}

/** Agent specification for TypeScript. */
export interface JsAgentSpec {
  /** Base agent name (shared across replicas, e.g., "fortuna") */
  name: string
  /**
   * Unique per-replica agent ID (e.g., "fortuna-abc12345").
   * Defaults to `name` when not provided (backward compat).
   */
  agentId?: 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
  /**
   * A2A surfaces JSON (issue #933 — TS A2A producer parity with Python /
   * Java). Optional — populated only when `agent_type=a2a` and the SDK has
   * at least one `mesh.a2a.mount(...)` surface registered. Stored as a
   * JSON-encoded string to match the Python `surfaces: Option<String>`
   * shape on `AgentSpec`; the Rust core re-parses before forwarding
   * verbatim to the registry's `MeshAgentRegistration.surfaces` field.
   */
  surfaces?: string
  /**
   * Issue #972: true if at least one A2A producer surface is declared.
   * Stamped by the TS layer (see `agent.ts` JsAgentSpec construction).
   */
  a2AProducer: boolean
  /**
   * Issue #972: true if at least one A2A consumer surface is declared.
   * Stamped by the TS layer.
   */
  a2AConsumer: boolean
}

/** 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
  /** Issue #547: canonical normalized expected schema (serialized JSON string) */
  expectedSchemaCanonical?: string
  /** Issue #547: SHA256 hash (sha256:<hex>) of expected_schema_canonical */
  expectedSchemaHash?: string
  /** Issue #547: schema match mode ("subset" or "strict") */
  matchMode?: 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
  /**
   * Provider tool's @mesh.tool kwargs as a JSON string. SDKs decode this
   * to configure the provider proxy from the producer's advertised
   * behavior (e.g. `stream_type`).
   */
  kwargs?: 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
  /**
   * Producer's @mesh.tool kwargs as a JSON string (for dependency_available
   * and dependency_changed). SDKs decode this to configure the consumer-side
   * proxy from the producer's advertised behavior (issue #645 bug 2).
   */
  kwargs?: string
  /** 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
  /** Issue #547: raw JSON Schema for output (return type) - serialized JSON string */
  outputSchema?: string
  /** Issue #547: canonical normalized input schema (post-normalize) - serialized JSON string */
  inputSchemaCanonical?: string
  /** Issue #547: SHA256 hash (sha256:<hex>) of input_schema_canonical */
  inputSchemaHash?: string
  /** Issue #547: canonical normalized output schema - serialized JSON string */
  outputSchemaCanonical?: string
  /** Issue #547: SHA256 hash (sha256:<hex>) of output_schema_canonical */
  outputSchemaHash?: string
  /** Issue #547: normalizer warnings (list of strings) */
  schemaWarnings?: Array<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

/**
 * Normalize a raw JSON schema into canonical form + SHA256 hash (Issue #547).
 *
 * Returns a JSON string with fields: canonical, hash, verdict, warnings.
 * Mirrors the Python `normalize_schema_py` binding so TypeScript runtimes can
 * emit the same canonical form + hash as Python producers/consumers.
 */
export declare function normalizeSchema(rawJson: string, origin?: string | undefined | null): string

/**
 * 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

/**
 * Submit a new job via the registry and return a [`JsJobProxy`].
 *
 * Mirrors [`SubmitJobArgs`] field-for-field. Single-arg shape matches
 * Python's PyO3 binding.
 */
export declare function submitJob(args: SubmitJobArgs): Promise<JobProxy>

/**
 * Arguments for [`submit_job_napi`]. Mirrors [`SubmitJobArgs`]
 * field-for-field; `payload` is any JSON-shaped JS value.
 *
 * Optional `i64` fields are typed as `Option<i64>` — JavaScript Number
 * safely represents integers up to 2^53; callers passing unix-epoch
 * timestamps stay well inside that range.
 */
export interface SubmitJobArgs {
  registryUrl: string
  capability: string
  payload: any
  submittedBy: string
  ownerInstanceId?: string
  maxDuration?: number
  maxRetries?: number
  totalDeadline?: number
}

export declare function withJobAsync(jobId: string, deadlineSecs: number | undefined | null, body: Promise<any>): Promise<any>
