merry 0.1.1

Rust SDK facade for the Merry coding agent runtime (CLI available as `merry-cli`).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Owned, provider-neutral contracts for foreign-language bindings.
//!
//! This module contains no PyO3 types. It adapts the Rust facade's
//! lifetime-bearing host handoff into an owned protocol while keeping the
//! pending batch lease, ordering checks, artifact ownership, and terminal
//! lifecycle in the facade/runtime layers.

pub use crate::agent::{
    ToolInvocation, ToolInvocationContent, ToolInvocationContentError, ToolInvocationResult,
    ToolInvocationSubmission,
};
use crate::{
    AgentError, HookDecision, HookInvocation, HookInvocationId, InteractiveControl,
    InteractiveEventStream, InteractiveInput, InteractiveRun, RunResult, RuntimeEvent,
    agent::AgentRun,
};
use merry_core::{PendingToolCall, ToolCallBatchId};

/// An owned message returned by a foreign-language agent run.
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq)]
pub enum OwnedAgentRunMessage {
    /// A durable runtime event.
    Event(Box<RuntimeEvent>),
    /// An ordered host-owned tool invocation batch.
    ToolInvocations {
        /// The batch must be submitted or cancelled before the run advances.
        batch: OwnedToolInvocationBatch,
    },
    /// A subscribed host-bridged lifecycle hook awaiting a decision.
    HookInvocation {
        /// The hook invocation must be resolved or failed before the run advances.
        invocation: Box<HookInvocation>,
    },
}

impl OwnedAgentRunMessage {
    /// Borrows the runtime event when this is an event message.
    #[must_use]
    pub fn as_event(&self) -> Option<&RuntimeEvent> {
        match self {
            Self::Event(event) => Some(event.as_ref()),
            Self::ToolInvocations { .. } | Self::HookInvocation { .. } => None,
        }
    }

    /// Borrows the tool invocation batch when this is a handoff message.
    #[must_use]
    pub fn as_tool_invocations(&self) -> Option<&OwnedToolInvocationBatch> {
        match self {
            Self::Event(_) | Self::HookInvocation { .. } => None,
            Self::ToolInvocations { batch } => Some(batch),
        }
    }

    /// Borrows the hook invocation when this is a bridged hook message.
    #[must_use]
    pub fn as_hook_invocation(&self) -> Option<&HookInvocation> {
        match self {
            Self::HookInvocation { invocation } => Some(invocation.as_ref()),
            Self::Event(_) | Self::ToolInvocations { .. } => None,
        }
    }
}

/// An owned ordered batch of host-executed tool invocations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwnedToolInvocationBatch {
    batch_id: ToolCallBatchId,
    invocations: Vec<ToolInvocation>,
}

impl OwnedToolInvocationBatch {
    pub(crate) fn new(batch_id: ToolCallBatchId, calls: Vec<PendingToolCall>) -> Option<Self> {
        if calls.is_empty() {
            return None;
        }
        Some(Self {
            batch_id,
            invocations: calls.into_iter().map(ToolInvocation::new).collect(),
        })
    }

    /// Returns the runtime-owned batch identifier.
    #[must_use]
    pub fn id(&self) -> &ToolCallBatchId {
        &self.batch_id
    }

    /// Returns invocations in model order.
    #[must_use]
    pub fn invocations(&self) -> &[ToolInvocation] {
        &self.invocations
    }

    /// Returns the number of invocations in this batch.
    #[must_use]
    pub fn len(&self) -> usize {
        self.invocations.len()
    }

    /// Returns whether this batch contains no invocations.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.invocations.is_empty()
    }
}

/// Owned single-consumer run handle intended for foreign-language bindings.
///
/// The handle exposes no runtime storage. It only owns the facade run and the
/// current batch view needed to bridge a language boundary without Rust
/// lifetimes. Rust continues to validate every submitted call and owns the
/// durable terminal result.
pub struct OwnedAgentRun {
    inner: AgentRun,
    pending_batch: Option<OwnedToolInvocationBatch>,
    pending_hook: Option<HookInvocation>,
    terminal_result: Option<RunResult>,
}

impl OwnedAgentRun {
    pub(crate) fn new(inner: AgentRun) -> Self {
        Self {
            inner,
            pending_batch: None,
            pending_hook: None,
            terminal_result: None,
        }
    }

    /// Returns the next event, host-tool invocation batch, or subscribed hook invocation.
    pub async fn next_message(&mut self) -> Result<Option<OwnedAgentRunMessage>, AgentError> {
        if self.pending_batch.is_some() {
            return Err(AgentError::ToolInvocationBatchPending);
        }
        if self.pending_hook.is_some() {
            return Err(AgentError::HookInvocationPending);
        }

        let message = self.inner.next_owned_message().await?;
        match &message {
            Some(OwnedAgentRunMessage::ToolInvocations { batch }) => {
                self.pending_batch = Some(batch.clone());
            }
            Some(OwnedAgentRunMessage::HookInvocation { invocation }) => {
                self.pending_hook = Some((**invocation).clone());
            }
            Some(OwnedAgentRunMessage::Event(_)) | None => {}
        }
        Ok(message)
    }

    /// Alias for [`Self::next_message`].
    pub async fn next(&mut self) -> Result<Option<OwnedAgentRunMessage>, AgentError> {
        self.next_message().await
    }

    /// Submits the complete result set for the active batch.
    ///
    /// The batch id and every call id are checked by the Rust facade. A
    /// correctable validation error leaves the batch active for retry.
    pub async fn submit_tool_invocation_results(
        &mut self,
        batch_id: &ToolCallBatchId,
        results: Vec<ToolInvocationResult>,
    ) -> Result<ToolInvocationSubmission, AgentError> {
        let Some(batch) = self.pending_batch.as_ref() else {
            return Err(AgentError::ToolInvocationBatchNotPending);
        };
        let invocations = batch.invocations.clone();
        let result = self
            .inner
            .submit_tool_invocation_results(batch_id, &invocations, results)
            .await;
        if result.is_ok() {
            self.pending_batch = None;
        }
        result
    }

    /// Submits a typed decision for the active bridged hook invocation.
    pub async fn submit_hook_decision(
        &mut self,
        invocation_id: &HookInvocationId,
        decision: HookDecision,
    ) -> Result<(), AgentError> {
        if self.pending_hook.is_none() {
            return Err(AgentError::HookInvocationNotPending);
        }
        let result = self
            .inner
            .submit_hook_decision(invocation_id, decision)
            .await;
        if result.is_ok() {
            self.pending_hook = None;
        }
        result
    }

    /// Reports a fail-closed host hook error for the active bridged hook invocation.
    pub async fn fail_hook_invocation(
        &mut self,
        invocation_id: &HookInvocationId,
        message: String,
    ) -> Result<(), AgentError> {
        if self.pending_hook.is_none() {
            return Err(AgentError::HookInvocationNotPending);
        }
        let result = self
            .inner
            .fail_hook_invocation(invocation_id, message)
            .await;
        if result.is_ok() {
            self.pending_hook = None;
        }
        result
    }

    /// Returns the terminal result after the run reaches EOF.
    ///
    /// A successful result is retained and returned again on repeated calls so
    /// a binding can recover after cancellation of a concurrent operation.
    pub async fn result(&mut self) -> Result<RunResult, AgentError> {
        if let Some(result) = self.terminal_result.as_ref() {
            return Ok(result.clone());
        }
        let result = self.inner.result().await?;
        self.terminal_result = Some(result.clone());
        Ok(result)
    }

    /// Cancels the run and waits for its durable terminal result.
    ///
    /// A successful result is retained and returned again on repeated calls.
    pub async fn cancel(&mut self) -> Result<RunResult, AgentError> {
        if let Some(result) = self.terminal_result.as_ref() {
            return Ok(result.clone());
        }
        self.pending_batch = None;
        self.pending_hook = None;
        let result = self.inner.cancel().await?;
        self.terminal_result = Some(result.clone());
        Ok(result)
    }
}

impl From<AgentRun> for OwnedAgentRun {
    fn from(run: AgentRun) -> Self {
        run.into_owned()
    }
}

/// Owned single-consumer interactive output stream for foreign-language bindings.
pub struct OwnedInteractiveStream {
    inner: InteractiveEventStream,
    pending_batch: Option<OwnedToolInvocationBatch>,
    pending_hook: Option<HookInvocation>,
}

impl OwnedInteractiveStream {
    pub(crate) fn new(inner: InteractiveEventStream) -> Self {
        Self {
            inner,
            pending_batch: None,
            pending_hook: None,
        }
    }

    /// Returns the next runtime event, host tool invocation batch, or subscribed hook invocation.
    pub async fn next_message(&mut self) -> Result<Option<OwnedAgentRunMessage>, AgentError> {
        let message = self.inner.next_owned_message().await?;
        match &message {
            Some(OwnedAgentRunMessage::ToolInvocations { batch }) => {
                self.pending_batch = Some(batch.clone());
                self.pending_hook = None;
            }
            Some(OwnedAgentRunMessage::HookInvocation { invocation }) => {
                self.pending_hook = Some((**invocation).clone());
                self.pending_batch = None;
            }
            Some(OwnedAgentRunMessage::Event(_)) | None => {
                self.pending_batch = None;
                self.pending_hook = None;
            }
        }
        Ok(message)
    }

    /// Submits the complete result set for the active interactive tool batch.
    pub async fn submit_tool_invocation_results(
        &mut self,
        batch_id: &ToolCallBatchId,
        results: Vec<ToolInvocationResult>,
    ) -> Result<ToolInvocationSubmission, AgentError> {
        let Some(batch) = self.pending_batch.as_ref() else {
            return Err(AgentError::ToolInvocationBatchNotPending);
        };
        let invocations = batch.invocations.clone();
        let result = self
            .inner
            .submit_owned_tool_invocation_results(batch_id, &invocations, results)
            .await;
        match &result {
            Ok(_) => {
                self.pending_batch = None;
            }
            Err(AgentError::Interactive {
                source:
                    merry_runtime::InteractiveError::NoPendingToolInvocations { .. }
                    | merry_runtime::InteractiveError::RunClosed { .. },
            }) => {
                self.pending_batch = None;
            }
            Err(_) => {}
        }
        result
    }

    /// Submits a typed decision for the active interactive bridged hook invocation.
    pub async fn submit_hook_decision(
        &mut self,
        invocation_id: &HookInvocationId,
        decision: HookDecision,
    ) -> Result<(), AgentError> {
        if self.pending_hook.is_none() {
            return Err(AgentError::HookInvocationNotPending);
        }
        let result = self
            .inner
            .submit_owned_hook_decision(invocation_id, decision)
            .await;
        match &result {
            Ok(()) => self.pending_hook = None,
            Err(AgentError::Interactive {
                source:
                    merry_runtime::InteractiveError::NoPendingHookInvocation { .. }
                    | merry_runtime::InteractiveError::RunClosed { .. },
            }) => self.pending_hook = None,
            Err(_) => {}
        }
        result
    }

    /// Reports a fail-closed host hook error for the active interactive bridged hook invocation.
    pub async fn fail_hook_invocation(
        &mut self,
        invocation_id: &HookInvocationId,
        message: String,
    ) -> Result<(), AgentError> {
        if self.pending_hook.is_none() {
            return Err(AgentError::HookInvocationNotPending);
        }
        let result = self
            .inner
            .fail_owned_hook_invocation(invocation_id, message)
            .await;
        match &result {
            Ok(()) => self.pending_hook = None,
            Err(AgentError::Interactive {
                source:
                    merry_runtime::InteractiveError::NoPendingHookInvocation { .. }
                    | merry_runtime::InteractiveError::RunClosed { .. },
            }) => self.pending_hook = None,
            Err(_) => {}
        }
        result
    }

    /// Requests cancellation of the interactive producer without awaiting shutdown.
    pub fn request_cancel(&self) {
        self.inner.request_cancel();
    }

    /// Cancels the interactive producer, drains buffered messages, and waits
    /// for durable shutdown (releasing the session's active step permit).
    pub async fn cancel_and_wait_until_closed(&mut self) -> Result<(), AgentError> {
        self.pending_batch = None;
        self.pending_hook = None;
        self.inner.cancel_and_wait_until_closed().await
    }
}

/// Owned interactive run handle intended for foreign-language bindings.
pub struct OwnedInteractiveRun {
    stream: OwnedInteractiveStream,
    input: InteractiveInput,
    control: InteractiveControl,
}

impl OwnedInteractiveRun {
    pub(crate) fn new(run: InteractiveRun) -> Self {
        let (stream, input, control) = run.split();
        Self {
            stream: OwnedInteractiveStream::new(stream),
            input,
            control,
        }
    }

    /// Splits this interactive run into its owned output stream, input queue
    /// handle, and control handle.
    #[must_use]
    pub fn split(self) -> (OwnedInteractiveStream, InteractiveInput, InteractiveControl) {
        (self.stream, self.input, self.control)
    }
}