merry-runtime 0.1.2

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
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
//! Host-side capture and one-shot dream.
//!
//! Maintenance is scheduled after a parent agent loop completes and does not
//! block that loop. A child runtime does not schedule it. Failure is logged
//! and never changes the user-visible turn result.

use std::{
    sync::Arc,
    time::{Duration, SystemTime},
};

use merry_llm::{
    GenerationConfig, ModelContent, ModelInputItem, ModelMessage, ModelMessageRole, ModelRequest,
    ModelResponseFormat, ModelStreamContext, ModelStructuredOutputFormat,
};
use schemars::Schema;
use tokio_util::sync::CancellationToken;

use crate::{
    RuntimeModelRole,
    durable_memory::{
        DurableMemory, DurableMemoryError,
        capture::{self, CaptureOutcome, CaptureWrite},
        condense::{self, count_external_turns},
        dream::{self, CLAIM_LIMIT, dream_should_run},
    },
    model_completion::{ModelCompletionError, complete_single_text},
    model_config::ModelProviderConfig,
    session::TranscriptItemSnapshot,
};

use super::state::RuntimeInner;

const CAPTURE_ATTEMPTS: u32 = 3;
const DREAM_PASSES: u32 = 3;
const CAPTURE_TIMEOUT: Duration = Duration::from_secs(120);
const DREAM_TIMEOUT: Duration = Duration::from_secs(240);
const MAX_OUTPUT_TOKENS: u64 = 16_384;

pub(super) fn schedule(inner: &Arc<RuntimeInner>) {
    if !inner.memory.maintenance_enabled {
        return;
    }
    let Some(memory) = inner.memory.durable.clone() else {
        return;
    };
    let inner = Arc::clone(inner);
    tokio::spawn(async move {
        let _queued = memory.maintenance().lock().await;
        maintain(&inner, &memory).await;
    });
}

async fn maintain(inner: &Arc<RuntimeInner>, memory: &Arc<DurableMemory>) {
    let Some(config) = inner
        .model_config_with_primary_fallback(RuntimeModelRole::SummaryMemory)
        .await
    else {
        tracing::warn!("durable memory maintenance skipped because no model is configured");
        return;
    };
    let (transcript, pruned_external_turns) = {
        let session = inner.session.lock().await;
        (
            session.full_transcript_snapshot(),
            session.pruned_external_turns(),
        )
    };
    let session_id = inner.session_id.as_str().to_owned();
    let turns = pruned_external_turns.saturating_add(count_external_turns(&transcript));
    let cursor = match blocking(Arc::clone(memory), {
        let session_id = session_id.clone();
        move |memory| memory.captured_turns(&session_id)
    })
    .await
    {
        Ok(cursor) => cursor,
        Err(error) => {
            tracing::warn!(error = %error, "durable memory cursor was not read");
            return;
        }
    };
    let scan = match blocking(Arc::clone(memory), |memory| memory.scan_inbox()).await {
        Ok(scan) => scan,
        Err(error) => {
            tracing::warn!(error = %error, "durable memory inbox was not scanned");
            return;
        }
    };
    let needs_capture = turns > cursor;
    let needs_dream = dream_should_run(&scan, SystemTime::now());
    if !needs_capture && !needs_dream {
        return;
    }
    let owner = format!("{}:{session_id}", std::process::id());
    let acquired = match blocking(Arc::clone(memory), {
        let owner = owner.clone();
        move |memory| memory.try_acquire_lease(&owner)
    })
    .await
    {
        Ok(acquired) => acquired,
        Err(error) => {
            tracing::warn!(error = %error, "durable memory lease was not acquired");
            return;
        }
    };
    if !acquired {
        tracing::info!("durable memory maintenance coalesced behind another lease");
        return;
    }
    let _lease = LeaseGuard {
        memory: Arc::clone(memory),
        owner: owner.clone(),
    };
    if needs_capture {
        capture_range(
            memory,
            &config,
            &owner,
            &session_id,
            CaptureSlice {
                transcript: &transcript,
                pruned_external_turns,
                from_turn: cursor.saturating_add(1),
                through_turn: turns,
            },
        )
        .await;
    }
    if needs_dream || capture_added_notes(memory).await {
        consolidate(memory, &config, &owner).await;
    }
}

async fn capture_added_notes(memory: &Arc<DurableMemory>) -> bool {
    match blocking(Arc::clone(memory), |memory| memory.scan_inbox()).await {
        Ok(scan) => dream_should_run(&scan, SystemTime::now()),
        Err(error) => {
            tracing::warn!(error = %error, "durable memory inbox was not rescanned");
            false
        }
    }
}

struct CaptureSlice<'a> {
    transcript: &'a [TranscriptItemSnapshot],
    pruned_external_turns: u32,
    from_turn: u32,
    through_turn: u32,
}

async fn capture_range(
    memory: &Arc<DurableMemory>,
    config: &ModelProviderConfig,
    owner: &str,
    session_id: &str,
    slice: CaptureSlice<'_>,
) {
    let CaptureSlice {
        transcript,
        pruned_external_turns,
        from_turn,
        through_turn,
    } = slice;
    if blocking(Arc::clone(memory), {
        let session_id = session_id.to_owned();
        move |memory| Ok(memory.observation_exists(&session_id, from_turn, through_turn))
    })
    .await
    .unwrap_or(false)
    {
        advance_cursor(memory, session_id, through_turn).await;
        return;
    }
    for attempt in 1..=CAPTURE_ATTEMPTS {
        if !refresh_lease(memory, owner).await {
            return;
        }
        let condensed = match condense::condense_turn_range_with_offset(
            transcript,
            pruned_external_turns,
            from_turn,
            through_turn,
        ) {
            Ok(condensed) => condensed,
            Err(error) => {
                tracing::warn!(error = %error, "durable memory transcript was not condensed");
                advance_cursor(memory, session_id, through_turn).await;
                return;
            }
        };
        let (system, user) = capture::extraction_request_text(
            condensed.note.as_deref(),
            session_id,
            from_turn,
            through_turn,
            &condensed.json,
        );
        let text = match complete_memory(
            config,
            "memory_capture",
            capture::extraction_schema(),
            &system,
            &user,
            CAPTURE_TIMEOUT,
        )
        .await
        {
            Ok(text) => text,
            Err(error) => {
                tracing::warn!(attempt, error = %error, "durable memory capture attempt failed");
                continue;
            }
        };
        match capture::parse_model_outcome(&text) {
            Ok(CaptureOutcome::Noop) => {
                advance_cursor(memory, session_id, through_turn).await;
                return;
            }
            Ok(CaptureOutcome::Observations(observations)) => {
                let model = config.model().as_str().to_owned();
                let session_owned = session_id.to_owned();
                let job_id = format!("capture-{session_owned}-{from_turn}-{through_turn}");
                let committed = blocking(Arc::clone(memory), move |memory| {
                    let write = CaptureWrite {
                        session_id: &session_owned,
                        from_turn,
                        through_turn,
                        extraction_model: &model,
                        created_at: i64::try_from(crate::durable_memory::state::unix_now())
                            .unwrap_or(i64::MAX),
                        job_id: &job_id,
                        observations: &observations,
                    };
                    memory.commit_capture(&write)
                })
                .await;
                match committed {
                    Ok(()) => {
                        advance_cursor(memory, session_id, through_turn).await;
                        return;
                    }
                    Err(error) => {
                        tracing::warn!(
                            attempt,
                            error = %error,
                            "durable memory observations were not written"
                        );
                    }
                }
            }
            Err(error) => {
                tracing::warn!(attempt, error = %error, "durable memory extraction was rejected");
            }
        }
    }
    tracing::warn!(
        from_turn,
        through_turn,
        "durable memory dropped an uncaptured turn after the final attempt"
    );
    advance_cursor(memory, session_id, through_turn).await;
}

async fn consolidate(memory: &Arc<DurableMemory>, config: &ModelProviderConfig, owner: &str) {
    for _pass in 0..DREAM_PASSES {
        if !refresh_lease(memory, owner).await {
            return;
        }
        let scan = match blocking(Arc::clone(memory), |memory| memory.scan_inbox()).await {
            Ok(scan) => scan,
            Err(error) => {
                tracing::warn!(error = %error, "durable memory dream scan failed");
                return;
            }
        };
        if !dream_should_run(&scan, SystemTime::now()) {
            return;
        }
        let claimed = scan
            .eligible
            .into_iter()
            .take(CLAIM_LIMIT)
            .collect::<Vec<_>>();
        if claimed.is_empty() {
            return;
        }
        let input = match blocking(Arc::clone(memory), {
            let claimed = claimed.clone();
            move |memory| memory.dream_input(&claimed)
        })
        .await
        {
            Ok(input) => input,
            Err(error) => {
                tracing::warn!(error = %error, "durable memory dream input was not built");
                return;
            }
        };
        let text = match complete_memory(
            config,
            "memory_dream",
            dream::dream_plan_schema(),
            dream::DREAM_SYSTEM_PROMPT,
            &input,
            DREAM_TIMEOUT,
        )
        .await
        {
            Ok(text) => text,
            Err(error) => {
                tracing::warn!(error = %error, "durable memory dream model call failed");
                return;
            }
        };
        match blocking(Arc::clone(memory), {
            let claimed = claimed.clone();
            let text = text.clone();
            move |memory| memory.apply_dream(&claimed, &text)
        })
        .await
        {
            Ok(operations) => {
                tracing::info!(
                    operations,
                    notes = claimed.len(),
                    "durable memory dream applied"
                );
            }
            Err(error) => {
                tracing::warn!(error = %error, "durable memory dream plan was rejected");
                return;
            }
        }
    }
}

async fn advance_cursor(memory: &Arc<DurableMemory>, session_id: &str, through_turn: u32) {
    let session_id = session_id.to_owned();
    if let Err(error) = blocking(Arc::clone(memory), move |memory| {
        memory.set_captured_turns(&session_id, through_turn)
    })
    .await
    {
        tracing::warn!(error = %error, "durable memory cursor was not advanced");
    }
}

async fn refresh_lease(memory: &Arc<DurableMemory>, owner: &str) -> bool {
    let owner = owner.to_owned();
    match blocking(Arc::clone(memory), move |memory| {
        memory.try_acquire_lease(&owner)
    })
    .await
    {
        Ok(true) => true,
        Ok(false) => {
            tracing::info!("durable memory lease was lost");
            false
        }
        Err(error) => {
            tracing::warn!(error = %error, "durable memory lease was not refreshed");
            false
        }
    }
}

async fn complete_memory(
    config: &ModelProviderConfig,
    schema_name: &str,
    schema: serde_json::Value,
    system: &str,
    user: &str,
    timeout: Duration,
) -> Result<String, String> {
    let schema =
        Schema::try_from(schema).map_err(|error| format!("memory schema was invalid: {error}"))?;
    let format =
        ModelStructuredOutputFormat::new(schema_name, schema).map_err(|error| error.to_string())?;
    let system_message = ModelInputItem::Message(
        ModelMessage::new(
            ModelMessageRole::System,
            ModelContent::text(system).map_err(|error| error.to_string())?,
        )
        .map_err(|error| error.to_string())?,
    );
    let user_message = ModelInputItem::Message(
        ModelMessage::new(
            ModelMessageRole::User,
            ModelContent::text(user).map_err(|error| error.to_string())?,
        )
        .map_err(|error| error.to_string())?,
    );
    let request = ModelRequest::new_with_input_and_stable_prefix_and_response_format(
        config.model().clone(),
        vec![system_message, user_message],
        Vec::new(),
        GenerationConfig::new(Some(MAX_OUTPUT_TOKENS), false).map_err(|error| error.to_string())?,
        1,
        Some(ModelResponseFormat::StructuredOutput(format)),
    )
    .map_err(|error| error.to_string())?;
    let token = CancellationToken::new();
    let provider = config.provider();
    let completion = complete_single_text(
        provider.as_ref(),
        request,
        ModelStreamContext::new(token.clone()),
        &token,
    );
    match tokio::time::timeout(timeout, completion).await {
        Ok(Ok(text)) => Ok(text),
        Ok(Err(error)) => Err(completion_error(&error)),
        Err(_) => Err("memory model call timed out".to_owned()),
    }
}

fn completion_error(error: &ModelCompletionError) -> String {
    match error {
        ModelCompletionError::Cancelled => "memory model call was cancelled".to_owned(),
        ModelCompletionError::Setup { message, .. }
        | ModelCompletionError::Stream { message, .. } => message.clone(),
        ModelCompletionError::ToolCallRequested => "memory model requested a tool".to_owned(),
        ModelCompletionError::NonStopFinish { finish_reason, .. } => {
            format!("memory model finished with {finish_reason:?}")
        }
        ModelCompletionError::NotSingleText => {
            "memory model did not return one text answer".to_owned()
        }
        ModelCompletionError::EndedBeforeCompletion => "memory model stream ended early".to_owned(),
    }
}

async fn blocking<T: Send + 'static>(
    memory: Arc<DurableMemory>,
    work: impl FnOnce(&DurableMemory) -> Result<T, DurableMemoryError> + Send + 'static,
) -> Result<T, DurableMemoryError> {
    match tokio::task::spawn_blocking(move || work(&memory)).await {
        Ok(result) => result,
        Err(_) => Err(DurableMemoryError::Denied {
            message: "memory task stopped".to_owned(),
        }),
    }
}

struct LeaseGuard {
    memory: Arc<DurableMemory>,
    owner: String,
}

impl Drop for LeaseGuard {
    fn drop(&mut self) {
        if let Err(error) = self.memory.release_lease(&self.owner) {
            tracing::warn!(error = %error, "durable memory lease was not released");
        }
    }
}