import type { AgentReplyMcpAppPart, AgentReplyPartFailure, AgentToolEnvironment } from "@mono-agent/agent-contracts"; import type { AcpCallbackContext, AcpInteractionRequest, AcpProfileDescriptor } from "@mono-agent/agent-runtime"; import type { PreparedSandboxCommand, SandboxCommandSpec, SandboxPolicy } from "./sandbox.js"; import type { ProcessJobsController } from "./process-jobs.js"; export interface MonoRuntimeSandboxEngine { readonly id?: string; isAvailable(): Promise; prepareCommand(command: SandboxCommandSpec, policy: SandboxPolicy): Promise; } export type RuntimeExecutionMode = "sdk" | "cli" | "acp"; export interface RuntimeModelReference { readonly sdk: string; readonly model: string; readonly provider?: string; readonly reference?: string; } /** One caller-defined Claude native `Task` profile. */ export interface RuntimeNativeSubagentDefinition { readonly name: string; readonly displayName?: string; readonly description?: string; readonly helperSystemPrompt?: string; readonly instructions?: string; readonly allowedTools?: readonly string[]; readonly disallowedTools?: readonly string[]; readonly modelRef?: string | RuntimeModelReference; readonly model?: RuntimeModelReference; readonly effort?: string; readonly mcpServers?: Readonly>; } /** * Caller-defined native profiles are a Claude-only request contract. Codex * owns its collaboration agents; codexLoadProjectDocs controls whether they * receive repository instructions. */ export interface RuntimeNativeSubagentsOptions { readonly provider: "claude"; readonly teammates: readonly RuntimeNativeSubagentDefinition[]; } export type MonoRuntimeBackendId = "claude-sdk" | "claude-code-cli" | "codex-app-cli" | "opencode-app-cli" | "pi-sdk" | "acp-stdio"; export type MonoAcpProfileResolver = (profileId: string, context?: Readonly>) => AcpProfileDescriptor | null | undefined | Promise; export type MonoAcpInteractionRequest = AcpInteractionRequest; export type MonoAcpInteractionHandler = (request: MonoAcpInteractionRequest, context?: AcpCallbackContext) => unknown | Promise; export interface MonoAcpControlOptions { readonly resolveAcpProfile: MonoAcpProfileResolver; readonly onAcpInteractionRequest?: MonoAcpInteractionHandler; /** Optional for probe/auth/logout; handle-bearing operations require it. */ readonly acpSessionTokenKey?: Uint8Array; readonly sandboxPolicy?: SandboxPolicy; readonly sandboxEngine?: MonoRuntimeSandboxEngine; readonly cwd?: string; readonly signal?: AbortSignal; readonly context?: Readonly>; /** The sandbox implementation is owned and injected by runtime-adapter. */ readonly sandbox?: never; } export interface MonoAcpSessionControlOptions extends MonoAcpControlOptions { /** Host-owned exact 32-byte key for confidential authenticated ACP handles. */ readonly acpSessionTokenKey: Uint8Array; } export interface MonoAcpListSessionsRequest { readonly cwd?: string | null; readonly cursor?: string | null; } /** * One row of the additive (sdk, executionMode) -> backend selection table. This * is a declarative building block exported alongside the backend descriptors; it * does not itself perform routing. `sdkAliases` lists every accepted spelling of * the sdk id for that backend (canonical first), so a runtime's fail-closed * `model.sdk` guard and the table share one vocabulary. */ export interface MonoRuntimeSelectionEntry { readonly sdk: string; readonly sdkAliases: readonly string[]; readonly executionMode: RuntimeExecutionMode; readonly backendId: MonoRuntimeBackendId; } export type MonoRuntimeBackendTransport = "sdk" | "cli" | "acp"; export interface MonoRuntimeBackendCapabilities { readonly kind?: string; readonly runtime?: string; readonly streaming?: boolean; readonly structured_output?: boolean; readonly supports_session_resume?: boolean; readonly native_runtime_config?: unknown; readonly supports_mcp?: boolean; readonly supports_mcp_apps?: boolean; readonly supports_skills?: boolean; readonly supports_builtin_tools?: boolean; readonly supports_live_input?: boolean; /** Native surface/activity support, not caller-defined profile injection. */ readonly supports_native_subagents?: boolean; readonly supports_request_tool_environment?: boolean; readonly tool_policy?: "projected" | "allow_all_only"; readonly [key: string]: unknown; } export interface MonoRuntimeBackendDescriptor { readonly id: MonoRuntimeBackendId; readonly runtimeBridgeId: string; readonly label: string; readonly sdk: RuntimeModelReference["sdk"]; readonly executionMode: RuntimeExecutionMode; readonly transport: MonoRuntimeBackendTransport; readonly providerBoundary: string; readonly modelReferenceExamples: readonly string[]; readonly acceptsProviderIds: boolean; readonly capabilities: MonoRuntimeBackendCapabilities; } export interface MonoRuntimeSupportDescription { readonly model: RuntimeModelReference; readonly executionMode: RuntimeExecutionMode; readonly compatible: boolean; readonly backend?: MonoRuntimeBackendDescriptor; readonly incompatibilityReason?: string; } export interface RuntimeMessage { readonly role: string; readonly content: unknown; readonly timestamp?: number | string; readonly [key: string]: unknown; } /** Provider-neutral identity attached to every normalized subagent event. */ export interface RuntimeSubagentIdentity { /** * Canonical parent attachment key: normally the initiating parent tool-use * id, with a stable synthetic fallback only for an orphan lifecycle record. */ readonly id: string; /** Provider-native task or thread id; correlation metadata only. */ readonly nativeId?: string; /** Provider-neutral profile or agent name. */ readonly name: string; /** Provider call-order ordinal; never an identity key. */ readonly callIndex: number; readonly label?: string; /** Provider-reported ancestry; informational only. */ readonly agentPath?: string; readonly costUsd?: number; } /** Normalized subagent lifecycle/activity phases. */ export type RuntimeSubagentActivityPhase = "agent_started" | "started" | "completed" | "message" | "agent_completed"; /** * Permissive compatibility shape for the runtime's open telemetry stream. * Use {@link isRuntimeSubagentActivityEvent} for the exact normalized subagent * event contract. */ export interface RuntimeEventLike { readonly type?: string; readonly [key: string]: unknown; } /** Durable terminal classification for one managed tool invocation. */ export type RuntimeToolLifecycleTerminalState = "success" | "rejected" | "error" | "exit_nonzero" | "timeout" | "signal" | "cancelled" | "interrupted"; /** Provider-neutral, host-persisted half of a managed tool lifecycle. */ export type RuntimeToolLifecycleEvent = { readonly phase: "invocation"; readonly toolCallId: string; readonly toolName: string; readonly arguments?: unknown; } | { readonly phase: "result"; readonly toolCallId: string; readonly toolName?: string; readonly content?: unknown; readonly state: RuntimeToolLifecycleTerminalState; /** Existing observability failure taxonomy; no competing errorKind. */ readonly failureKind?: string; readonly detailCode?: string; readonly executionMs?: number; readonly artifacts?: readonly { readonly path: string; readonly available?: boolean; }[]; }; /** Metadata returned by the host after one lifecycle half becomes durable. */ export interface RuntimeToolLifecyclePersistence { readonly recordId?: string; readonly sequence?: number; readonly persistence: "persisted" | "failed"; readonly truncated?: boolean; readonly originalBytes?: number; readonly retainedBytes?: number; readonly artifactReferences?: readonly { readonly id: string; readonly available: boolean; }[]; readonly errorCode?: string; } /** Awaited host boundary used to persist managed tool lifecycles. */ export type RuntimeToolLifecycleSink = (event: RuntimeToolLifecycleEvent) => Promise; /** One exact normalized native or in-process subagent activity event. */ export interface RuntimeSubagentActivityEvent extends RuntimeEventLike { readonly type: "subagent_activity"; readonly subagent: RuntimeSubagentIdentity; readonly phase: RuntimeSubagentActivityPhase; /** Unique lifecycle/tool/message row id, namespaced from `subagent.id`. */ readonly id: string; readonly name?: string; readonly arguments?: unknown; readonly content?: unknown; readonly kind?: "text" | "thinking" | "status" | "warning" | "error"; readonly role?: "assistant" | "user"; readonly isError?: boolean; readonly executionMs?: number; readonly totalTokens?: number; } /** Narrow an open runtime event to the exact normalized subagent contract. */ export declare function isRuntimeSubagentActivityEvent(value: unknown): value is RuntimeSubagentActivityEvent; export interface RuntimeResult { readonly text?: string | null; readonly structuredResult?: unknown; readonly structuredResultSource?: string | null; readonly events?: readonly RuntimeEventLike[]; readonly usage?: unknown; readonly cost?: unknown; readonly durationMs?: number; readonly numTurns?: number; readonly model?: string; readonly effort?: string; readonly sdk?: string; readonly cancelled?: boolean; readonly error?: string | null; readonly errorDetails?: unknown; readonly failureKind?: string | null; readonly providerSessionId?: string | null; readonly runtimeWarnings?: unknown; readonly diagnostics?: unknown; readonly capabilitiesUsed?: unknown; readonly [key: string]: unknown; } /** * Typed per-run tool-output limits (mirrors agent-runtime's RuntimeToolLimits, * ai/types.js). The supported replacement for the deprecated `settings` tool * keys; build one with {@link resolveRuntimePolicies}. */ export interface RuntimeToolLimits { readonly toolTextLimitChars?: number; readonly bashOutputLimitChars?: number; readonly mcpTextLimitChars?: number; readonly searchResultLimit?: number; readonly imageInlineMaxBytes?: number; readonly toolPayloadMaxBytes?: number; readonly mcpCallTimeoutMs?: number; readonly mcpCallMaxTotalTimeoutMs?: number; /** * Foreground ceiling and default for Bash/Exec timeouts on the Pi bridge * (defaults to 120_000). Background process-job hand-offs ignore it and are * bounded by `processJobs.maxRuntimeMs` on the host side instead. */ readonly bashTimeoutMs?: number; } /** * Typed per-run context-compaction policy (mirrors agent-runtime's * RuntimeCompactionPolicy). The supported replacement for the deprecated * `settings` compaction keys. Omitted scalar budgets resolve adaptively against * the effective model context window. */ export interface RuntimeCompactionPolicy { readonly enabled?: boolean; readonly triggerRatio?: number; readonly keepRecentTokens?: number; readonly summaryMaxTokens?: number; readonly minSavingsTokens?: number; readonly fixedOverheadEnabled?: boolean; readonly contextWindowOverride?: number; } /** The pair {@link resolveRuntimePolicies} returns from a legacy settings bag. */ export interface RuntimePolicies { readonly toolLimits: RuntimeToolLimits; readonly compaction: RuntimeCompactionPolicy; } /** * Per-run prompt-fragment overrides (mirrors agent-runtime's * RuntimePromptOverrides). Precedence run over host over the kernel default. */ export interface RuntimePromptOverrides { readonly structuredOutputInstruction?: (systemPrompt: string) => string; readonly structuredOutputFinalization?: () => string; readonly liveInputGuidance?: (body: string) => string; } /** One live follow-up delivered to a provider bridge. */ export interface RuntimeLiveInputMessage { readonly body: string; readonly id?: string; readonly receivedAt?: string; /** Called only after the provider's native steering boundary accepts it. */ readonly acknowledge?: () => void; /** Per-attempt rejection; a later provider attempt may still replay it. */ readonly reject?: (reason?: unknown) => void; } /** Provider transport requested for Pi-native runs. Unsupported providers ignore it. */ export declare const PI_TRANSPORTS: readonly ["auto", "sse", "websocket", "websocket-cached"]; export type PiTransport = (typeof PI_TRANSPORTS)[number]; /** Exact live MCP connection leased to the app-owned host after a UI tool call. */ export interface RuntimeMcpAppConnection { readonly connectionId: string; readResource(uri: string): Promise; callTool(name: string, args: unknown, signal?: AbortSignal): Promise; close(): Promise; } export interface RuntimeMcpAppRegistration { readonly runId?: string; readonly serverName: string; readonly toolName: string; readonly title?: string; readonly description?: string; readonly toolCallId: string; readonly resourceUri: string; readonly protocolVersion: string; readonly toolInput: unknown; readonly toolResult: unknown; readonly resource: unknown; readonly appVisibleTools: readonly string[]; readonly connection: RuntimeMcpAppConnection; } /** App-owned registry consumed only by Pi's exact MCP client path. */ export interface RuntimeMcpAppHost { readonly protocolVersions: readonly string[]; readonly mimeTypes: readonly string[]; register(input: RuntimeMcpAppRegistration): Promise<{ readonly part: AgentReplyMcpAppPart | AgentReplyPartFailure; readonly retainConnection: boolean; }>; recordFailure(input: { readonly runId?: string; readonly serverName: string; readonly toolName: string; readonly toolCallId: string; readonly code: AgentReplyPartFailure["code"]; readonly message: string; }): Promise; } export interface RuntimeRunOptions { readonly model: RuntimeModelReference; readonly messages: readonly RuntimeMessage[]; readonly abortSignal: AbortSignal; /** Host-only environment applied to Bash, Exec, and their nested subagents for this run. */ readonly toolEnvironment?: AgentToolEnvironment; /** Host-only Pi-native process-job controller; never model/provider visible. */ readonly processJobs?: ProcessJobsController; readonly executionMode?: RuntimeExecutionMode; readonly onEvent?: (event: RuntimeEventLike) => void; /** Host-owned, incremental durable tool-lifecycle writer for this run. */ readonly toolLifecycleSink?: RuntimeToolLifecycleSink; readonly effort?: string; readonly cwd?: string; readonly maxTurns?: number; readonly allowedTools?: readonly string[]; readonly disallowedTools?: readonly string[]; /** * Request-scoped MCP servers. Direct ACP runs reject a non-empty map because * ACP MCP ownership belongs to the resolved profile descriptor; routed ACP * entries are capability-skipped instead of silently dropping these servers. */ readonly mcpServers?: Record; /** Exact-connection MCP Apps host. Currently consumed by Pi-native routes. */ readonly mcpApps?: RuntimeMcpAppHost; readonly mcpConfigPath?: string; readonly sandboxPolicy?: SandboxPolicy; readonly sandboxEngine?: MonoRuntimeSandboxEngine; /** The sandbox implementation is owned by createMonoRuntime; callers supply policy/engine data only. */ readonly sandbox?: never; /** Typed tool-output limits (supported replacement for the `settings` tool keys). */ readonly toolLimits?: RuntimeToolLimits; /** Typed compaction policy (supported replacement for the `settings` compaction keys). */ readonly compaction?: RuntimeCompactionPolicy; /** Per-run prompt-fragment overrides. */ readonly prompts?: RuntimePromptOverrides; /** Per-run ACP profile resolution; preferred when profile config is worker/request scoped. */ readonly resolveAcpProfile?: MonoAcpProfileResolver; /** Per-run permission/elicitation callback; wins over the host default. */ readonly onAcpInteractionRequest?: MonoAcpInteractionHandler; /** Host-owned exact 32-byte key required for ACP task runs. */ readonly acpSessionTokenKey?: Uint8Array; /** In-flight user guidance consumed by a provider's native steering API. */ readonly liveInput?: AsyncIterable; /** * Claude Agent SDK filesystem setting sources. Omitted/empty disables user, * project, and local sources; Anthropic managed settings still apply. These * sources may execute configured hooks and plugins, so enable only trusted * settings and avoid opting in while running in an untrusted checkout. */ readonly settingSources?: readonly ("user" | "project" | "local")[]; /** * Restore Codex app-server's native project-document loading defaults. * Omitted/false disables automatic discovery; explicit app-server args win. */ readonly codexLoadProjectDocs?: boolean; /** * Code-only Codex app-server network control. Only strict `true` enables * network access for plan/read-only and default/acceptEdits/workspace-write * turns. No-tool probes and danger-full-access retain their fixed behavior. * This is unrelated to RuntimeRunOptions.sandboxPolicy, which controls * mono-agent's own sandbox and is not consumed by Codex's provider-owned tool * loop. Default/acceptEdits workspace-write plus network true grants * repository read and network egress in the same turn; prefer plan when only * read-only browsing is needed. */ readonly codexSandboxNetworkAccess?: boolean; /** Caller-defined Claude native `Task` profiles. Direct Codex rejects these definitions. */ readonly nativeSubagents?: RuntimeNativeSubagentsOptions; readonly piTransport?: PiTransport; readonly piMaxRetries?: number; readonly maxRetryDelayMs?: number; readonly piSessionsRoot?: string; /** Local-first WebSearch backend selection for this run. */ readonly webSearchConfig?: { readonly backend?: "auto" | "searxng" | "codex" | "keyless"; readonly endpoint?: string; readonly codex?: { readonly model?: string; }; }; /** Static WebFetch extraction and optional isolated browser-render policy. */ readonly webFetchConfig?: { readonly render?: "never" | "auto"; readonly browserCommand?: string; }; /** Built-in tool scheduling. Safe parallelism keeps stateful/mutating tools sequential. */ readonly piToolExecutionMode?: "sequential" | "safe-parallel"; /** @deprecated Use piToolExecutionMode. */ readonly piToolParallelismMode?: "one-at-a-time" | "all"; readonly [key: string]: unknown; } export interface MonoRuntimeLike { run(systemPrompt: string, options: RuntimeRunOptions): Promise; configureTools?(next?: RuntimeToolOptions): void; /** Flush provider-owned durable transcript state before host history commit. */ syncSession?(providerSessionId: string): Promise; /** * Guarantee that the next resume cannot reuse process-local provider state. * Resolves for both removed and already-absent handles; rejects if the * guarantee cannot be made. Durable provider transcripts remain intact. */ refreshSession?(providerSessionId: string): Promise; /** * Permanently remove every provider transcript with this exact id from the * supplied durable sessions root. Absence is success; uncertainty rejects. */ retireDurableSession?(providerSessionId: string, sessionsRoot: string): Promise; disposeSession?(providerSessionId: string): Promise; /** Permanently discard live and durable provider transcript state. */ invalidateSession?(providerSessionId: string): Promise; disposeAllSessions?(): Promise; } export interface RuntimeToolOptions { readonly workspace?: string; readonly repoRoot?: string; readonly ripgrepPath?: string; readonly qaOutputDir?: string; readonly sandboxPolicy?: SandboxPolicy; readonly sandboxEngine?: MonoRuntimeSandboxEngine; /** The sandbox implementation is owned by createMonoRuntime; callers supply policy/engine data only. */ readonly sandbox?: never; readonly [key: string]: unknown; } /** A parsed model reference as agent-runtime's pricing resolvers receive it (see ai/cost.js's ParsedModelReference). */ export interface MonoRuntimeParsedPricingModel { readonly sdk: string | null; readonly provider?: string; readonly model: string; } /** agent-runtime's normalized per-token pricing row (see ai/cost.js's NormalizedPricing). */ export interface MonoRuntimePricing { readonly input: number | null; readonly cacheRead: number | null; readonly cacheWrite: number | null; readonly output: number | null; readonly source: string; readonly priced: boolean; } /** Payload passed to `onToolApprovalRequest` (see agent/approval.js's ApprovalRequestPayload). */ export interface MonoRuntimeApprovalRequest { readonly requestId: string; readonly toolName: string; readonly toolUseId: string | null; readonly argumentsSummary: string; readonly riskTier: "low" | "medium" | "high"; readonly model: string | null; } /** A host's response to a MonoRuntimeApprovalRequest. */ export interface MonoRuntimeApprovalDecision { readonly decision: "approve" | "deny" | "always"; readonly reason?: string; } /** Payload passed to `onCompactionRecorded` after a successful context compaction (see ai/providers/pi-native.js). */ export interface MonoRuntimeCompactionRecord { readonly task_run_id: string | null; readonly trigger: string; readonly provider_kind: string; readonly model: string | null; readonly tokens_before: number | null; readonly summary: string; readonly first_kept_entry_id: string | null; readonly status: "succeeded"; readonly created_at: number; } export interface MonoRuntimeHostOptions extends RuntimeToolOptions { readonly observers?: readonly unknown[]; readonly runtimeBrand?: unknown; /** Host-level prompt-fragment override defaults; a per-run `prompts` wins over these. */ readonly prompts?: RuntimePromptOverrides; readonly resolveCustomPricing?: (parsed: MonoRuntimeParsedPricingModel) => MonoRuntimePricing | null; readonly resolvePiApiKey?: (provider: string) => Promise; /** Optional default; a per-run resolver wins. */ readonly resolveAcpProfile?: MonoAcpProfileResolver; /** Optional default; a per-run interaction callback wins. */ readonly onAcpInteractionRequest?: MonoAcpInteractionHandler; /** Optional default host-owned exact 32-byte key for ACP task runs. */ readonly acpSessionTokenKey?: Uint8Array; readonly persistArtifact?: (artifact: { readonly filename: string; readonly buffer: Buffer; readonly toolName: string; readonly toolUseId: string | null; }) => string | null; readonly onCompactionRecorded?: (record: MonoRuntimeCompactionRecord) => void; readonly onToolApprovalRequest?: (payload: MonoRuntimeApprovalRequest) => Promise; readonly toolRiskTiers?: Readonly>; readonly approvalDefaultRiskTier?: "low" | "medium" | "high"; readonly approvalTimeoutMs?: number; readonly approvalAlwaysAllowTools?: readonly string[]; readonly [key: string]: unknown; } //# sourceMappingURL=types.d.ts.map