/**
* 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;
/**
* AgentTurnEvent - All lightweight turn events
*/
type AgentTurnEvent2 = ToEngineEventUnion<AgentTurnEvent>;
/**
* 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;
}
/**
* 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>;
/**
* 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;
/**
* StreamEvent - All lightweight stream events
*/
type StreamEvent = ToEngineEventUnion<AgentStreamEvent>;
/**
* 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;
/**
* AgentStateEvent - All lightweight state events
*/
type AgentStateEvent2 = ToEngineEventUnion<AgentStateEvent>;
/**
* 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;
/**
* AgentMessageEvent - All lightweight message events
*/
type AgentMessageEvent2 = ToEngineEventUnion<AgentMessageEvent>;
/**
* All possible output types from Agent
*/
type AgentOutput = StreamEvent | AgentStateEvent2 | AgentMessageEvent2 | AgentTurnEvent2;
/**
* 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;
/**
* 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>;
/**
* 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";
/**
* State change event payload
*/
interface StateChange {
	prev: AgentState;
	current: AgentState;
}
/**
* State change handler type
*/
type StateChangeHandler = (change: StateChange) => void;
/**
* AgentStateMachine interface
*
* Processes StateEvents to update internal agent state and notify subscribers.
*/
interface AgentStateMachine {
	/**
	* Current agent state
	*/
	readonly state: AgentState;
	/**
	* Process a StateEvent and update internal state
	*
	* @param event - StateEvent from MealyMachine
	*/
	process(event: AgentOutput): void;
	/**
	* Subscribe to state changes
	*
	* @param handler - Callback receiving { prev, current } state change
	* @returns Unsubscribe function
	*/
	onStateChange(handler: StateChangeHandler): Unsubscribe;
	/**
	* Reset state machine (used on destroy)
	*/
	reset(): void;
}
export { Unsubscribe, AgentStateMachine, AgentOutputCallback, AgentMiddlewareNext, AgentMiddleware, AgentInterceptorNext, AgentInterceptor, AgentEventHandler };
