-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAgentThoughtSummaryMarkerWindowPolicy.cs
More file actions
83 lines (71 loc) · 2.4 KB
/
Copy pathAgentThoughtSummaryMarkerWindowPolicy.cs
File metadata and controls
83 lines (71 loc) · 2.4 KB
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
// SPDX-License-Identifier: BUSL-1.1
using System.Text;
using Coven.Core.Streaming;
namespace Coven.Agents.OpenAI;
/// <summary>
/// Emits when a summary marker is observed in the thought stream.
/// The marker is any bold Markdown segment ("**...**") followed by a newline sequence.
/// Recognized sequences: "\n\n", "\r\n\r\n", or "\r\n".
/// </summary>
public sealed class AgentThoughtSummaryMarkerWindowPolicy : IWindowPolicy<AgentAfferentThoughtChunk>
{
public int MinChunkLookback => 10;
public bool ShouldEmit(StreamWindow<AgentAfferentThoughtChunk> window)
{
StringBuilder stringBuilder = new();
foreach (AgentAfferentThoughtChunk chunk in window.PendingChunks)
{
if (!string.IsNullOrEmpty(chunk.Text))
{
stringBuilder.Append(chunk.Text);
}
}
if (stringBuilder.Length == 0)
{
return false;
}
string text = stringBuilder.ToString();
ReadOnlySpan<char> span = text.AsSpan();
return HasBoldFollowedByNewline(span);
}
private static bool HasBoldFollowedByNewline(ReadOnlySpan<char> span)
{
int position = 0;
while (position < span.Length)
{
int start = span[position..].IndexOf("**");
if (start < 0)
{
return false;
}
start += position;
int afterOpen = start + 2;
if (afterOpen >= span.Length)
{
return false;
}
int end = span[afterOpen..].IndexOf("**");
if (end < 0)
{
// Unmatched opener; advance past it and continue scanning later content
position = start + 2;
continue;
}
end += afterOpen;
// Require non-empty content between markers
if (end > start + 2)
{
int after = end + 2;
ReadOnlySpan<char> tail = after <= span.Length ? span[after..] : [];
if (tail.StartsWith("\r\n\r\n", StringComparison.Ordinal) ||
tail.StartsWith("\n\n", StringComparison.Ordinal) ||
tail.StartsWith("\r\n", StringComparison.Ordinal))
{
return true;
}
}
position = end + 2;
}
return false;
}
}