/**
* LogLevel - Standard log level type
*
* Defines the severity levels for logging.
* Uses string literal types for better readability and type safety.
*/
type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
/**
* Logging context metadata
*/
type LogContext = Record<string, unknown>;
/**
* Logger interface
*
* All logger implementations must follow this interface.
*
* @example
* ```typescript
* class PinoLogger implements Logger {
*   private pino: Pino.Logger;
*
*   constructor(name: string) {
*     this.pino = pino({ name });
*   }
*
*   get name() { return this.pino.name; }
*   get level() { return LogLevel.DEBUG; }
*
*   debug(message: string, context?: LogContext) {
*     this.pino.debug(context, message);
*   }
*   // ... other methods
* }
* ```
*/
interface Logger {
	/**
	* Logger name (typically class name or module path)
	*/
	readonly name: string;
	/**
	* Current log level
	*/
	readonly level: LogLevel;
	/**
	* Log debug message
	*/
	debug(message: string, context?: LogContext): void;
	/**
	* Log info message
	*/
	info(message: string, context?: LogContext): void;
	/**
	* Log warning message
	*/
	warn(message: string, context?: LogContext): void;
	/**
	* Log error message or Error object
	*/
	error(message: string | Error, context?: LogContext): void;
	/**
	* Check if debug level is enabled
	*/
	isDebugEnabled(): boolean;
	/**
	* Check if info level is enabled
	*/
	isInfoEnabled(): boolean;
	/**
	* Check if warn level is enabled
	*/
	isWarnEnabled(): boolean;
	/**
	* Check if error level is enabled
	*/
	isErrorEnabled(): boolean;
}
/**
* LoggerFactory interface
*
* Factory for creating named Logger instances.
*/
interface LoggerFactory {
	/**
	* Get or create a logger with the specified name
	*
	* @param name - Logger name (typically class name or module path)
	* @returns Logger instance
	*/
	getLogger(name: string): Logger;
}
/**
* createLogger - Factory function for creating Logger instances
*
* This is the authoritative API definition.
* The agentx-common package must implement this function exactly.
*
* Uses lazy initialization: safe to call at module level before
* Runtime is configured. The actual logger implementation is
* resolved on first use.
*
* @param name - Logger name (hierarchical, e.g., "engine/AgentEngine")
* @returns Logger instance (lazy proxy)
*
* @example
* ```typescript
* // Safe at module level (before Runtime configured)
* const logger = createLogger("engine/AgentEngine");
*
* // Later, at runtime
* logger.debug("Processing event", { agentId, eventType });
* ```
*/
declare function createLogger(name: string): Logger;
/**
* MCP Server Config (SDK Compatible)
*
* Configuration for MCP servers, compatible with Claude Agent SDK.
* Used in AgentConfig.mcpServers.
*
* Note: For stdio type, the 'type' field is optional (defaults to stdio).
*/
type McpServerConfig = McpStdioServerConfig | McpSseServerConfig | McpHttpServerConfig | McpSdkServerConfig;
/**
* Stdio Server Config (SDK Compatible)
* Type is optional, defaults to stdio when omitted.
*/
interface McpStdioServerConfig {
	type?: "stdio";
	command: string;
	args?: string[];
	env?: Record<string, string>;
}
/**
* SSE Server Config (SDK Compatible)
*/
interface McpSseServerConfig {
	type: "sse";
	url: string;
	headers?: Record<string, string>;
}
/**
* HTTP Server Config (SDK Compatible)
*/
interface McpHttpServerConfig {
	type: "http";
	url: string;
	headers?: Record<string, string>;
}
/**
* SDK Server Config (SDK Compatible)
* For in-process MCP servers.
*/
interface McpSdkServerConfig {
	type: "sdk";
	name: string;
	instance: unknown;
}
/**
* Image metadata for storing provider-specific data
*/
interface ImageMetadata {
	/** Claude SDK session ID for conversation resume */
	claudeSdkSessionId?: string;
	/** User context - serialized JSON string for passing to LLM Proxy via URL */
	userContext?: string;
}
/**
* Image storage record
*
* Represents a conversation that persists across server restarts.
*/
interface ImageRecord {
	/**
	* Unique image identifier
	* Pattern: `img_${nanoid()}`
	*/
	imageId: string;
	/**
	* Container ID (user isolation boundary)
	*/
	containerId: string;
	/**
	* Session ID for message storage
	* Messages are stored in Session, not duplicated here
	*/
	sessionId: string;
	/**
	* Conversation name (displayed to user)
	*/
	name: string;
	/**
	* Conversation description (optional)
	*/
	description?: string;
	/**
	* System prompt - controls agent behavior
	*/
	systemPrompt?: string;
	/**
	* Parent image ID (for fork/branch feature)
	*/
	parentImageId?: string;
	/**
	* MCP servers configuration
	*/
	mcpServers?: Record<string, McpServerConfig>;
	/**
	* Blacklist of disallowed tools (tool names)
	* When set, these tools will be disabled for the agent
	*/
	disallowedTools?: string[];
	/**
	* Restrict available tools - can be array of tool names or preset
	* More granular control over which built-in tools are available
	*/
	tools?: string[] | {
		type: "preset"
		preset: "claude_code"
	};
	/**
	* Claude Code 风格的 Skills
	* 每个 skill 会被写入 .claude/skills/{name}/SKILL.md
	* SDK 自动发现并注入到 Claude 的 context 中
	*/
	skills?: import("~/agentx").SkillDefinition[];
	/**
	* Per-image LLM configuration (optional)
	*
	* When set, this image's agent will use this LLM config instead of the global Runtime-level config.
	* Enables different conversations/roles to use different LLM providers or models.
	* Fields are merged with global config: only non-empty fields override the global defaults.
	*/
	llmConfig?: {
		apiKey?: string
		baseUrl?: string
		model?: string
	};
	/**
	* Provider-specific metadata (e.g., Claude SDK session ID)
	*/
	metadata?: ImageMetadata;
	/**
	* Creation timestamp (Unix milliseconds)
	*/
	createdAt: number;
	/**
	* Last update timestamp (Unix milliseconds)
	*/
	updatedAt: number;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
/**
* 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>;
}
/**
* 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;
}
/**
* AgentDefinition - Static template for defining an Agent
*
* Used to define agent behavior and capabilities before instantiation.
* This is the "application layer" configuration that describes what an agent does.
*
* @example
* ```typescript
* const MyAgent = defineAgent({
*   name: "Assistant",
*   description: "A helpful AI assistant",
*   systemPrompt: "You are a helpful assistant.",
*   mcpServers: {
*     filesystem: {
*       command: "npx",
*       args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
*     }
*   }
* });
* ```
*/
interface AgentDefinition {
	/**
	* Agent name (required)
	*/
	name: string;
	/**
	* Agent description
	*/
	description?: string;
	/**
	* System prompt - controls agent behavior
	*/
	systemPrompt?: string;
	/**
	* MCP servers configuration
	*
	* Key is server name, value is server configuration.
	* Supports stdio, sse, http, and sdk transport types.
	*/
	mcpServers?: Record<string, McpServerConfig>;
	/**
	* Blacklist of disallowed tools (tool names)
	* When set, these tools will be disabled for the agent
	*/
	disallowedTools?: string[];
	/**
	* Restrict available tools - can be array of tool names or preset
	* More granular control over which built-in tools are available
	*/
	tools?: string[] | {
		type: "preset"
		preset: "claude_code"
	};
	/**
	* Claude Code 风格的 Skills
	*
	* 每个 skill 会被写入 .claude/skills/{name}/SKILL.md
	* SDK 自动发现并注入到 Claude 的 context 中
	*/
	skills?: SkillDefinition2[];
	/**
	* Per-agent LLM configuration (optional)
	*
	* When set, this agent will use the specified LLM instead of the Runtime-level default.
	* Enables different roles/agents to use different LLM providers or models.
	*
	* @example
	* ```typescript
	* llmConfig: {
	*   apiKey: "sk-...",
	*   baseUrl: "https://api.deepseek.com/v1",
	*   model: "deepseek-chat"
	* }
	* ```
	*/
	llmConfig?: {
		apiKey?: string
		baseUrl?: string
		model?: string
	};
}
/**
* SkillDefinition - Claude Code 风格的 Skill 定义
*
* 每个 skill 对应 .claude/skills/{name}/SKILL.md
* SDK 自动发现并注入到 Claude 的 context 中。
*
* Skills 是按需加载的 system prompt 片段：
* - description 常驻 context（Claude 用来判断什么时候用）
* - content 按需加载（匹配时才加载完整内容）
*
* @example
* ```typescript
* const skill: SkillDefinition = {
*   name: "shopify-spy",
*   description: "分析 Shopify 店铺和竞争对手，追踪产品目录、定价策略",
*   content: `# Shopify 店铺分析

当用户需要分析 Shopify 店铺时...
`,
* };
* ```
*/
interface SkillDefinition2 {
	/**
	* Skill 名称（目录名）
	* 小写字母、数字和连字符，最长 64 字符
	* @example "browser-use", "shopify-spy"
	*/
	name: string;
	/**
	* 描述：Claude 根据这个判断什么时候使用该 skill
	* 常驻 context，建议控制在 200 字符以内
	*/
	description: string;
	/**
	* SKILL.md 的 markdown 内容（不含 frontmatter，frontmatter 会自动生成）
	*/
	content: string;
	/**
	* 是否禁止 Claude 自动调用
	* true = 只能用户通过 /skill-name 显式调用
	* @default false
	*/
	disableModelInvocation?: boolean;
	/**
	* Skill 激活时允许使用的工具列表
	* @example ["Read", "Grep", "Glob"]
	*/
	allowedTools?: string[];
	/**
	* 运行上下文
	* "fork" = 在独立的子 agent 中运行
	*/
	context?: "fork";
}
export { createLogger, SessionRepository, SessionRecord, Persistence, LoggerFactory, Logger, LogLevel, LogContext, ImageRepository, ImageRecord, ContainerRepository, ContainerRecord, AgentDefinition };
