/**
* SystemEvent - Base interface for all events in the system
*
* Unified Event Structure:
* ```
* SystemEvent
* │
* │  All events have: type, timestamp, data, source, category, intent
* │
* ├── source: "command"       ← API operations (request/response)
* │   ├── category: "request"   → container_create_request, agent_run_request...
* │   └── category: "response"  → container_create_response, agent_run_response...
* │
* ├── source: "environment"   ← External world (Claude API, Network)
* │   ├── category: "stream"    → message_start, text_delta, message_stop, tool_call...
* │   └── category: "connection"→ connected, disconnected, reconnecting
* │
* ├── source: "container"     ← Container operations
* │   └── category: "lifecycle" → container_created, container_destroyed, agent_registered...
* │
* ├── source: "session"       ← Session operations
* │   ├── category: "lifecycle" → session_created, session_destroyed
* │   ├── category: "persist"   → session_saved, message_persisted
* │   └── category: "action"    → session_resumed, session_forked
* │
* ├── source: "sandbox"       ← Sandbox resources
* │   ├── category: "workdir"   → file_read, file_written
* │   └── category: "mcp"       → tool_execute, mcp_server_connected
* │
* └── source: "agent"         ← Agent internal
*     ├── category: "stream"    → (forwarded from environment)
*     ├── category: "state"     → state transitions
*     ├── category: "message"   → complete messages
*     └── category: "turn"      → conversation turns
* ```
*
* Design Principles:
* - Unified: All events share the same base structure
* - Self-describing: source/category/intent tell you everything
* - Filterable: Easy to subscribe by source, category, or type
*/
/**
* Event source - where the event originated
*/
type EventSource = "environment" | "agent" | "session" | "container" | "sandbox" | "command";
/**
* Event intent - what the event represents
*/
type EventIntent = "request" | "result" | "notification";
/**
* Event category - fine-grained classification within source
*/
type EventCategory = "stream" | "connection" | "state" | "message" | "turn" | "error" | "lifecycle" | "persist" | "action" | "workdir" | "mcp" | "request" | "response";
/**
* UserContext - User-defined request context passed from client
*
* This context is passed through the entire request lifecycle:
* Client → WebSocket → Runtime → Agent → Model Service
*
* Purely user-customizable - define any fields you need for your application:
* - Authentication (userId, token, apiKey)
* - Multi-tenancy (tenantId, orgId)
* - Audit logging (clientIp, userAgent)
* - Business logic (permissions, roles, preferences)
*
* @example
* ```typescript
* const userContext: UserContext = {
*   userId: "user-123",
*   tenantId: "tenant-456",
*   token: "jwt-token",
*   roles: ["admin", "editor"],
*   preferences: { theme: "dark" }
* };
* ```
*/
type UserContext = Record<string, unknown>;
/**
* EventContext - Scope information attached to events
*/
interface EventContext {
	/**
	* Container ID (isolation boundary)
	*/
	containerId?: string;
	/**
	* Image ID (persistent conversation identity)
	*/
	imageId?: string;
	/**
	* Agent ID (if event is agent-scoped)
	*/
	agentId?: string;
	/**
	* Session ID (if event is session-scoped)
	*/
	sessionId?: string;
	/**
	* Turn ID (for correlating events within a single turn)
	* A turn = one user message + assistant response cycle
	*/
	turnId?: string;
	/**
	* Correlation ID (for request-response tracking)
	*/
	correlationId?: string;
	/**
	* User request context (passed from client)
	*
	* Contains user identity, authentication, and custom metadata
	* that flows through the entire request lifecycle.
	*/
	userContext?: UserContext;
}
/**
* SystemEvent - Base interface for ALL events in the system
*
* Every event has:
* - type: What happened (e.g., "text_delta", "session_saved")
* - timestamp: When it happened
* - data: Event payload
* - source: Where it came from
* - category: What kind of event
* - intent: What it means (notification/request/result)
* - context: Optional scope information
* - broadcastable: Whether to broadcast to external clients (default: true)
*/
interface SystemEvent<
	T extends string = string,
	D = unknown,
	S extends EventSource = EventSource,
	C extends EventCategory = EventCategory,
	I extends EventIntent = EventIntent
> {
	/**
	* Event type identifier (e.g., "text_delta", "session_saved")
	*/
	readonly type: T;
	/**
	* Event timestamp (Unix milliseconds)
	*/
	readonly timestamp: number;
	/**
	* Event payload data
	*/
	readonly data: D;
	/**
	* Event source - where the event originated
	*/
	readonly source: S;
	/**
	* Event category - fine-grained classification
	*/
	readonly category: C;
	/**
	* Event intent - what the event represents
	*/
	readonly intent: I;
	/**
	* Event context - scope information (optional)
	*/
	readonly context?: EventContext;
	/**
	* Whether to broadcast this event to external clients (SSE/WebSocket)
	*
	* - true or undefined: Broadcast to all external clients
	* - false: Only consumed internally, not broadcast
	*
	* Used for internal events like DriveableEvent that should be
	* processed by the engine but not sent directly to clients.
	* @default true
	*/
	readonly broadcastable?: boolean;
}
/**
* MCP Server Config (SDK Compatible)
*
* Configuration for MCP servers, compatible with Claude Agent SDK.
* Used in AgentConfig.mcpServers.
*
* Note: For stdio type, the 'type' field is optional (defaults to stdio).
*/
type McpServerConfig = McpStdioServerConfig | McpSseServerConfig | McpHttpServerConfig | McpSdkServerConfig;
/**
* Stdio Server Config (SDK Compatible)
* Type is optional, defaults to stdio when omitted.
*/
interface McpStdioServerConfig {
	type?: "stdio";
	command: string;
	args?: string[];
	env?: Record<string, string>;
}
/**
* SSE Server Config (SDK Compatible)
*/
interface McpSseServerConfig {
	type: "sse";
	url: string;
	headers?: Record<string, string>;
}
/**
* HTTP Server Config (SDK Compatible)
*/
interface McpHttpServerConfig {
	type: "http";
	url: string;
	headers?: Record<string, string>;
}
/**
* SDK Server Config (SDK Compatible)
* For in-process MCP servers.
*/
interface McpSdkServerConfig {
	type: "sdk";
	name: string;
	instance: unknown;
}
/**
* Image metadata for storing provider-specific data
*/
interface ImageMetadata {
	/** Claude SDK session ID for conversation resume */
	claudeSdkSessionId?: string;
	/** User context - serialized JSON string for passing to LLM Proxy via URL */
	userContext?: string;
}
/**
* Image storage record
*
* Represents a conversation that persists across server restarts.
*/
interface ImageRecord {
	/**
	* Unique image identifier
	* Pattern: `img_${nanoid()}`
	*/
	imageId: string;
	/**
	* Container ID (user isolation boundary)
	*/
	containerId: string;
	/**
	* Session ID for message storage
	* Messages are stored in Session, not duplicated here
	*/
	sessionId: string;
	/**
	* Conversation name (displayed to user)
	*/
	name: string;
	/**
	* Conversation description (optional)
	*/
	description?: string;
	/**
	* System prompt - controls agent behavior
	*/
	systemPrompt?: string;
	/**
	* Parent image ID (for fork/branch feature)
	*/
	parentImageId?: string;
	/**
	* MCP servers configuration
	*/
	mcpServers?: Record<string, McpServerConfig>;
	/**
	* Blacklist of disallowed tools (tool names)
	* When set, these tools will be disabled for the agent
	*/
	disallowedTools?: string[];
	/**
	* Restrict available tools - can be array of tool names or preset
	* More granular control over which built-in tools are available
	*/
	tools?: string[] | {
		type: "preset"
		preset: "claude_code"
	};
	/**
	* Claude Code 风格的 Skills
	* 每个 skill 会被写入 .claude/skills/{name}/SKILL.md
	* SDK 自动发现并注入到 Claude 的 context 中
	*/
	skills?: import("~/agentx").SkillDefinition[];
	/**
	* Per-image LLM configuration (optional)
	*
	* When set, this image's agent will use this LLM config instead of the global Runtime-level config.
	* Enables different conversations/roles to use different LLM providers or models.
	* Fields are merged with global config: only non-empty fields override the global defaults.
	*/
	llmConfig?: {
		apiKey?: string
		baseUrl?: string
		model?: string
	};
	/**
	* Provider-specific metadata (e.g., Claude SDK session ID)
	*/
	metadata?: ImageMetadata;
	/**
	* Creation timestamp (Unix milliseconds)
	*/
	createdAt: number;
	/**
	* Last update timestamp (Unix milliseconds)
	*/
	updatedAt: number;
}
/**
* Text Part
*
* Plain text content in a message.
*/
interface TextPart {
	/** Content type discriminator */
	type: "text";
	/** The text content (supports Markdown) */
	text: string;
}
/**
* Image Part
*
* Image content in a message.
*/
interface ImagePart {
	/** Content type discriminator */
	type: "image";
	/** Image data (base64-encoded string or URL) */
	data: string;
	/** Image MIME type */
	mediaType: "image/png" | "image/jpeg" | "image/gif" | "image/webp";
	/** Optional image name/filename */
	name?: string;
}
/**
* File Part
*
* File attachment in a message (PDF, documents, etc.).
*/
interface FilePart {
	/** Content type discriminator */
	type: "file";
	/** File data (base64-encoded string or URL) */
	data: string;
	/** File MIME type (IANA media type) */
	mediaType: string;
	/** Optional filename */
	filename?: string;
}
/**
* User Content Part
*
* Subset of ContentPart types that users can send in messages.
* - TextPart: Plain text content
* - ImagePart: Image attachments (JPEG, PNG, GIF, WebP)
* - FilePart: File attachments (PDF, documents, etc.)
*/
type UserContentPart = TextPart | ImagePart | FilePart;
/**
* Base interface for Command request events
*/
interface BaseCommandRequest<
	T extends string,
	D = unknown
> extends SystemEvent<T, D, "command", "request", "request"> {}
/**
* Base interface for Command response events
*/
interface BaseCommandResponse<
	T extends string,
	D = unknown
> extends SystemEvent<T, D, "command", "response", "result"> {}
/**
* Request to create a container
*/
interface ContainerCreateRequest extends BaseCommandRequest<"container_create_request", {
	requestId: string
	containerId: string
}> {}
/**
* Response to container creation
*/
interface ContainerCreateResponse extends BaseCommandResponse<"container_create_response", {
	requestId: string
	containerId: string
	error?: string
}> {}
/**
* Request to get a container
*/
interface ContainerGetRequest extends BaseCommandRequest<"container_get_request", {
	requestId: string
	containerId: string
}> {}
/**
* Response to container get
*/
interface ContainerGetResponse extends BaseCommandResponse<"container_get_response", {
	requestId: string
	containerId?: string
	exists: boolean
	error?: string
}> {}
/**
* Request to list containers
*/
interface ContainerListRequest extends BaseCommandRequest<"container_list_request", {
	requestId: string
}> {}
/**
* Response to container list
*/
interface ContainerListResponse extends BaseCommandResponse<"container_list_response", {
	requestId: string
	containerIds: string[]
	error?: string
}> {}
/**
* Request to get an agent
*/
interface AgentGetRequest extends BaseCommandRequest<"agent_get_request", {
	requestId: string
	agentId: string
}> {}
/**
* Response to agent get
*/
interface AgentGetResponse extends BaseCommandResponse<"agent_get_response", {
	requestId: string
	agentId?: string
	containerId?: string
	exists: boolean
	error?: string
}> {}
/**
* Request to list agents
*/
interface AgentListRequest extends BaseCommandRequest<"agent_list_request", {
	requestId: string
	containerId: string
}> {}
/**
* Response to agent list
*/
interface AgentListResponse extends BaseCommandResponse<"agent_list_response", {
	requestId: string
	agents: Array<{
		agentId: string
		containerId: string
		imageId: string
	}>
	error?: string
}> {}
/**
* Request to destroy an agent
*/
interface AgentDestroyRequest extends BaseCommandRequest<"agent_destroy_request", {
	requestId: string
	agentId: string
}> {}
/**
* Response to agent destroy
*/
interface AgentDestroyResponse extends BaseCommandResponse<"agent_destroy_response", {
	requestId: string
	agentId: string
	success: boolean
	error?: string
}> {}
/**
* Request to destroy all agents in a container
*/
interface AgentDestroyAllRequest extends BaseCommandRequest<"agent_destroy_all_request", {
	requestId: string
	containerId: string
}> {}
/**
* Response to destroy all agents
*/
interface AgentDestroyAllResponse extends BaseCommandResponse<"agent_destroy_all_response", {
	requestId: string
	containerId: string
	error?: string
}> {}
/**
* Request to send a message
* Can use either imageId (preferred) or agentId
* If using imageId and agent is not running, it will be auto-activated
*/
interface MessageSendRequest extends BaseCommandRequest<"message_send_request", {
	requestId: string
	/** Image ID (preferred) - will auto-activate if offline */
	imageId?: string
	/** Agent ID (legacy) - must be already running */
	agentId?: string
	/** Message content (text-only or multimodal) */
	content: string | UserContentPart[]
	/**
	* User request context (passed from client)
	*
	* Contains user identity, authentication, and custom metadata.
	* This context flows through the entire request lifecycle:
	* Client → Runtime → Agent → Model Service
	*/
	userContext?: UserContext
}> {}
/**
* Response to message send (acknowledges message received, not completion)
*/
interface MessageSendResponse extends BaseCommandResponse<"message_send_response", {
	requestId: string
	imageId?: string
	agentId: string
	error?: string
}> {}
/**
* Request to interrupt an agent
* Can use either imageId or agentId
*/
interface AgentInterruptRequest extends BaseCommandRequest<"agent_interrupt_request", {
	requestId: string
	/** Image ID (preferred) */
	imageId?: string
	/** Agent ID (legacy) */
	agentId?: string
	/** User request context (for audit logging) */
	userContext?: UserContext
}> {}
/**
* Response to agent interrupt
*/
interface AgentInterruptResponse extends BaseCommandResponse<"agent_interrupt_response", {
	requestId: string
	imageId?: string
	agentId?: string
	error?: string
}> {}
/**
* Request to create a new image (conversation)
*/
interface ImageCreateRequest extends BaseCommandRequest<"image_create_request", {
	requestId: string
	containerId: string
	config: {
		name?: string
		description?: string
		systemPrompt?: string
		/** Blacklist of disallowed tools (tool names) */
		disallowedTools?: string[]
		/** Restrict available tools - can be array of tool names or preset */
		tools?: string[] | {
			type: "preset"
			preset: "claude_code"
		}
		/** Claude Code 风格的 Skills */
		skills?: import("~/agentx").SkillDefinition[]
		/** Per-image LLM configuration - overrides Runtime-level config */
		llmConfig?: {
			apiKey?: string
			baseUrl?: string
			model?: string
		}
	}
	/** User request context (for audit logging and access control) */
	userContext?: UserContext
}> {}
/**
* Response to image creation
*/
interface ImageCreateResponse extends BaseCommandResponse<"image_create_response", {
	requestId: string
	record: ImageRecord
	error?: string
}> {}
/**
* Request to run an image (create or reuse agent)
*/
interface ImageRunRequest extends BaseCommandRequest<"image_run_request", {
	requestId: string
	imageId: string
}> {}
/**
* Response to image run
*/
interface ImageRunResponse extends BaseCommandResponse<"image_run_response", {
	requestId: string
	imageId: string
	agentId: string
	/** true if reusing existing agent, false if newly created */
	reused: boolean
	error?: string
}> {}
/**
* Request to stop an image (destroy agent, keep image)
*/
interface ImageStopRequest extends BaseCommandRequest<"image_stop_request", {
	requestId: string
	imageId: string
}> {}
/**
* Response to image stop
*/
interface ImageStopResponse extends BaseCommandResponse<"image_stop_response", {
	requestId: string
	imageId: string
	error?: string
}> {}
/**
* Request to update an image (name, description, etc.)
*/
interface ImageUpdateRequest extends BaseCommandRequest<"image_update_request", {
	requestId: string
	imageId: string
	updates: {
		name?: string
		description?: string
	}
}> {}
/**
* Response to image update
*/
interface ImageUpdateResponse extends BaseCommandResponse<"image_update_response", {
	requestId: string
	record: ImageRecord
	error?: string
}> {}
/**
* Request to list all images
*/
interface ImageListRequest extends BaseCommandRequest<"image_list_request", {
	requestId: string
	containerId?: string
}> {}
/**
* Image list item with online status
*/
interface ImageListItem extends ImageRecord {
	/** Whether an agent is currently running for this image */
	online: boolean;
	/** Current agent ID if online */
	agentId?: string;
}
/**
* Response to image list
*/
interface ImageListResponse extends BaseCommandResponse<"image_list_response", {
	requestId: string
	records: ImageListItem[]
	error?: string
}> {}
/**
* Request to get an image by ID
*/
interface ImageGetRequest extends BaseCommandRequest<"image_get_request", {
	requestId: string
	imageId: string
}> {}
/**
* Response to image get
*/
interface ImageGetResponse extends BaseCommandResponse<"image_get_response", {
	requestId: string
	record?: ImageListItem | null
	error?: string
}> {}
/**
* Request to delete an image
*/
interface ImageDeleteRequest extends BaseCommandRequest<"image_delete_request", {
	requestId: string
	imageId: string
}> {}
/**
* Response to image delete
*/
interface ImageDeleteResponse extends BaseCommandResponse<"image_delete_response", {
	requestId: string
	imageId: string
	error?: string
}> {}
/**
* Request to get messages for an image
*/
interface ImageMessagesRequest extends BaseCommandRequest<"image_messages_request", {
	requestId: string
	imageId: string
}> {}
/**
* Response to image messages request
*/
interface ImageMessagesResponse extends BaseCommandResponse<"image_messages_response", {
	requestId: string
	imageId: string
	messages: Array<{
		id: string
		role: "user" | "assistant" | "tool_call" | "tool_result"
		content: unknown
		timestamp: number
	}>
	error?: string
}> {}
/**
* CommandEventMap - Maps event type string to event interface
*
* Enables type-safe event handling:
* ```typescript
* bus.onCommand("container_create_request", (event) => {
*   event.data.requestId;    // ✓ string
*   event.data.containerId;  // ✓ string
* });
* ```
*/
interface CommandEventMap {
	container_create_request: ContainerCreateRequest;
	container_create_response: ContainerCreateResponse;
	container_get_request: ContainerGetRequest;
	container_get_response: ContainerGetResponse;
	container_list_request: ContainerListRequest;
	container_list_response: ContainerListResponse;
	agent_get_request: AgentGetRequest;
	agent_get_response: AgentGetResponse;
	agent_list_request: AgentListRequest;
	agent_list_response: AgentListResponse;
	agent_destroy_request: AgentDestroyRequest;
	agent_destroy_response: AgentDestroyResponse;
	agent_destroy_all_request: AgentDestroyAllRequest;
	agent_destroy_all_response: AgentDestroyAllResponse;
	message_send_request: MessageSendRequest;
	message_send_response: MessageSendResponse;
	agent_interrupt_request: AgentInterruptRequest;
	agent_interrupt_response: AgentInterruptResponse;
	image_create_request: ImageCreateRequest;
	image_create_response: ImageCreateResponse;
	image_run_request: ImageRunRequest;
	image_run_response: ImageRunResponse;
	image_stop_request: ImageStopRequest;
	image_stop_response: ImageStopResponse;
	image_update_request: ImageUpdateRequest;
	image_update_response: ImageUpdateResponse;
	image_list_request: ImageListRequest;
	image_list_response: ImageListResponse;
	image_get_request: ImageGetRequest;
	image_get_response: ImageGetResponse;
	image_delete_request: ImageDeleteRequest;
	image_delete_response: ImageDeleteResponse;
	image_messages_request: ImageMessagesRequest;
	image_messages_response: ImageMessagesResponse;
}
/**
* Maps request event type to its corresponding response event type
*/
interface CommandRequestResponseMap {
	container_create_request: "container_create_response";
	container_get_request: "container_get_response";
	container_list_request: "container_list_response";
	agent_get_request: "agent_get_response";
	agent_list_request: "agent_list_response";
	agent_destroy_request: "agent_destroy_response";
	agent_destroy_all_request: "agent_destroy_all_response";
	message_send_request: "message_send_response";
	agent_interrupt_request: "agent_interrupt_response";
	image_create_request: "image_create_response";
	image_run_request: "image_run_response";
	image_stop_request: "image_stop_response";
	image_update_request: "image_update_response";
	image_list_request: "image_list_response";
	image_get_request: "image_get_response";
	image_delete_request: "image_delete_response";
	image_messages_request: "image_messages_response";
}
/**
* All command request types
*/
type CommandRequestType = keyof CommandRequestResponseMap;
/**
* Get response type for a request type
*/
type ResponseTypeFor<T extends CommandRequestType> = CommandRequestResponseMap[T];
/**
* Get response event for a request type
*/
type ResponseEventFor<T extends CommandRequestType> = CommandEventMap[ResponseTypeFor<T>];
/**
* Get request data type (without requestId, as it's auto-generated)
*/
type RequestDataFor<T extends CommandRequestType> = Omit<CommandEventMap[T]["data"], "requestId">;
/**
* LogLevel - Standard log level type
*
* Defines the severity levels for logging.
* Uses string literal types for better readability and type safety.
*/
type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
/**
* Logging context metadata
*/
type LogContext = Record<string, unknown>;
/**
* Logger interface
*
* All logger implementations must follow this interface.
*
* @example
* ```typescript
* class PinoLogger implements Logger {
*   private pino: Pino.Logger;
*
*   constructor(name: string) {
*     this.pino = pino({ name });
*   }
*
*   get name() { return this.pino.name; }
*   get level() { return LogLevel.DEBUG; }
*
*   debug(message: string, context?: LogContext) {
*     this.pino.debug(context, message);
*   }
*   // ... other methods
* }
* ```
*/
interface Logger {
	/**
	* Logger name (typically class name or module path)
	*/
	readonly name: string;
	/**
	* Current log level
	*/
	readonly level: LogLevel;
	/**
	* Log debug message
	*/
	debug(message: string, context?: LogContext): void;
	/**
	* Log info message
	*/
	info(message: string, context?: LogContext): void;
	/**
	* Log warning message
	*/
	warn(message: string, context?: LogContext): void;
	/**
	* Log error message or Error object
	*/
	error(message: string | Error, context?: LogContext): void;
	/**
	* Check if debug level is enabled
	*/
	isDebugEnabled(): boolean;
	/**
	* Check if info level is enabled
	*/
	isInfoEnabled(): boolean;
	/**
	* Check if warn level is enabled
	*/
	isWarnEnabled(): boolean;
	/**
	* Check if error level is enabled
	*/
	isErrorEnabled(): boolean;
}
/**
* LoggerFactory interface
*
* Factory for creating named Logger instances.
*/
interface LoggerFactory {
	/**
	* Get or create a logger with the specified name
	*
	* @param name - Logger name (typically class name or module path)
	* @returns Logger instance
	*/
	getLogger(name: string): Logger;
}
/**
* AgentXResponse - Unified response data structure
*
* All command response `data` fields should extend this type.
* Provides unified base fields and extensibility.
*
* ## Design Philosophy
*
* - **Convention over Configuration**: Responses that include `__subscriptions`
*   automatically trigger client-side session subscriptions
* - **Extensible**: Future features (caching, tracing, deprecation) can be added
*   without changing existing response definitions
* - **Type-safe**: TypeScript ensures all responses have required fields
*
* ## Usage
*
* ```typescript
* // Define a response data type
* interface ImageCreateResponseData extends AgentXResponse {
*   record: ImageRecord;
* }
*
* // Server: Include subscriptions in response
* createResponse("image_create_response", {
*   requestId,
*   record,
*   __subscriptions: [record.sessionId],
* });
*
* // Client: Automatically subscribes to sessions
* // (handled by createRemoteAgentX)
* ```
*
* @packageDocumentation
*/
/**
* AgentXResponse - Base interface for all command response data
*
* All command response data types should extend this interface
* to ensure consistent structure and enable automatic client-side handling.
*/
interface AgentXResponse {
	/**
	* Request ID for correlation and tracking
	*
	* Links the response to its originating request.
	* Used for request-response matching and debugging.
	*/
	requestId: string;
	/**
	* Error message if the request failed
	*
	* Undefined or absent means the request succeeded.
	* Present means the request failed, and this contains the error description.
	*/
	error?: string;
	/**
	* Session IDs that the client should subscribe to
	*
	* When present, the client will automatically subscribe to these sessions
	* to receive real-time events. This solves the reconnection event loss problem.
	*
	* @example
	* ```typescript
	* // Single session (e.g., image_create_response)
	* { __subscriptions: [record.sessionId] }
	*
	* // Multiple sessions (e.g., image_list_response)
	* { __subscriptions: records.map(r => r.sessionId) }
	* ```
	*/
	__subscriptions?: string[];
}
/**
* Check if a response has subscriptions
*/
declare function hasSubscriptions(response: AgentXResponse): response is AgentXResponse & {
	__subscriptions: string[]
};
/**
* Check if a response indicates an error
*/
declare function isErrorResponse(response: AgentXResponse): boolean;
/**
* LLM configuration
*/
interface LLMConfig {
	/**
	* Anthropic API key (required)
	*/
	apiKey: string;
	/**
	* API base URL
	* @default "https://api.anthropic.com"
	*/
	baseUrl?: string;
	/**
	* Model name
	* @default "claude-sonnet-4-20250514"
	*/
	model?: string;
}
/**
* Storage driver type
*/
type StorageDriver = "memory" | "fs" | "redis" | "mongodb" | "sqlite" | "mysql" | "postgresql";
/**
* Storage configuration
*/
interface StorageConfig {
	/**
	* Storage driver
	* @default "memory"
	*/
	driver?: StorageDriver;
	/**
	* File path (for sqlite, fs drivers)
	* @example "./data.db" for sqlite
	* @example "./data" for fs
	*/
	path?: string;
	/**
	* Connection URL (for redis, mongodb, mysql, postgresql)
	* @example "redis://localhost:6379"
	* @example "mongodb://localhost:27017/agentx"
	* @example "mysql://user:pass@localhost:3306/agentx"
	* @example "postgres://user:pass@localhost:5432/agentx"
	*/
	url?: string;
}
/**
* Logger configuration
*/
interface LoggerConfig {
	/**
	* Log level
	* @default LogLevel.INFO
	*/
	level?: LogLevel;
	/**
	* Custom logger factory implementation
	* If provided, this factory will be used to create all logger instances.
	* If not provided, uses ConsoleLogger with console options.
	*/
	factory?: LoggerFactory;
	/**
	* Console logger options (only used when factory is not provided)
	*/
	console?: {
		/**
		* Enable colored output
		* @default true (Node.js), false (browser)
		*/
		colors?: boolean
		/**
		* Include timestamps in log output
		* @default true
		*/
		timestamps?: boolean
	};
}
/**
* Local mode configuration
*
* Runs AgentX with local runtime, connecting directly to LLM API.
*/
interface LocalConfig {
	/**
	* LLM configuration
	*/
	llm?: LLMConfig;
	/**
	* Logger configuration
	*/
	logger?: LoggerConfig;
	/**
	* Default agent definition
	*
	* When creating a new image without explicit config, these values are used.
	* The definition is copied to ImageRecord at creation time.
	*/
	defaultAgent?: AgentDefinition;
	agentxDir?: string;
	/**
	* Runtime environment configuration
	* For advanced settings like Claude Code executable path
	*/
	environment?: {
		/**
		* Path to Claude Code executable
		* Required for binary distribution where Claude Code is bundled
		* @example "/path/to/claude-code/cli.js"
		*/
		claudeCodePath?: string
		/**
		* Path to Node.js executable
		* Used in packaged apps to run cli.js with bundled node instead of system node
		* @example "/path/to/bundled/node"
		*/
		nodePath?: string
		/**
		* Path to Git Bash executable (Windows only)
		* Required by Claude Code SDK on Windows for shell command execution
		* If bundled, point to the bundled bash.exe
		* @example "C:\\Program Files\\Git\\bin\\bash.exe"
		*/
		gitBashPath?: string
	};
	/**
	* Message interceptor for WebSocket client messages.
	*
	* Called before each client message is forwarded to the Runtime.
	* Can modify the event (e.g., inject llmConfig based on roleId)
	* or return null to drop the message.
	*
	* @example
	* ```typescript
	* const agentx = await createAgentX({
	*   onClientMessage: (event) => {
	*     if (event.type === "image_create_request") {
	*       // Inject server-side llmConfig based on roleId
	*       const roleId = event.data.config?.name?.split("_")[0];
	*       const role = roleCache.get(roleId);
	*       if (role?.llmConfig) {
	*         event.data.config.llmConfig = role.llmConfig;
	*       }
	*     }
	*     return event;
	*   }
	* });
	* ```
	*/
	onClientMessage?: (event: any) => any | null;
	/**
	* HTTP server to attach WebSocket to.
	* If provided, WebSocket upgrade will be handled on the same port.
	* The server should handle authentication before upgrading.
	*
	* @example
	* ```typescript
	* import { createServer } from "http";
	* import { Hono } from "hono";
	*
	* const app = new Hono();
	* // ... add auth middleware
	*
	* const server = createServer(app.fetch);
	* const agentx = await createAgentX({ server });
	*
	* server.listen(5200);
	* ```
	*/
	server?: {
		on(event: "upgrade", listener: (request: {
			url?: string
			headers: {
				host?: string
			}
		}, socket: unknown, head: unknown) => void): void
	};
}
/**
* Headers provider type
*
* Can be static headers or a function that returns headers (sync or async).
* Used for WebSocket connection authentication.
*/
type HeadersProvider = Record<string, string> | (() => Record<string, string>) | (() => Promise<Record<string, string>>);
/**
* Context provider type
*
* Can be static context or a function that returns context (sync or async).
* Used for per-request user context that flows to backend services.
*/
type ContextProvider = Record<string, unknown> | (() => Record<string, unknown>) | (() => Promise<Record<string, unknown>>);
/**
* Request options for per-request overrides
*/
interface RequestOptions {
	/**
	* Context to merge with default context for this request
	*/
	context?: Record<string, unknown>;
	/**
	* Request timeout in milliseconds
	*/
	timeout?: number;
}
/**
* Remote mode configuration
*
* Connects to a remote AgentX server via WebSocket.
*
* @example
* ```typescript
* // Simple static configuration
* const agentx = await createAgentX({
*   serverUrl: "ws://localhost:5200",
*   headers: { Authorization: "Bearer sk-xxx" },
*   context: { userId: "123", tenantId: "abc" },
* });
*
* // Dynamic configuration (functions)
* const agentx = await createAgentX({
*   serverUrl: "ws://localhost:5200",
*   headers: () => ({ Authorization: `Bearer ${getToken()}` }),
*   context: () => ({
*     userId: useAuth().userId,
*     permissions: useAuth().permissions,
*   }),
* });
*
* // Per-request override
* await agentx.request("message_send", { content: "Hello" }, {
*   context: { traceId: "trace-xxx" },  // Merged with default context
* });
* ```
*/
interface RemoteConfig {
	/**
	* Remote server URL (WebSocket)
	* @example "ws://localhost:5200"
	*/
	serverUrl: string;
	/**
	* Connection headers (for WebSocket authentication)
	*
	* Static headers or a function that returns headers.
	* Headers are sent during WebSocket connection handshake.
	*
	* @example
	* ```typescript
	* // Static headers
	* headers: { Authorization: "Bearer token" }
	*
	* // Dynamic headers
	* headers: () => ({ Authorization: `Bearer ${getToken()}` })
	* ```
	*/
	headers?: HeadersProvider;
	/**
	* Request context (flows to backend services)
	*
	* Static context or a function that returns context.
	* Context is attached to every request and flows through the system.
	*
	* @example
	* ```typescript
	* // Static context
	* context: { userId: "123", tenantId: "abc" }
	*
	* // Dynamic context
	* context: () => ({ userId: getUser().id, token: getToken() })
	* ```
	*/
	context?: ContextProvider;
	/**
	* WebSocket reconnection options
	*/
	reconnect?: {
		/**
		* Enable automatic reconnection
		* @default true
		*/
		enabled?: boolean
		/**
		* Maximum reconnection attempts
		* @default 5
		*/
		maxAttempts?: number
		/**
		* Base delay between reconnection attempts (ms)
		* Uses exponential backoff: delay * 2^attempt
		* @default 1000
		*/
		delay?: number
	};
}
/**
* AgentX configuration
*
* - LocalConfig: Run with local runtime (default)
* - RemoteConfig: Connect to remote server
*/
type AgentXConfig = LocalConfig | RemoteConfig;
/**
* Type guard: is this a remote config?
*/
declare function isRemoteConfig(config: AgentXConfig): config is RemoteConfig;
/**
* Type guard: is this a local config?
*/
declare function isLocalConfig(config: AgentXConfig): config is LocalConfig;
/**
* Unsubscribe function
*/
type Unsubscribe = () => void;
/**
* AgentX - Main API interface
*
* Unified API for both local and remote modes.
*/
interface AgentX {
	/**
	* Send a command request and wait for response.
	*
	* @example
	* ```typescript
	* // Basic request
	* const res = await agentx.request("container_create_request", {
	*   containerId: "my-container"
	* });
	*
	* // With per-request context override
	* const res = await agentx.request("message_send", { content: "Hello" }, {
	*   context: { traceId: "trace-xxx" },
	*   timeout: 60000,
	* });
	* ```
	*/
	request<T extends CommandRequestType>(type: T, data: RequestDataFor<T>, options?: RequestOptions | number): Promise<ResponseEventFor<T>>;
	/**
	* Subscribe to events.
	*
	* @example
	* ```typescript
	* agentx.on("text_delta", (e) => {
	*   process.stdout.write(e.data.text);
	* });
	* ```
	*/
	on<T extends string>(type: T, handler: (event: SystemEvent & {
		type: T
	}) => void): Unsubscribe;
	/**
	* Subscribe to command events with full type safety.
	*
	* @example
	* ```typescript
	* agentx.onCommand("container_create_response", (e) => {
	*   console.log(e.data.containerId);
	* });
	* ```
	*/
	onCommand<T extends keyof CommandEventMap>(type: T, handler: (event: CommandEventMap[T]) => void): Unsubscribe;
	/**
	* Emit a command event.
	*
	* For fine-grained control. Usually prefer `request()`.
	*/
	emitCommand<T extends keyof CommandEventMap>(type: T, data: CommandEventMap[T]["data"]): void;
	/**
	* Start listening for remote connections.
	*
	* Only available in local mode.
	*
	* @example
	* ```typescript
	* await agentx.listen(5200);
	* console.log("Server running on ws://localhost:5200");
	* ```
	*/
	listen(port: number, host?: string): Promise<void>;
	/**
	* Stop listening for remote connections.
	*/
	close(): Promise<void>;
	/**
	* Dispose AgentX and release all resources.
	*/
	dispose(): Promise<void>;
}
/**
* Create AgentX instance
*
* @example
* ```typescript
* // Local mode (default)
* const agentx = await createAgentX();
*
* // Local mode with config
* const agentx = await createAgentX({
*   llm: { apiKey: "sk-..." },
*   storage: { driver: "sqlite", path: "./data.db" },
* });
*
* // Remote mode
* const agentx = await createAgentX({ server: "ws://localhost:5200" });
* ```
*/
declare function createAgentX(config?: AgentXConfig): Promise<AgentX>;
/**
* AgentDefinition - Static template for defining an Agent
*
* Used to define agent behavior and capabilities before instantiation.
* This is the "application layer" configuration that describes what an agent does.
*
* @example
* ```typescript
* const MyAgent = defineAgent({
*   name: "Assistant",
*   description: "A helpful AI assistant",
*   systemPrompt: "You are a helpful assistant.",
*   mcpServers: {
*     filesystem: {
*       command: "npx",
*       args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
*     }
*   }
* });
* ```
*/
interface AgentDefinition {
	/**
	* Agent name (required)
	*/
	name: string;
	/**
	* Agent description
	*/
	description?: string;
	/**
	* System prompt - controls agent behavior
	*/
	systemPrompt?: string;
	/**
	* MCP servers configuration
	*
	* Key is server name, value is server configuration.
	* Supports stdio, sse, http, and sdk transport types.
	*/
	mcpServers?: Record<string, McpServerConfig>;
	/**
	* Blacklist of disallowed tools (tool names)
	* When set, these tools will be disabled for the agent
	*/
	disallowedTools?: string[];
	/**
	* Restrict available tools - can be array of tool names or preset
	* More granular control over which built-in tools are available
	*/
	tools?: string[] | {
		type: "preset"
		preset: "claude_code"
	};
	/**
	* Claude Code 风格的 Skills
	*
	* 每个 skill 会被写入 .claude/skills/{name}/SKILL.md
	* SDK 自动发现并注入到 Claude 的 context 中
	*/
	skills?: SkillDefinition2[];
	/**
	* Per-agent LLM configuration (optional)
	*
	* When set, this agent will use the specified LLM instead of the Runtime-level default.
	* Enables different roles/agents to use different LLM providers or models.
	*
	* @example
	* ```typescript
	* llmConfig: {
	*   apiKey: "sk-...",
	*   baseUrl: "https://api.deepseek.com/v1",
	*   model: "deepseek-chat"
	* }
	* ```
	*/
	llmConfig?: {
		apiKey?: string
		baseUrl?: string
		model?: string
	};
}
/**
* SkillDefinition - Claude Code 风格的 Skill 定义
*
* 每个 skill 对应 .claude/skills/{name}/SKILL.md
* SDK 自动发现并注入到 Claude 的 context 中。
*
* Skills 是按需加载的 system prompt 片段：
* - description 常驻 context（Claude 用来判断什么时候用）
* - content 按需加载（匹配时才加载完整内容）
*
* @example
* ```typescript
* const skill: SkillDefinition = {
*   name: "shopify-spy",
*   description: "分析 Shopify 店铺和竞争对手，追踪产品目录、定价策略",
*   content: `# Shopify 店铺分析

当用户需要分析 Shopify 店铺时...
`,
* };
* ```
*/
interface SkillDefinition2 {
	/**
	* Skill 名称（目录名）
	* 小写字母、数字和连字符，最长 64 字符
	* @example "browser-use", "shopify-spy"
	*/
	name: string;
	/**
	* 描述：Claude 根据这个判断什么时候使用该 skill
	* 常驻 context，建议控制在 200 字符以内
	*/
	description: string;
	/**
	* SKILL.md 的 markdown 内容（不含 frontmatter，frontmatter 会自动生成）
	*/
	content: string;
	/**
	* 是否禁止 Claude 自动调用
	* true = 只能用户通过 /skill-name 显式调用
	* @default false
	*/
	disableModelInvocation?: boolean;
	/**
	* Skill 激活时允许使用的工具列表
	* @example ["Read", "Grep", "Glob"]
	*/
	allowedTools?: string[];
	/**
	* 运行上下文
	* "fork" = 在独立的子 agent 中运行
	*/
	context?: "fork";
}
/**
* Define an Agent with type safety
*
* Helper function that provides type inference for AgentDefinition.
* The returned definition can be used with AgentX to create agent instances.
*
* Implementation is in `agentxjs` package.
*
* @example
* ```typescript
* import { defineAgent } from "agentxjs";
*
* const MyAgent = defineAgent({
*   name: "MyAgent",
*   systemPrompt: "You are helpful.",
*   mcpServers: {
*     github: { type: "sse", url: "http://localhost:3000/sse" }
*   }
* });
* ```
*/
declare function defineAgent<T extends AgentDefinition>(definition: T): T;
export { isRemoteConfig, isLocalConfig, isErrorResponse, hasSubscriptions, defineAgent, createAgentX, UserContext, Unsubscribe, StorageDriver, StorageConfig, SkillDefinition2 as SkillDefinition, RequestOptions, RemoteConfig, LoggerConfig, LocalConfig, LLMConfig, HeadersProvider, ContextProvider, AgentXResponse, AgentXConfig, AgentX, AgentDefinition };
