/** * Type definitions for Agent Loop Engine * * Includes types for: * - Claude API request/response * - Content blocks (text, tool_use, tool_result) * - MCP tool definitions and inputs * - Agent loop configuration * - Agent context and role awareness */ import type { RoleConfig } from '../cli/config/types.js'; import type { Envelope } from '../envelope/types.js'; import type { WikiPublishAdapter } from '../wiki-artifacts/wiki-publish-adapter.js'; import type { TemporalReconcileInput, TemporalWorkContext } from '../operator/temporal-effect.js'; import type { ContextCompileService } from './context-compile-service.js'; import type { GatewayToolExecutor } from './gateway-tool-executor.js'; import type { AppendToolTraceInput, BeginModelRunInput, ContextCompileInput as CoreContextCompileInput, ModelRunRecord, ToolTraceRecord } from '@jungjaehoon/mama-core'; export type { AppendToolTraceInput, BeginModelRunInput, ModelRunRecord, ToolTraceRecord, } from '@jungjaehoon/mama-core'; export type ContextCompileInput = CoreContextCompileInput; export type TemporalReconcileToolInput = TemporalReconcileInput & { context_packet_id: string; }; /** Agent-authored decision only; candidate authority remains in claimed workorder state. */ export interface ExternalBindingToolInput { candidate_id: string; decision: 'bind' | 'decline'; reason: string; expected_revision: number; } /** Agent-authored decision only; task, event, and status are host-recovered. */ export interface ExternalLifecycleReconcileToolInput { candidate_id: string; decision: 'apply' | 'retain'; reason: string; expected_revision: number; } export interface PrincipalRepository { resolveByExternal(connector: string, namespace: string, externalId: string): { principalId: string; kind: 'owner' | 'member'; status: string; } | null; registerMember(input: { displayName?: string; connector: string; namespace: string; externalId: string; now: number; }): string; bindIdentity(principalId: string, connector: string, namespace: string, externalId: string, now: number): void; suspend(principalId: string, now: number): void; offboard(principalId: string, now: number): void; ensureOwner(input: { connector: string; namespace: string; externalId: string; now: number; }): 'created' | 'exists' | 'conflict'; listMembers(): Array<{ principalId: string; displayName?: string; status: string; }>; } /** * Platform identifiers for agent context */ export type AgentPlatform = 'viewer' | 'discord' | 'telegram' | 'slack' | 'chatwork' | 'cli'; /** * Session information for agent context */ export interface SessionInfo { /** Unique session identifier */ sessionId: string; /** Channel or conversation ID */ channelId?: string; /** User ID who initiated the interaction */ userId?: string; /** Username for display purposes */ userName?: string; /** Timestamp when session started */ startedAt: Date; } /** * Agent context for role-aware execution * Provides information about the agent's current operating environment */ export interface AgentContext { /** * Message source identifier * @example "discord", "viewer", "telegram" */ source: string; /** * Platform type (normalized) */ platform: AgentPlatform; /** * Role name for this context * @example "os_agent", "chat_bot" */ roleName: string; /** * Role configuration with permissions */ role: RoleConfig; /** * Session information */ session: SessionInfo; /** * Human-readable capabilities summary * @example ["mama_search", "mama_save", "Read", "discord_send"] */ capabilities: string[]; /** * Human-readable limitations summary * @example ["Cannot execute Bash", "Cannot write files", "Limited path access"] */ limitations: string[]; /** * Agent tier level for Code-Act sandbox permission * @default 1 */ tier?: 1 | 2 | 3; /** * Backend type for this agent context * Used for backend-specific AGENTS.md injection */ backend?: 'claude' | 'codex' | 'cline'; } export type GatewayExecutionSurface = 'model_tool' | 'reactive_internal' | 'code_act' | 'direct'; export interface BackgroundTaskRegistry { register(task: Promise): void; } export type GatewayToolExecutionContext = { agentContext?: AgentContext; agentId?: string; source?: string; channelId?: string; envelope?: Envelope; executionSurface: GatewayExecutionSurface; sourceTurnId?: string; sourceMessageRef?: string; modelRunId?: string | null; gatewayCallId?: string; /** Host-issued claimed system-row id; never accepted from model tool input. */ workorderAttemptId?: number; /** Host-built temporal authority; never accepted from tool input or fallback state. */ temporalWorkContext?: TemporalWorkContext; /** * The delta batch this run was handed. Host-supplied; never accepted from tool input. * * The unit of bounded work: a reconcile run addresses ONE channel's new events, so every * durable change it makes rests on them. Carried on the run rather than asked of the * agent, which is the difference between a fact and a claim. */ causeEventIds?: readonly string[]; /** Cancellation for the owning model turn. */ signal?: AbortSignal; /** Parent gateway tool when execution is nested (for example inside code_act). */ parentToolName?: string; backgroundTasks?: BackgroundTaskRegistry; /** Per-call gateway tool blocks (e.g. OS-agent must delegate instead). */ disallowedGatewayTools?: string[]; }; /** * Claude API message role */ export type MessageRole = 'user' | 'assistant'; /** * Content block types in Claude API */ export type ContentBlockType = 'text' | 'image' | 'document' | 'tool_use' | 'tool_result'; /** * Text content block */ export interface TextBlock { type: 'text'; text: string; } /** * Image source for base64 encoded images */ export interface ImageSourceBase64 { type: 'base64'; media_type: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp'; data: string; } /** * Image content block for multimodal input */ export interface ImageBlock { type: 'image'; source: ImageSourceBase64; } /** * Document content block for document understanding */ export interface DocumentBlock { type: 'document'; source: { type: 'base64'; media_type: string; data: string; }; } /** * Tool use content block (Claude requesting tool execution) */ export interface ToolUseBlock { type: 'tool_use'; id: string; name: string; input: Record; } /** * Tool result content block (response to tool_use) */ export interface ToolResultBlock { type: 'tool_result'; tool_use_id: string; content: string; is_error?: boolean; } export interface CompletedToolExchange { toolUse: ToolUseBlock; toolResult: ToolResultBlock; } export interface PromptTerminalError { code: 'CODE_ACT_MUTATION_COMMITTED_AFTER_ABORT' | 'CODE_ACT_MUTATION_OUTCOME_UNKNOWN'; message: string; } export interface PromptResult { response: string; usage: { input_tokens: number; output_tokens: number; cache_creation_input_tokens?: number; cache_read_input_tokens?: number; }; session_id: string; cost_usd?: number; /** Only tool uses that still require host execution. */ toolUseBlocks?: ToolUseBlock[]; hasToolUse?: boolean; /** Host-completed MCP exchanges observed on the Claude stream, in result order. */ completedToolExchanges?: CompletedToolExchange[]; /** Trusted terminal mutation outcome decoded from a completed local MCP exchange. */ terminalError?: PromptTerminalError; duration_ms?: number; } export declare class ClaudeToolStreamProtocolError extends Error { readonly code = "CLAUDE_TOOL_STREAM_PROTOCOL"; constructor(message: string); } export declare class McpResultMissingError extends Error { readonly toolUseIds: readonly string[]; readonly code = "MCP_RESULT_MISSING"; readonly retryable = false; constructor(toolUseIds: readonly string[]); } export declare class McpCompletedMutationInterruptedError extends Error { readonly completedToolExchanges: readonly CompletedToolExchange[]; readonly code = "MCP_COMPLETED_MUTATION_INTERRUPTED"; readonly retryable = false; constructor(completedToolExchanges: readonly CompletedToolExchange[]); } /** * Union type for all content blocks */ export type ContentBlock = TextBlock | ImageBlock | DocumentBlock | ToolUseBlock | ToolResultBlock; /** * Message in conversation history */ export interface Message { role: MessageRole; content: ContentBlock[] | string; } /** * Stop reasons from Claude API */ export type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence'; /** * Usage information from Claude API */ export interface Usage { input_tokens: number; output_tokens: number; cache_creation_input_tokens?: number; cache_read_input_tokens?: number; cost_usd?: number; } /** * Claude API response */ export interface ClaudeResponse { id: string; type: 'message'; role: 'assistant'; content: ContentBlock[]; model: string; stop_reason: StopReason; stop_sequence: string | null; usage: Usage; } /** * Claude API error response */ export interface ClaudeErrorResponse { type: 'error'; error: { type: string; message: string; }; } /** * Claude API request body */ export interface ClaudeRequest { model: string; max_tokens: number; system?: string; messages: Message[]; tools?: ToolDefinition[]; stream?: boolean; } /** * Streaming event types */ export type StreamEventType = 'message_start' | 'content_block_start' | 'content_block_delta' | 'content_block_stop' | 'message_delta' | 'message_stop'; /** * Content block delta for streaming */ export interface ContentBlockDelta { type: 'text_delta' | 'input_json_delta'; text?: string; partial_json?: string; } /** * Common response shape passed to onFinal callbacks. * Both PersistentCLI and Codex app-server normalize their output to this format. */ export interface PromptFinalResponse { content: string; toolUseBlocks: ToolUseBlock[]; } /** * Callbacks for PersistentCLI / Codex app-server prompt calls. * Shared across all backend adapters to avoid duplicate definitions. */ export interface PromptCallbacks { onDelta?: (text: string) => void; onToolUse?: (name: string, input: Record) => void; onToolComplete?: (tool: string, toolUseId: string, isError: boolean) => void; onFinal?: (response: PromptFinalResponse) => void; onError?: (error: Error) => void; } /** * Streaming callbacks for real-time updates. * Structurally identical to PromptCallbacks — kept as alias for semantic clarity. */ export type StreamCallbacks = PromptCallbacks; /** * JSON Schema for tool input */ export interface ToolInputSchema { type: 'object'; properties: Record; required?: string[]; } /** * Tool definition for Claude API */ export interface ToolDefinition { name: string; description: string; input_schema: ToolInputSchema; } /** * Input for save tool (decision) */ export type MemoryScopeKind = 'global' | 'user' | 'channel' | 'project'; export interface ScopeRef { kind: MemoryScopeKind; id: string; } export interface SaveDecisionInput { type: 'decision'; topic: string; decision: string; reasoning: string; confidence?: number; is_static?: number; scopes?: ScopeRef[]; context_packet_id?: string; /** ISO 8601 date when the event actually occurred (e.g. "2024-01-15") */ event_date?: string; } export interface SaveDecisionPayload { type: 'user_decision'; topic: string; decision: string; reasoning: string; confidence?: number; is_static?: number; scopes?: ScopeRef[]; /** ISO 8601 date when the event actually occurred (e.g. "2024-01-15") */ event_date?: string; } /** * Input for save tool (checkpoint) */ export interface SaveCheckpointInput { type: 'checkpoint'; summary: string; next_steps?: string; open_files?: string[]; } /** * Union type for save tool input */ export type SaveInput = SaveDecisionInput | SaveCheckpointInput; /** * Input for search tool */ export interface SearchInput { query?: string; type?: 'all' | 'decision' | 'checkpoint'; limit?: number; scopes?: ScopeRef[]; threshold?: number; strict?: boolean; strictness?: 'recall' | 'balanced' | 'strict'; disableRecency?: boolean; includeRelated?: boolean; topicPrefix?: string; minLexicalSupport?: boolean; diagnostics?: boolean; } /** * Ask what a stored claim rests on. Scopes are optional and default to the active * boundary, exactly as recall does - a memory id is a handle, never an authorization. */ export interface ProvenanceInput { memory_id: string; scopes?: ScopeRef[]; } export interface RecallInput { query: string; scopes?: ScopeRef[]; } /** * Input for update tool */ export interface UpdateInput { id: string; outcome: 'success' | 'failed' | 'partial' | 'SUCCESS' | 'FAILED' | 'PARTIAL'; reason?: string; } /** * Input for load_checkpoint tool (no input required) */ export type LoadCheckpointInput = Record; /** * Browser navigate input */ /** * Browser screenshot input */ /** * Browser click input */ /** * Browser type input */ /** * Browser scroll input */ /** * Browser wait for input */ /** * Browser evaluate input */ /** * Browser PDF input */ /** * Bot platform types */ export type BotPlatform = 'discord' | 'telegram' | 'slack' | 'chatwork'; /** * Input for os_add_bot tool */ /** * Input for os_set_permissions tool */ /** * Input for os_set_model tool */ /** * Input for os_get_config tool */ export interface GetConfigInput { /** Section to retrieve (optional, returns all if not specified) */ section?: 'agent' | 'database' | 'logging' | 'roles' | 'discord' | 'telegram' | 'slack' | 'chatwork'; /** Include sensitive data (tokens) - only works for viewer */ includeSensitive?: boolean; } /** * Input for os_list_bots tool */ /** * Bot status information */ /** * Input for os_restart_bot tool */ /** * Input for os_stop_bot tool */ /** * Input for code_act sandbox execution */ export interface CodeActInput { /** JavaScript source to execute in the sandbox */ code: string; /** Optional request-local include filter for gateway tools exposed inside the sandbox */ allowedTools?: string[]; /** Optional request-local exclude filter applied after active role permissions */ blockedTools?: string[]; } export interface DriveBrowseInput { folderId?: string; driveId?: string; query?: string; } export interface DriveFindFolderInput { driveId: string; path: string; } export interface DriveDownloadInput { fileId: string; fileName?: string; } export interface DriveUploadInput { localPath: string; folderId: string; fileName?: string; destinationCapability?: string; } export type MemberCandidatesInput = Record; export interface MemberRegisterInput { candidate_id: string; } export interface MemberPrincipalInput { principal_id: string; } export type MemberListInput = Record; /** * Union type for all MCP tool inputs */ export type GatewayToolInput = SaveInput | SearchInput | RecallInput | CoreContextCompileInput | UpdateInput | LoadCheckpointInput | GetConfigInput | CodeActInput | DriveBrowseInput | DriveFindFolderInput | DriveDownloadInput | DriveUploadInput | MemberCandidatesInput | MemberRegisterInput | MemberPrincipalInput | MemberListInput | TemporalReconcileToolInput | ExternalBindingToolInput | ExternalLifecycleReconcileToolInput; /** * MAMA tool names (Gateway tools, NOT MCP protocol) */ export type GatewayToolName = 'mama_save' | 'mama_search' | 'mama_recall' | 'mama_provenance' | 'context_compile' | 'mama_update' | 'mama_load_checkpoint' | 'Read' | 'Write' | 'Bash' | 'discord_send' | 'slack_send' | 'telegram_send' | 'ocr_image' | 'create_fb_overlay' | 'translate_conti' | 'drive_translate_conti' | 'drive_list_drives' | 'drive_browse' | 'drive_find_folder' | 'drive_download' | 'drive_upload' | 'save_integration_token' | 'os_get_config' | 'webchat_send' | 'code_act' | 'delegate' | 'report_publish' | 'report_request' | 'board_read' | 'audit_findings_read' | 'workorder_request' | 'workorder_status' | 'console_brief_update' | 'member_candidates' | 'member_register' | 'member_suspend' | 'member_offboard' | 'member_list' | 'wiki_publish' | 'obsidian' | 'kagemusha_overview' | 'kagemusha_entities' | 'kagemusha_tasks' | 'kagemusha_messages' | 'trello_search' | 'trello_card' | 'trello_kanban' | 'task_list' | 'task_external_correlation' | 'task_external_bind' | 'task_lifecycle_reconcile' | 'changes_read' | 'task_create' | 'task_update' | 'task_temporal_reconcile' | 'contract_no_update' | 'schedule_upcoming' | 'agent_notices'; /** * Save tool result */ export interface SaveResult { success: boolean; id?: string; type?: 'decision' | 'checkpoint'; message?: string; code?: string; skipped?: boolean; similar_decisions?: Array<{ id: string; topic: string; decision: string; similarity: number; created_at: string; }>; warning?: string; collaboration_hint?: string; } /** * Search result item */ export interface SearchHitDiagnostics { retrieval_source: string; vector_similarity: number | null; lexical_support: boolean; entity_support: boolean; scope_support: boolean; graph_source: 'primary' | 'expanded' | null; is_vector_only: boolean; confirmation_signals: string[]; metadata_signals: string[]; candidate_threshold_used: number; } export interface SearchDiagnostics { candidate_counts?: { vector: number; lexical: number; entity: number; graph_expanded: number; vector_only: number; rejected_by_strictness: number; }; threshold?: number; strictness?: 'recall' | 'balanced' | 'strict'; } export interface SearchResultItem { id: string; topic?: string; decision?: string; reasoning?: string; summary?: string; similarity?: number; created_at: string; type: 'decision' | 'checkpoint'; retrieval_diagnostics?: SearchHitDiagnostics; contributing_leaf_diagnostics?: Record; } /** * Search tool result */ export interface SearchResult { success: boolean; results: SearchResultItem[]; count: number; diagnostics?: SearchDiagnostics | null; meta?: Record; error?: string; code?: string; } /** * Update tool result */ export interface UpdateResult { success: boolean; message?: string; } /** * Load checkpoint result */ export interface LoadCheckpointResult { success: boolean; summary?: string; next_steps?: string; open_files?: string[]; message?: string; } export interface EnvelopeDenialResult { success: false; error: string; code: string; } /** * Union type for all MCP tool results */ export type GatewayToolResult = SaveResult | SearchResult | UpdateResult | LoadCheckpointResult | EnvelopeDenialResult | { success: boolean; [key: string]: unknown; }; /** * Streaming context for image-based requests */ export interface StreamingContext { useStreaming: boolean; placeholderMessage?: any; } /** * Agent loop configuration options */ export interface AgentLoopOptions { /** * Backend to use for CLI execution * - 'claude': Claude CLI (uses PersistentCLI for fast responses) * - 'codex': Codex app-server * Required at construction time (validated by config-manager) */ backend?: 'claude' | 'codex' | 'cline'; /** System prompt for Claude */ systemPrompt?: string; /** Exact policy-keyed Gateway Tools catalog for this run (Claude non-Code-Act only). */ gatewayToolsPrompt?: string; /** Lazily rebuild the complete prompt when a durable Codex thread must be replaced. */ freshSessionSystemPrompt?: () => Promise; /** Stable identity/rules fingerprint for durable Codex threads. */ sessionPolicyFingerprint?: string; /** User identifier for the frontdoor message source */ userId?: string; /** Maximum number of conversation turns (default: 10) */ maxTurns?: number; /** Maximum tokens per response (default: 4096) */ maxTokens?: number; /** Request timeout in milliseconds (mapped to Codex CLI `timeoutMs`) */ timeoutMs?: number; /** * Per-run override for the CLI request timeout (ms), threaded to the model * runner for THIS run only. Unlike `timeoutMs` (fixed at construction on the * shared boot executor), this lets a single long run (operator worker gather * runs) lift the request bound without touching chat runs on the same pool. */ requestTimeoutMs?: number; /** Claude model to use (must be provided via config) */ model?: string; /** Callback for each turn */ onTurn?: (turn: TurnInfo) => void; /** Callback for tool execution */ onToolUse?: (toolName: string, input: unknown, result: unknown) => void; /** Session key for lane-based concurrency (e.g., "discord:channel:user") */ sessionKey?: string; /** Enable lane-based concurrency (default: false for backward compatibility) */ useLanes?: boolean; /** Disable auto-recall memory injection (for skill execution) */ disableAutoRecall?: boolean; /** Message source for session pool (e.g., "discord", "slack", "viewer") */ source?: string; /** Channel ID for session pool */ channelId?: string; /** * Agent context for role-aware execution * Provides platform, role, and permission information */ agentContext?: AgentContext; /** Host-issued claimed system-row id; never accepted from model tool input. */ workorderAttemptId?: number; /** Host-built temporal authority for one claimed temporal workorder. */ temporalWorkContext?: TemporalWorkContext; /** The delta batch a bounded run was handed; becomes the cause of what it changes. */ causeEventIds?: readonly string[]; /** * Tool routing configuration for hybrid Gateway/MCP mode * If not specified, all tools use Gateway mode (default) */ toolsConfig?: { /** Tools executed via GatewayToolExecutor (supports wildcards: "browser_*") */ gateway?: string[]; /** Tools routed to MCP server (supports wildcards: "mama_*") */ mcp?: string[]; /** Path to MCP config file */ mcp_config?: string; }; /** Explicit MCP config path for runtimes that consume an external MCP config directly. */ mcpConfigPath?: string; /** Explicit Cline CLI command path. */ clineCommand?: string; /** Cline CLI working directory. */ clineCwd?: string; /** Cline provider id (defaults to Cline's hosted provider). */ clineProvider?: string; /** Isolated Cline state directory. */ clineDataDir?: string; /** Cline native tools explicitly exposed to this loop; omitted means fail-closed except owner. */ clineNativeAllowedTools?: string[]; /** Cline native tools explicitly denied even when another policy allows them. */ clineNativeDisallowedTools?: string[]; /** Permit Cline's native spawn-agent primitive for this loop. */ clineAllowSpawnAgent?: boolean; /** Permit Cline's native agent-team primitive for this loop. */ clineAllowAgentTeams?: boolean; /** Codex app-server working directory (managed runtime construction only). */ codexCwd?: string; /** Explicit Codex app-server command path (managed runtime/tests). */ codexCommand?: string; /** Codex app-server sandbox policy. */ codexSandbox?: 'read-only' | 'workspace-write' | 'danger-full-access'; /** Managed Codex credential/config home. */ codexHome?: string; /** Isolated HOME used by managed Codex app-server. */ codexIsolatedHome?: string; /** Durable managed Codex thread registry root. */ codexRegistryRoot?: string; /** * Resume existing CLI session instead of starting new one * When true, uses --resume flag and skips system prompt injection * (CLI already has context from previous requests) */ resumeSession?: boolean; /** * CLI session ID from MessageRouter * When provided, AgentLoop uses this instead of calling getSession() again * This prevents double-locking of the session pool */ cliSessionId?: string; /** Notify the caller when recovery replaces the pooled CLI session ID. */ onCliSessionReset?: (sessionId: string) => void; /** * Start this run on a brand-new pool session (stateless lane). Used by the * operator report lane: session context is a cache, not persistence - every * run self-gathers and recalls, so carrying prior runs' gather dumps only * grows the context until runs outlive their envelope TTL. */ freshSession?: boolean; /** * Skip permission prompts for CLI tool execution * WARNING: Security risk - enables autonomous tool execution without user approval * @default false */ dangerouslySkipPermissions?: boolean; /** * PostToolUse handler configuration * Auto-extracts API contracts after Write/Edit tool execution and saves to MAMA */ postToolUse?: { enabled: boolean; contractSaveLimit?: number; }; /** * PreCompact handler configuration * Detects unsaved decisions before context window reset */ preCompact?: { enabled: boolean; maxDecisionsToDetect?: number; }; /** * Stop/Continuation handler configuration * Auto-resumes when agent stops with incomplete work (opt-in) */ stopContinuation?: { enabled: boolean; maxRetries?: number; completionMarkers?: string[]; }; /** * Token usage recording callback * Called after each API response to track token consumption */ onTokenUsage?: (record: TokenUsageRecord) => void; /** * CLI tools to structurally disallow via --disallowedTools flag. * Prevents Claude CLI from exposing these tools to the agent. */ disallowedTools?: string[]; /** * Native Claude Code built-in tool surface (--tools value). Pass-through to * the PersistentCLIAdapter; '' disables all built-ins so gateway tools are the * only surface. Consumed only by the claude backend; a no-op on codex. */ builtinTools?: string; /** * Enable Code-Act mode: LLM writes JS code blocks instead of tool_call blocks * Multiple tools composed in a single QuickJS sandbox execution * @default false */ useCodeAct?: boolean; /** Streaming callbacks for real-time progress events to external consumers */ streamCallbacks?: StreamCallbacks; /** Runtime authority envelope bound to this agent loop invocation */ envelope?: Envelope; /** Stable per-message source turn id for memory provenance. */ sourceTurnId?: string; /** Compact source/channel/message ref for memory provenance. */ sourceMessageRef?: string; /** Active model-run id for memory provenance. */ modelRunId?: string | null; /** Parent model-run id when this run is a child/background follow-up. */ parentModelRunId?: string | null; /** * Stop the agent loop after the current tool batch completes when any * of these tools executed successfully in that batch. */ stopAfterSuccessfulTools?: string[]; /** * Metric recording callback (STORY-020) * Called at key emission points: prompt latency, tool execution, errors */ onMetric?: (name: string, value: number, labels?: Record) => void; /** * Boot-wired GatewayToolExecutor to share. When provided, AgentLoop uses it * and constructs nothing - every dependency wiring (task ledger, report * publisher, event bus, gateways, wiki, obsidian, ...) reaches persona lanes * by construction. Omit ONLY for deliberately isolated loops (memory agent, * `mama run` CLI) that own their own dep set. */ executor?: GatewayToolExecutor; } /** * Token usage record for tracking API consumption */ export interface TokenUsageRecord { channel_key: string; agent_id?: string; agent_version?: number; input_tokens: number; output_tokens: number; cache_read_tokens?: number; cost_usd?: number; } /** * Information about each turn in the agent loop */ export interface TurnInfo { turn: number; role: MessageRole; content: ContentBlock[]; stopReason?: StopReason; usage?: Usage; } /** * Agent loop run result */ /** Why a run produced no resolvable handle, when it did not. */ export type ModelRunProvenance = 'available' | 'backend_no_run' | 'commit_failed'; export interface AgentLoopResult { /** Final text response from Claude */ response: string; /** Total number of turns */ turns: number; /** Full conversation history */ history: Message[]; /** Total token usage */ totalUsage: { input_tokens: number; output_tokens: number; }; /** Stop reason for the final turn */ stopReason: StopReason; /** Active model run id when the loop owns or inherited one. */ modelRunId?: string | null; /** * Why `modelRunId` is absent, when it is. Distinguishes a backend that produces no run * identity - an ordinary capability state - from a run that was created and then failed * to commit, which leaves an orphaned record and needs repair. */ modelRunProvenance?: ModelRunProvenance; } /** * Error codes for agent loop errors */ export type AgentErrorCode = 'API_ERROR' | 'CLI_ERROR' | 'AGENT_STOPPED' | 'AUTH_ERROR' | 'RATE_LIMIT' | 'MAX_TOKENS' | 'MAX_TURNS' | 'EMERGENCY_MAX_TURNS' | 'INFINITE_LOOP_DETECTED' | 'NETWORK_ERROR' | 'TOOL_ERROR' | 'UNKNOWN_TOOL' | 'INVALID_RESPONSE' | 'ENVELOPE_EXPIRED' | 'WORKORDER_SUPERSEDED' | 'CLAUDE_TOOL_STREAM_PROTOCOL' | 'MCP_RESULT_MISSING' | 'MCP_COMPLETED_MUTATION_INTERRUPTED' | 'CODE_ACT_MUTATION_COMMITTED_AFTER_ABORT' | 'CODE_ACT_MUTATION_OUTCOME_UNKNOWN'; /** * Custom error class for agent loop errors */ export declare class AgentError extends Error { readonly code: AgentErrorCode; readonly cause?: Error | undefined; readonly retryable: boolean; constructor(message: string, code: AgentErrorCode, cause?: Error | undefined, retryable?: boolean); } /** * Claude client configuration options */ export interface ClaudeClientOptions { /** Custom fetch function for testing */ fetchFn?: typeof fetch; /** Maximum retry attempts (default: 3) */ maxRetries?: number; /** Base delay for exponential backoff in ms (default: 1000) */ baseDelayMs?: number; /** Maximum delay between retries in ms (default: 30000) */ maxDelayMs?: number; } /** * Claude API headers */ export type ClaudeHeaders = Record; /** * MCP Executor configuration options */ /** * Minimal session store interface for gateway tool executor. * SessionStore implements getHistory/getHistoryByChannel but NOT getRecentMessages/restoreMessages. */ export interface GatewaySessionStore { getHistory?(sessionId: string): unknown[]; getHistoryByChannel?(source: string, channelId: string): unknown[]; } export interface GatewayToolExecutorOptions { /** Database path for MAMA (default: ~/.claude/mama-memory.db) */ mamaDbPath?: string; /** * Live channel-grant provider for the memory read mirror (test seam; * defaults to the connector-config grant). */ channelGrantProvider?: () => Record; /** Session store for checkpoint conversation access */ sessionStore?: GatewaySessionStore; /** Custom MAMA API instance for testing */ mamaApi?: MAMAApiInterface; /** Roles configuration from config.yaml */ rolesConfig?: import('../cli/config/types.js').RolesConfig; /** Runtime envelope issuance mode (off disables missing-envelope enforcement). */ envelopeIssuanceMode?: 'off' | 'enabled' | 'required'; /** Optional metrics store for envelope/audit counters. */ metricsStore?: import('../observability/metrics-store.js').MetricsStore | null; /** Shared context compile service for gateway context_compile calls. */ contextCompileService?: ContextCompileService; /** Test/runtime seam around the trusted context-packet store lookup. */ temporalContextPacketLookup?: (input: { packetId: string; envelopeHash: string; callerModelRunId: string; }) => Promise<{ packet_id: string; task: string; packet_json: string; source_refs: unknown[]; created_at: number; } | null>; /** Optional wiki publish adapter for source-linked artifact persistence. */ wikiPublishAdapter?: WikiPublishAdapter | null; /** Core-backed principal repository for owner-only member administration. */ principalRepository?: PrincipalRepository; } export interface MemoryWriteProvenance { actor?: 'memory_agent' | 'main_agent' | `actor:${string}`; agent_id?: string; model_run_id?: string; envelope_hash?: string; tool_name?: string; gateway_call_id?: string; context_packet_id?: string; source_turn_id?: string; source_message_ref?: string; source_refs?: string[]; } export interface TrustedMemoryWriteOptions { provenance: MemoryWriteProvenance; capability: unknown; projectTruth?: boolean; } /** * Interface for MAMA API (for dependency injection) */ export interface MAMAApiInterface { save(input: SaveDecisionPayload): Promise; saveWithTrustedProvenance?(input: SaveDecisionPayload, options: TrustedMemoryWriteOptions): Promise; saveCheckpoint(summary: string, openFiles: string[], nextSteps: string, recentConversation?: any[]): Promise; listDecisions(options?: { limit?: number; scopes?: ScopeRef[]; }): Promise; suggest(query: string, options?: { limit?: number; scopes?: ScopeRef[]; threshold?: number; strict?: boolean; strictness?: 'recall' | 'balanced' | 'strict'; disableRecency?: boolean; includeRelated?: boolean; topicPrefix?: string; minLexicalSupport?: boolean; diagnostics?: boolean; }): Promise; recallMemory?(query: string, options?: { scopes?: ScopeRef[]; includeProfile?: boolean; }): Promise; ingestMemory?(input: Record): Promise; ingestWithTrustedProvenance?(input: Record, options: TrustedMemoryWriteOptions): Promise; saveMemoryWithTrustedProvenance?(input: Record, options: TrustedMemoryWriteOptions): Promise; ingestConversationWithTrustedProvenance?(input: Record, options: TrustedMemoryWriteOptions): Promise; getMemoryProvenance?(memoryId: string, options?: Record): Promise; listMemoriesByEnvelopeHash?(envelopeHash: string, options?: Record): Promise; listMemoriesByGatewayCallId?(gatewayCallId: string, options?: Record): Promise; listMemoriesByModelRunId?(modelRunId: string, options?: Record): Promise; beginModelRun?(input: BeginModelRunInput): Promise; commitModelRun?(modelRunId: string, summary?: string): Promise; failModelRun?(modelRunId: string, errorSummary: string): Promise; getModelRun?(modelRunId: string): Promise; appendToolTrace?(input: AppendToolTraceInput): Promise; listToolTracesForRun?(modelRunId: string): Promise; buildProfile?(scopes?: ScopeRef[], options?: Record): Promise; updateOutcome(id: string, input: { outcome: string; failure_reason?: string; }): Promise; loadCheckpoint(): Promise; } export type MAMAApiListProvider = { listDecisions: MAMAApiInterface['listDecisions']; list?: MAMAApiInterface['listDecisions']; } | { list: MAMAApiInterface['listDecisions']; listDecisions?: MAMAApiInterface['listDecisions']; }; /** Full executor API or the raw mama-core boot shape that exports list() as its alias. */ export type MAMAApiSetInput = MAMAApiInterface | (Omit & MAMAApiListProvider); //# sourceMappingURL=types.d.ts.map