/**
* 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;
/**
* 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;
}
/**
* 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;
}
/**
* Agent event categories
*/
type AgentEventCategory = "stream" | "state" | "message" | "turn";
/**
* BaseAgentEvent - Base interface for all Agent events
*
* Extends SystemEvent with fixed source and intent.
*/
interface BaseAgentEvent<
	T extends string,
	D,
	C extends AgentEventCategory
> extends SystemEvent<T, D, "agent", C, "notification"> {
	/**
	* Runtime context (optional, added by Presenter)
	*/
	readonly context?: EventContext;
}
/**
* Base type for turn events
*/
interface AgentTurnEventBase<
	T extends string,
	D
> extends BaseAgentEvent<T, D, "turn"> {}
/**
* Token usage information
*/
interface TokenUsage {
	inputTokens: number;
	outputTokens: number;
	totalTokens?: number;
}
/**
* TurnRequestEvent - Turn started (user message received)
*/
interface TurnRequestEvent extends AgentTurnEventBase<"turn_request", {
	turnId: string
	messageId: string
	content: string
	timestamp: number
}> {}
/**
* TurnResponseEvent - Turn completed (assistant response finished)
*/
interface TurnResponseEvent extends AgentTurnEventBase<"turn_response", {
	turnId: string
	messageId: string
	duration: number
	usage?: TokenUsage
	model?: string
	stopReason?: string
	timestamp: number
}> {}
/**
* AgentTurnEvent - All turn events
*/
type AgentTurnEvent = TurnRequestEvent | TurnResponseEvent;
/**
* EngineEvent - Lightweight event base for AgentEngine domain
*
* EngineEvent is the simplified event structure used inside AgentEngine.
* It only contains: type, timestamp, data
*
* This is distinct from the full AgentEvent (in @agentxjs/types/event/agent)
* which extends SystemEvent with source, category, intent, context.
*
* ## Relationship
*
* ```
* AgentEvent (Runtime domain)          EngineEvent (Engine domain)
* ─────────────────────────────────────────────────────────────────
* {                                    {
*   type: "text_delta",                  type: "text_delta",
*   timestamp: 123,                      timestamp: 123,
*   data: { text: "Hi" },                data: { text: "Hi" },
*   source: "agent",          ←── not in Engine
*   category: "stream",       ←── not in Engine
*   intent: "notification",   ←── not in Engine
*   context: { ... },         ←── not in Engine
* }                                    }
* ```
*
* Use `ToEngineEvent<T>` to convert AgentEvent to EngineEvent.
*/
/**
* EngineEvent - Lightweight event for Engine internal use
*
* Only contains the essential fields:
* - type: What happened
* - timestamp: When it happened
* - data: Event payload
*/
interface EngineEvent<
	T extends string = string,
	D = unknown
> {
	/**
	* Event type identifier (e.g., "text_delta", "assistant_message")
	*/
	readonly type: T;
	/**
	* Event timestamp (Unix milliseconds)
	*/
	readonly timestamp: number;
	/**
	* Event payload data
	*/
	readonly data: D;
}
/**
* ToEngineEvent - Extract lightweight event from full AgentEvent
*
* Picks only { type, timestamp, data } from the full SystemEvent structure.
*
* @example
* ```typescript
* import type { TextDeltaEvent as FullTextDeltaEvent } from "@agentxjs/types/event/agent";
* import type { ToEngineEvent } from "./EngineEvent";
*
* // FullTextDeltaEvent has: type, timestamp, data, source, category, intent, context
* // TextDeltaEvent only has: type, timestamp, data
* type TextDeltaEvent = ToEngineEvent<FullTextDeltaEvent>;
* ```
*/
type ToEngineEvent<E> = E extends {
	type: infer T
	timestamp: number
	data: infer D
} ? EngineEvent<T extends string ? T : string, D> : never;
/**
* ToEngineEventUnion - Convert a union of AgentEvents to EngineEvents
*
* @example
* ```typescript
* type AgentStreamEvent = TextDeltaEvent | MessageStartEvent | ...;
* type StreamEvent = ToEngineEventUnion<AgentStreamEvent>;
* // StreamEvent is now the lightweight version of each event in the union
* ```
*/
type ToEngineEventUnion<E> = E extends unknown ? ToEngineEvent<E> : never;
/**
* TurnEvent - Base type for turn events
* @deprecated Use specific event types instead
*/
interface TurnEvent<
	T extends string = string,
	D = unknown
> extends EngineEvent<T, D> {}
type TurnRequestEvent2 = ToEngineEvent<TurnRequestEvent>;
type TurnResponseEvent2 = ToEngineEvent<TurnResponseEvent>;
/**
* AgentTurnEvent - All lightweight turn events
*/
type AgentTurnEvent2 = ToEngineEventUnion<AgentTurnEvent>;
/**
* Type guard: is this a turn event?
*/
declare function isTurnEvent(event: EngineEvent): event is AgentTurnEvent2;
/**
* 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 Subtype
*
* Represents the specific type/category of the message.
* Used together with role for serialization and type discrimination.
*/
type MessageSubtype = "user" | "assistant" | "tool-call" | "tool-result" | "error";
/**
* 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;
/**
* Message Role
*
* Represents who sent the message in the conversation.
* Five fundamental roles in the conversation.
*/
type MessageRole = "user" | "assistant" | "tool" | "system" | "error";
/**
* 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;
/**
* Base type for stream events
*/
interface AgentStreamEventBase<
	T extends string,
	D
> extends BaseAgentEvent<T, D, "stream"> {}
/**
* Stop reason for message completion
*/
type StopReason = "end_turn" | "max_tokens" | "stop_sequence" | "tool_use";
/**
* AgentMessageStartEvent - Streaming message begins
*/
interface AgentMessageStartEvent extends AgentStreamEventBase<"message_start", {
	messageId: string
	model: string
}> {}
/**
* AgentMessageDeltaEvent - Message-level updates (usage info)
*/
interface AgentMessageDeltaEvent extends AgentStreamEventBase<"message_delta", {
	usage?: {
		inputTokens: number
		outputTokens: number
	}
}> {}
/**
* AgentMessageStopEvent - Streaming message completes
*/
interface AgentMessageStopEvent extends AgentStreamEventBase<"message_stop", {
	stopReason?: StopReason
}> {}
/**
* AgentTextDeltaEvent - Incremental text output
*/
interface AgentTextDeltaEvent extends AgentStreamEventBase<"text_delta", {
	text: string
}> {}
/**
* AgentToolUseStartEvent - Tool use block started
*/
interface AgentToolUseStartEvent extends AgentStreamEventBase<"tool_use_start", {
	toolCallId: string
	toolName: string
}> {}
/**
* AgentInputJsonDeltaEvent - Incremental tool input JSON
*/
interface AgentInputJsonDeltaEvent extends AgentStreamEventBase<"input_json_delta", {
	partialJson: string
}> {}
/**
* AgentToolUseStopEvent - Tool use block completed
*/
interface AgentToolUseStopEvent extends AgentStreamEventBase<"tool_use_stop", {
	toolCallId: string
	toolName: string
	input: Record<string, unknown>
}> {}
/**
* AgentToolResultEvent - Tool execution result
*/
interface AgentToolResultEvent extends AgentStreamEventBase<"tool_result", {
	toolCallId: string
	result: unknown
	isError?: boolean
}> {}
/**
* AgentErrorReceivedEvent - Error received from environment
*
* Processed by MealyMachine to produce:
* - error_occurred (StateEvent)
* - error_message (MessageEvent)
*/
interface AgentErrorReceivedEvent extends AgentStreamEventBase<"error_received", {
	/** Error message (human-readable) */
	message: string
	/** Error code (e.g., "rate_limit_error", "api_error") */
	errorCode?: string
}> {}
/**
* AgentStreamEvent - All stream events
*/
type AgentStreamEvent = AgentMessageStartEvent | AgentMessageDeltaEvent | AgentMessageStopEvent | AgentTextDeltaEvent | AgentToolUseStartEvent | AgentInputJsonDeltaEvent | AgentToolUseStopEvent | AgentToolResultEvent | AgentErrorReceivedEvent;
type MessageStartEvent = ToEngineEvent<AgentMessageStartEvent>;
type MessageDeltaEvent = ToEngineEvent<AgentMessageDeltaEvent>;
type MessageStopEvent = ToEngineEvent<AgentMessageStopEvent>;
type TextDeltaEvent = ToEngineEvent<AgentTextDeltaEvent>;
type ToolUseStartEvent = ToEngineEvent<AgentToolUseStartEvent>;
type InputJsonDeltaEvent = ToEngineEvent<AgentInputJsonDeltaEvent>;
type ToolUseStopEvent = ToEngineEvent<AgentToolUseStopEvent>;
type ToolResultEvent = ToEngineEvent<AgentToolResultEvent>;
/**
* StreamEvent - All lightweight stream events
*/
type StreamEvent = ToEngineEventUnion<AgentStreamEvent>;
/**
* StreamEventType - String literal union
*/
type StreamEventType = StreamEvent["type"];
/**
* AgentState
*
* Agent conversation states for fine-grained monitoring.
*
* State transitions:
* ```
* idle → thinking → responding → idle
*                       ↓
*              planning_tool → awaiting_tool_result
*                       ↓
*                   thinking → responding → idle
*
* Any state can transition to error:
* thinking/responding/planning_tool/awaiting_tool_result → error → idle
* ```
*/
/**
* Agent state types
*/
type AgentState = "idle" | "thinking" | "responding" | "planning_tool" | "awaiting_tool_result" | "error";
/**
* Base type for state events
*/
interface AgentStateEventBase<
	T extends string,
	D
> extends BaseAgentEvent<T, D, "state"> {}
/**
* ConversationQueuedEvent - Message queued for processing
*/
interface ConversationQueuedEvent extends AgentStateEventBase<"conversation_queued", {
	messageId: string
}> {}
/**
* ConversationStartEvent - Conversation started
*/
interface ConversationStartEvent extends AgentStateEventBase<"conversation_start", {
	messageId: string
}> {}
/**
* ConversationThinkingEvent - Agent is thinking
*/
interface ConversationThinkingEvent extends AgentStateEventBase<"conversation_thinking", Record<string, never>> {}
/**
* ConversationRespondingEvent - Agent is responding
*/
interface ConversationRespondingEvent extends AgentStateEventBase<"conversation_responding", Record<string, never>> {}
/**
* ConversationEndEvent - Conversation ended
*/
interface ConversationEndEvent extends AgentStateEventBase<"conversation_end", {
	reason: "completed" | "interrupted" | "error"
}> {}
/**
* ConversationInterruptedEvent - Conversation interrupted
*/
interface ConversationInterruptedEvent extends AgentStateEventBase<"conversation_interrupted", {
	reason: string
}> {}
/**
* ToolPlannedEvent - Tool use planned
*/
interface ToolPlannedEvent extends AgentStateEventBase<"tool_planned", {
	toolId: string
	toolName: string
}> {}
/**
* ToolExecutingEvent - Tool is executing
*/
interface ToolExecutingEvent extends AgentStateEventBase<"tool_executing", {
	toolId: string
	toolName: string
	input: Record<string, unknown>
}> {}
/**
* ToolCompletedEvent - Tool execution completed
*/
interface ToolCompletedEvent extends AgentStateEventBase<"tool_completed", {
	toolId: string
	toolName: string
	result: unknown
}> {}
/**
* ToolFailedEvent - Tool execution failed
*/
interface ToolFailedEvent extends AgentStateEventBase<"tool_failed", {
	toolId: string
	toolName: string
	error: string
}> {}
/**
* ErrorOccurredEvent - Error occurred during processing
*/
interface ErrorOccurredEvent extends AgentStateEventBase<"error_occurred", {
	code: string
	message: string
	recoverable: boolean
	category?: string
}> {}
/**
* AgentStateEvent - All state events
*/
type AgentStateEvent = ConversationQueuedEvent | ConversationStartEvent | ConversationThinkingEvent | ConversationRespondingEvent | ConversationEndEvent | ConversationInterruptedEvent | ToolPlannedEvent | ToolExecutingEvent | ToolCompletedEvent | ToolFailedEvent | ErrorOccurredEvent;
/**
* StateEvent - Base type for state events
* @deprecated Use specific event types instead
*/
interface StateEvent<
	T extends string = string,
	D = unknown
> extends EngineEvent<T, D> {}
type ConversationQueuedEvent2 = ToEngineEvent<ConversationQueuedEvent>;
type ConversationStartEvent2 = ToEngineEvent<ConversationStartEvent>;
type ConversationThinkingEvent2 = ToEngineEvent<ConversationThinkingEvent>;
type ConversationRespondingEvent2 = ToEngineEvent<ConversationRespondingEvent>;
type ConversationEndEvent2 = ToEngineEvent<ConversationEndEvent>;
type ConversationInterruptedEvent2 = ToEngineEvent<ConversationInterruptedEvent>;
type ToolPlannedEvent2 = ToEngineEvent<ToolPlannedEvent>;
type ToolExecutingEvent2 = ToEngineEvent<ToolExecutingEvent>;
type ToolCompletedEvent2 = ToEngineEvent<ToolCompletedEvent>;
type ToolFailedEvent2 = ToEngineEvent<ToolFailedEvent>;
type ErrorOccurredEvent2 = ToEngineEvent<ErrorOccurredEvent>;
/**
* Alias for ErrorOccurredEvent (legacy compatibility)
*/
type AgentErrorOccurredEvent = ErrorOccurredEvent2;
/**
* AgentStateEvent - All lightweight state events
*/
type AgentStateEvent2 = ToEngineEventUnion<AgentStateEvent>;
/**
* Type guard: is this a state event?
*/
declare function isStateEvent(event: EngineEvent): event is AgentStateEvent2;
/**
* Base type for message events
*/
interface AgentMessageEventBase<
	T extends string,
	D
> extends BaseAgentEvent<T, D, "message"> {}
/**
* UserMessageEvent - User sent a message
* Data: Complete UserMessage object
*/
interface UserMessageEvent extends AgentMessageEventBase<"user_message", UserMessage> {}
/**
* AssistantMessageEvent - Assistant response message
* Data: Complete AssistantMessage object
*/
interface AssistantMessageEvent extends AgentMessageEventBase<"assistant_message", AssistantMessage> {}
/**
* ToolCallMessageEvent - Tool call message (part of assistant turn)
* Data: Complete ToolCallMessage object
*/
interface ToolCallMessageEvent extends AgentMessageEventBase<"tool_call_message", ToolCallMessage> {}
/**
* ToolResultMessageEvent - Tool result message
* Data: Complete ToolResultMessage object
*/
interface ToolResultMessageEvent extends AgentMessageEventBase<"tool_result_message", ToolResultMessage> {}
/**
* ErrorMessageEvent - Error message displayed in chat
* Data: Complete ErrorMessage object
*
* Generated when error_received StreamEvent is processed by MealyMachine.
* Displayed in the chat history so users can see what went wrong.
*/
interface ErrorMessageEvent extends AgentMessageEventBase<"error_message", ErrorMessage> {}
/**
* AgentMessageEvent - All message events
*/
type AgentMessageEvent = UserMessageEvent | AssistantMessageEvent | ToolCallMessageEvent | ToolResultMessageEvent | ErrorMessageEvent;
/**
* MessageEvent - Base type for message events
* @deprecated Use specific event types instead
*/
interface MessageEvent<
	T extends string = string,
	D = unknown
> extends EngineEvent<T, D> {}
type UserMessageEvent2 = ToEngineEvent<UserMessageEvent>;
type AssistantMessageEvent2 = ToEngineEvent<AssistantMessageEvent>;
type ToolCallMessageEvent2 = ToEngineEvent<ToolCallMessageEvent>;
type ToolResultMessageEvent2 = ToEngineEvent<ToolResultMessageEvent>;
type ErrorMessageEvent2 = ToEngineEvent<ErrorMessageEvent>;
/**
* AgentMessageEvent - All lightweight message events
*/
type AgentMessageEvent2 = ToEngineEventUnion<AgentMessageEvent>;
/**
* Type guard: is this a message event?
*/
declare function isMessageEvent(event: EngineEvent): event is AgentMessageEvent2;
/**
* All possible output types from Agent
*/
type AgentOutput = StreamEvent | AgentStateEvent2 | AgentMessageEvent2 | AgentTurnEvent2;
/**
* Unsubscribe function returned by on()
*/
type Unsubscribe = () => void;
/**
* Agent output event callback function type
*/
type AgentOutputCallback<T extends AgentOutput = AgentOutput> = (event: T) => void;
/**
* @deprecated Use AgentOutputCallback instead
*/
type AgentEventHandler<T extends AgentOutput = AgentOutput> = AgentOutputCallback<T>;
/**
* Next function to continue the middleware chain
*/
type AgentMiddlewareNext = (message: UserMessage) => Promise<void>;
/**
* Middleware function type
*
* @param message - The user message being processed
* @param next - Call to continue to next middleware or actual receive
*/
type AgentMiddleware = (message: UserMessage, next: AgentMiddlewareNext) => Promise<void>;
/**
* Next function to continue the interceptor chain
*/
type AgentInterceptorNext = (event: AgentOutput) => void;
/**
* Interceptor function type
*
* @param event - The event being dispatched
* @param next - Call to continue to next interceptor or actual dispatch
*/
type AgentInterceptor = (event: AgentOutput, next: AgentInterceptorNext) => void;
/**
* MessageQueue - Pending message queue interface
*
* Exposes read-only queue state for observability.
* Queue operations (enqueue/dequeue) are internal to Agent implementation.
*/
/**
* MessageQueue interface
*
* Read-only view of the message queue state.
*/
interface MessageQueue {
	/**
	* Number of messages in queue
	*/
	readonly length: number;
	/**
	* Whether queue is empty
	*/
	readonly isEmpty: boolean;
}
/**
* State change event payload
*/
interface StateChange {
	prev: AgentState;
	current: AgentState;
}
/**
* State change handler type
*/
type StateChangeHandler = (change: StateChange) => void;
/**
* Event handler map for batch subscription
*
* Generic handler map - concrete event types are defined in runtime/event.
* AgentEngine package is independent of specific event type definitions.
*
* Usage:
* ```typescript
* engine.on({
*   text_delta: (event) => console.log(event.data.text),
*   assistant_message: (event) => setMessages(prev => [...prev, event.data]),
* });
* ```
*/
type EventHandlerMap = Record<string, ((event: AgentOutput) => void) | undefined>;
/**
* React-style handler map for fluent event subscription
*
* Generic handler map - concrete event types are defined in runtime/event.
* AgentEngine package is independent of specific event type definitions.
*
* Usage:
* ```typescript
* engine.react({
*   onTextDelta: (event) => console.log(event.data.text),
*   onAssistantMessage: (event) => setMessages(prev => [...prev, event.data]),
* });
* ```
*/
type ReactHandlerMap = Record<string, ((event: AgentOutput) => void) | undefined>;
/**
* AgentEngine interface - Event Processing Unit
*
* Core responsibilities:
* - State management (AgentState)
* - Event subscription and distribution
* - Middleware/Interceptor chain
*/
interface AgentEngine {
	/**
	* Unique agent instance ID
	*/
	readonly agentId: string;
	/**
	* Creation timestamp
	*/
	readonly createdAt: number;
	/**
	* Current conversation state
	*/
	readonly state: AgentState;
	/**
	* Message queue for pending messages
	*/
	readonly messageQueue: MessageQueue;
	/**
	* Receive a message from user
	*
	* @param message - String content or UserMessage object
	* @deprecated Use handleStreamEvent for push-based event processing
	*/
	receive(message: string | UserMessage): Promise<void>;
	/**
	* Handle a stream event from the driver
	*
	* This is the push-based API for event processing.
	* Events are pushed by BusDriver when DriveableEvents arrive.
	*
	* @param event - StreamEvent to process through MealyMachine
	*/
	handleStreamEvent(event: StreamEvent): void;
	/**
	* Subscribe to all events
	*/
	on(handler: AgentOutputCallback): Unsubscribe;
	/**
	* Batch subscribe to multiple event types
	*/
	on(handlers: EventHandlerMap): Unsubscribe;
	/**
	* Subscribe to specific event type by name
	*/
	on(type: string, handler: AgentOutputCallback): Unsubscribe;
	/**
	* Subscribe to multiple event types by name
	*/
	on(types: string[], handler: AgentOutputCallback): Unsubscribe;
	/**
	* Subscribe to state changes
	*
	* @param handler - Callback receiving { prev, current } state change
	* @returns Unsubscribe function
	*/
	onStateChange(handler: StateChangeHandler): Unsubscribe;
	/**
	* React-style fluent event subscription
	*/
	react(handlers: ReactHandlerMap): Unsubscribe;
	/**
	* Subscribe to agent ready event
	*
	* Called when agent is ready to receive messages.
	* If already ready, handler is called immediately.
	*/
	onReady(handler: () => void): Unsubscribe;
	/**
	* Subscribe to agent destroy event
	*
	* Called when agent is destroyed.
	*/
	onDestroy(handler: () => void): Unsubscribe;
	/**
	* Add middleware to intercept incoming messages (receive side)
	*/
	use(middleware: AgentMiddleware): Unsubscribe;
	/**
	* Add interceptor to intercept outgoing events (event side)
	*/
	intercept(interceptor: AgentInterceptor): Unsubscribe;
	/**
	* Interrupt - User-initiated stop
	*
	* Stops the current operation gracefully.
	* The agent will return to idle state.
	*/
	interrupt(): void;
	/**
	* Destroy - Clean up resources
	*/
	destroy(): Promise<void>;
}
/**
* AgentError - Error types for Agent layer
*
* Standardized error structure for agent operations.
*/
/**
* Error category
*/
type AgentErrorCategory = "network" | "validation" | "system" | "business";
/**
* AgentError - Standardized error structure
*/
interface AgentError {
	/**
	* Error category
	*/
	category: AgentErrorCategory;
	/**
	* Error code (e.g., "NETWORK_TIMEOUT", "INVALID_INPUT")
	*/
	code: string;
	/**
	* Human-readable error message
	*/
	message: string;
	/**
	* Whether the error is recoverable
	*/
	recoverable: boolean;
	/**
	* Original error (if any)
	*/
	cause?: Error;
	/**
	* Additional context
	*/
	context?: Record<string, unknown>;
}
/**
* AgentDriver interface
*
* A message processor that receives user messages and yields StreamEvents.
* Lifecycle (creation, resume, destruction) is managed by Container.
*/
interface AgentDriver {
	/**
	* Driver name (for identification and logging)
	*/
	readonly name: string;
	/**
	* Optional description
	*/
	readonly description?: string;
	/**
	* Receive a user message and yield stream events
	*
	* @param message - User message to process
	* @returns AsyncIterable of StreamEvent
	*/
	receive(message: UserMessage): AsyncIterable<StreamEvent>;
	/**
	* Interrupt the current operation
	*
	* Stops the current receive() operation gracefully.
	* Driver should abort any ongoing requests.
	*/
	interrupt(): void;
}
/**
* AgentPresenter interface
*
* A named, self-describing presenter that receives agent outputs
* and presents them to external systems.
*/
interface AgentPresenter {
	/**
	* Presenter name (for identification and logging)
	*/
	readonly name: string;
	/**
	* Optional description
	*/
	readonly description?: string;
	/**
	* Present an agent output
	*
	* @param agentId - The agent ID
	* @param output - The output to present
	*/
	present(agentId: string, output: AgentOutput): void | Promise<void>;
}
/**
* Options for creating an AgentEngine
*/
interface CreateAgentOptions {
	/**
	* Driver - Event producer (LLM interaction)
	*/
	driver: AgentDriver;
	/**
	* Presenter - Event consumer (side effects)
	*/
	presenter: AgentPresenter;
}
/**
* Factory function to create an AgentEngine
*
* AgentEngine is a logical processing unit that coordinates:
* - Driver: produces stream events from LLM
* - MealyMachine: assembles events (internal, created automatically)
* - Presenter: consumes processed events
*
* @example
* ```typescript
* const engine = createAgent({
*   driver: new ClaudeDriver(config),
*   presenter: new SSEPresenter(connection),
* });
*
* engine.on("text_delta", (e) => console.log(e.data.text));
* await engine.receive("Hello!");
* ```
*/
declare function createAgent(options: CreateAgentOptions): AgentEngine;
/**
* @deprecated Use EngineEvent instead
*/
type AgentEvent<
	T extends string = string,
	D = unknown
> = EngineEvent<T, D>;
export { isTurnEvent, isStateEvent, isMessageEvent, createAgent, UserMessageEvent2 as UserMessageEvent, UserMessage, UserContentPart, Unsubscribe, TurnResponseEvent2 as TurnResponseEvent, TurnRequestEvent2 as TurnRequestEvent, TurnEvent, ToolUseStopEvent, ToolUseStartEvent, ToolResultPart, ToolResultOutput, ToolResultMessageEvent2 as ToolResultMessageEvent, ToolResultMessage, ToolResultEvent, ToolPlannedEvent2 as ToolPlannedEvent, ToolFailedEvent2 as ToolFailedEvent, ToolExecutingEvent2 as ToolExecutingEvent, ToolCompletedEvent2 as ToolCompletedEvent, ToolCallPart, ToolCallMessageEvent2 as ToolCallMessageEvent, ToolCallMessage, TokenUsage, ToEngineEventUnion, ToEngineEvent, ThinkingPart, TextPart, TextDeltaEvent, StreamEventType, StreamEvent, StopReason, StateEvent, StateChangeHandler, StateChange, ReactHandlerMap, MessageSubtype, MessageStopEvent, MessageStartEvent, MessageRole, MessageQueue, MessageEvent, MessageDeltaEvent, Message, InputJsonDeltaEvent, ImagePart, FilePart, EventHandlerMap, ErrorOccurredEvent2 as ErrorOccurredEvent, ErrorMessageEvent2 as ErrorMessageEvent, ErrorMessage, EngineEvent, CreateAgentOptions, ConversationThinkingEvent2 as ConversationThinkingEvent, ConversationStartEvent2 as ConversationStartEvent, ConversationRespondingEvent2 as ConversationRespondingEvent, ConversationQueuedEvent2 as ConversationQueuedEvent, ConversationInterruptedEvent2 as ConversationInterruptedEvent, ConversationEndEvent2 as ConversationEndEvent, ContentPart, AssistantMessageEvent2 as AssistantMessageEvent, AssistantMessage, AgentTurnEvent2 as AgentTurnEvent, AgentStateEvent2 as AgentStateEvent, AgentState, AgentPresenter, AgentOutputCallback, AgentOutput, AgentMessageEvent2 as AgentMessageEvent, AgentEventHandler, AgentEvent, AgentErrorOccurredEvent, AgentErrorCategory, AgentError, AgentEngine, AgentDriver };
