/**
* AgentLifecycle - Runtime Agent lifecycle states
*
* - running: Agent is active, can receive messages
* - stopped: Agent is paused, session data preserved, can resume
* - destroyed: Agent is removed, all data cleaned up
*/
type AgentLifecycle = "running" | "stopped" | "destroyed";
/**
* 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;
/**
* 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;
}
/**
* Runtime Agent interface
*/
interface Agent {
	/**
	* Unique agent identifier
	*/
	readonly agentId: string;
	/**
	* Agent name (from config or default)
	*/
	readonly name: string;
	/**
	* Parent container ID
	*/
	readonly containerId: string;
	/**
	* Current lifecycle state
	*/
	readonly lifecycle: AgentLifecycle;
	/**
	* Creation timestamp (Unix milliseconds)
	*/
	readonly createdAt: number;
	/**
	* Send a message to the agent
	*
	* @param content - User message content (string or multimodal content parts)
	* @param requestId - Optional request ID for event correlation
	* @param userContext - Optional user context for authentication and tracking
	*/
	receive(content: string | UserContentPart[], requestId?: string, userContext?: UserContext): Promise<void>;
	/**
	* Interrupt current processing
	*
	* Stops the current operation gracefully.
	*
	* @param requestId - Optional request ID for event correlation
	* @param userContext - Optional user context for authentication and tracking
	*/
	interrupt(requestId?: string, userContext?: UserContext): void;
	/**
	* Stop the agent
	*
	* Pauses the agent, preserving session data.
	* Can be resumed later with resume().
	*/
	stop(): Promise<void>;
	/**
	* Resume a stopped agent
	*
	* Restores the agent from preserved session data.
	*/
	resume(): Promise<void>;
	/**
	* Destroy the agent
	*
	* Completely removes the agent and all associated data.
	* Cannot be resumed after destruction.
	*/
	destroy(): Promise<void>;
}
declare const SUPPORTED_PROTOCOL_VERSIONS: readonly ["2025-06-18", "2025-03-26", "2024-11-05"];
type McpProtocolVersion = (typeof SUPPORTED_PROTOCOL_VERSIONS)[number];
/**
* MCP Tool Types
*
* Tool definitions and execution results for Model Context Protocol.
*/
/**
* JSON Schema Definition
*
* Simplified JSON Schema for tool input parameters.
* Based on JSON Schema Draft 7.
*/
interface JsonSchema {
	/** Schema type (always "object" for MCP tools) */
	type: "object";
	/** Property definitions */
	properties?: Record<string, JsonSchemaProperty>;
	/** Required property names */
	required?: string[];
	/** Additional properties allowed */
	additionalProperties?: boolean;
	/** Schema description */
	description?: string;
}
interface JsonSchemaProperty {
	type: "string" | "number" | "boolean" | "object" | "array" | "null";
	description?: string;
	enum?: unknown[];
	items?: JsonSchemaProperty;
	properties?: Record<string, JsonSchemaProperty>;
	required?: string[];
	default?: unknown;
}
/**
* Tool Definition
*
* Defines a tool that can be invoked by the LLM.
*/
interface McpTool {
	/** Tool name (unique identifier) */
	name: string;
	/** Human-readable description of what the tool does */
	description?: string;
	/** JSON Schema for input parameters */
	inputSchema: JsonSchema;
	/** Optional annotations (e.g., UI hints) */
	annotations?: {
		/** Display title */
		title?: string
		/** Additional metadata */
		[key: string]: unknown
	};
}
/**
* MCP Resource Types
*
* Resource definitions for Model Context Protocol.
* Resources are static data sources (files, documents, etc.) that can be read by the LLM.
*/
/**
* Resource Definition
*
* Defines a resource that can be accessed by the LLM.
*/
interface McpResource {
	/** Unique resource identifier (URI) */
	uri: string;
	/** Resource name */
	name: string;
	/** Optional human-readable title */
	title?: string;
	/** Optional description */
	description?: string;
	/** MIME type of the resource */
	mimeType?: string;
	/** Optional resource size in bytes */
	size?: number;
	/** Optional metadata */
	annotations?: Record<string, unknown>;
}
/**
* MCP Prompt Types
*
* Prompt templates for Model Context Protocol.
* Prompts are reusable message templates that can be parameterized.
*/
/**
* Prompt Argument
*
* Defines a parameter for a prompt template.
*/
interface McpPromptArgument {
	/** Argument name */
	name: string;
	/** Optional description */
	description?: string;
	/** Whether this argument is required */
	required?: boolean;
}
/**
* Prompt Definition
*
* Defines a reusable prompt template.
*/
interface McpPrompt {
	/** Prompt name (unique identifier) */
	name: string;
	/** Optional display title */
	title?: string;
	/** Optional description */
	description?: string;
	/** Prompt arguments/parameters */
	arguments?: McpPromptArgument[];
}
/**
* Server Information
*
* Metadata about the MCP server.
*/
interface McpServerInfo {
	/** Server name */
	name: string;
	/** Server version */
	version: string;
}
/**
* MCP Transport Types
*
* Transport layer configuration for Model Context Protocol.
* Defines how to connect to MCP servers via different protocols.
*/
/**
* Stdio Transport Configuration
*
* Connect to MCP server via standard input/output (spawned process).
* Common for local MCP servers.
*/
interface McpStdioTransport {
	/** Transport type discriminator */
	type: "stdio";
	/** Command to execute */
	command: string;
	/** Command arguments */
	args?: string[];
	/** Environment variables */
	env?: Record<string, string>;
	/** Working directory */
	cwd?: string;
}
/**
* SSE Transport Configuration
*
* Connect to MCP server via Server-Sent Events.
* Common for remote MCP servers with streaming support.
*/
interface McpSseTransport {
	/** Transport type discriminator */
	type: "sse";
	/** Server URL */
	url: string;
	/** HTTP headers */
	headers?: Record<string, string>;
	/** Request timeout in milliseconds */
	timeout?: number;
}
/**
* HTTP Transport Configuration
*
* Connect to MCP server via HTTP requests.
* Common for stateless remote MCP servers.
*/
interface McpHttpTransport {
	/** Transport type discriminator */
	type: "http";
	/** Server URL */
	url: string;
	/** HTTP headers */
	headers?: Record<string, string>;
	/** Request timeout in milliseconds */
	timeout?: number;
}
/**
* SDK Transport Configuration
*
* Use an in-process MCP server instance.
* Common for embedded MCP servers in the same application.
*/
interface McpSdkTransport {
	/** Transport type discriminator */
	type: "sdk";
	/** Server name */
	name: string;
	/** Server instance (implementation-specific) */
	instance: unknown;
}
/**
* MCP Transport Config
*
* Union of all transport configuration types.
*/
type McpTransportConfig = McpStdioTransport | McpSseTransport | McpHttpTransport | McpSdkTransport;
/**
* 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;
}
/**
* MCP Request Types
*
* Request/response types for JSON-RPC based MCP communication.
*/
/**
* Base Request Parameters
*
* Common parameters for all MCP requests.
*/
interface McpBaseParams {
	/** Optional metadata */
	_meta?: Record<string, unknown>;
}
/**
* MCP Request
*
* Generic request structure.
*/
interface McpRequest {
	/** RPC method name */
	method: string;
	/** Request parameters */
	params?: McpBaseParams;
}
/**
* 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;
}
/**
* Container interface for managing Agent instances at runtime
*/
interface Container {
	/**
	* Unique container identifier
	*/
	readonly containerId: string;
	/**
	* Container creation timestamp
	*/
	readonly createdAt: number;
	/**
	* Run an Image - create or reuse an Agent for the given Image
	*
	* @param image - ImageRecord to run
	* @returns { agent, reused } - the agent and whether it was reused
	*/
	runImage(image: ImageRecord): Promise<{
		agent: Agent
		reused: boolean
	}>;
	/**
	* Stop an Image - destroy the Agent but keep the Image
	*
	* @param imageId - Image to stop
	* @returns true if agent was found and destroyed
	*/
	stopImage(imageId: string): Promise<boolean>;
	/**
	* Get agent ID for an image (if running)
	*/
	getAgentIdForImage(imageId: string): string | undefined;
	/**
	* Check if an image has a running agent
	*/
	isImageOnline(imageId: string): boolean;
	/**
	* Get an Agent by ID
	*/
	getAgent(agentId: string): Agent | undefined;
	/**
	* List all Agents in this container
	*/
	listAgents(): Agent[];
	/**
	* Get the number of Agents in this container
	*/
	get agentCount(): number;
	/**
	* Destroy an Agent by ID
	*
	* Cleans up Agent resources and removes from container.
	*
	* @param agentId - Agent to destroy
	* @returns true if agent was found and destroyed
	*/
	destroyAgent(agentId: string): Promise<boolean>;
	/**
	* Destroy all Agents in this container
	*/
	destroyAllAgents(): Promise<void>;
	/**
	* Dispose the container and all its Agents
	*/
	dispose(): Promise<void>;
}
/**
* Workdir - Working Directory
*
* Represents an isolated working directory for an Agent.
* The actual path is determined by Runtime, not defined here.
*
* Workdir is a location declaration, not an operation interface.
* Claude SDK has its own tools (Bash, file operations), we just
* tell it where to work (cwd).
*/
interface Workdir {
	/**
	* Unique workdir identifier
	*/
	readonly id: string;
	/**
	* Human-readable workdir name
	*/
	readonly name: string;
	/**
	* Absolute path to working directory
	*
	* Examples:
	* - NodeRuntime: ~/.agentx/workdirs/{id}/
	* - CloudRuntime: /workdir/ (in container)
	*/
	readonly path: string;
}
/**
* Sandbox - External tool resource isolation
*
* Isolates external tool resources for an Agent:
* - Workdir: Isolated working directory
* - MCP: Model Context Protocol tools (future)
*
* Note: LLM is NOT part of Sandbox - it's at container level.
*/
interface Sandbox {
	/** Sandbox identifier */
	readonly name: string;
	/** Isolated working directory for file operations */
	readonly workdir: Workdir;
}
/**
* LLM - Large Language Model definition
*
* Defines the capabilities and metadata of a language model.
* Provider-agnostic design allows supporting multiple LLM vendors.
*/
interface LLM {
	/**
	* Provider name (e.g., "anthropic", "openai", "custom")
	*/
	provider: string;
	/**
	* Provider-specific model identifier
	* Examples: "claude-3-5-sonnet-20241022", "gpt-4-turbo"
	*/
	modelId: string;
	/**
	* Whether the model supports streaming output
	*/
	supportsStreaming: boolean;
	/**
	* Whether the model supports tool calling
	*/
	supportsTools: boolean;
	/**
	* Whether the model supports vision/image inputs
	*/
	supportsVision: boolean;
	/**
	* Whether the model supports prompt caching
	*/
	supportsCaching: boolean;
	/**
	* Whether the model supports extended thinking
	*/
	supportsThinking?: boolean;
}
/**
* LLM inference configuration
*
* Parameters that control how the language model generates responses.
* These are the standard parameters supported by most LLM providers.
*/
interface LLMConfig {
	/**
	* Model identifier to use for inference
	* Examples: "claude-3-5-sonnet-20241022", "gpt-4-turbo"
	*/
	model: string;
	/**
	* Sampling temperature (0-2)
	* Higher values make output more random, lower values more deterministic
	* @default 1.0
	*/
	temperature?: number;
	/**
	* Maximum number of tokens to generate
	*/
	maxTokens?: number;
	/**
	* Top-p sampling (nucleus sampling)
	* Range: 0-1
	*/
	topP?: number;
	/**
	* Top-k sampling
	* Only consider the top k tokens
	*/
	topK?: number;
	/**
	* Presence penalty (-2.0 to 2.0)
	* Penalize tokens that have already appeared
	*/
	presencePenalty?: number;
	/**
	* Frequency penalty (-2.0 to 2.0)
	* Penalize tokens based on their frequency
	*/
	frequencyPenalty?: number;
	/**
	* Stop sequences
	* Generation stops when any of these sequences is encountered
	*/
	stopSequences?: string[];
	/**
	* Maximum number of thinking tokens (for models with extended thinking)
	*/
	maxThinkingTokens?: number;
}
/**
* User Message
*
* Message sent by the user.
* Can contain simple text or rich content (text, images, files).
*/
interface UserMessage {
	/** Unique identifier */
	id: string;
	/** Message role */
	role: "user";
	/** Message subtype for serialization */
	subtype: "user";
	/** Message content - can be simple string or array of parts */
	content: string | UserContentPart[];
	/** When this message was created (Unix timestamp in milliseconds) */
	timestamp: number;
	/** Parent message ID for threading (optional) */
	parentId?: string;
}
/**
* Thinking Part
*
* AI's reasoning/thinking process (extended thinking).
*/
interface ThinkingPart {
	/** Content type discriminator */
	type: "thinking";
	/** The reasoning text */
	reasoning: string;
	/** Tokens used for thinking (optional) */
	tokenCount?: number;
}
/**
* Token usage information
*/
interface TokenUsage {
	inputTokens: number;
	outputTokens: number;
	totalTokens?: number;
}
/**
* Assistant Message
*
* Message generated by the AI assistant.
* Contains text, thinking process, or files.
*
* Note: Tool calls are separate - use ToolCallMessage for tool invocations.
*/
interface AssistantMessage {
	/** Unique identifier */
	id: string;
	/** Message role */
	role: "assistant";
	/** Message subtype for serialization */
	subtype: "assistant";
	/** Message content - can be simple string or array of parts */
	content: string | Array<TextPart | ThinkingPart | FilePart>;
	/** When this message was created (Unix timestamp in milliseconds) */
	timestamp: number;
	/** Parent message ID for threading (optional) */
	parentId?: string;
	/** Token usage for this AI response (optional) */
	usage?: TokenUsage;
}
/**
* Tool Call Part
*
* AI's request to invoke a tool.
*/
interface ToolCallPart {
	/** Content type discriminator */
	type: "tool-call";
	/** Unique identifier for this tool call */
	id: string;
	/** Tool name */
	name: string;
	/** Tool input parameters */
	input: Record<string, unknown>;
}
/**
* Tool Call Message
*/
interface ToolCallMessage {
	/** Unique message identifier */
	id: string;
	/** Message role - assistant initiates tool calls */
	role: "assistant";
	/** Message subtype for serialization */
	subtype: "tool-call";
	/** Tool call details */
	toolCall: ToolCallPart;
	/** When this message was created (Unix timestamp in milliseconds) */
	timestamp: number;
	/** Parent message ID (the assistant message that triggered this) */
	parentId?: string;
}
/**
* Tool Result Output
*
* Enhanced tool result format supporting multiple output types.
* Based on Vercel AI SDK and industry best practices.
*/
type ToolResultOutput = {
	type: "text"
	value: string
} | {
	type: "json"
	value: unknown
} | {
	type: "error-text"
	value: string
} | {
	type: "error-json"
	value: unknown
} | {
	type: "execution-denied"
	reason?: string
} | {
	type: "content"
	value: Array<TextPart | ImagePart | FilePart>
};
/**
* Tool Result Part
*
* Result of tool execution.
*/
interface ToolResultPart {
	/** Content type discriminator */
	type: "tool-result";
	/** Tool call ID this result corresponds to */
	id: string;
	/** Tool name */
	name: string;
	/** Tool execution output */
	output: ToolResultOutput;
}
/**
* Tool Result Message
*/
interface ToolResultMessage {
	/** Unique message identifier */
	id: string;
	/** Message role - tool returns results */
	role: "tool";
	/** Message subtype for serialization */
	subtype: "tool-result";
	/** Tool result details */
	toolResult: ToolResultPart;
	/** ID of the corresponding tool call */
	toolCallId: string;
	/** When this message was created (Unix timestamp in milliseconds) */
	timestamp: number;
}
/**
* Error Message
*
* Message representing an error that occurred during conversation.
* Displayed in the chat history so users can see what went wrong.
*/
interface ErrorMessage {
	/** Unique identifier */
	id: string;
	/** Message role */
	role: "error";
	/** Message subtype for serialization */
	subtype: "error";
	/** Error message content (human-readable) */
	content: string;
	/** Error code (e.g., "rate_limit_error", "api_error") */
	errorCode?: string;
	/** When this error occurred (Unix timestamp in milliseconds) */
	timestamp: number;
	/** Parent message ID for threading (optional) */
	parentId?: string;
}
/**
* Message
*
* Discriminated union of all message types.
* Use `subtype` field for precise type discrimination.
*
* Role: Who sent it (user, assistant, tool, system, error)
* Subtype: What type of message (user, assistant, tool-call, tool-result, error)
*
* @example
* ```typescript
* function handleMessage(msg: Message) {
*   switch (msg.subtype) {
*     case "user":
*       console.log(msg.content);
*       break;
*     case "assistant":
*       console.log(msg.content);
*       break;
*     case "tool-call":
*       console.log(msg.toolCall.name);
*       break;
*     case "tool-result":
*       console.log(msg.toolResult.output);
*       break;
*     case "error":
*       console.log(msg.content);
*       break;
*   }
* }
* ```
*/
type Message = UserMessage | AssistantMessage | ToolCallMessage | ToolResultMessage | ErrorMessage;
/**
* Complete LLM inference request (stateless)
*
* Contains everything needed for a single LLM inference call.
* The LLM is stateless - all context must be provided in messages.
*
* IMPORTANT: This does NOT include tool definitions.
* Tools are external capabilities provided by the runtime environment.
*/
interface LLMRequest {
	/**
	* Context messages
	* All conversation history that the LLM should consider
	*/
	messages: Message[];
	/**
	* Inference configuration
	* Controls how the model generates responses
	*/
	config: LLMConfig;
	/**
	* System prompt (optional)
	* High-level instructions that guide the model's behavior
	*/
	systemPrompt?: string;
}
/**
* Content Part
*
* Discriminated union of all content part types.
* Used in messages to support multi-modal and complex content.
*/
type ContentPart = TextPart | ThinkingPart | ImagePart | FilePart | ToolCallPart | ToolResultPart;
/**
* Token Usage
*
* Tracks token consumption for AI messages.
*/
interface TokenUsage2 {
	/** Input tokens used */
	input: number;
	/** Output tokens generated */
	output: number;
	/** Tokens read from cache (optional) */
	cacheRead?: number;
	/** Tokens written to cache (optional) */
	cacheWrite?: number;
}
/**
* Reason why the LLM stopped generating
*
* Based on common stop reasons across multiple LLM providers:
* - Anthropic Claude: end_turn, max_tokens, tool_use, stop_sequence
* - OpenAI: stop, length, tool_calls, content_filter
* - Vercel AI SDK: stop, length, tool-calls, content-filter, error, other
*/
type StopReason = "end_turn" | "max_tokens" | "tool_use" | "stop_sequence" | "content_filter" | "error" | "other";
/**
* Complete LLM inference response (stateless)
*
* Contains everything returned from a single LLM inference call.
* Given the same LLMRequest (with temperature=0), the response should be reproducible.
*/
interface LLMResponse {
	/**
	* Generated content
	* Can be text, thinking, tool calls, etc.
	*/
	content: string | ContentPart[];
	/**
	* Why the model stopped generating
	*/
	stopReason: StopReason;
	/**
	* Token usage statistics
	*/
	usage: TokenUsage2;
	/**
	* When the generation finished
	*/
	finishTime: Date;
	/**
	* Model that generated this response
	*/
	model?: string;
}
/**
* Streaming output chunk types
*
* When LLM generates responses in streaming mode, it emits chunks of different types.
* This allows real-time display of the generation process.
*/
/**
* Text content chunk
*/
interface TextChunk {
	type: "text";
	/**
	* Text delta (incremental content)
	*/
	delta: string;
	/**
	* Cumulative index of this chunk
	*/
	index: number;
}
/**
* Thinking process chunk (for models with extended thinking)
*/
interface ThinkingChunk {
	type: "thinking";
	/**
	* Thinking delta (incremental reasoning)
	*/
	delta: string;
	/**
	* Cumulative index of this chunk
	*/
	index: number;
}
/**
* Tool use chunk (when model requests tool usage)
*/
interface ToolUseChunk {
	type: "tool-use";
	/**
	* Tool name
	*/
	name: string;
	/**
	* Tool call ID
	*/
	id: string;
	/**
	* Partial input (may be incomplete JSON)
	*/
	inputDelta?: string;
}
/**
* Union type of all streaming chunks
*/
type StreamChunk = TextChunk | ThinkingChunk | ToolUseChunk;
/**
* LLMProvider - Large Language Model Supply Service
*
* Provides LLM invocation capabilities to Drivers.
* This is a resource component managed by Runtime.
*
* ## Architecture Decision Record (ADR)
*
* ### Context
*
* AgentX separates "business components" from "resource components":
*
* - **Business Components**: Agent-specific logic (Driver, Presenter, Middleware)
* - **Resource Components**: Infrastructure capabilities (LLM, FileSystem, Process)
*
* LLM access (apiKey, baseUrl, model) is a resource that:
* 1. Should not be exposed to Agent business code
* 2. Can be shared across multiple Agents
* 3. May have different supply strategies (static, pooled, proxy)
* 4. Needs unified management (quota, billing, load balancing)
*
* ### Decision
*
* Create `LLMProvider` as a minimal generic interface:
*
* ```typescript
* interface LLMProvider<TSupply = unknown> {
*   readonly name: string;
*   provide(): TSupply;
* }
* ```
*
* - `name`: Provider identifier (for logging, debugging)
* - `provide()`: Returns whatever the Driver needs
* - `TSupply`: User-defined, can be anything (config, client, token, etc.)
*
* ### Usage
*
* ```typescript
* // User defines their own supply type
* interface MyLLMSupply {
*   apiKey: string;
*   baseUrl?: string;
* }
*
* // Create provider
* const provider: LLMProvider<MyLLMSupply> = {
*   name: "claude",
*   provide: () => ({
*     apiKey: process.env.ANTHROPIC_API_KEY!,
*   }),
* };
*
* // Driver uses it
* const supply = runtime.llm.provide();
* ```
*
* ### Status
*
* **Accepted** - 2024-11-30
*/
/**
* LLMProvider - Large Language Model supply service
*
* @typeParam TSupply - User-defined supply type (config, client, token, etc.)
*/
interface LLMProvider<TSupply = unknown> {
	/**
	* Provider identifier
	*/
	readonly name: string;
	/**
	* Provide LLM access
	*/
	provide(): TSupply;
}
/**
* ImageRepository - Storage operations for images
*/
interface ImageRepository {
	/**
	* Save an image record (create or update)
	*/
	saveImage(record: ImageRecord): Promise<void>;
	/**
	* Find image by ID
	*/
	findImageById(imageId: string): Promise<ImageRecord | null>;
	/**
	* Find all images
	*/
	findAllImages(): Promise<ImageRecord[]>;
	/**
	* Find images by agent name
	*/
	findImagesByName(name: string): Promise<ImageRecord[]>;
	/**
	* Find images by container ID
	*/
	findImagesByContainerId(containerId: string): Promise<ImageRecord[]>;
	/**
	* Delete image by ID
	*/
	deleteImage(imageId: string): Promise<void>;
	/**
	* Check if image exists
	*/
	imageExists(imageId: string): Promise<boolean>;
	/**
	* Update image metadata (e.g., Claude SDK session ID)
	* Merges with existing metadata
	*/
	updateMetadata(imageId: string, metadata: Partial<ImageMetadata>): Promise<void>;
}
/**
* ContainerRecord - Storage record for Container
*
* Represents a logical container (resource isolation unit).
* Each container provides an isolated environment for running Agents.
*
* In multi-tenant scenarios:
* - Application layer maps tenant → containerId
* - ContainerManager manages containers
* - Each container has its own Sandbox (workspace, LLM config)
*/
/**
* Container configuration (extensible)
*
* Future configurations may include:
* - Resource quotas (max tokens, max agents)
* - Custom workspace path
* - LLM provider overrides
*/
interface ContainerConfig {
	[key: string]: unknown;
}
/**
* ContainerRecord - Persistent container data
*
* Stored in Repository for container lifecycle management.
*/
interface ContainerRecord {
	/** Unique container identifier (auto-generated on create) */
	containerId: string;
	/** Container creation timestamp */
	createdAt: number;
	/** Last update timestamp */
	updatedAt: number;
	/** Container configuration (extensible for future needs) */
	config?: ContainerConfig;
}
/**
* ContainerRepository - Storage operations for containers
*/
interface ContainerRepository {
	/**
	* Save a container record (create or update)
	*/
	saveContainer(record: ContainerRecord): Promise<void>;
	/**
	* Find container by ID
	*/
	findContainerById(containerId: string): Promise<ContainerRecord | null>;
	/**
	* Find all containers
	*/
	findAllContainers(): Promise<ContainerRecord[]>;
	/**
	* Delete container by ID
	*/
	deleteContainer(containerId: string): Promise<void>;
	/**
	* Check if container exists
	*/
	containerExists(containerId: string): Promise<boolean>;
}
/**
* SessionRecord - Storage schema for Session persistence
*
* Session stores conversation messages for an Image.
* Each Image has exactly one Session.
*/
/**
* Session storage record
*/
interface SessionRecord {
	/**
	* Unique session identifier
	*/
	sessionId: string;
	/**
	* Associated image ID (owner of this session)
	*/
	imageId: string;
	/**
	* Container this session belongs to
	*/
	containerId: string;
	/**
	* Creation timestamp (Unix milliseconds)
	*/
	createdAt: number;
	/**
	* Last update timestamp (Unix milliseconds)
	*/
	updatedAt: number;
}
/**
* SessionRepository - Storage operations for sessions
*/
interface SessionRepository {
	/**
	* Save a session record (create or update)
	*/
	saveSession(record: SessionRecord): Promise<void>;
	/**
	* Find session by ID
	*/
	findSessionById(sessionId: string): Promise<SessionRecord | null>;
	/**
	* Find session by image ID
	*/
	findSessionByImageId(imageId: string): Promise<SessionRecord | null>;
	/**
	* Find all sessions for a container
	*/
	findSessionsByContainerId(containerId: string): Promise<SessionRecord[]>;
	/**
	* Find all sessions
	*/
	findAllSessions(): Promise<SessionRecord[]>;
	/**
	* Delete session by ID
	*/
	deleteSession(sessionId: string): Promise<void>;
	/**
	* Check if session exists
	*/
	sessionExists(sessionId: string): Promise<boolean>;
	/**
	* Add a message to a session
	*/
	addMessage(sessionId: string, message: Message): Promise<void>;
	/**
	* Get all messages for a session
	*/
	getMessages(sessionId: string): Promise<Message[]>;
	/**
	* Clear all messages for a session
	*/
	clearMessages(sessionId: string): Promise<void>;
}
/**
* Repository - Unified persistence interface
*
* Combines all domain repositories for convenient single-point configuration.
*/
interface Repository extends ContainerRepository, ImageRepository, SessionRepository {}
/**
* Persistence - Unified storage interface with domain-specific access
*/
interface Persistence {
	/**
	* Image storage operations
	*/
	readonly images: ImageRepository;
	/**
	* Container storage operations
	*/
	readonly containers: ContainerRepository;
	/**
	* Session storage operations
	*/
	readonly sessions: SessionRepository;
}
/**
* Message Role
*
* Represents who sent the message in the conversation.
* Five fundamental roles in the conversation.
*/
type MessageRole = "user" | "assistant" | "tool" | "system" | "error";
/**
* Message storage record
*/
interface MessageRecord {
	/**
	* Unique message identifier
	*/
	messageId: string;
	/**
	* Associated session identifier
	*/
	sessionId: string;
	/**
	* Message role: user, assistant, tool-call, tool-result
	*/
	role: MessageRole;
	/**
	* Serialized message content (JSON)
	* Structure varies by role type
	*/
	content: Record<string, unknown>;
	/**
	* Creation timestamp (Unix milliseconds)
	*/
	createdAt: number;
}
/**
* EnvironmentRecord - Storage for Environment implementation private state
*
* Used by Environment implementations (Receptor + Effector) to store
* their private state that maps to our Session. The business layer
* doesn't care about the internal structure of `state`.
*
* Examples:
* - ClaudeEnvironment: { sdkSessionId: "claude_xxx" }
* - OpenAIEnvironment: { threadId: "thread_xxx" }
* - CustomEnvironment: any implementation-specific data
*
* Relationship:
* ```
* SessionRecord (business layer)
*     │
*     │ sessionId
*     ▼
* EnvironmentRecord (implementation layer)
*     │
*     │ state (opaque to business layer)
*     ▼
* External SDK/API state
* ```
*/
/**
* EnvironmentRecord - Environment implementation private state storage
*/
interface EnvironmentRecord {
	/**
	* Associated session ID (foreign key to SessionRecord)
	*/
	sessionId: string;
	/**
	* Environment type identifier
	* Examples: "claude", "openai", "custom"
	*/
	environmentType: string;
	/**
	* Environment private state (opaque to business layer)
	* Structure is defined by each Environment implementation
	*/
	state: Record<string, unknown>;
	/**
	* Creation timestamp (Unix milliseconds)
	*/
	createdAt: number;
	/**
	* Last update timestamp (Unix milliseconds)
	*/
	updatedAt: number;
}
/**
* 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">;
/**
* SystemBusProducer interface - Write-only view
*
* Components receiving this interface can only emit events,
* preventing them from creating event loops by subscribing.
*/
interface SystemBusProducer {
	/**
	* Emit a single event to the bus
	*
	* @param event - The event to emit
	*/
	emit(event: SystemEvent): void;
	/**
	* Emit multiple events (batch operation)
	*
	* @param events - Array of events to emit
	*/
	emitBatch(events: SystemEvent[]): void;
	/**
	* Emit a typed command event
	*
	* @param type - The command event type
	* @param data - Event data (type-checked)
	*/
	emitCommand<T extends keyof CommandEventMap>(type: T, data: CommandEventMap[T]["data"]): void;
}
/**
* Receptor - Perceives external world and emits events to SystemBus
*/
interface Receptor {
	/**
	* Connect to SystemBus producer to emit events
	*
	* Receptor only needs Producer (write-only) because it only emits events.
	*/
	connect(producer: SystemBusProducer): void;
}
/**
* Unsubscribe function type
*/
type Unsubscribe = () => void;
/**
* Event handler function type
*/
type BusEventHandler<E extends SystemEvent = SystemEvent> = (event: E) => void;
/**
* Subscription options for advanced event handling
*/
interface SubscribeOptions<E extends SystemEvent = SystemEvent> {
	/**
	* Event filter - only events returning true will trigger the handler
	* Useful for filtering by agentId, sessionId, etc.
	*/
	filter?: (event: E) => boolean;
	/**
	* Priority - higher numbers execute first (default: 0)
	* Useful for ensuring certain handlers run before others
	*/
	priority?: number;
	/**
	* Whether to trigger only once then auto-unsubscribe
	*/
	once?: boolean;
}
/**
* SystemBusConsumer interface - Read-only view
*
* Components receiving this interface can only subscribe to events,
* preventing them from emitting events.
*/
interface SystemBusConsumer {
	/**
	* Subscribe to a specific event type
	*
	* @param type - The event type to listen for
	* @param handler - Callback invoked when event is received
	* @param options - Subscription options (filter, priority, once)
	* @returns Unsubscribe function
	*/
	on<T extends string>(type: T, handler: BusEventHandler<SystemEvent & {
		type: T
	}>, options?: SubscribeOptions<SystemEvent & {
		type: T
	}>): Unsubscribe;
	/**
	* Subscribe to multiple event types
	*
	* @param types - Array of event types to listen for
	* @param handler - Callback invoked when any matching event is received
	* @param options - Subscription options
	* @returns Unsubscribe function
	*/
	on(types: string[], handler: BusEventHandler, options?: SubscribeOptions): Unsubscribe;
	/**
	* Subscribe to all events
	*
	* @param handler - Callback invoked for every event
	* @param options - Subscription options
	* @returns Unsubscribe function
	*/
	onAny(handler: BusEventHandler, options?: SubscribeOptions): Unsubscribe;
	/**
	* Subscribe to an event type once (auto-unsubscribes after first trigger)
	*
	* @param type - Event type to subscribe to
	* @param handler - Callback function
	* @returns Unsubscribe function
	*/
	once<T extends string>(type: T, handler: BusEventHandler<SystemEvent & {
		type: T
	}>): Unsubscribe;
	/**
	* Subscribe to a CommandEvent with full type safety
	*
	* @example
	* ```typescript
	* consumer.onCommand("container_create_request", (event) => {
	*   event.data.requestId;    // ✓ string
	*   event.data.containerId;  // ✓ string
	* });
	* ```
	*
	* @param type - The command event type
	* @param handler - Callback with fully typed event
	* @returns Unsubscribe function
	*/
	onCommand<T extends keyof CommandEventMap>(type: T, handler: (event: CommandEventMap[T]) => void): Unsubscribe;
	/**
	* Send a command request and wait for response
	*
	* Automatically generates requestId, emits request, waits for matching response.
	*
	* @example
	* ```typescript
	* const response = await consumer.request("container_create_request", {
	*   containerId: "my-container"
	* });
	* // response is ContainerCreateResponse
	* console.log(response.data.containerId);
	* ```
	*
	* @param type - The request event type
	* @param data - Request data (without requestId)
	* @param timeout - Timeout in milliseconds (default: 30000)
	* @returns Promise of response event
	*/
	request<T extends CommandRequestType>(type: T, data: RequestDataFor<T>, timeout?: number): Promise<ResponseEventFor<T>>;
}
/**
* Effector - Subscribes to SystemBus and acts upon external world
*/
interface Effector {
	/**
	* Connect to SystemBus consumer to subscribe to events
	*
	* Effector only needs Consumer (read-only) because it only subscribes to events.
	*/
	connect(consumer: SystemBusConsumer): void;
}
/**
* Environment - External world interface
*/
interface Environment {
	/**
	* Environment name
	*/
	readonly name: string;
	/**
	* Receptor - perceives external world, emits to SystemBus
	*/
	readonly receptor: Receptor;
	/**
	* Effector - subscribes to SystemBus, acts on external world
	*/
	readonly effector: Effector;
	/**
	* Optional warmup - pre-initialize environment to reduce first message latency
	*/
	warmup?(): Promise<void>;
}
/**
* Runtime Environment Configuration
*
* Global runtime settings that don't need to be passed through layers.
* Used internally by RuntimeEnvironment singleton.
*/
interface RuntimeEnvironmentConfig {
	/**
	* Path to Claude Code executable
	* Required for binary distribution where Claude Code is bundled
	* @example "/path/to/dist/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
	* @example "C:\\Program Files\\Git\\bin\\bash.exe"
	*/
	gitBashPath?: string;
}
/**
* Session - Collects and stores messages
*/
interface Session {
	/**
	* Unique session identifier
	*/
	readonly sessionId: string;
	/**
	* Associated image ID (persistent conversation entity)
	*/
	readonly imageId: string;
	/**
	* Associated container ID
	*/
	readonly containerId: string;
	/**
	* Session creation timestamp (Unix ms)
	*/
	readonly createdAt: number;
	/**
	* Add a message to the session
	*/
	addMessage(message: Message): Promise<void>;
	/**
	* Get all messages
	*/
	getMessages(): Promise<Message[]>;
	/**
	* Clear all messages
	*/
	clear(): Promise<void>;
}
/**
* Unsubscribe function type.
*/
type Unsubscribe2 = () => void;
/**
* Event handler function type.
*/
type BusEventHandler2<E extends SystemEvent = SystemEvent> = (event: E) => void;
/**
* Subscription options for advanced event handling.
*/
interface SubscribeOptions2<E extends SystemEvent = SystemEvent> {
	/**
	* Event filter - only events returning true will trigger the handler.
	* Useful for filtering by agentId, sessionId, etc.
	*/
	filter?: (event: E) => boolean;
	/**
	* Priority - higher numbers execute first (default: 0).
	* Useful for ensuring certain handlers run before others.
	*/
	priority?: number;
	/**
	* Whether to trigger only once then auto-unsubscribe.
	*/
	once?: boolean;
}
/**
* SystemBus interface - Central event bus for ecosystem communication.
*
* Extends both Producer and Consumer interfaces for internal use.
* External components should use restricted views via asProducer/asConsumer.
*/
interface SystemBus {
	/**
	* Emit an event to the bus.
	*
	* All subscribed handlers will receive this event.
	*
	* @param event - The event to emit
	*/
	emit(event: SystemEvent): void;
	/**
	* Emit multiple events (batch operation).
	*
	* @param events - Array of events to emit
	*/
	emitBatch(events: SystemEvent[]): void;
	/**
	* Subscribe to a specific event type.
	*
	* @param type - The event type to listen for
	* @param handler - Callback invoked when event is received
	* @param options - Subscription options (filter, priority, once)
	* @returns Unsubscribe function
	*/
	on<T extends string>(type: T, handler: BusEventHandler2<SystemEvent & {
		type: T
	}>, options?: SubscribeOptions2<SystemEvent & {
		type: T
	}>): Unsubscribe2;
	/**
	* Subscribe to multiple event types.
	*
	* @param types - Array of event types to listen for
	* @param handler - Callback invoked when any matching event is received
	* @param options - Subscription options
	* @returns Unsubscribe function
	*/
	on(types: string[], handler: BusEventHandler2, options?: SubscribeOptions2): Unsubscribe2;
	/**
	* Subscribe to all events.
	*
	* @param handler - Callback invoked for every event
	* @param options - Subscription options
	* @returns Unsubscribe function
	*/
	onAny(handler: BusEventHandler2, options?: SubscribeOptions2): Unsubscribe2;
	/**
	* Subscribe to an event type once (auto-unsubscribes after first trigger).
	*
	* @param type - Event type to subscribe to
	* @param handler - Callback function
	* @returns Unsubscribe function
	*/
	once<T extends string>(type: T, handler: BusEventHandler2<SystemEvent & {
		type: T
	}>): Unsubscribe2;
	/**
	* Subscribe to a CommandEvent with full type safety.
	*
	* @example
	* ```typescript
	* bus.onCommand("container_create_request", (event) => {
	*   event.data.requestId;    // ✓ string
	*   event.data.containerId;  // ✓ string
	* });
	* ```
	*
	* @param type - The command event type
	* @param handler - Callback with fully typed event
	* @returns Unsubscribe function
	*/
	onCommand<T extends keyof CommandEventMap>(type: T, handler: (event: CommandEventMap[T]) => void): Unsubscribe2;
	/**
	* Emit a CommandEvent with full type safety.
	*
	* @example
	* ```typescript
	* bus.emitCommand("container_create_request", {
	*   requestId: "req_123",
	*   containerId: "my-container"
	* });
	* ```
	*
	* @param type - The command event type
	* @param data - Event data (type-checked)
	*/
	emitCommand<T extends keyof CommandEventMap>(type: T, data: CommandEventMap[T]["data"]): void;
	/**
	* Send a command request and wait for response.
	*
	* Automatically generates requestId, emits request, waits for matching response.
	*
	* @example
	* ```typescript
	* const response = await bus.request("container_create_request", {
	*   containerId: "my-container"
	* });
	* // response is ContainerCreateResponse
	* console.log(response.data.containerId);
	* ```
	*
	* @param type - The request event type
	* @param data - Request data (without requestId)
	* @param timeout - Timeout in milliseconds (default: 30000)
	* @returns Promise of response event
	*/
	request<T extends CommandRequestType>(type: T, data: RequestDataFor<T>, timeout?: number): Promise<ResponseEventFor<T>>;
	/**
	* Get a read-only consumer view of the bus.
	*
	* Use this to safely expose event subscription to external code
	* without allowing them to emit events.
	*
	* @example
	* ```typescript
	* class BusDriver {
	*   constructor(consumer: SystemBusConsumer) {
	*     // Can only subscribe, cannot emit
	*     consumer.on('text_delta', ...);
	*   }
	* }
	* ```
	*
	* @returns SystemBusConsumer - Read-only view
	*/
	asConsumer(): SystemBusConsumer;
	/**
	* Get a write-only producer view of the bus.
	*
	* Use this to give components the ability to emit events
	* without exposing subscription capabilities.
	*
	* @example
	* ```typescript
	* class ClaudeReceptor {
	*   constructor(producer: SystemBusProducer) {
	*     // Can only emit, cannot subscribe
	*     producer.emit({ type: 'text_delta', ... });
	*   }
	* }
	* ```
	*
	* @returns SystemBusProducer - Write-only view
	*/
	asProducer(): SystemBusProducer;
	/**
	* Destroy the bus and clean up resources.
	*
	* All subscriptions will be terminated.
	* After calling destroy():
	* - All subscriptions are removed
	* - New emissions are ignored
	* - New subscriptions are no-ops
	*/
	destroy(): void;
}
/**
* Error context for error handling
*
* Provides context information when handling errors in event handlers.
*/
interface ErrorContext {
	/**
	* Event source that triggered the error
	*/
	source?: EventSource;
	/**
	* Request ID (if error is related to a request)
	*/
	requestId?: string;
	/**
	* Error severity
	*/
	severity?: "info" | "warn" | "error" | "fatal";
	/**
	* Operation name (for logging and debugging)
	*/
	operation?: string;
	/**
	* Additional error details
	*/
	details?: Record<string, unknown>;
	/**
	* Optional callback to handle error (e.g., emit error response)
	*/
	onError?: (err: unknown) => void;
}
export { Workdir, Unsubscribe2 as Unsubscribe, TokenUsage2 as TokenUsage, SystemBusProducer, SystemBusConsumer, SystemBus, SubscribeOptions2 as SubscribeOptions, StreamChunk, StopReason, SessionRepository, SessionRecord, Session, Sandbox, RuntimeEnvironmentConfig, Repository, Receptor, Persistence, MessageRecord, McpTransportConfig, McpTool, McpServerInfo, McpServerConfig, McpResource, McpRequest, McpProtocolVersion, McpPrompt, LLMResponse, LLMRequest, LLMProvider, LLMConfig, LLM, ImageRepository, ImageRecord, ImageMetadata, ErrorContext, EnvironmentRecord, Environment, Effector, ContainerRepository, ContainerRecord, ContainerConfig, Container, BusEventHandler2 as BusEventHandler };
