Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion docs/interactive-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ Configure the standard .NET configuration stack under `SharpClaw:Compaction` (or
"TriggerRatio": 0.8,
"SummaryMaxTokens": 4096,
"RetainedMessageCount": 6,
"MaxSummaryCalls": 32,
"ModelContextWindows": {
"provider/model": 128000
}
Expand All @@ -61,7 +62,23 @@ Configure the standard .NET configuration stack under `SharpClaw:Compaction` (or

Replace `provider/model` with the exact resolved provider/model key. The output reserve is increased when a request's maximum output is higher. Budgeting uses estimates (approximately characters divided by four, with an image allowance), not a provider tokenizer; configure conservative windows for your models.

Invalid summaries, persistence failures, or oversized irreducible requests fail visibly instead of silently dropping context. The original history remains intact. A single oversized request/exchange or an archive larger than the summarizer's window requires smaller tool outputs or a larger configured model window. This first implementation does not recursively summarize oversized archives. Automatic maintenance does not change the existing manual `/compact` command.
Invalid summaries, persistence failures, or oversized irreducible requests fail visibly instead of silently dropping context. The original history remains intact. Archives larger than the summarizer window are processed as bounded text fragments. Each call carries the prior validated working state forward; a single replacement event is published only after every fragment succeeds. `MaxSummaryCalls` bounds the work per compaction. Recent requests or tool exchanges that cannot fit even after retaining the minimum safe context still fail clearly. Automatic maintenance does not change the existing manual `/compact` command.

## Bounded tool output and overflow recovery

The Runtime registers `IToolResultContextFormatter` at the agent dispatcher boundary. Provider-facing tool text larger than `SharpClaw:ToolOutput:MaxCharacters` (default 32,000; minimum 2,048) becomes a bounded head/tail preview with an opaque artifact ID. The full text is durably saved before the preview is used. Original `ToolResult` objects, structured output, permission decisions, and tool-completion events stay unchanged. This bounds model input; it does not cap the original process output, event log size, or artifact disk usage.

`read_tool_output` retrieves the complete text in windows:

```json
{"artifactId":"artifact-<id>","offset":0,"limit":4096}
```

The requested limit is capped further when needed to fit the configured output-preview budget, including JSON escaping, so retrieval does not recursively create oversized artifacts. The returned JSON includes `artifactId`, `offset`, `content`, `totalCharacters`, and `nextOffset` (null at EOF). Offsets count UTF-16 code units. Windows avoid splitting surrogate pairs; a one-character request can return a two-unit character, and an offset inside a pair moves back to its start. Follow `nextOffset` to page without overlap. The tool accepts only opaque IDs and only reads the active session's tenant-aware storage partition. It uses the normal tool executor, including allow-list and permission checks. A restricted tool list must include `read_tool_output` to permit model-driven retrieval.

Artifacts are immutable files in the session's `artifacts` directory, including when core session records use SQLite. They survive host restart. They follow the session storage lifetime; no independent automatic artifact deletion is performed. Storage failures stop context preparation instead of dropping the full output. These files are runtime session state, like event logs, rather than workspace edits or undoable mutations.

When a provider explicitly rejects an input as exceeding its context window, the kernel permits **one recovery attempt per agent invocation**. It forces durable compaction even below the normal estimate threshold, retains the latest complete exchange and pinned context, then retries the same provider with fresh stream buffers. Already executed tools are not replayed; partial tool calls emitted by a failed stream are discarded. Repeated overflows and unavailable recovery follow existing provider failure/fallback handling. Irreducible context or failed compaction stops with an explicit error. Authentication, rate limits, and generic server failures do not trigger this recovery. The failure enum adds `ContextWindowExceeded`; existing numeric values and event shapes remain unchanged.

## Live turn control

Expand Down
2 changes: 2 additions & 0 deletions docs/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,5 @@ Compiler-backed .NET tools are described in [.NET intelligence](dotnet-intellige
The permission-gated `verify_workspace` tool and CLI/REPL equivalents are documented in [Verification](verification.md).

The additive `read_file_snapshot` and `edit_file_snapshot` tools support bounded reads, stale-content rejection, and non-overlapping single-file edit batches through the same permission executor and mutation journal. Existing file-tool contracts are unchanged. See [snapshot editing](interactive-runtime.md#snapshot-aware-editing) for schemas, newline handling, and publication guarantees.

Runtime provider context uses bounded previews for large tool results while retaining complete results and events. The permission-aware `read_tool_output` tool retrieves full text from session artifacts. See [runtime resilience](interactive-runtime.md#bounded-tool-output-and-overflow-recovery).
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ public interface IAgentContextManager
{
/// <summary>Persists any compaction before returning replacement messages. Never executes tools.</summary>
Task<AgentContextPreparation> PrepareAsync(AgentRunContext context, IModelProvider provider, ProviderRequest request, CancellationToken cancellationToken);

/// <summary>Attempts stronger compaction after a confirmed context overflow. Null means no smaller safe request is available.</summary>
Task<AgentContextPreparation?> RecoverAsync(AgentRunContext context, IModelProvider provider, ProviderRequest request, CancellationToken cancellationToken)
=> Task.FromResult<AgentContextPreparation?>(null);
}

/// <summary>A prepared request and the measured usage of any summarization call.</summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using SharpClaw.Code.Protocol.Models;
using SharpClaw.Code.Tools.Models;

namespace SharpClaw.Code.Agents.Abstractions;

/// <summary>Bounds provider-facing tool content without altering the original tool result or its durable events.</summary>
public interface IToolResultContextFormatter
{
/// <summary>Persists full text before replacing it with a bounded preview and retrieval reference.</summary>
Task<ContentBlock> PrepareAsync(ContentBlock block, string toolName, ToolExecutionContext context, CancellationToken cancellationToken);
}
15 changes: 15 additions & 0 deletions src/SharpClaw.Code.Agents/Internal/ProviderBackedAgentKernel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ internal async Task<ProviderInvocationResult> ExecuteAsync(
var compactionUsage = new UsageSnapshot(0, 0, 0, 0, 0);
ProviderRequest? lastProviderRequest = null;

var contextRecoveryAttempted = false;
var iteration = 0;
for (; iteration < options.MaxToolIterations; iteration++)
{
Expand Down Expand Up @@ -223,6 +224,7 @@ internal async Task<ProviderInvocationResult> ExecuteAsync(
var candidateToolUseEvents = new List<ProviderEvent>();
UsageSnapshot? candidateUsage = null;

var providerStarted = false;
using var providerScope = new ProviderActivityScope(provider.ProviderName, candidateModel, providerRequest.Id);
try
{
Expand All @@ -234,6 +236,7 @@ internal async Task<ProviderInvocationResult> ExecuteAsync(
if (prepared.CompactionUsage is { } used)
compactionUsage = AddUsage(compactionUsage, used);
}
providerStarted = true;
var stream = await provider.StartStreamAsync(providerRequest, cancellationToken).ConfigureAwait(false);
await foreach (var providerEvent in stream.Events.WithCancellation(cancellationToken))
{
Expand Down Expand Up @@ -276,6 +279,18 @@ internal async Task<ProviderInvocationResult> ExecuteAsync(
{
providerScope.SetError(exception.Message);
lastStreamFailure = exception;
if (providerStarted && !contextRecoveryAttempted && contextManager is not null && ProviderStreamFailureClassifier.IsContextOverflow(exception))
{
contextRecoveryAttempted = true;
var recovered = await contextManager.RecoverAsync(request.Context, provider, providerRequest, cancellationToken).ConfigureAwait(false);
if (recovered is not null)
{
messages = recovered.Request.Messages?.ToList() ?? messages;
if (recovered.CompactionUsage is { } recoveredUsage) compactionUsage = AddUsage(compactionUsage, recoveredUsage);
candidateIndex--; // Retry this provider with a new request ID and fresh buffers.
continue;
}
}
if (candidateIndex == providerCandidates.Count - 1)
{
break;
Expand Down
9 changes: 7 additions & 2 deletions src/SharpClaw.Code.Agents/Internal/ToolCallDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ namespace SharpClaw.Code.Agents.Internal;
/// </summary>
public sealed class ToolCallDispatcher(
IToolExecutor toolExecutor,
ISubAgentOrchestrator subAgentOrchestrator)
ISubAgentOrchestrator subAgentOrchestrator,
IToolResultContextFormatter? contextFormatter = null)
{
/// <summary>
/// Executes a tool call and returns a tool-result content block.
Expand Down Expand Up @@ -43,7 +44,9 @@ public sealed class ToolCallDispatcher(

if (string.Equals(toolName, SubAgentToolContract.ToolName, StringComparison.OrdinalIgnoreCase))
{
return await DispatchSubAgentsAsync(toolUseEvent, toolUseId, toolInputJson, context, cancellationToken).ConfigureAwait(false);
var delegated = await DispatchSubAgentsAsync(toolUseEvent, toolUseId, toolInputJson, context, cancellationToken).ConfigureAwait(false);
if (contextFormatter is not null) delegated.ResultBlock = await contextFormatter.PrepareAsync(delegated.ResultBlock, toolName, context, cancellationToken).ConfigureAwait(false);
return delegated;
}

// Execute the tool — ToolExecutor already publishes ToolStartedEvent and ToolCompletedEvent
Expand Down Expand Up @@ -73,6 +76,8 @@ public sealed class ToolCallDispatcher(
true);
}

if (contextFormatter is not null) resultBlock = await contextFormatter.PrepareAsync(resultBlock, toolName, context, cancellationToken).ConfigureAwait(false);

// Events are already published by ToolExecutor; return empty list to avoid duplicates.
return (resultBlock, envelope.Result, []);
}
Expand Down
7 changes: 7 additions & 0 deletions src/SharpClaw.Code.Protocol/Models/ToolOutputArtifact.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace SharpClaw.Code.Protocol.Models;

/// <summary>Complete provider-facing tool text retained outside the active model context.</summary>
public sealed record ToolOutputArtifact(string Id, string SessionId, string TurnId, string ToolName, DateTimeOffset CreatedAtUtc, string Content);

/// <summary>A bounded UTF-16 character window into a session-owned output artifact.</summary>
public sealed record ToolOutputArtifactPage(string ArtifactId, int Offset, string Content, int TotalCharacters, int? NextOffset);
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ namespace SharpClaw.Code.Protocol.Serialization;
[JsonSerializable(typeof(CSharpToolArguments))]
[JsonSerializable(typeof(ContextCompactedEvent))]
[JsonSerializable(typeof(TurnSteeredEvent))]
[JsonSerializable(typeof(ToolOutputArtifact))]
[JsonSerializable(typeof(ToolOutputArtifactPage))]
[JsonSerializable(typeof(CompactionWorkingState))]
[JsonSerializable(typeof(CSharpReference))]
[JsonSerializable(typeof(CSharpReferenceResult))]
Expand Down
3 changes: 3 additions & 0 deletions src/SharpClaw.Code.Providers/Models/ProviderFailureKind.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,7 @@ public enum ProviderFailureKind
/// The provider failed while starting or streaming the request.
/// </summary>
StreamFailed,

/// <summary>The provider rejected an input that exceeds its context window.</summary>
ContextWindowExceeded,
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Globalization;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using SharpClaw.Code.Protocol.Models;

namespace SharpClaw.Code.Providers.Models;
Expand Down Expand Up @@ -39,13 +40,14 @@ public static string Describe(Exception exception)
public static ProviderFailureKind ClassifyFailedEvent(ProviderEvent providerEvent)
=> LooksLikeAuthenticationFailure(providerEvent.Content)
? ProviderFailureKind.AuthenticationUnavailable
: ProviderFailureKind.StreamFailed;
: LooksLikeContextOverflow(providerEvent.Content) ? ProviderFailureKind.ContextWindowExceeded : ProviderFailureKind.StreamFailed;

/// <summary>
/// Returns whether an exception represents provider authentication or authorization failure.
/// </summary>
public static bool IsAuthenticationFailure(Exception exception)
{
if (exception is ProviderExecutionException { Kind: ProviderFailureKind.AuthenticationUnavailable }) return true;
var statusCode = TryGetStatusCode(exception);
if (statusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
{
Expand All @@ -60,6 +62,16 @@ public static bool IsAuthenticationFailure(Exception exception)
|| (exception.InnerException is not null && IsAuthenticationFailure(exception.InnerException));
}

/// <summary>Recognizes explicit context-window rejections without treating rate limits or authentication failures as overflow.</summary>
public static bool IsContextOverflow(Exception exception)
=> exception is ProviderExecutionException { Kind: ProviderFailureKind.ContextWindowExceeded }
|| (!IsAuthenticationFailure(exception) && (LooksLikeContextOverflow(exception.Message)
|| exception.InnerException is not null && IsContextOverflow(exception.InnerException)));

private static bool LooksLikeContextOverflow(string? message)
=> message is not null && new[] { "context_length_exceeded", "maximum context length", "prompt is too long", "context window exceeded", "exceeds the context window", "input token count exceeds" }
.Any(pattern => message.Contains(pattern, StringComparison.OrdinalIgnoreCase));

private static bool LooksLikeAuthenticationFailure(string? message)
{
if (string.IsNullOrWhiteSpace(message))
Expand All @@ -68,7 +80,7 @@ private static bool LooksLikeAuthenticationFailure(string? message)
}

var value = message.ToLowerInvariant();
if (value.Contains("401", StringComparison.Ordinal)
if (Regex.IsMatch(value, @"(?:^|\W)401(?:\W|$)", RegexOptions.CultureInvariant)
|| value.Contains("unauthorized", StringComparison.Ordinal)
|| value.Contains("forbidden", StringComparison.Ordinal))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ private static IServiceCollection AddSharpClawRuntimeCore(
var compactionOptions = services.AddOptions<AutomaticCompactionOptions>();
if (configuration is not null) compactionOptions.Bind(configuration.GetSection("SharpClaw:Compaction"));
compactionOptions.Validate(options => options.ContextWindowTokens > 0 && options.ReservedOutputTokens >= 0
&& options.SummaryMaxTokens > 0 && options.RetainedMessageCount >= 2 && options.TriggerRatio is > 0 and < 1
&& options.SummaryMaxTokens > 0 && options.MaxSummaryCalls > 0 && options.RetainedMessageCount >= 2 && options.TriggerRatio is > 0 and < 1
&& options.ModelContextWindows.Values.All(value => value > 0), "Invalid automatic compaction budgets.").ValidateOnStart();
services.AddSingleton<SharpClaw.Code.Agents.Abstractions.IAgentContextManager, AutomaticContextManager>();
services.AddSingleton<LiveTurnControlService>();
Expand Down Expand Up @@ -137,6 +137,12 @@ private static IServiceCollection AddSharpClawRuntimeCore(
services.AddSingleton<IRuntimeEventPersistence, EventStoreRuntimeEventPersistence>();
services.AddSingleton<ICheckpointStore, FileCheckpointStore>();
services.AddSingleton<IMutationSetStore, FileMutationSetStore>();
services.AddSingleton<IToolOutputArtifactStore, FileToolOutputArtifactStore>();
var toolOutputOptions = services.AddOptions<ToolOutputOptions>();
if (configuration is not null) toolOutputOptions.Bind(configuration.GetSection("SharpClaw:ToolOutput"));
toolOutputOptions.Validate(options => options.MaxCharacters >= 2048, "Tool output previews require at least 2048 characters.").ValidateOnStart();
services.AddSingleton<SharpClaw.Code.Agents.Abstractions.IToolResultContextFormatter, ToolResultContextFormatter>();
services.AddSingleton<ISharpClawTool, SharpClaw.Code.Runtime.Tools.ReadToolOutputTool>();
services.AddSingleton<IWorkspaceSessionAttachmentStore, FileWorkspaceSessionAttachmentStore>();
services.AddSingleton<IEditorContextBuffer, EditorContextBuffer>();
services.AddSingleton<MutationWorkspaceApplier>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,6 @@ public sealed class AutomaticCompactionOptions
public int SummaryMaxTokens { get; set; } = 4096;
/// <summary>Recent messages retained verbatim, extended to keep tool exchanges intact.</summary>
public int RetainedMessageCount { get; set; } = 6;
/// <summary>Maximum tool-free summary calls per compaction, bounding work on unusually large archives.</summary>
public int MaxSummaryCalls { get; set; } = 32;
}
8 changes: 8 additions & 0 deletions src/SharpClaw.Code.Runtime/Configuration/ToolOutputOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace SharpClaw.Code.Runtime.Configuration;

/// <summary>Controls provider-facing output previews; original tool results and events remain complete.</summary>
public sealed class ToolOutputOptions
{
/// <summary>Maximum UTF-16 characters per provider-facing tool result, including its artifact reference.</summary>
public int MaxCharacters { get; set; } = 32_000;
}
Loading
Loading