loopctl 0.2.1

A trait-based framework for building agent loops with pluggable LLM clients, tools, and memory
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
//! Named runtime profiles for `BareLoop`.
//!
//! A [`ConstrainedProfile`] bundles the small-model reliability machinery —
//! verify-on-write, tool-call memoization, output truncation, goal
//! re-injection, and strict tool-call decoding — behind one type, so a
//! consumer gets "small-model-ready by default" without per-feature wiring.
//! [`FrontierProfile`] is the named opt-out: v0.1.0-style defaults with none
//! of the small-model machinery installed.
//!
//! Apply a profile with [`ConstrainedProfile::apply`] (pipeline + contributor)
//! or compose the individual pieces ([`ConstrainedProfile::session_config`],
//! [`ConstrainedProfile::run_config`],
//! [`ConstrainedProfile::pipeline_builder`],
//! [`ConstrainedProfile::request_options`]) by hand.
//!
//! # Example
//!
//! ```rust,ignore
//! use loopctl::engine::BareLoop;
//! use loopctl::presets::ConstrainedProfile;
//! use loopctl::tool::ToolRegistry;
//! use std::sync::Arc;
//!
//! // `client` is any ApiClient impl; `registry` is your tool set.
//! let mut agent = BareLoop::new(client, registry, ConstrainedProfile::session_config());
//! agent.set_request_options(ConstrainedProfile::request_options());
//! ConstrainedProfile::apply(&mut agent).unwrap();
//! ```

use std::sync::Arc;

use crate::config::SessionConfig;
use crate::engine::RunConfig;
use crate::engine::{BareLoop, ContextContributor, ContributorContext};
use crate::error::LoopError;
use crate::message::{Message, MessagePart, Role};
use crate::middleware::{
    MemoizingMiddleware, NoopPathExtractor, NoopVerifier, OutputLimitMiddleware, ToolPipeline,
    VerifyMiddleware,
};
use crate::structured::{RequestOptions, ToolConstraint};

/// Default per-tool-output cap (characters) applied by `OutputLimitMiddleware`.
const OUTPUT_CAP_CHARS: usize = 16_384;
/// Default cache TTL (turns) for the preset's `MemoizingMiddleware`.
const MEMOIZE_TTL_TURNS: u32 = 5;
/// Default reminder cadence (turns) for [`GoalReminder`].
const GOAL_REMINDER_EVERY_N_TURNS: usize = 5;
/// Default write-class tool names the preset wires into its middleware. Advisory.
const WRITE_TOOLS: &[&str] = &["Write", "Edit", "MultiEdit"];
/// Default memoized tool names the preset wires into its middleware. Advisory.
const MEMOIZED_TOOLS: &[&str] = &["Read", "Glob", "Grep", "LS"];

/// The small-model-tuned runtime profile.
///
/// Bundles aggressive context budgeting (smaller window, fewer turns),
/// verify-on-write ([`VerifyMiddleware`] with [`NoopVerifier`]),
/// tool-call memoization ([`MemoizingMiddleware`] with [`NoopPathExtractor`]),
/// output truncation ([`OutputLimitMiddleware`]), goal re-injection
/// ([`GoalReminder`]), and strict tool-call decoding
/// ([`ToolConstraint::Strict`]) into one coherent profile.
///
/// This is the harder-problem profile: it assumes the model drifts off-goal,
/// repeats tool calls, ships broken edits, and emits malformed tool
/// arguments, and installs machinery that catches each. Frontier models
/// tolerate the same defaults fine; use [`FrontierProfile`] to opt out.
///
/// The no-op verifier and path extractor are wired by default so the profile
/// is functional out of the box — but no actual verification or path-based
/// cache invalidation happens until you swap in real impls. The verify
/// middleware still registers and the cache still works by TTL; replacing
/// [`NoopVerifier`] with `cargo check` / `tsc` and [`NoopPathExtractor`] with
/// a path-aware extractor is the intended upgrade path.
pub struct ConstrainedProfile;

impl ConstrainedProfile {
    /// A [`SessionConfig`] tuned for a small model.
    ///
    /// Sets a smaller context window than the default — small models degrade
    /// faster as context fills, so the window is tightened. Compaction
    /// threshold is unchanged (tightness comes from the window, not from
    /// compacting earlier).
    ///
    /// Value: `context_window = 32_768`.
    #[must_use]
    pub fn session_config() -> SessionConfig {
        SessionConfig::default().with_context_window(32_768)
    }

    /// A [`RunConfig`] tuned for a small model.
    ///
    /// Fewer max turns than the default, since small models are more prone to
    /// non-converging tool loops. All other run-scoped knobs stay at their
    /// defaults.
    ///
    /// Value: `max_turns = 100`.
    #[must_use]
    pub fn run_config() -> RunConfig {
        RunConfig {
            max_turns: 100,
            ..RunConfig::default()
        }
    }

    /// A [`ToolPipeline`] builder pre-loaded with the small-model middleware stack.
    ///
    /// Middleware order (execution order, outermost last): verify → memoize
    /// → output-limit. Verify's appended diagnostics flow through memoize
    /// (cached alongside the result) and then through the output cap
    /// (truncated if the combined output exceeds the cap).
    ///
    /// No `.with_core()` is set — pass the result to
    /// [`BareLoop::set_pipeline`], which attaches the tool registry.
    #[must_use]
    pub fn pipeline_builder() -> crate::middleware::ToolPipelineBuilder {
        ToolPipeline::builder()
            .with_middleware(VerifyMiddleware::new(
                Arc::new(NoopVerifier),
                WRITE_TOOLS.iter().map(|s| (*s).to_string()).collect(),
            ))
            .with_middleware(MemoizingMiddleware::new(
                MEMOIZED_TOOLS.iter().map(|s| (*s).to_string()).collect(),
                WRITE_TOOLS.iter().map(|s| (*s).to_string()).collect(),
                Arc::new(NoopPathExtractor),
                MEMOIZE_TTL_TURNS,
            ))
            .with_middleware(OutputLimitMiddleware::new(OUTPUT_CAP_CHARS))
    }

    /// [`RequestOptions`] requesting strict tool-call decoding.
    ///
    /// Apply via [`BareLoop::set_request_options`] so the constraint reaches
    /// the provider on every turn.
    #[must_use]
    pub fn request_options() -> RequestOptions {
        RequestOptions::new().with_tool_constraint(ToolConstraint::Strict)
    }

    /// Apply the profile's pipeline and goal-reminder contributor to a
    /// [`BareLoop`].
    ///
    /// Sets the small-model middleware stack (via [`Self::pipeline_builder`]) and
    /// registers a [`GoalReminder`] firing every 5 turns. Does **not** set
    /// the loop's config or request options — those are set separately at
    /// construction (`BareLoop::new`) and via
    /// [`BareLoop::set_request_options`].
    ///
    /// # Errors
    ///
    /// Returns [`LoopError`] if [`BareLoop::set_pipeline`] fails.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use loopctl::engine::BareLoop;
    /// use loopctl::presets::ConstrainedProfile;
    /// use loopctl::tool::ToolRegistry;
    /// use std::sync::Arc;
    ///
    /// // `client` is any ApiClient impl.
    /// let mut agent = BareLoop::new(Arc::new(client), ToolRegistry::new(), ConstrainedProfile::session_config());
    /// ConstrainedProfile::apply(&mut agent).unwrap();
    /// ```
    pub fn apply<C: crate::api::ApiClient>(loop_: &mut BareLoop<C>) -> Result<(), LoopError> {
        loop_.set_pipeline(Self::pipeline_builder())?;
        loop_.add_contributor(Box::new(GoalReminder::new(GOAL_REMINDER_EVERY_N_TURNS)));
        Ok(())
    }
}

/// The frontier-opt-out profile.
///
/// Produces default session/run configuration, no small-model
/// middleware, no tool-call constraint. Named (rather than just "don't use
/// [`ConstrainedProfile`]") so the opt-out is explicit and discoverable.
pub struct FrontierProfile;

impl FrontierProfile {
    /// A default [`SessionConfig`] — no small-model tightening.
    ///
    /// Literally [`SessionConfig::default`]: the full context budget
    /// (200k window). The opt-out counterpart to
    /// [`ConstrainedProfile::session_config`](ConstrainedProfile::session_config);
    /// the two are swap-in replacements at the call site.
    #[must_use]
    pub fn session_config() -> SessionConfig {
        SessionConfig::default()
    }

    /// A default [`RunConfig`] — no small-model tightening.
    ///
    /// Literally [`RunConfig::default`]: the full turn/token budget
    /// (200 turns). The opt-out counterpart to
    /// [`ConstrainedProfile::run_config`](ConstrainedProfile::run_config).
    #[must_use]
    pub fn run_config() -> RunConfig {
        RunConfig::default()
    }

    /// An empty middleware pipeline — no small-model middleware installed.
    ///
    /// Returns a bare [`ToolPipeline::builder()`] with nothing wired; pass it
    /// to [`BareLoop::set_pipeline`] to get the plain v0.1.0 tool-dispatch
    /// path (no verify-on-write, no memoization, no output cap). The opt-out
    /// counterpart to
    /// [`ConstrainedProfile::pipeline_builder`](ConstrainedProfile::pipeline_builder).
    #[must_use]
    pub fn pipeline_builder() -> crate::middleware::ToolPipelineBuilder {
        ToolPipeline::builder()
    }

    /// Default [`RequestOptions`] — no tool-call constraint.
    ///
    /// Literally [`RequestOptions::default`] (`tool_constraint: None`), so
    /// tool calls are unconstrained. The opt-out counterpart to
    /// [`ConstrainedProfile::request_options`](ConstrainedProfile::request_options)
    /// (which sets `Strict`); apply via [`BareLoop::set_request_options`].
    #[must_use]
    pub fn request_options() -> RequestOptions {
        RequestOptions::default()
    }
}

/// A [`ContextContributor`] that re-injects the first user message as a
/// [`Role::System`] reminder every `n` turns.
///
/// Small models drift off-goal after several turns of tool calling.
/// Re-emitting the original request periodically keeps the model anchored to
/// what the user actually asked for. The reminder text is the **first**
/// [`Role::User`] message in the conversation, taken verbatim — the first
/// thing the user asked is a reasonable goal proxy and avoids parsing user
/// prose.
///
/// Construct with [`GoalReminder::new`], or get a default-cadence one via
/// [`ConstrainedProfile::apply`].
pub struct GoalReminder {
    /// Reminder cadence in turns. The reminder fires when
    /// `turn > 0 && turn % every_n_turns == 0`.
    every_n_turns: usize,
}

impl GoalReminder {
    /// Create a goal reminder that fires every `every_n_turns` turns.
    ///
    /// `every_n_turns` of 0 or 1 disables the cadence guard; with 0 the
    /// reminder never fires (turn 0 is always skipped), with 1 it fires on
    /// every turn after the first. Sensible values are 3–10.
    #[must_use]
    pub fn new(every_n_turns: usize) -> Self {
        Self { every_n_turns }
    }
}

impl ContextContributor for GoalReminder {
    fn contribute(&self, ctx: &ContributorContext<'_>) -> Option<Message> {
        // Skip turn 0 — the user's message is fresh context, no reminder yet.
        if ctx.turn == 0 || self.every_n_turns == 0 {
            return None;
        }

        if !ctx.turn.is_multiple_of(self.every_n_turns) {
            return None;
        }

        // Find the first user message and re-emit its text verbatim.
        let first_user_text = ctx.conversation.iter().find_map(|m| {
            if !matches!(m.role, Role::User) {
                return None;
            }
            let texts: Vec<&str> = m
                .parts
                .iter()
                .filter_map(|p| match p {
                    MessagePart::Text { text } => Some(text.as_str()),
                    _ => None,
                })
                .collect();
            if texts.is_empty() {
                None
            } else {
                Some(texts.join("\n"))
            }
        })?;
        Some(Message::new(
            Role::System,
            vec![MessagePart::text(first_user_text)],
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_constrained_config_values() {
        let session = ConstrainedProfile::session_config();
        assert_eq!(session.context_window, 32_768);

        let run = ConstrainedProfile::run_config();
        assert_eq!(run.max_turns, 100);
    }

    #[test]
    fn test_constrained_request_options_strict() {
        let opts = ConstrainedProfile::request_options();
        assert!(matches!(opts.tool_constraint, ToolConstraint::Strict));
        assert!(opts.response_format.is_none());
    }

    #[test]
    fn test_frontier_config_matches_default() {
        let session = FrontierProfile::session_config();
        assert_eq!(
            session.context_window,
            SessionConfig::default().context_window
        );

        let run = FrontierProfile::run_config();
        let default = RunConfig::default();
        assert_eq!(run.max_turns, default.max_turns);
    }

    #[test]
    fn test_frontier_request_options_default() {
        let opts = FrontierProfile::request_options();
        assert!(matches!(opts.tool_constraint, ToolConstraint::None));
        assert!(opts.response_format.is_none());
    }

    fn ctx_at(turn: usize, conv: &[Message]) -> ContributorContext<'_> {
        ContributorContext::new(turn, conv)
    }

    #[test]
    fn test_goal_reminder_skips_turn_zero() {
        let reminder = GoalReminder::new(5);
        let conv = [Message::user("ship the demo")];
        let ctx = ctx_at(0, &conv);
        assert!(
            reminder.contribute(&ctx).is_none(),
            "turn 0 must be skipped"
        );
    }

    #[test]
    fn test_goal_reminder_never_fires_when_n_is_zero() {
        let reminder = GoalReminder::new(0);
        let conv = [Message::user("ship the demo")];
        // Even on a multiple-of-0-ish turn, n=0 disables firing.
        let ctx = ctx_at(5, &conv);
        assert!(
            reminder.contribute(&ctx).is_none(),
            "n=0 disables the reminder"
        );
    }

    #[test]
    fn test_goal_reminder_fires_every_n_turns() {
        let reminder = GoalReminder::new(5);
        let conv = [Message::user("goal")];
        for turn in [1, 2, 3, 4, 6, 7, 8, 9, 11] {
            let ctx = ctx_at(turn, &conv);
            assert!(
                reminder.contribute(&ctx).is_none(),
                "turn {turn} must not fire (cadence 5)"
            );
        }
        for turn in [5, 10, 15, 20] {
            let ctx = ctx_at(turn, &conv);
            assert!(
                reminder.contribute(&ctx).is_some(),
                "turn {turn} must fire (cadence 5)"
            );
        }
    }

    #[test]
    fn test_goal_reminder_injects_first_user_message_verbatim() {
        let reminder = GoalReminder::new(5);
        let conv = [
            Message::assistant("hi"),                   // not a user message
            Message::user("ship the demo"),             // first user message
            Message::user("a later unrelated request"), // must NOT be picked
        ];
        let ctx = ctx_at(5, &conv);
        let msg = reminder.contribute(&ctx).expect("turn 5 fires");
        assert_eq!(msg.role, Role::System);
        // The reminder text is the FIRST user message, verbatim.
        match &msg.parts[0] {
            MessagePart::Text { text } => assert_eq!(text, "ship the demo"),
            other => panic!("expected Text part, got {other:?}"),
        }
    }

    #[test]
    fn test_goal_reminder_returns_none_with_no_user_message() {
        let reminder = GoalReminder::new(5);
        let conv = [Message::assistant("no user here")];
        let ctx = ctx_at(5, &conv);
        assert!(
            reminder.contribute(&ctx).is_none(),
            "no user message → no reminder, even on a firing turn"
        );
    }

    #[test]
    fn test_goal_reminder_handles_multi_part_first_user_message() {
        // A first user message with multiple text parts: they are joined
        // with newlines into a single reminder.
        let reminder = GoalReminder::new(1);
        let conv = [Message::new(
            Role::User,
            vec![MessagePart::text("line one"), MessagePart::text("line two")],
        )];
        let ctx = ctx_at(1, &conv);
        let msg = reminder.contribute(&ctx).expect("turn 1 fires (cadence 1)");
        match &msg.parts[0] {
            MessagePart::Text { text } => {
                assert_eq!(text, "line one\nline two");
            }
            other => panic!("expected Text part, got {other:?}"),
        }
    }
}