supercode-harness 0.4.15

The optional native Supercode agent and tool harness
Documentation
//! Claude runtime compatibility tools edit the imported manifest and nothing
//! else: no timer exists here or anywhere downstream. Every provider here is
//! an in-memory deterministic script.

use std::sync::atomic::{AtomicUsize, Ordering};

use async_trait::async_trait;
use supercode_harness::{
    Agent, ChatMessage, ChatRequest, ClaudeRuntimeManifest, Config, FunctionCall, Provider, Role,
    ToolCall, Usage,
};

fn imported_manifest() -> ClaudeRuntimeManifest {
    serde_json::from_value(serde_json::json!({
        "schema_version": 1,
        "posture": {
            "permission_mode": null,
            "last_prompt_leaf_uuid": null,
            "last_prompt": null,
            "timestamp": null,
            "entrypoint": "cli",
            "user_type": "external",
            "version": "2.1.197",
            "cwd": "/tmp/fleet"
        },
        "active_crons": [
            {
                "id": "old-a",
                "tool_use_id": "import-a",
                "schedule": "6,26,46 * * * *",
                "recurring": true,
                "durable_requested": true,
                "prompt": "DO_NOT_EXECUTE_CRON_A",
                "created_at": "2026-07-14T10:00:00Z",
                "expires_after_seconds": null,
                "creation_result": "Scheduled recurring job old-a (6,26,46 * * * *)."
            },
            {
                "id": "old-b",
                "tool_use_id": "import-b",
                "schedule": "4,14,24,34,44,54 * * * *",
                "recurring": true,
                "durable_requested": false,
                "prompt": "DO_NOT_EXECUTE_CRON_B",
                "created_at": "2026-07-14T10:01:00Z",
                "expires_after_seconds": null,
                "creation_result": "Scheduled recurring job old-b (4,14,24,34,44,54 * * * *)."
            }
        ],
        "pending_wakeups": [],
        "queue": {"enqueued": 0, "dequeued": 0, "removed": 0, "pending": []},
        "background_children": [],
        "reported_pending_background_children": 0,
        "residue": []
    }))
    .unwrap()
}

fn call(id: &str, name: &str, arguments: serde_json::Value) -> ChatMessage {
    ChatMessage {
        role: Role::Assistant,
        content: None,
        content_parts: None,
        tool_calls: Some(vec![ToolCall {
            id: id.to_string(),
            kind: "function".to_string(),
            function: FunctionCall {
                name: name.to_string(),
                arguments: arguments.to_string(),
            },
        }]),
        tool_call_id: None,
        name: None,
        metadata: Default::default(),
    }
}

struct ClaudeBuiltinAliasScript(AtomicUsize);

#[async_trait]
impl Provider for ClaudeBuiltinAliasScript {
    async fn complete(
        &self,
        req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode_harness::Result<(ChatMessage, Usage)> {
        for name in ["Bash", "Read", "Write", "Edit", "Glob", "Grep"] {
            assert!(req.tools.iter().any(|schema| schema.name == name));
        }
        let message = match self.0.fetch_add(1, Ordering::SeqCst) {
            0 => call(
                "claude-bash",
                "Bash",
                serde_json::json!({"command": "printf alias-ok", "timeout": 5000}),
            ),
            1 => {
                let result = req.messages.last().unwrap();
                assert_eq!(result.role, Role::Tool);
                assert_eq!(result.name.as_deref(), Some("Bash"));
                assert!(result.content.as_deref().unwrap().contains("alias-ok"));
                ChatMessage::assistant("alias executed")
            }
            other => panic!("unexpected provider turn {other}"),
        };
        Ok((message, Usage::default()))
    }
}

#[tokio::test]
async fn imported_claude_builtin_names_are_advertised_and_execute_natively() {
    let config = Config::builder()
        .claude_runtime_tools_enabled(true)
        .max_iterations(3)
        .build();
    let mut agent = Agent::with_provider(
        config,
        Box::new(ClaudeBuiltinAliasScript(AtomicUsize::new(0))),
    );
    assert_eq!(agent.send("continue").await.unwrap(), "alias executed");
}

struct PausedRuntimeScript {
    turn: AtomicUsize,
    injected_runtime_prompts: AtomicUsize,
}

#[async_trait]
impl Provider for PausedRuntimeScript {
    async fn complete(
        &self,
        req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode_harness::Result<(ChatMessage, Usage)> {
        for message in &req.messages {
            if message.role == Role::User
                && message.content.as_deref().is_some_and(|text| {
                    text.starts_with("DO_NOT_EXECUTE_CRON")
                        || text.starts_with("DO_NOT_EXECUTE_WAKEUP")
                })
            {
                self.injected_runtime_prompts.fetch_add(1, Ordering::SeqCst);
            }
        }

        let names: Vec<&str> = req
            .tools
            .iter()
            .map(|schema| schema.name.as_str())
            .collect();
        for expected in ["CronCreate", "CronDelete", "CronList", "ScheduleWakeup"] {
            assert!(names.contains(&expected), "missing schema {expected}");
        }

        let turn = self.turn.fetch_add(1, Ordering::SeqCst);
        let message = match turn {
            0 => call("list", "CronList", serde_json::json!({})),
            1 => {
                let result: serde_json::Value =
                    serde_json::from_str(req.messages.last().unwrap().content.as_deref().unwrap())
                        .unwrap();
                assert_eq!(result["execution_state"], "paused");
                assert_eq!(result["jobs"].as_array().unwrap().len(), 2);
                call(
                    "create",
                    "CronCreate",
                    serde_json::json!({
                        "cron": "*/5 * * * *",
                        "prompt": "DO_NOT_EXECUTE_CRON_NEW",
                        "recurring": true,
                        "durable": true
                    }),
                )
            }
            2 => {
                let result = req.messages.last().unwrap().content.as_deref().unwrap();
                assert!(result.contains("PAUSED"));
                assert!(result.contains("will not execute"));
                call("delete", "CronDelete", serde_json::json!({"id": "old-a"}))
            }
            3 => call(
                "wake-one",
                "ScheduleWakeup",
                serde_json::json!({
                    "delaySeconds": 30,
                    "reason": "first",
                    "prompt": "DO_NOT_EXECUTE_WAKEUP_ONE"
                }),
            ),
            4 => {
                let result = req.messages.last().unwrap().content.as_deref().unwrap();
                assert!(result.contains("PAUSED"));
                assert!(result.contains("no timer is running"));
                call(
                    "wake-two",
                    "ScheduleWakeup",
                    serde_json::json!({
                        "delaySeconds": 90,
                        "reason": "replacement",
                        "prompt": "DO_NOT_EXECUTE_WAKEUP_TWO"
                    }),
                )
            }
            5 => ChatMessage::assistant("paused runtime state updated"),
            other => panic!("unexpected provider turn {other}"),
        };
        Ok((message, Usage::default()))
    }
}

#[tokio::test]
async fn imported_crons_mutate_and_wakeup_replaces_without_execution() {
    let provider = PausedRuntimeScript {
        turn: AtomicUsize::new(0),
        injected_runtime_prompts: AtomicUsize::new(0),
    };
    let config = Config::builder()
        .claude_runtime_tools_enabled(true)
        .max_iterations(8)
        .build();
    let mut agent = Agent::with_provider(config, Box::new(provider));
    agent.set_claude_runtime_manifest(imported_manifest());

    let reply = agent.send("continue safely").await.unwrap();
    assert_eq!(reply, "paused runtime state updated");

    let manifest = agent.claude_runtime_manifest().unwrap();
    let ids: Vec<&str> = manifest
        .active_crons
        .iter()
        .map(|job| job.id.as_str())
        .collect();
    assert_eq!(ids, ["old-b", "sc000001"]);
    assert_eq!(manifest.pending_wakeups.len(), 1);
    assert_eq!(manifest.pending_wakeups[0].tool_use_id, "wake-two");
    assert_eq!(manifest.pending_wakeups[0].delay_seconds, 90);
    assert_eq!(
        manifest.pending_wakeups[0].prompt.as_deref(),
        Some("DO_NOT_EXECUTE_WAKEUP_TWO")
    );

    // Runtime prompts only ever occurred inside assistant tool arguments;
    // none was injected as an executable user turn.
    assert!(!agent.history().iter().any(|message| {
        message.role == Role::User
            && message.content.as_deref().is_some_and(|text| {
                text.starts_with("DO_NOT_EXECUTE_CRON") || text.starts_with("DO_NOT_EXECUTE_WAKEUP")
            })
    }));
}

#[test]
fn compatibility_surface_is_default_off() {
    let agent = Agent::with_provider(Config::default(), Box::new(NeverCalled));
    let names: Vec<String> = agent
        .tool_schemas()
        .into_iter()
        .map(|schema| schema.name)
        .collect();
    for absent in ["CronCreate", "CronDelete", "CronList", "ScheduleWakeup"] {
        assert!(!names.iter().any(|name| name == absent));
    }
}

struct NeverCalled;

#[async_trait]
impl Provider for NeverCalled {
    async fn complete(
        &self,
        _req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode_harness::Result<(ChatMessage, Usage)> {
        panic!("provider must not be called")
    }
}