polyc-agent 2026.7.1

The agent turn loop: provider + tool-call routing, shared by the control plane and harness.
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
//! LLM-backed anchored-iterative [`Summarizer`].
//!
//! The agent crate's [`StubSummarizer`](crate::StubSummarizer) keeps the
//! summarization data path live without a provider. This module is the
//! one-trait swap-in that lands actual compression on long conversations.
//!
//! # Design
//!
//! Anchored iterative summarization (cf. Factory's 36k-message engineering-
//! session eval): each compaction *merges* into the prior summary rather than
//! re-summarizing the whole transcript from scratch. The prior summary is the
//! persistent state that survives every subsequent compaction; the new
//! transcript chunk is the delta. This preserves identifiers, commitments,
//! decisions and errors across compactions instead of losing them as the
//! window slides past them.
//!
//! # Failure mode
//!
//! Provider errors and missing-output are handled fail-soft: the summarizer
//! returns the existing `prior_summary` unchanged and logs a `warn`. The next
//! compaction will retry on the new transcript, and crucially the anchor is
//! never lost. If we returned an empty string on failure the next
//! `reconstruct_history` would still find the *previous* `summary:{uuid}`
//! event in the journal — but a subsequent successful compaction would then
//! anchor against a stale prior, so failing soft to the anchor is the safe
//! shape.

use std::sync::Arc;

use async_trait::async_trait;
use polyc_llm::{
    CompletionRequest, Content as LlmContent, LlmProvider, Message as LlmMessage, Role,
    turn::collect_turn,
};

use crate::Summarizer;

/// System prompt used by [`LlmSummarizer`].
///
/// Pinned in source (not a config knob) so on-disk summaries are reproducible:
/// the prompt that produced a given summary is the prompt encoded in the
/// shipped binary at that revision. If we ever need to evolve this we'll bump
/// it explicitly and accept that older summaries were produced under a prior
/// prompt — that's a feature, not a bug, for the eval story.
const SYSTEM_PROMPT: &str = "You compress agent transcripts for long-running conversations. \
You receive (a) a PRIOR_SUMMARY representing the conversation so far, and \
(b) a TRANSCRIPT chunk that just happened. \
Produce a NEW_SUMMARY that fully replaces PRIOR_SUMMARY going forward: it \
must preserve every commitment, identifier, decision, error, and unresolved \
question from PRIOR_SUMMARY, then merge in the new content from TRANSCRIPT. \
Be terse. No preamble. Maximum 500 words. Do not invent facts. \
Describe tool calls and results in plain prose; never reproduce raw \
[tool_call …] or [tool_result …] markers or verbatim JSON.";

/// Provider-backed anchored-iterative [`Summarizer`].
///
/// Wraps any [`LlmProvider`] behind the trait the control plane already
/// consumes. The control plane builds one of these from whatever provider it
/// instantiated for turns and injects it via `AgentSvc::with_summarizer`.
///
/// # Fields
///
/// - `provider` — the same trait the turn loop uses; sharing one `Arc` keeps
///   pooled connections / auth state hot across turns *and* summarizations.
/// - `model` — kept separate from the turn's model so production can point
///   summarization at a cheaper / smaller model (e.g. flash-lite vs flash)
///   without coupling the two upgrade paths.
/// - `max_output_tokens` — cap on the generated summary. The prompt asks for
///   "≤500 words" but the provider is the final guard; the cap is here to
///   protect against a runaway provider regardless of the prompt.
pub struct LlmSummarizer<P: ?Sized> {
    /// The provider used to run the summarization completion.
    provider: Arc<P>,
    /// Model identifier sent to the provider for summarization calls.
    model: String,
    /// Hard cap on output tokens; the prompt also asks for ≤500 words.
    max_output_tokens: u64,
}

impl<P: ?Sized> LlmSummarizer<P> {
    /// Build a new [`LlmSummarizer`] over an existing provider.
    pub fn new(provider: Arc<P>, model: impl Into<String>, max_output_tokens: u64) -> Self {
        Self {
            provider,
            model: model.into(),
            max_output_tokens,
        }
    }
}

/// Per-tool-call byte budgets for the summarizer transcript. Generous enough to
/// keep the identifiers, URLs, statuses and errors a summary must preserve, yet
/// bounded so one fat payload can't dominate the chunk fed to the (small)
/// summary model. Results carry the durable facts, so they get the larger
/// budget; args (inputs) are usually short and reconstructable from context.
/// Both stay well under the upstream 16 KiB per-tool-result cap in
/// [`crate`]'s tool loop, which already bounds what reaches history.
const TOOL_ARGS_CLIP_BYTES: usize = 1_024;
const TOOL_RESULT_CLIP_BYTES: usize = 4_096;

/// Clip an embedded JSON blob so one fat tool payload can't dominate the
/// transcript (or be parroted wholesale by a cheap summarizer). Truncates on a
/// UTF-8 char boundary at or below `max_bytes` in a single pass and notes how
/// many bytes were dropped. Mirrors the char-boundary clip the control plane
/// uses in `compaction_preview`.
fn clip(s: &str, max_bytes: usize) -> String {
    if s.len() <= max_bytes {
        return s.to_owned();
    }
    // Largest char boundary <= max_bytes (`str::floor_char_boundary` is still
    // unstable, so walk back the few bytes by hand).
    let mut end = max_bytes;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    format!("{}… ({} bytes omitted)", &s[..end], s.len() - end)
}

/// Render a transcript slice into the user-message body — one `role: text`
/// line per message. Non-text content is rendered as a stable marker so the
/// model sees the call/result happened without us fabricating its content.
fn render_transcript(transcript: &[LlmMessage]) -> String {
    let mut s = String::new();
    for msg in transcript {
        let role = match msg.role {
            Role::Assistant => "assistant",
            Role::Tool => "tool",
            Role::System => "system",
            // `Role` is `#[non_exhaustive]`; default any future variant to
            // `user` so the model still sees the message rather than us
            // refusing to render it.
            _ => "user",
        };
        for content in &msg.content {
            match content {
                LlmContent::Text(t) => {
                    s.push_str(role);
                    s.push_str(": ");
                    s.push_str(t);
                    s.push('\n');
                }
                LlmContent::ToolUse(tc) => {
                    s.push_str(role);
                    s.push_str(": called tool ");
                    s.push_str(&tc.name);
                    s.push('(');
                    s.push_str(&clip(&tc.args_json, TOOL_ARGS_CLIP_BYTES));
                    s.push_str(")\n");
                }
                LlmContent::ToolResult(tr) => {
                    // Keep the call id so the summarizer can pair a result to
                    // its call when several tool calls interleave in one folded
                    // turn (parallel tool use). It is a plain id, not a marker.
                    s.push_str(role);
                    s.push_str(": tool result for ");
                    s.push_str(&tr.tool_call_id);
                    s.push_str("");
                    s.push_str(&clip(&tr.result_json, TOOL_RESULT_CLIP_BYTES));
                    s.push('\n');
                }
                LlmContent::Image(_) => {
                    s.push_str(role);
                    s.push_str(": [image]\n");
                }
                // `Content` is `#[non_exhaustive]`; if a future variant lands
                // (audio, video, …) we render a placeholder rather than
                // refusing to summarize and stalling the journal.
                _ => {
                    s.push_str(role);
                    s.push_str(": [unknown]\n");
                }
            }
        }
    }
    s
}

#[async_trait]
impl<P> Summarizer for LlmSummarizer<P>
where
    P: LlmProvider + Send + Sync + ?Sized,
{
    #[tracing::instrument(
        skip_all,
        fields(
            model = %self.model,
            transcript_messages = transcript.len(),
            prior_summary_len = prior_summary.len(),
        ),
    )]
    async fn summarize(&self, prior_summary: &str, transcript: &[LlmMessage]) -> String {
        // Empty-input shortcut: nothing to compress and no anchor to preserve.
        if transcript.is_empty() && prior_summary.is_empty() {
            return String::new();
        }

        let prior_block = if prior_summary.is_empty() {
            "(none — first compaction)".to_owned()
        } else {
            prior_summary.to_owned()
        };
        let transcript_block = if transcript.is_empty() {
            "(empty)".to_owned()
        } else {
            render_transcript(transcript)
        };
        let user_text = format!("PRIOR_SUMMARY:\n{prior_block}\n\nTRANSCRIPT:\n{transcript_block}");

        let mut req = CompletionRequest::new(&self.model);
        req.system = Some(SYSTEM_PROMPT.to_owned());
        req.messages.push(LlmMessage::user(user_text));
        // Cap output to bound the journal write and protect against runaway
        // providers. `max_tokens` is u32 on the request; saturate the cast.
        req.max_tokens = Some(u32::try_from(self.max_output_tokens).unwrap_or(u32::MAX));
        // Low temperature for compaction: summarization is a deterministic
        // rewriting task, not a creative one.
        req.temperature = Some(0.2);

        match self.provider.complete(req).await {
            Ok(stream) => match collect_turn(stream).await {
                Ok(out) => {
                    let trimmed = out.text.trim();
                    if trimmed.is_empty() {
                        tracing::warn!("summarizer received empty output; keeping prior summary");
                        prior_summary.to_owned()
                    } else {
                        trimmed.to_owned()
                    }
                }
                Err(err) => {
                    tracing::warn!(error = %err, "summarizer stream error; keeping prior summary");
                    prior_summary.to_owned()
                }
            },
            Err(err) => {
                tracing::warn!(error = %err, "summarizer provider error; keeping prior summary");
                prior_summary.to_owned()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;
    use async_trait::async_trait;
    use futures::{StreamExt, stream};
    use polyc_llm::{Chunk, CompletionRequest, LlmProvider, StopReason, error::DummyError};
    use std::sync::Mutex;

    /// Provider that returns a fixed canned text. Used to verify the
    /// summarizer wires through provider → collect_turn → string.
    struct CannedProvider {
        text: String,
        seen: Mutex<Option<CompletionRequest>>,
    }

    impl CannedProvider {
        fn new(text: &str) -> Self {
            Self {
                text: text.to_owned(),
                seen: Mutex::new(None),
            }
        }
    }

    #[async_trait]
    impl LlmProvider for CannedProvider {
        type Error = DummyError;

        async fn complete(
            &self,
            req: CompletionRequest,
        ) -> Result<futures::stream::BoxStream<'static, Result<Chunk, Self::Error>>, Self::Error>
        {
            *self.seen.lock().unwrap() = Some(req);
            let chunks = vec![
                Ok(Chunk::text_delta(self.text.clone())),
                Ok(Chunk::Stop(StopReason::EndTurn)),
            ];
            Ok(stream::iter(chunks).boxed())
        }
    }

    /// Provider that always returns a pre-stream error. Used to verify the
    /// fail-soft path returns `prior_summary` unchanged.
    struct ErroringProvider;

    #[async_trait]
    impl LlmProvider for ErroringProvider {
        type Error = DummyError;

        async fn complete(
            &self,
            _req: CompletionRequest,
        ) -> Result<futures::stream::BoxStream<'static, Result<Chunk, Self::Error>>, Self::Error>
        {
            Err(DummyError::Other("nope".to_owned()))
        }
    }

    #[tokio::test]
    async fn returns_provider_output_trimmed() {
        let provider = Arc::new(CannedProvider::new("  the new summary  "));
        let summ = LlmSummarizer::new(provider.clone(), "test-model", 1024);
        let prior = "prior anchor";
        let transcript = vec![LlmMessage::user("hi"), LlmMessage::assistant("hello")];
        let out = summ.summarize(prior, &transcript).await;
        assert_eq!(out, "the new summary");
        // The provider saw a request shaped as expected: a system prompt,
        // one user message, and the configured model + cap.
        let seen = provider.seen.lock().unwrap().clone().expect("request seen");
        assert_eq!(seen.model, "test-model");
        assert!(seen.system.is_some_and(|s| s.contains("PRIOR_SUMMARY")));
        assert_eq!(seen.messages.len(), 1);
        assert_eq!(seen.max_tokens, Some(1024));
        // The rendered user message embeds both PRIOR_SUMMARY and TRANSCRIPT.
        let user_text = match &seen.messages[0].content[0] {
            LlmContent::Text(t) => t.clone(),
            _ => panic!("expected text content"),
        };
        assert!(user_text.contains("PRIOR_SUMMARY:"));
        assert!(user_text.contains("prior anchor"));
        assert!(user_text.contains("TRANSCRIPT:"));
        assert!(user_text.contains("user: hi"));
        assert!(user_text.contains("assistant: hello"));
    }

    #[tokio::test]
    async fn first_compaction_uses_none_marker() {
        let provider = Arc::new(CannedProvider::new("first summary"));
        let summ = LlmSummarizer::new(provider.clone(), "test-model", 256);
        let out = summ
            .summarize("", &[LlmMessage::user("a"), LlmMessage::assistant("b")])
            .await;
        assert_eq!(out, "first summary");
        let seen = provider.seen.lock().unwrap().clone().expect("request seen");
        let user_text = match &seen.messages[0].content[0] {
            LlmContent::Text(t) => t.clone(),
            _ => panic!("expected text content"),
        };
        assert!(user_text.contains("(none — first compaction)"));
    }

    #[tokio::test]
    async fn provider_error_returns_prior_summary_unchanged() {
        let summ = LlmSummarizer::new(Arc::new(ErroringProvider), "test-model", 256);
        let prior = "this is the anchor";
        let out = summ.summarize(prior, &[LlmMessage::user("hi")]).await;
        assert_eq!(
            out, prior,
            "fail-soft: prior summary survives provider errors"
        );
    }

    #[tokio::test]
    async fn empty_inputs_short_circuit() {
        // No provider call should be made when both inputs are empty.
        let summ = LlmSummarizer::new(Arc::new(ErroringProvider), "test-model", 256);
        let out = summ.summarize("", &[]).await;
        assert!(out.is_empty());
    }

    #[tokio::test]
    async fn empty_output_falls_back_to_prior() {
        // A provider that yields no text deltas (just stop). Fail-soft keeps
        // the prior anchor rather than overwriting it with "".
        struct EmptyProvider;
        #[async_trait]
        impl LlmProvider for EmptyProvider {
            type Error = DummyError;
            async fn complete(
                &self,
                _req: CompletionRequest,
            ) -> Result<futures::stream::BoxStream<'static, Result<Chunk, Self::Error>>, Self::Error>
            {
                Ok(stream::iter(vec![Ok(Chunk::Stop(StopReason::EndTurn))]).boxed())
            }
        }
        let summ = LlmSummarizer::new(Arc::new(EmptyProvider), "test-model", 256);
        let out = summ.summarize("keep me", &[LlmMessage::user("x")]).await;
        assert_eq!(out, "keep me");
    }

    #[test]
    fn tool_calls_render_as_clipped_prose_not_bracket_dsl() {
        // An args payload over the args budget must be clipped and rendered as
        // prose, with no `[tool_call …]` bracket-DSL for a cheap summarizer to
        // echo back verbatim.
        let long_args = format!("{{\"q\":\"{}\"}}", "x".repeat(TOOL_ARGS_CLIP_BYTES));
        let use_msg = LlmMessage {
            role: Role::Assistant,
            content: vec![LlmContent::tool_use("call-1", "search", long_args)],
        };
        let use_rendered = render_transcript(&[use_msg]);
        assert!(!use_rendered.contains("[tool_call"));
        assert!(use_rendered.contains("called tool search("));
        assert!(use_rendered.contains("bytes omitted"));

        // A result over the result budget is clipped too, rendered as prose,
        // never the `[tool_result …]` bracket form, and keeps the call id so a
        // result can be paired to its call.
        let long_result = format!("{{\"id\":\"{}\"}}", "y".repeat(TOOL_RESULT_CLIP_BYTES));
        let result_msg = LlmMessage {
            role: Role::Tool,
            content: vec![LlmContent::tool_result("call-1", long_result, false, true)],
        };
        let result_rendered = render_transcript(&[result_msg]);
        assert!(result_rendered.contains("tool result for call-1 →"));
        assert!(!result_rendered.contains("[tool_result"));
        assert!(result_rendered.contains("bytes omitted"));

        // A short result is preserved verbatim (under budget → no clip marker),
        // so identifiers smaller than the budget are never lost.
        let short = render_transcript(&[LlmMessage {
            role: Role::Tool,
            content: vec![LlmContent::tool_result(
                "call-2",
                "{\"ok\":true}",
                false,
                true,
            )],
        }]);
        assert!(short.contains("tool result for call-2 → {\"ok\":true}"));
        assert!(!short.contains("bytes omitted"));
    }

    #[test]
    fn clip_truncates_on_char_boundary_without_panicking() {
        // A multibyte string clipped at a byte budget that lands mid-char must
        // back off to a valid boundary (no panic) and report bytes dropped.
        let s = "é".repeat(100); // 2 bytes each = 200 bytes
        let out = clip(&s, 5); // 5 is not a char boundary for 'é' pairs
        assert!(out.contains("bytes omitted"));
        assert!(out.starts_with("éé")); // 4 bytes kept, boundary respected
    }
}