monoloop-contracts 0.1.4

Shared identities, dialect descriptors, errors, and port contracts for Monoloop
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! Transaction request, events, terminal, sinks, and runtime port.

use crate::canonical::CanonicalUnitEvent;
use crate::config::{InvocationConfig, SessionConfig};
use crate::id::ToolId;
use crate::id::{ChannelId, SessionId, SessionKey, TransactionId};
use crate::input::CanonicalInput;
use crate::safe::SafeDiagnostic;
use crate::tool::ToolLifecycleEvent;
use serde::{Deserialize, Serialize};
use std::future::Future;
use std::pin::Pin;
use thiserror::Error;

/// Future returned by event delivery (no async_trait required).
pub type EventDelivery =
    Pin<Box<dyn Future<Output = Result<(), EventDeliveryError>> + Send + 'static>>;

/// Caller event sink (push-based).
pub trait TransactionEventSink: Send + Sync + 'static {
    /// Deliver one ordered event. Must return promptly with a future.
    fn deliver(&self, event: TransactionEvent) -> EventDelivery;
}

/// Future returned by completion callback.
pub type CompletionDelivery =
    Pin<Box<dyn Future<Output = Result<(), CompletionDeliveryError>> + Send + 'static>>;

/// One-shot completion callback.
pub trait CompletionCallback: Send + 'static {
    /// Invoke exactly once with the terminal result.
    fn call(self: Box<Self>, end: TransactionEnd) -> CompletionDelivery;
}

/// Closure adapter for [`TransactionEventSink`].
pub struct FnEventSink<F>(pub F);

impl<F> TransactionEventSink for FnEventSink<F>
where
    F: Fn(TransactionEvent) -> EventDelivery + Send + Sync + 'static,
{
    fn deliver(&self, event: TransactionEvent) -> EventDelivery {
        (self.0)(event)
    }
}

/// Closure adapter for [`CompletionCallback`].
pub struct FnCompletionCallback<F>(pub F);

impl<F> CompletionCallback for FnCompletionCallback<F>
where
    F: FnOnce(TransactionEnd) -> CompletionDelivery + Send + 'static,
{
    fn call(self: Box<Self>, end: TransactionEnd) -> CompletionDelivery {
        (self.0)(end)
    }
}

/// Runtime v2 submission request — concrete mailboxes, no host traits in-core.
pub struct TransactionSubmitRequest {
    /// Explicit Channel selection.
    pub channel_id: ChannelId,
    /// Existing session when known; `None` for new external create or direct-LLM generate.
    pub session_id: Option<SessionId>,
    /// Canonical input messages.
    pub input: CanonicalInput,
    /// Optional external-agent session configuration.
    pub session_config: Option<SessionConfig>,
    /// Invocation configuration.
    pub invocation_config: InvocationConfig,
    /// Selected host tool ids (deduplicated at admission).
    pub tools: Vec<ToolId>,
    /// Library-created delivery ports (caller holds the receiver half).
    pub delivery: crate::delivery::TransactionDelivery,
}

/// Immediate admission receipt (no network performed).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AdmissionReceipt {
    /// Generated transaction id.
    pub transaction_id: TransactionId,
    /// Session id when already known (direct LLM or existing external).
    pub session_id: Option<SessionId>,
}

/// How to address an in-flight transaction for control.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum TransactionSelector {
    /// By transaction id (valid during external session creation).
    Transaction(TransactionId),
    /// By established session key.
    Session(SessionKey),
}

/// Termination mode.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TerminationMode {
    /// Cooperative cancellation.
    Cancel {
        /// Reason.
        reason: CancellationReason,
    },
    /// Forced terminate.
    ForceTerminate {
        /// Reason.
        reason: TerminationReason,
    },
}

/// Cancellation reason.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CancellationReason {
    /// Closed code.
    pub code: CancellationReasonCode,
    /// Optional safe detail.
    pub detail: Option<SafeDiagnostic>,
}

/// Cancellation reason codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CancellationReasonCode {
    /// Caller requested cancel.
    CallerRequested,
    /// Runtime is shutting down.
    RuntimeShutdown,
}

/// Force-termination reason.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TerminationReason {
    /// Closed code.
    pub code: TerminationReasonCode,
    /// Optional safe detail.
    pub detail: Option<SafeDiagnostic>,
}

/// Termination reason codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TerminationReasonCode {
    /// Caller requested force.
    CallerRequested,
    /// Cancel grace expired.
    CancellationGraceExpired,
    /// Runtime is shutting down.
    RuntimeShutdown,
}

/// Immediate disposition of a terminate request.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TerminationDisposition {
    /// Request accepted.
    Accepted,
    /// Already terminal or already requested.
    AlreadyRequested,
    /// Transaction already terminal.
    AlreadyTerminal,
    /// Unknown selector.
    NotFound,
    /// Control queue was full — request not enqueued (Law 22 fail-closed; D-039).
    ///
    /// This is **not** [`Self::AlreadyTerminal`]: the transaction may still be live.
    ControlCapacityExceeded,
    /// Control queue closed (runtime stopping / stopped) — request not enqueued.
    RuntimeClosed,
}

/// Shutdown future type.
pub type Shutdown = Pin<Box<dyn Future<Output = ShutdownDisposition> + Send + 'static>>;

/// Shutdown summary counts.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct ShutdownDisposition {
    /// Actors finalized normally.
    pub normally_finalized: u64,
    /// Supervisor claimed finalization after abort.
    pub supervisor_finalized: u64,
    /// Callback future failed.
    pub callback_failed: u64,
    /// Callback future aborted at deadline.
    pub callback_aborted: u64,
    /// Invariant failures during shutdown.
    pub invariant_failed: u64,
}

/// Ordered transaction event.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TransactionEvent {
    /// Transaction id.
    pub transaction_id: TransactionId,
    /// Channel id.
    pub channel_id: ChannelId,
    /// Session id (established by this point for ordinary events).
    pub session_id: SessionId,
    /// Contiguous sequence starting at 1, including `Ended`.
    pub sequence: u64,
    /// Payload.
    pub payload: TransactionEventPayload,
}

/// Event payload variants.
///
/// Live assistant text arrives only as [`Self::CanonicalUnit`] (complete units).
/// There is **no** token / delta stream on this port.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TransactionEventPayload {
    /// External session identity established.
    SessionEstablished {
        /// Authoritative external id.
        external_session_id: crate::id::ExternalSessionId,
    },
    /// Complete canonical unit from Interpreter composition (not a token delta).
    CanonicalUnit(CanonicalUnitEvent),
    /// Host tool lifecycle.
    ToolLifecycle(ToolLifecycleEvent),
    /// Safe diagnostic.
    Diagnostic(TransactionDiagnostic),
    /// Terminal event (exactly once) — legacy v1 shape with embedded delivery.
    Ended(TransactionEnd),
    /// Terminal event body without self-referential delivery (Runtime v2).
    EndedEvent(TransactionEndEvent),
}

/// Bounded safe transaction diagnostic.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransactionDiagnostic {
    /// Safe diagnostic.
    pub diagnostic: SafeDiagnostic,
}

/// Terminal transaction result.
///
/// **Legacy (v1):** embeds `event_delivery` inside the terminal event itself.
/// Runtime v2 publishes [`TransactionEndEvent`] on the event stream and reports
/// delivery/cleanup on [`TransactionCompletion`] instead.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransactionEnd {
    /// Transaction id.
    pub transaction_id: TransactionId,
    /// Session when established.
    pub session_id: Option<SessionId>,
    /// Channel.
    pub channel_id: ChannelId,
    /// Terminal kind.
    pub kind: TransactionEndKind,
    /// Prior cause when terminal selection raced (optional).
    pub prior_terminal_cause: Option<TransactionEndKind>,
    /// Whether the terminal event was accepted by the sink.
    pub event_delivery: EventDeliveryOutcome,
    /// Number of events emitted including `Ended`.
    pub emitted_events: u64,
    /// Bounded usage facts.
    pub usage: TransactionUsage,
    /// Safe diagnostics.
    pub diagnostics: Vec<TransactionDiagnostic>,
}

/// Terminal event body for the v2 event stream (no self-referential delivery).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransactionEndEvent {
    /// Transaction id.
    pub transaction_id: TransactionId,
    /// Session when established.
    pub session_id: Option<SessionId>,
    /// Channel.
    pub channel_id: ChannelId,
    /// Terminal kind.
    pub kind: TransactionEndKind,
    /// Number of events emitted including this terminal event.
    pub emitted_events: u64,
    /// Bounded usage facts.
    pub usage: TransactionUsage,
    /// Safe diagnostics.
    pub diagnostics: Vec<TransactionDiagnostic>,
}

/// Outcome of attempting to enqueue the terminal `Ended` event (v2).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TerminalEventDelivery {
    /// Terminal event was accepted by the event mailbox.
    Published,
    /// Event receiver was dropped / channel closed.
    QueueClosed,
    /// Terminal-event budget elapsed before enqueue.
    DeadlineExceeded,
    /// Item or byte capacity rejected the terminal event.
    LimitExceeded,
    /// No publisher / Seal was ever attempted (e.g. shutdown before Start).
    ///
    /// Spec §6.4 / D-041: never-attempted is **not** [`Self::Published`].
    NotAttempted,
}

/// Status of owned cleanup after completion publication (v2).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum CleanupStatus {
    /// All owned tasks/processes have been observed finished.
    Complete,
    /// Completion was published while owned work remains.
    Pending {
        /// Owned Tokio tasks still registered.
        owned_tasks: u32,
        /// Owned child processes still registered.
        owned_processes: u32,
        /// Cooperative in-process tools still outstanding.
        cooperative_tools: u32,
    },
    /// Cleanup failed with a closed code.
    Failed {
        /// Stable cleanup failure code.
        code: CleanupFailureCode,
    },
}

/// Closed cleanup failure codes (v2).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum CleanupFailureCode {
    /// Join observed a panic.
    TaskPanicked,
    /// Process reap failed.
    ProcessReapFailed,
    /// Internal ownership invariant broken.
    InvariantFailed,
}

/// One-shot completion mailbox payload (v2).
///
/// Separates terminal event data from terminal-event delivery and cleanup.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransactionCompletion {
    /// Terminal event body (also published on the event stream when possible).
    pub end: TransactionEndEvent,
    /// Result of the terminal event enqueue attempt, or [`TerminalEventDelivery::NotAttempted`]
    /// when Seal / `Ended` was never issued.
    pub terminal_event_delivery: TerminalEventDelivery,
    /// Whether owned cleanup is complete.
    pub cleanup: CleanupStatus,
}

/// Wait outcome for [`crate`] runtime owner shutdown (v2).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ShutdownWaitOutcome {
    /// Stopped invariants hold; shutdown generation is complete.
    Stopped(ShutdownReport),
    /// Wait deadline elapsed; runtime remains `Quiescing` and retains ownership.
    TimedOut(ShutdownSnapshot),
}

/// Final shutdown report when the runtime reaches `Stopped` (v2).
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct ShutdownReport {
    /// Admitted transactions that received a completion publication attempt.
    pub completions_published: u64,
    /// Completions where the host had dropped its receiver.
    pub completions_receiver_dropped: u64,
    /// Completions that hit an invariant on the sender.
    pub completions_invariant_failed: u64,
    /// Transactions terminated because of runtime shutdown.
    pub runtime_shutdown_terminals: u64,
}

/// Point-in-time shutdown progress while still `Quiescing` (v2).
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct ShutdownSnapshot {
    /// Shutdown generation id (shared by concurrent waiters).
    pub generation: u64,
    /// Ledger entries still present.
    pub ledger_entries: u32,
    /// Owned Tokio tasks still registered.
    pub owned_tasks: u32,
    /// Owned child processes still registered.
    pub owned_processes: u32,
    /// Outstanding MCP routes.
    pub mcp_routes: u32,
    /// Completion publications attempted so far in this generation.
    pub completions_published: u64,
}

/// Closed terminal kinds.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TransactionEndKind {
    /// Successful completion.
    Completed,
    /// Caller must continue (caller-controlled policy).
    ContinuationRequired,
    /// Cancelled.
    Cancelled,
    /// Force-terminated.
    Terminated,
    /// Runtime shutdown.
    RuntimeShutdown,
    /// Deadline exceeded.
    DeadlineExceeded,
    /// Channel open/attach failed.
    ChannelOpenFailed,
    /// Outbound encoding failed.
    EncodingFailed,
    /// Connector failed.
    ConnectorFailed,
    /// Interpretation failed.
    InterpretationFailed,
    /// Tool exchange failed.
    ToolExchangeFailed,
    /// Event delivery failed.
    EventDeliveryFailed,
    /// Resource limit exceeded.
    LimitExceeded,
    /// Internal invariant failed.
    InvariantFailed,
}

/// Terminal event delivery outcome.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum EventDeliveryOutcome {
    /// Sink accepted.
    Accepted,
    /// Sink failed or timed out.
    Failed,
}

/// Bounded usage facts (unavailable is not zero).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct TransactionUsage {
    /// Provider input tokens when known.
    pub provider_input_tokens: Option<u64>,
    /// Provider output tokens when known.
    pub provider_output_tokens: Option<u64>,
    /// Number of provider exchanges.
    pub provider_exchanges: u32,
    /// Number of tool executions started.
    pub tools_started: u32,
    /// Number of tool executions completed (success or domain failure).
    pub tools_completed: u32,
}

/// Event delivery error (safe).
#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum EventDeliveryError {
    /// Sink rejected or failed.
    #[error("event delivery failed")]
    Failed,
    /// Delivery deadline exceeded.
    #[error("event delivery deadline exceeded")]
    DeadlineExceeded,
}

/// Completion callback delivery error (safe).
#[derive(Clone, Debug, Error, PartialEq, Eq)]
pub enum CompletionDeliveryError {
    /// Callback failed.
    #[error("completion callback failed")]
    Failed,
    /// Callback deadline exceeded.
    #[error("completion callback deadline exceeded")]
    DeadlineExceeded,
}

/// Synchronous admission error.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[error("{kind:?}: {message}")]
pub struct AdmissionError {
    /// Closed kind.
    pub kind: AdmissionErrorKind,
    /// Safe bounded message.
    pub message: String,
}

impl AdmissionError {
    /// Construct an admission error.
    pub fn new(kind: AdmissionErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
        }
    }
}

/// Admission error kinds.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AdmissionErrorKind {
    /// Runtime not accepting.
    RuntimeShuttingDown,
    /// Unknown Channel id.
    UnknownChannel,
    /// Session already has an active transaction.
    SessionAlreadyActive,
    /// Unknown tool id.
    UnknownTool,
    /// Duplicate tool id in request.
    DuplicateTool,
    /// Invalid canonical input.
    InvalidInput,
    /// Invalid configuration merge.
    InvalidConfiguration,
    /// Capability mismatch for Channel/tools/session.
    CapabilityMismatch,
    /// Capacity exceeded.
    CapacityExceeded,
    /// Actor spawn failed.
    SpawnFailed,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::input::user_text_input;
    use std::sync::Arc;

    #[test]
    fn end_kind_round_trip() {
        let kind = TransactionEndKind::Completed;
        let json = serde_json::to_string(&kind).unwrap();
        let back: TransactionEndKind = serde_json::from_str(&json).unwrap();
        assert_eq!(kind, back);
    }

    #[tokio::test]
    async fn sink_adapters_return_futures() {
        let sink = FnEventSink(|_e| Box::pin(async { Ok(()) }) as EventDelivery);
        let events: Arc<dyn TransactionEventSink> = Arc::new(sink);
        let end = TransactionEnd {
            transaction_id: TransactionId::generate(),
            session_id: None,
            channel_id: ChannelId::try_new("ch").unwrap(),
            kind: TransactionEndKind::Completed,
            prior_terminal_cause: None,
            event_delivery: EventDeliveryOutcome::Accepted,
            emitted_events: 1,
            usage: TransactionUsage::default(),
            diagnostics: vec![],
        };
        let ev = TransactionEvent {
            transaction_id: end.transaction_id,
            channel_id: end.channel_id.clone(),
            session_id: SessionId::try_new("s").unwrap(),
            sequence: 1,
            payload: TransactionEventPayload::Ended(end.clone()),
        };
        events.deliver(ev).await.unwrap();

        let cb: Box<dyn CompletionCallback> = Box::new(FnCompletionCallback(|_e| {
            Box::pin(async { Ok(()) }) as CompletionDelivery
        }));
        cb.call(end).await.unwrap();

        let _input = user_text_input("hello").unwrap();
    }
}