Skip to main content

Crate merry_runtime

Crate merry_runtime 

Source
Expand description

Runtime session orchestration for Merry.

This crate owns the MVP runtime facade for session execution:

A few lower-level primitives are currently public because the in-memory MVP still needs explicit composition and tests around structured state: ContextCompiler and context entries. Treat these as unstable implementation-facing surfaces unless a Runtime method provides the same read or mutation path.

Runtime state is structured and recorded before observable events are emitted. The crate boundary is intentionally provider-neutral. Provider adapters normalize requests and events in merry-llm/provider crates rather than storing provider response formats here.

Structs§

AcceptedLocalWorkspaceProcessAdmission
Explicit admission for the process runner used by the local workspace lane.
AcceptedLocalWorkspaceProcessRunnerProfile
Accepted local workspace process lane carried by a runtime profile.
ActionProposal
Runtime-owned, provider-neutral proposal for a mutating registered action.
AgentLoopConfig
Configuration for crate::Runtime::run_agent_loop.
AgentLoopControl
AgentLoopError
Runtime method error returned while an agent loop was running.
AgentLoopInput
AgentLoopResult
Result of a completed or policy-blocked agent loop run.
AgentRun
Runtime-owned single-consumer protocol for one agent run.
ArchiveConfig
Configuration for HistoryRetention::Archive.
BackgroundHandoffNotice
Notice returned when a foreground wait hands active children off to background execution.
BackgroundProcessId
Identifier returned to the model when a background process is retained.
BackgroundProcessLookupError
A model-supplied id did not match a retained process.
BackgroundProcessOutput
Captured output for one retained background process.
BackgroundProcessStop
Result of asking a retained process to stop.
BackgroundProcessSummary
Compact row for a retained background process.
BuiltChildRuntime
Constructed child runtime plus optional resolved per-role execution overrides.
CancelSubagentsInput
Provider-visible input for cancel_subagents.
ChannelPermissionAdmissionSource
Channel-backed human fallback source.
CheckpointId
CheckpointRef
CheckpointRefId
CheckpointRefManifest
CheckpointSequenceRange
ChildRuntimeInput
Runtime-owned input passed to ChildRuntimeFactory when starting one child.
ChildWorkspaceFinalization
Outcome collected when finalizing an isolated child workspace after a run settles.
ChildWorkspaceScope
Parent-authored workspace scope carried into child runtime construction.
CitationCompactionInput
CitationCompactionPolicy
Summary acceptance limits and preferred raw-history retention.
CompactedCheckpoint
Runtime-owned checkpoint left after compacting earlier dynamic state.
CompactedCheckpointSummary
Payload-free notice that a prose checkpoint is installed.
CompactionConfig
Runtime-owned policy for checkpoint compaction.
CompactionOutcome
CompiledContext
Reproducible compiled context snapshot.
ContextBudget
Derived context body budget and the one compaction trigger.
ContextCompiler
Compiles allowlisted structured runtime state into a deterministic context snapshot.
ContextFileRef
Validated workspace-relative file reference with an optional 1-based inclusive line range.
ContextSummary
Runtime-owned dynamic context note or summary entry.
DurableMemory
Open memory store for one workspace, shared by parent and child runtimes.
FileSessionStore
File-backed session storage. Durable session facts append directly to journal.jsonl.
FinalOutput
Structured final output recorded by the runtime.
FinalOutputContract
Runtime-owned final-output contract rendered as a synthetic tool.
ImageSummary
Lightweight public summary of an attached image without raw bytes.
InteractiveAgentRun
InteractiveInputItem
InteractiveInputSnapshot
InteractivePrimaryModel
Provider-neutral model selection for subsequent interactive requests.
InteractiveRunEventStream
Single-consumer output stream for one interactive run.
InteractiveRunId
InteractiveSettingsUpdate
Runtime settings applied by an interactive run at the next model-request boundary.
InteractiveSubagentSettings
Subagent admission and concurrency settings for subsequent delegated work.
LoadedSession
A validated persisted session loaded once before runtime construction.
MemoryLayout
Roots for the global scope and one workspace scope.
ParentPrimaryModel
Snapshot of the parent runtime’s currently active primary provider/model.
PathAccessRule
One platform-neutral path access rule consumed by sandbox backends.
PermissionAdmissionContext
Cancellation-aware permission admission context.
PermissionAdmissionReview
Metadata for one admission decision.
PermissionRequest
Runtime-owned normalized permission request.
PermissionReviewRequest
A pending host-facing permission review request.
PermissionReviewResponse
Host response for one pending permission review request.
PermissionReviewRules
User-trusted custom rules and environment notes for AI permission review.
PreloadedContextFile
One preloaded file slice ready for injection into <merry_subagent_handoff>.
PreparedProcessPermission
An adapter’s prepared action runner and normalized capability evidence.
ProcessActionIntent
Provider-neutral, typed intent for a local process action.
ProcessExecutionEvidence
Provider-neutral evidence recorded after a process action executes.
ProcessOutputChunk
Live incremental output chunk emitted while a process action is running.
ProcessOutputEnvelope
Shared fields of a full process result artifact, including lossless captures.
ProcessOutputSink
Non-blocking sink for forwarding bounded live process output chunks to UI observers.
ProcessOutputStream
One captured stream, with optional metadata absent in older artifacts.
ProcessPathGrant
A normalized approved path and the constraints found while materializing it.
ProcessPermissionProfileId
Stable identifier for a runtime-owned process permission profile.
ProcessRunnerContext
Context passed to a process runner.
ProcessRunnerOutput
Bounded output returned by a process runner.
ProcessSessionPermissionSnapshot
Immutable capabilities retained by one runtime session.
ProcessSessionPermissionView
Read-only access supplied to process adapters; it cannot record a grant.
ProcessSessionPermissions
Capability state owned by a single runtime session, never a global store. Network, explicitly reviewed paths, and protected metadata remain action-only.
ProjectRules
Stable project instructions explicitly loaded by runtime construction.
PromptBlock
One stable provider-neutral prompt block supplied by a higher-level policy.
PromptProfile
Stable prompt material and its runtime placement contract.
QueuedInputId
Stable runtime-assigned identifier for one pending interactive input.
RegisteredTool
Runtime-owned registered tool definition.
RejectedSubagentView
Compact provider-visible view of a rejected child task.
RequestedPathCapability
Requested filesystem capability for one path.
ResolvedCitationCompactionBudget
Soft guidance, hard acceptance, and the preferred raw-history budget.
ResolvedContextWindow
Resolved model context window and the metadata source that supplied it.
ResumableChildSession
Cloneable single-take container carrying a persisted child LoadedSession across the synchronous ChildRuntimeFactory boundary when waking a subagent after parent session resume.
Runtime
Merry runtime handle for one session.
RuntimeBuilder
Builder for a Merry runtime.
RuntimeCapabilities
Merry-managed low-level capability policy.
RuntimeEventStream
Stream of SDK-facing runtime events.
RuntimeJournalEventStream
Stream of provider-neutral runtime journal events.
RuntimeProfile
Complete runtime shape applied by crate::RuntimeBuilder::with_profile.
RuntimeProfileBuilder
Builder for a complete runtime profile.
SendSubagentMessageInput
Provider-visible input for send_subagent_message.
SendSubagentMessageOptions
Delivery options for SubagentManager::send_message_with_options.
SendSubagentMessageOutput
Provider-visible output for send_subagent_message.
SessionContextSnapshot
Session-owned context state and internal projections.
SessionPermissionedProcessRunnerFactory
Runtime decorator that records approved capabilities, not OS mount policy.
SessionReservation
Exclusive ownership of one session’s on-disk state for the lifetime of a run. The operating-system file lock is released when this value is dropped, including when the owning process is terminated.
SkillCatalog
Deterministic catalog of available skill metadata.
SkillLoadWarning
Non-fatal warning raised while loading skill roots.
SkillMetadata
Model-visible metadata for one skill.
SpawnSubagentTaskInput
Provider-visible task item for spawn_subagents.
SpawnSubagentsInput
Provider-visible input for spawn_subagents.
SpawnSubagentsOutput
Provider-visible output for spawn_subagents.
SpawnedSubagentView
Compact provider-visible view of an accepted child task.
StaticPermissionedProcessRunnerFactory
Compatibility factory that always returns the same runner.
StepContext
Context shared with runtime step producers.
StepInput
Input snapshot for a runtime step.
StructuredOutputRetryPolicy
Retry policy for application-level structured final-output decoding.
SubagentActivityHub
Runtime-owned latest-value activity projection for UI consumers.
SubagentConfig
Runtime configuration for subagent delegation limits.
SubagentInspectSession
Lazy inspection handle returned when a product surface drills into a subagent.
SubagentManager
Runtime-owned manager for bounded child agent execution.
SubagentResultView
Explicit result returned by a child agent to its parent.
SubagentStatusView
Provider-visible compact child status.
SubagentTaskSpec
Parent-authored specification for a bounded child agent task.
SubagentWorktreeView
Metadata reported for a child subagent executed inside an isolated Git worktree.
TaskAnchor
Current task objective pinned by a future /task-style control command.
Tool
A typed application tool executed by the Merry runtime.
ToolAdmission
Runtime-owned allowlist for tool execution.
ToolExecutionContext
Context passed to a tool executor.
ToolExecutionOutcome
Domain-level result from a tool execution.
ToolOutputPreview
Bounded UTF-8 preview of a recorded tool output.
ToolSpec
Provider-neutral tool specification.
UserImageInput
A validated normalized PNG attached to one user message.
UserMessageInput
One validated user message with zero or more normalized PNG attachments.
WaitSubagentsInput
Provider-visible input for wait_subagents.
WaitSubagentsOutput
Provider-visible compact status output for wait_subagents.
WorkspacePatchChangeEvidence
Per-file metadata for a constrained workspace patch change.
WorkspacePatchExecutionEvidence
Execute-time metadata for a constrained workspace patch.
WorkspacePatchProposal
Deterministic metadata for a constrained workspace patch proposal.

Enums§

ActionExecutionEvidence
Provider-neutral internal evidence attached after a mutating action executes.
ActionProposalError
Validation errors for runtime-owned action proposal values.
ActionProposalEvidence
Provider-neutral deterministic evidence attached to an action proposal.
AgentLoopBlockedReason
Reasons a loop can stop without final model completion.
AgentLoopConfigError
Invalid agent loop configuration.
AgentLoopStatus
Terminal or blocked status for an agent loop run.
AgentRunMessage
Message emitted by an AgentRun.
BackgroundProcessState
Lifecycle of one retained background process.
CheckpointDecision
Whether the dynamic body has reached the compaction threshold.
CheckpointError
CheckpointSourceKind
CompactionError
CompiledContextSection
A section in the compiled context snapshot.
ContextEntry
Structured input item for the public context compiler view.
ContextError
Errors raised while constructing or compiling structured context.
ContextWindowSource
Source used to resolve a model context window.
DurableMemoryError
Why a durable-memory operation failed.
FinalOutputContractError
Errors raised while constructing a final-output contract.
FrontmatterError
Errors raised while extracting and parsing SKILL.md frontmatter.
HistoryRetention
Policy governing how compacted session history is retained in memory and on disk.
HostFallbackReason
Why a permission request reached the host after AI review was attempted.
HostIntegration
Host integration and supporting client files exposed to inner process actions. Trusted global configuration is the capability ceiling and preauthorizes the inner action sandbox; an integration the configuration did not enable can still be requested for one permissioned action when the backend supports it and its endpoint is visible.
InteractiveError
InteractiveRunMessage
Runtime message contract shared by interactive and non-interactive runs. Runtime message contract shared by interactive and non-interactive runs. Runtime message contract shared by interactive and non-interactive runs. Message emitted by an AgentRun.
InterruptReason
LocalWorkspaceProcessSandboxProfile
Declared sandbox/profile associated with local workspace process admission.
MemoryWriteKind
Kind of apply_patch change aimed at a memory file.
PathAccess
Filesystem access granted or denied for one configured path.
PathAccessRuleSource
Trust source for a path access rule.
PermissionActor
Identifies whether a permission review request originated from the main session or a managed subagent.
PermissionAdmissionDecision
Result returned by a permission admission gate.
PermissionAdmissionError
Errors raised by permission request parsing or admission.
PermissionAdmissionReviewSource
PermissionReviewMode
Review mode for explicit permission requests.
PermissionReviewResponseError
Error returned when a host responds to a pending review request.
PermissionReviewRisk
PermissionUserAuthorization
PermissionedAction
Exact action covered by a permission request.
PlanError
Typed errors returned by Plan Mode state transitions and document authoring.
ProcessActionError
Validation errors for provider-neutral process action values.
ProcessCommandToolError
Errors raised while constructing the runtime-owned process command tool.
ProcessEnvPolicy
Minimal process environment override policy for SP1.
ProcessExitStatus
Provider-neutral process completion status.
ProcessPathGrantConstraint
Backend facts that constrain retention of an approved path capability.
ProcessRunnerError
Infrastructure errors returned by a process runner.
PromptError
Invalid typed prompt composition.
RequestedCapability
Extra capability requested for a permissioned action.
RuntimeError
Errors raised by Merry runtime construction and step admission.
RuntimeModelRole
Runtime model role for a configured provider/model pair.
RuntimeProfileError
Errors raised while building a complete runtime profile.
RuntimeTrustLevel
How much runtime should trust the host/runtime owner for permission gates.
SendSubagentMessageOutcome
Strongly typed, non-ambiguous delivery outcome for send_subagent_message.
SessionStoreError
SessionTranscriptItem
Read-only public projection of persisted session transcript items.
SkillError
Errors raised while validating skill metadata or configured skill roots.
SkillLoadWarningReason
Reason a discovered SKILL.md file was left out of the catalog.
SpawnWaitMode
Optional wait behavior for spawn_subagents.
SpawnedSubagentStatusLabel
Provider-visible status labels possible immediately after spawn.
SubagentError
Validation errors for subagent task contracts and configuration.
SubagentLimitBehavior
Admission behavior when a spawn request exceeds max_threads.
SubagentMessageDelivery
Delivery policy for send_subagent_message.
SubagentStatusLabel
Compact child lifecycle status.
SubagentWorkspaceMode
Filesystem isolation mode for a child subagent.
SubagentWorktreeBase
Snapshot source used when creating a child Git worktree.
ToolActionKind
Runtime-owned action category for registered tools.
ToolActionPreflight
Result of a tool action preflight/proposal hook.
ToolBuildError
Errors raised while constructing a typed application tool.
ToolConcurrency
Runtime execution policy for calls that appear in the same model batch.
ToolExecutionError
Infrastructure-level errors raised by tool executors.
ToolOutput
Complete public text or JSON output for a tool result.
ToolOutputKind
Kind of recorded tool output.
ToolOutputStream
Output stream carrying a live RuntimeEvent::ToolCallOutputDelta chunk.
ToolRunner
Where a registered tool is executed.
WaitMode
Wait behavior for wait_subagents.

Constants§

DEFAULT_AGENT_LOOP_MAX_MODEL_TURNS
Generic SDK/runtime default for one top-level agent run.
DEFAULT_CONTEXT_WINDOW_FALLBACK_TOKENS
Coding-agent fallback used when config, provider metadata, and model catalogs are absent.
DEFAULT_FOREGROUND_WAIT_BUDGET_SECS
Default foreground wait budget in seconds before handing off to background.
DEFAULT_MAX_MODEL_TURNS
Default bounded child loop model-turn count.
DEFAULT_MIN_MODEL_TURNS
Default minimum model-turn budget for a generic child task.
DEFAULT_PROCESS_WAIT_TIMEOUT_SECS
Default foreground wait timeout in seconds before handing off to background.
FINAL_OUTPUT_TOOL_NAME
Reserved provider-visible tool name used for structured terminal output.
MAX_CONTEXT_FILES_TOTAL_BYTES
Maximum total UTF-8 bytes preloaded across all context_files for one child task.
MAX_CONTEXT_FILE_REFS
Maximum number of context_files references accepted for one child task.
MAX_PROCESS_ARGV_ITEMS
Maximum accepted number of argv items in a process intent.
MAX_PROCESS_ARG_BYTES
Maximum accepted byte length for one argv item in a process intent.
MAX_PROCESS_CWD_BYTES
Maximum accepted byte length for a workspace-relative process cwd.
MAX_PROCESS_OUTPUT_LIMIT_BYTES
Maximum accepted captured byte limit per process output stream.
MAX_PROCESS_STDIN_TEXT_BYTES
Maximum accepted byte length for inline stdin text.
MAX_PROCESS_WAIT_TIMEOUT_SECS
Maximum accepted foreground wait timeout in seconds for one run_process call.
MAX_USER_IMAGES
Maximum number of images accepted in one user message.
MAX_USER_IMAGE_DIMENSION
Maximum width or height accepted for one image.
MAX_USER_IMAGE_PIXELS
Maximum decoded pixel count accepted for one image.
MAX_USER_IMAGE_PNG_BYTES
Maximum encoded PNG size accepted for one image.
MAX_USER_IMAGE_TOTAL_PNG_BYTES
Maximum combined encoded PNG size accepted for one user message.
SUBAGENT_HANDOFF_CONTEXT_ID
Construction-context id for the child’s preloaded files and expected output handoff.

Traits§

BackgroundProcessControl
Session-owned control surface for retained background processes.
ChildRuntimeFactory
Object-safe factory for constructing bounded child runtimes.
ChildWorkspaceLifecycle
Runtime-owned hook invoked when a child with an isolated workspace settles.
PermissionAdmissionSource
Object-safe permission admission boundary.
PermissionedProcessRunnerFactory
Factory for runners created from approved permission requests.
ProcessRunner
Object-safe runtime process runner boundary.
ToolExecutor
Object-safe runtime tool executor boundary.

Functions§

citation_compaction_tail_directive
Instructions appended to a compaction request.
decide_checkpoint
Decides whether dynamic body growth has reached the compaction threshold.
host_shell_chain_separator
Returns the error-propagating command chain separator for the active host shell ("&&" on Unix, pwsh, and Git Bash; ";" on Windows PowerShell 5.1 and cmd.exe).
host_shell_has_unix_utilities
Returns whether Unix text/search utilities (grep, find, sed, head, tail) are expected to be available in the active host shell.
host_shell_name
Returns the short name of the active host shell ("bash" on Unix; "pwsh", "powershell", "bash", or "cmd.exe" on Windows).
is_low_risk_process_action_intent
Returns whether a process intent may enter the SP3-A low-risk process lane.
is_read_only_shell_process_action_intent
Returns whether a process intent is a plain read-only shell-wrapper action.
parse_permission_request
Parses a permission request tool call without additional review context.
preload_context_files
Safely preloads context_files within the child’s effective read boundary and byte cap.
process_command_tool
Creates a registered process command tool for runtime agent loops.
read_background_process_tool
Registers the read-only background process tool.
render_subagent_handoff
Renders <merry_subagent_handoff> when either preloaded files or expected_output exist.
request_permissions_tool
resolve_context_window
Resolves context window metadata without provider probing.
shell_command_for_argv
Converts an argv vector into one shell command string for a model-facing command field. Existing platform shell wrappers are unwrapped so their script is preserved; direct argv items are quoted for the host shell.
stop_background_process_tool
Registers the tool that stops one retained background process group.
subagent_base_instructions
Builds dedicated base instructions for a bounded subagent runtime.
subagent_registered_tools
Returns provider-visible subagent tool specs with runtime-owned executors.
subagent_registered_tools_with_roles
Returns provider-visible subagent tool specs advertising the enabled role catalog in spawn_subagents’s description.
subagent_tool_specs
Returns provider-visible subagent tool specs.
user_image_label
Returns the canonical one-based label for a user image.
validate_no_write_scope_conflicts
Rejects child batches where two shared-workspace write scopes overlap.

Type Aliases§

PermissionAdmissionFuture
Boxed admission review future.
ProcessRunnerFuture
Boxed process runner future used for object-safe runtime process boundaries.
ProcessRunnerResult
Result returned by a runtime-owned process runner.
SubagentActivityReceiver
Receiver for the latest sorted activity snapshot set.
ToolActionProposalFuture
Boxed action proposal future used for object-safe async tool boundaries.
ToolActionProposalResult
Optional proposal returned before a write-classified tool can be resolved by policy.
ToolExecutionResult
Result returned by a runtime-owned tool executor.
ToolExecutorFuture
Boxed tool executor future used for object-safe async tool boundaries.