merry-runtime 0.1.2

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
use crate::{
    RuntimeError, request_permissions_tool,
    runtime::{
        DIAGNOSTIC_TOOL_ACTION_POLICY_DENIED, Runtime, RuntimeBuilder,
        TOOL_ACTION_POLICY_DENIED_MESSAGE,
        tests::support::common::{RuntimeSessionStateTestExt, session_id},
    },
    tool::{RegisteredTool, ToolActionKind, ToolExecutor},
};
use merry_core::{
    PendingToolCall, RuntimeJournalEvent, RuntimeJournalPayload, ToolCallArguments, ToolCallId,
    ToolInputSchema, ToolName, ToolSpec,
};
use schemars::Schema;
use serde_json::json;
use std::sync::Arc;

pub(in crate::runtime::tests) fn registered_tool_spec() -> ToolSpec {
    let schema =
        Schema::try_from(json!({ "type": "object" })).expect("test schema should be a JSON schema");
    ToolSpec::new(
        ToolName::new("registered_tool").expect("valid tool name"),
        "Registered test tool",
        ToolInputSchema::new(schema).expect("valid tool schema"),
    )
    .expect("valid tool spec")
}

pub(in crate::runtime::tests) fn policy_tool_spec(name: &str) -> ToolSpec {
    let schema =
        Schema::try_from(json!({ "type": "object" })).expect("test schema should be a JSON schema");
    ToolSpec::new(
        ToolName::new(name).expect("valid tool name"),
        "Policy test tool",
        ToolInputSchema::new(schema).expect("valid tool schema"),
    )
    .expect("valid tool spec")
}

pub(in crate::runtime::tests) fn required_query_tool_spec(name: &str) -> ToolSpec {
    let schema = Schema::try_from(json!({
        "type": "object",
        "properties": {
            "query": { "type": "string" }
        },
        "required": ["query"],
        "additionalProperties": false
    }))
    .expect("test schema should be a JSON schema");
    ToolSpec::new(
        ToolName::new(name).expect("valid tool name"),
        "Validated test tool",
        ToolInputSchema::new(schema).expect("valid tool schema"),
    )
    .expect("valid tool spec")
}

pub(in crate::runtime::tests) fn policy_pending_tool_call(id: &str, name: &str) -> PendingToolCall {
    PendingToolCall::new(
        ToolCallId::new(id).expect("valid tool call id"),
        ToolName::new(name).expect("valid tool name"),
        ToolCallArguments::new(Default::default()),
    )
}

pub(in crate::runtime::tests) fn permission_pending_tool_call(
    id: &str,
    reason: &str,
    command: &str,
) -> PendingToolCall {
    PendingToolCall::new(
        ToolCallId::new(id).expect("valid tool call id"),
        ToolName::new("request_permissions").expect("valid tool name"),
        ToolCallArguments::try_from(serde_json::json!({
            "reason": reason,
            "requested": { "network": true },
            "for_action": {
                "command": command,
                "cwd": ".",
            }
        }))
        .expect("valid permission arguments"),
    )
}

pub(in crate::runtime::tests) fn path_permission_pending_tool_call(
    id: &str,
    path: &str,
    access: &str,
) -> PendingToolCall {
    PendingToolCall::new(
        ToolCallId::new(id).expect("valid tool call id"),
        ToolName::new("request_permissions").expect("valid tool name"),
        ToolCallArguments::try_from(serde_json::json!({
            "reason": "Need the requested path for this exact command.",
            "requested": {
                "paths": [{ "path": path, "access": access }]
            },
            "for_action": {
                "command": "printf '%s\\n' 'hello' > /tmp/hello-work.txt",
                "cwd": ".",
            }
        }))
        .expect("valid path permission arguments"),
    )
}

pub(in crate::runtime::tests) fn invalid_permission_pending_tool_call(id: &str) -> PendingToolCall {
    PendingToolCall::new(
        ToolCallId::new(id).expect("valid tool call id"),
        ToolName::new("request_permissions").expect("valid tool name"),
        ToolCallArguments::try_from(serde_json::json!({
            "requested": {
                "paths": [
                    { "path": "/tmp/cache", "access": "ro" },
                    { "path": "/tmp/cache", "access": "rw" }
                ]
            },
            "for_action": {
                "command": "cargo test",
                "cwd": ".",
            }
        }))
        .expect("valid JSON arguments"),
    )
}

pub(in crate::runtime::tests) fn resolved_tool_result(
    events: &[RuntimeJournalEvent],
) -> &merry_core::ToolCallResult {
    events
        .iter()
        .find_map(|event| match &event.payload {
            RuntimeJournalPayload::ToolCallResolved { result } => Some(result),
            _ => None,
        })
        .expect("tool call should resolve")
}

/// Reads the stored output of a resolved tool result and parses it as JSON.
pub(in crate::runtime::tests) async fn resolved_artifact_json(
    runtime: &Runtime,
    result: &merry_core::ToolCallResult,
    label: &str,
) -> serde_json::Value {
    let output = runtime
        .read_tool_output(result.call_id())
        .await
        .unwrap_or_else(|error| panic!("{label} tool output should be readable: {error}"))
        .unwrap_or_else(|| panic!("{label} tool output should exist"));
    serde_json::from_str(output.as_str())
        .unwrap_or_else(|error| panic!("{label} tool output should parse as JSON: {error}"))
}

pub(in crate::runtime::tests) async fn register_policy_pending_tool(
    session: &str,
    tool_name: &str,
    call_id: &str,
    action_kind: ToolActionKind,
    executor: impl ToolExecutor + 'static,
) -> (Runtime, PendingToolCall) {
    register_policy_pending_registered_tool(
        session,
        tool_name,
        call_id,
        RegisteredTool::new(policy_tool_spec(tool_name), Arc::new(executor), action_kind),
    )
    .await
}

pub(in crate::runtime::tests) async fn register_policy_pending_registered_tool(
    session: &str,
    tool_name: &str,
    call_id: &str,
    tool: RegisteredTool,
) -> (Runtime, PendingToolCall) {
    register_policy_pending_registered_tool_with_builder(
        session,
        tool_name,
        call_id,
        tool,
        RuntimeBuilder::build,
    )
    .await
}

pub(in crate::runtime::tests) async fn register_policy_pending_registered_tool_with_builder(
    session: &str,
    tool_name: &str,
    call_id: &str,
    tool: RegisteredTool,
    configure: impl FnOnce(RuntimeBuilder) -> Result<Runtime, RuntimeError>,
) -> (Runtime, PendingToolCall) {
    let spec = policy_tool_spec(tool_name);
    let pending = policy_pending_tool_call(call_id, spec.name().as_str());
    let runtime = configure(Runtime::builder(session_id(session)).register_tool(tool))
        .expect("runtime should build");
    {
        let mut session = runtime.inner.session.lock().await;
        session.record_session_started_if_needed();
        session
            .record_test_tool_call_pending(pending.clone())
            .expect("pending call should record");
    }
    (runtime, pending)
}

pub(in crate::runtime::tests) async fn register_permission_pending_tool_with_builder(
    session_id_value: &str,
    call_id: &str,
    configure: impl FnOnce(RuntimeBuilder) -> Result<Runtime, RuntimeError>,
) -> (Runtime, PendingToolCall) {
    let pending = permission_pending_tool_call(
        call_id,
        "Need network for this exact command.",
        "cargo test",
    );
    let runtime = configure(
        Runtime::builder(session_id(session_id_value))
            .register_tool(request_permissions_tool().expect("permission tool builds")),
    )
    .expect("runtime should build");
    {
        let mut session = runtime.inner.session.lock().await;
        session.record_session_started_if_needed();
        session
            .record_test_user_message_body(
                "Please run cargo test; if network is blocked, request network for that command.",
            )
            .expect("user records");
        session
            .record_test_tool_call_pending(pending.clone())
            .expect("pending call should record");
    }
    (runtime, pending)
}

pub(in crate::runtime::tests) async fn denied_action_content(
    runtime: &Runtime,
    events: &[RuntimeJournalEvent],
) -> serde_json::Value {
    let result = resolved_tool_result(events);
    resolved_artifact_json(runtime, result, "denial").await
}

pub(in crate::runtime::tests) fn assert_sanitized_policy_denial_content(
    content: &serde_json::Value,
    tool_name: &str,
) {
    assert_eq!(
        content,
        &json!({
            "ok": false,
            "tool": tool_name,
            "error": {
                "code": DIAGNOSTIC_TOOL_ACTION_POLICY_DENIED,
                "message": TOOL_ACTION_POLICY_DENIED_MESSAGE
            }
        })
    );
    assert!(content.get("call_id").is_none());
    assert!(content.get("action_kind").is_none());
    assert!(content.get("policy").is_none());
    assert!(content.get("reason").is_none());
    assert!(content.get("provider").is_none());
    assert!(content.get("provider_response").is_none());
    assert!(content.get("wire").is_none());
    assert!(content.get("previous_response_id").is_none());
}

pub(in crate::runtime::tests) fn event_kind_names_for_tool_execution(
    events: &[RuntimeJournalEvent],
) -> Vec<&'static str> {
    events
        .iter()
        .map(|event| match event.payload {
            RuntimeJournalPayload::AssistantOutputRecorded { .. } => "AssistantOutputRecorded",
            RuntimeJournalPayload::ToolCallResolved { .. } => "ToolCallResolved",
            RuntimeJournalPayload::SessionUsageUpdated { .. } => "SessionUsageUpdated",
            RuntimeJournalPayload::SessionStarted => "SessionStarted",
            RuntimeJournalPayload::StepStarted => "StepStarted",
            RuntimeJournalPayload::StepCompleted => "StepCompleted",
            RuntimeJournalPayload::Cancelled { .. } => "Cancelled",
            RuntimeJournalPayload::Failed { .. } => "Failed",
            RuntimeJournalPayload::ToolCallPending { .. } => "ToolCallPending",
            RuntimeJournalPayload::SkillUsed { .. } => "SkillUsed",
            _ => "Other",
        })
        .collect()
}