opencode-sdk

    MoonBit SDK for running OpenCode through its CLI

    opencode
    sdk
    cli
    moonbit
    Download zip
    Author
    Version
    0.2.0
    License
    MIT
    Last updated
    3 months ago
    Downloads
    287

    #OpenCode SDK for MoonBit

    Embed the OpenCode agent in MoonBit workflows and applications through the installed opencode run --format json command.

    The public client shape intentionally follows totto2727/codex-sdk: create an OpenCode client, start or resume a Thread, then call run or run_streamed. Provider-specific options and events remain OpenCode-native because the CLIs do not share a wire protocol.

    #Usage

    ///|
    async fn example {
    let opencode = @opencode_sdk.OpenCode::OpenCode()
    let thread = opencode.start_thread(
    options=@opencode_sdk.ThreadOptions::ThreadOptions(
    model="opencode-go/deepseek-v4-flash",
    ),
    )
    let turn = thread.run(
    @opencode_sdk.Input::Prompt("Explain this repository in one paragraph."),
    )
    println(turn.final_response)
    }

    Add the package to a MoonBit project and import it with an alias:

    import {
    "totto2727/opencode-sdk@0.1.1",
    }

    import {
    "totto2727/opencode-sdk" @opencode_sdk,
    }

    #Streaming

    MoonBit uses an asynchronous callback in place of an async generator.

    ///|
    async fn stream_example {
    let thread = @opencode_sdk.OpenCode::OpenCode().start_thread()
    thread.run_streamed(
    @opencode_sdk.Input::Prompt("Summarize the current changes."),
    async fn(event) {
    match event {
    @opencode_sdk.Text(text) => println(text.text)
    _ => ()
    }
    @async.pause()
    },
    )
    }

    ThreadEvent models the JSONL events emitted by the OpenCode CLI: completed text and reasoning parts, completed or failed tool calls, step start and finish records, and stream errors. Step-finish events retain cost and token usage, while Thread::run joins completed text parts into Turn::final_response.

    #Options and lifecycle

    OpenCodeOptions accepts an explicit executable path, an environment map, and recursively typed configuration serialized to OPENCODE_CONFIG_CONTENT. ThreadOptions forwards model, agent, working directory, variant, title, and thinking output through the corresponding official CLI flags, while UserInputs forwards local files with repeated --file flags.

    The task that calls run or run_streamed owns the OpenCode subprocess. Cancelling that task hard-cancels and waits for the child process before control returns.

    The managed-server implementation remains available separately as totto2727/opencode-server-sdk.

    OpenCodeConfigObject

    type OpenCodeConfigObject = Map[String, OpenCodeConfigValue]

    An OpenCode configuration object serialized into OPENCODE_CONFIG_CONTENT.

    RunStreamedResult

    type RunStreamedResult = Unit

    Alias describing the result returned by Thread::run_streamed.

    StreamedTurn

    type StreamedTurn = Unit

    The result type returned after a streamed callback completes.

    OpenCodeSdkError

    pub(all) suberror OpenCodeSdkError {
    InvalidEvent(message~ : String)
    TurnFailed(message~ : String)
    ExecFailed(code~ : Int, stderr~ : String)
    } derive(Eq,
    Debug
    )

    Errors raised at OpenCode configuration, protocol, and process boundaries.

    Input

    pub(all) enum Input {
    Prompt(String)
    UserInputs(Array[UserInput])
    } derive(Eq)

    Input accepted by an OpenCode turn.

    OpenCode

    pub struct OpenCode {
    // private fields
    }

    Main client for interacting with the OpenCode agent through its CLI.

    OpenCode::OpenCode

    fn OpenCode::OpenCode(options? : OpenCodeOptions) -> OpenCode

    Construct an OpenCode CLI client.

    OpenCode::resume_thread

    fn OpenCode::resume_thread(self : OpenCode, id : String, options? : ThreadOptions) -> Thread

    Resume a persisted OpenCode session by identifier.

    OpenCode::start_thread

    fn OpenCode::start_thread(self : OpenCode, options? : ThreadOptions) -> Thread

    Start a new persisted OpenCode session.

    OpenCodeConfigValue

    pub(all) enum OpenCodeConfigValue {
    ConfigString(String)
    ConfigInt(Int)
    ConfigDouble(Double)
    ConfigBool(Bool)
    ConfigArray(Array[OpenCodeConfigValue])
    ConfigObject(Map[String, OpenCodeConfigValue])
    } derive(Eq,
    Debug
    )

    A recursively typed OpenCode configuration value.

    OpenCodeExec

    type OpenCodeExec

    Process adapter for opencode run --format json.

    OpenCodeOptions

    pub(all) struct OpenCodeOptions {
    opencode_path_override :
    Path
    ?
    config : Map[String, OpenCodeConfigValue]?
    env : Map[String, String]?
    } derive(Eq)

    Options shared by every thread created from an OpenCode client.

    OpenCodeOptions::OpenCodeOptions

    fn OpenCodeOptions::OpenCodeOptions(opencode_path_override? :
    Path
    , config? : Map[String, OpenCodeConfigValue], env? : Map[String, String]) -> OpenCodeOptions

    Construct client-wide OpenCode CLI options.

    ReasoningEvent

    pub(all) struct ReasoningEvent {
    session_id : String
    text : String
    } derive(Eq,
    Debug
    )

    A completed reasoning part emitted when thinking output is enabled.

    StepFinishEvent

    pub(all) struct StepFinishEvent {
    session_id : String
    reason : String
    cost : Double
    usage : Usage
    } derive(Eq,
    Debug
    )

    A marker and usage payload emitted when OpenCode finishes a model step.

    StepStartEvent

    pub(all) struct StepStartEvent {
    session_id : String
    } derive(Eq,
    Debug
    )

    A marker emitted when OpenCode begins a model step.

    TextEvent

    pub(all) struct TextEvent {
    session_id : String
    text : String
    } derive(Eq,
    Debug
    )

    A completed text part emitted by OpenCode.

    Thread

    pub struct Thread {
    // private fields
    }

    One persisted OpenCode session.

    Thread::id

    fn Thread::id(self : Thread) -> String?

    Return the persisted session identifier after the first event arrives.

    Thread::run

    async fn Thread::run(self : Thread, input : Input) -> Turn

    Run one turn and buffer its typed events and final text response.

    Thread::run_streamed

    async fn Thread::run_streamed(self : Thread, input : Input, on_event : async (ThreadEvent) -> Unit) -> Unit

    Run one turn and deliver typed OpenCode events as they arrive.

    ThreadErrorEvent

    pub(all) struct ThreadErrorEvent {
    session_id : String?
    message : String
    } derive(Eq,
    Debug
    )

    A fatal error emitted by the OpenCode event stream.

    ThreadEvent

    pub(all) enum ThreadEvent {
    Text(TextEvent)
    Reasoning(ReasoningEvent)
    ToolUse(ToolUseEvent)
    StepStart(StepStartEvent)
    StepFinish(StepFinishEvent)
    StreamError(ThreadErrorEvent)
    } derive(Eq,
    Debug
    )

    One typed JSONL event emitted by opencode run --format json.

    ThreadOptions

    pub(all) struct ThreadOptions {
    model : String?
    agent : String?
    working_directory :
    Path
    ?
    variant : String?
    title : String?
    thinking : Bool
    } derive(Eq)

    Options applied to every turn in one OpenCode session.

    ThreadOptions::ThreadOptions

    fn ThreadOptions::ThreadOptions(model? : String, agent? : String, working_directory? :
    Path
    , variant? : String, title? : String, thinking? : Bool) -> ThreadOptions

    Construct optional OpenCode session settings.

    ToolUseEvent

    pub(all) struct ToolUseEvent {
    session_id : String
    call_id : String
    tool : String
    status : ToolUseStatus
    } derive(Eq,
    Debug
    )

    A tool-use part emitted by OpenCode.

    ToolUseStatus

    pub(all) enum ToolUseStatus {
    Completed
    Failed
    } derive(Eq,
    Debug
    )

    The terminal or active state of an OpenCode tool call.

    Turn

    #alias(RunResult)
    pub(all) struct Turn {
    events : ReadOnlyArray[ThreadEvent]
    final_response : String
    } derive(Eq,
    Debug
    )

    A completed OpenCode turn.

    Usage

    pub(all) struct Usage {
    input_tokens : Int
    output_tokens : Int
    reasoning_tokens : Int
    cache_read_tokens : Int
    cache_write_tokens : Int
    } derive(Eq,
    Debug
    )

    Token usage reported when OpenCode finishes a model step.

    UserInput

    pub(all) enum UserInput {
    Text(String)
    LocalFile(
    Path
    )
    } derive(Eq)

    One structured input entry sent to OpenCode.

    Powered by MoonBit

    Site sourceReport issueModulesSkillsBuild queueStatistics

    © 2026 mooncakes.io