SharpCoder 0.25.0

There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package SharpCoder --version 0.25.0
                    
NuGet\Install-Package SharpCoder -Version 0.25.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="SharpCoder" Version="0.25.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="SharpCoder" Version="0.25.0" />
                    
Directory.Packages.props
<PackageReference Include="SharpCoder" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add SharpCoder --version 0.25.0
                    
#r "nuget: SharpCoder, 0.25.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package SharpCoder@0.25.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=SharpCoder&version=0.25.0
                    
Install as a Cake Addin
#tool nuget:?package=SharpCoder&version=0.25.0
                    
Install as a Cake Tool

SharpCoder

NuGet NuGet tool License: MIT

A standalone, embeddable autonomous coding agent for .NET — built on Microsoft.Extensions.AI.

SharpCoder gives any IChatClient (OpenAI, Ollama, Azure, Anthropic, etc.) the ability to read files, write code, search codebases, and execute shell commands autonomously. Plug it into your app with a few lines of code.

Features

  • Provider-agnostic — works with any IChatClient implementation
  • Built-in tools — file read/write/edit, glob, grep, bash, and skills
  • Persistent sessions — multi-turn conversations with save/load to JSON
  • Streaming — IAsyncEnumerable<StreamingUpdate> for real-time token delivery
  • Auto-compaction — summarizes old context to stay within token limits
  • Security by default — path traversal protection, bash disabled by default, home-directory guard for shell commands
  • Workspace-aware — auto-loads AGENTS.md and .github/copilot-instructions.md
  • Rich results and usage accounting — per-call token usage, tool call count, full message history, diagnostics
  • XML documentation — shipped with both packages for IntelliSense
  • Targets net11.0 — requires the .NET 11 runtime and SDK

Quick Start

GitHub Copilot provider requests use the per-account API endpoint advertised by GitHub when it can be discovered; if the lookup fails or the endpoint is untrusted, requests quietly fall back to https://api.githubcopilot.com. GitHub Enterprise (*.ghe.com) endpoints are not supported.

dotnet add package SharpCoder
# OllamaSharp is the provider client used below; any IChatClient works.
dotnet add package OllamaSharp
using Microsoft.Extensions.AI;
using OllamaSharp;
using SharpCoder;

// Use any IChatClient — OpenAI, Ollama, Azure, etc.
IChatClient chatClient = new OllamaApiClient(new Uri("http://localhost:11434"), "qwen2.5-coder");

var agent = new CodingAgent(chatClient, new AgentOptions
{
    WorkDirectory = "/path/to/your/project",
    MaxSteps = 15
});

var result = await agent.ExecuteAsync("Add unit tests for the Calculator class");

Console.WriteLine($"Status: {result.Status}");
Console.WriteLine($"Tool calls: {result.ToolCallCount}");
Console.WriteLine($"Tokens used: input={result.TokenUsage.Total.InputTokens}, output={result.TokenUsage.Total.OutputTokens}");
Console.WriteLine(result.Message);

Host tool authorization

Use AgentOptions.AuthorizeTool to approve each locally invokable tool call before it runs. The callback receives the tool name, captured correlation ID and read-only argument snapshot, and returns Allow or a host-authored Deny decision:

using System.Threading;
using System.Threading.Tasks;
using SharpCoder;

var options = new AgentOptions
{
    WorkDirectory = "/path/to/project",
    ToolAuthorizationCorrelationId = "user-123",
    AuthorizeTool = (context, cancellationToken) =>
    {
        if (context.ToolName == "write_file" || context.ToolName == "edit_file")
            return Task.FromResult(ToolAuthorizationDecision.Deny("File writes are not allowed for this user."));

        return Task.FromResult(ToolAuthorizationDecision.Allow);
    }
};

var agent = new CodingAgent(chatClient, options);

The callback and correlation ID are captured together when the CodingAgent is constructed and stay fixed for its lifetime. Accepted sub-agent children inherit that captured pair; later AgentOptions mutations affect only agents constructed afterwards. A denial, callback fault or null decision fails closed before tool side effects. Callback-fault details are sanitized and never shown to the model on both the manual-streaming and FunctionInvokingChatClient paths; the host-approved reason supplied to Deny is model-visible. Caller cancellation propagates.

All locally invokable tools are guarded: built-in bash, file-operation and skills tools, custom AIFunction tools, and the four sub-agent tools. When authorization is enabled, non-AIFunction custom tools fail closed while BuildChatOptions builds the model request. With no callback configured, tool behavior is unchanged from previous versions.

This callback boundary covers only tools SharpCoder registers for the model. Trusted host entry points are outside it and must be authorized by the host when needed: direct use of raw FileTools, host-retained unwrapped custom functions, and public SubAgentManager.StartAsync.

Web tools

SharpCoder.Providers includes an Ollama web transport and optional model-tool adapter. The host configures the HTTPS backend endpoint, owns the HttpClient and supplies a credential accessor; successful transport DTOs remain host-only. To expose web_search and web_fetch, provide a mandatory output transform and pass the adapter's tools to your agent or other IChatClient consumer:

using SharpCoder.Providers.Web;

var webClient = new OllamaWebClient(new OllamaWebClientOptions
{
    BaseUri = new Uri("https://ollama.example/"),
    HttpClient = httpClient, // Host-created and host-owned.
    CredentialAccessor = () => credentialProvider.GetToken()
});

var webTools = new OllamaWebTools(webClient, new OllamaWebToolsOptions
{
    OutputTransform = (value, cancellationToken) => RedactAsync(value, cancellationToken)
});

var tools = webTools.Tools; // web_search, web_fetch

Queries and fetch URLs reach the configured backend before output transformation. Hosts must authorize backend access and input disclosure, and define egress/redirect/TLS/logging policy, redaction, and prompt-injection handling. The transform governs model output only; it does not authorize requests. Apply any general AgentOptions.AuthorizeTool policy separately. This section documents the root README; SharpCoder.Providers has a separate packed README.

Sessions

Sessions provide persistent, multi-turn conversations. The agent remembers prior turns and builds on them:

var session = AgentSession.Create();

// Turn 1 — agent reads the codebase
await agent.ExecuteAsync(session, "Read the Calculator class and understand it");

// Turn 2 — agent remembers what it read
await agent.ExecuteAsync(session, "Now add tests for the edge cases you found");

// Save session to disk for crash recovery
await session.SaveAsync("session.json");

// Load a saved session later
var restored = await AgentSession.LoadAsync("session.json");
await agent.ExecuteAsync(restored, "What did we do so far?");

Session Forking

AgentSession.Fork() creates a deep copy of a session — useful for branching a conversation without affecting the original:

var session = AgentSession.Create();
await agent.ExecuteAsync(session, "Analyse the codebase");

// Fork the session for an independent sub-task
var forked = session.Fork();
await agent.ExecuteAsync(forked, "Now refactor the Parser class");

// Original session is unaffected — continue where you left off
await agent.ExecuteAsync(session, "Now add tests for what you found");

Forked sessions get a new session ID, zeroed token counters, and fresh timestamps. Message history is deep-copied so mutations to either session are independent. LastKnownContextTokens is preserved for accurate compaction decisions.

Sessions track cumulative token usage, tool call counts, and exact context size from the most recent API response.

Passing images directly to ExecuteAsync

You can also attach images directly to any turn when your own code loads or captures them. Pass an IReadOnlyList<ImageAttachment> to the image-capable ExecuteAsync or ExecuteStreamingAsync overload. The user message is sent as TextContent plus one DataContent per attachment. Callers must set ImageAttachment.MediaType explicitly (for example "image/png", "image/jpeg", "application/pdf"); there is no automatic inference from file extension for direct attachments.

using Microsoft.Extensions.AI;
using OllamaSharp;
using SharpCoder;

IChatClient chatClient = new OllamaApiClient(new Uri("http://localhost:11434"), "llama3.2-vision");
var agent = new CodingAgent(chatClient, new AgentOptions
{
    WorkDirectory = "/path/to/project",
    MaxSteps = 15
});

string path = "screenshot.png";
byte[] screenshotBytes = await File.ReadAllBytesAsync(path);

var images = new List<ImageAttachment>
{
    new ImageAttachment
    {
        Data = screenshotBytes,
        MediaType = "image/png",
        Name = path
    }
};

var result = await agent.ExecuteAsync("What does this screenshot show?", images, CancellationToken.None);
Console.WriteLine(result.Message);

Images count toward AgentSession.EstimatedContextTokens with a flat per-attachment estimate. Image attachments are not persisted across AgentSession.SaveAsync/LoadAsync or Fork().

Sub-agents

Delegate self-contained subtasks — codebase analysis, large-text summarization, and parallel research — to background sub-sessions. Only their summaries and status metadata return to the main session, never full transcripts. Successful sub-agents retain their complete final response text verbatim as the summary through the await_sub_agents and get_sub_agent_status handoff; child conversation and tool transcripts are still not forwarded.

v0.20.0 breaking migration: SubAgentOptions.MaxSummaryChars and its plumbing were removed with no replacement or compatibility alias. Remove property assignments and dependent assertions, rebuild consuming applications against the updated packages, and keep SharpCoder and SharpCoder.Providers versions aligned when used together.

using Microsoft.Extensions.AI;
using OllamaSharp;
using SharpCoder;
using SharpCoder.SubAgents;

IChatClient mainClient = new OllamaApiClient(new Uri("http://localhost:11434"), "qwen2.5-coder");

var agent = new CodingAgent(mainClient, new AgentOptions
{
    WorkDirectory = "/path/to/project",
    MaxSteps = 25,
    SubAgents = new SubAgentOptions
    {
        MaxConcurrentSubAgents = 4,
        DefaultTimeout = TimeSpan.FromMinutes(10),
        MaxTimeout = TimeSpan.FromMinutes(30),
        AvailableModels =
        {
            new SubAgentModelInfo("llama3.2", "Fast summarizer", 128_000),
            new SubAgentModelInfo("qwen2.5-coder", "Coding specialist", 131_072)
        },
        ClientFactory = modelId => new OllamaApiClient(new Uri("http://localhost:11434"), modelId)
    }
});

// The agent gains four tools: start_sub_agent, await_sub_agents,
// get_sub_agent_status, list_sub_agent_models.
// Sub-agents run read-only by default and cannot exceed the parent's capabilities.

var result = await agent.ExecuteAsync("Analyze the codebase and summarize the architecture");

// Always dispose to cancel any running sub-agents
await agent.DisposeAsync();
Setting Default Description
MaxConcurrentSubAgents 4 Maximum concurrently running sub-agents
DefaultTimeout 10 min Per-sub-agent timeout if not overridden
MaxTimeout 30 min Upper bound for per-request timeouts; larger values clamped
DefaultEnableBash false Default bash tool flag for sub-agents
DefaultEnableFileOps true Default file-ops tool flag for sub-agents
DefaultEnableFileWrites false Default file-writes tool flag for sub-agents
DefaultEnableSkills true Default skills tool flag for sub-agents
MaxSteps 25 Maximum agent-loop steps per sub-agent
ClientFactory null Maps a model ID to an IChatClient; required when a sub-agent requests a model from AvailableModels
DefaultClient null Fallback client when no model is specified; when null the parent agent's client is used

Sub-agents can never exceed the parent agent's enabled capabilities (bash, file ops, file writes, skills). LLM-supplied overrides are clamped by the parent's flags, snapshotted at manager creation. Sub-agents run read-only by default.

Observing sub-agent progress

Subscribe to agent.SubAgentChanged before calling ExecuteAsync to catch all events — the sub-agent manager is created lazily inside BuildChatOptions at the start of each execution call (before any sub-agent is started), and the agent-level event forwards to the manager's event at creation time. Two notifications fire per accepted run (start + terminal). The payload is a detached SubAgentInfo snapshot safe to read from any thread; a fresh instance is passed to each handler. Handlers are invoked synchronously in registration order; a throwing handler is caught and logged without affecting other handlers.

agent.SubAgentChanged += info =>
{
    Console.WriteLine($"Sub-agent {info.Id}: {info.Status}");
    // info.Status is Running, Completed, Failed, TimedOut, or Cancelled
};

Sub-agents cannot spawn their own sub-agents. This flat-design limitation is planned for a future release.

  • Mark vision-capable models in SubAgentOptions.AvailableModels with new SubAgentModelInfo(..., supportsVision: true); the LLM can discover them through the supports_vision field emitted by list_sub_agent_models.

Handing images to a vision sub-agent

A parent agent that does not itself need vision can still delegate image or PDF analysis to a vision-capable sub-agent. Use start_sub_agent with the image_paths argument and configure the sub-agent with a vision-capable model. Paths are repo-relative to WorkDirectory and are confined by the same path-safety rules as file tools.

By default, image_paths resolve only within the parent agent's WorkDirectory. Set SubAgentOptions.AdditionalImagesRoot to an absolute directory path to allow image_paths to also resolve within that directory — useful for temporary or uploaded attachments outside the repo. The value is validated and snapshotted at manager construction; null (the default) means no additional root is configured.

var agent = new CodingAgent(mainClient, new AgentOptions
{
    WorkDirectory = "/path/to/project",
    MaxSteps = 25,
    SubAgents = new SubAgentOptions
    {
        MaxConcurrentSubAgents = 4,
        DefaultTimeout = TimeSpan.FromMinutes(10),
        MaxTimeout = TimeSpan.FromMinutes(30),
        AvailableModels =
        {
            new SubAgentModelInfo("llama3.2-vision", "Vision-capable analyzer", 128_000)
        },
        ClientFactory = modelId => new OllamaApiClient(new Uri("http://localhost:11434"), modelId)
    }
});

// The LLM can call:
// start_sub_agent(
//     task: "Describe this UI screenshot and suggest accessibility fixes",
//     model: "llama3.2-vision",
//     image_paths: new[] { "docs/screenshots/homepage.png" })
//
// Only the summary returns to the parent session; the full image transcript
// never enters the main conversation.

Streaming

Stream text tokens as they arrive instead of waiting for the full response:

await foreach (var update in agent.ExecuteStreamingAsync(session, "Refactor the Parser class"))
{
    switch (update.Kind)
    {
        case StreamingUpdateKind.TextDelta:
            Console.Write(update.Text); // incremental text chunk
            break;
        case StreamingUpdateKind.Completed:
            Console.WriteLine($"\nDone: {update.Result!.Status}");
            break;
    }
}

Streaming uses the same tool invocation pipeline as ExecuteAsync — tools execute transparently between text chunks. The session is persisted after the stream completes.

Configuration

All behavior is controlled through AgentOptions:

var options = new AgentOptions
{
    // Where the agent operates (default: current directory)
    WorkDirectory = "/my/project",

    // Max tool call iterations before stopping (default: 25)
    MaxSteps = 25,

    // Enable shell command execution (default: false — security risk!)
    EnableBash = false,
    // Which shell execute_bash_command launches (default: Auto —
    // pwsh → powershell.exe → cmd.exe on Windows; bash → /bin/sh on Linux/macOS)
    BashShell = SharpCoder.ShellPreference.Auto,
    // Refuse $HOME assignment and destructive home-path commands before launch (default: true)
    BashHomeGuard = true,

    // File system tools (default: true)
    EnableFileOps = true,
    EnableFileWrites = true,

    // Skill loading from .github/skills/ (default: true)
    EnableSkills = true,

    // Override the default system prompt
    SystemPrompt = "You are a test-writing expert.",

    // Append custom instructions to the system prompt
    CustomInstructions = "Always use xUnit. Prefer Arrange-Act-Assert.",

    // Auto-load AGENTS.md and copilot-instructions.md (default: true)
    AutoLoadWorkspaceInstructions = true,

    // Add your own custom AITools
    CustomTools = new List<AITool>
    {
        AIFunctionFactory.Create(MyCustomTool)
    },

    // Context management
    MaxContextTokens = 100_000,   // model's context window
    CompactionThreshold = 0.8,    // compact at 80% usage
    CompactionRetainRecent = 2,     // floor: always keep at least this many recent messages
    CompactionRetainTokens = 16_000, // keep as many recent messages as fit in 16k tokens
    EnableToolResultElision = true,  // stub out bulky old tool results instead of summarizing them
    EnableAutoCompaction = true,  // enabled by default

    // Optional: separate (cheaper) model for context compaction summaries
    CompactionClient = new OllamaApiClient(new Uri("http://localhost:11434"), "llama3.2"),

    // Optional: compaction model's context window (enables chunked compaction when set)
    CompactionMaxTokens = 16_000, // compaction model's context window; null = use MaxContextTokens

    // Optional: reasoning effort for models with extended thinking
    ReasoningEffort = ReasoningEffort.Medium,

    // Optional: callback invoked before compaction begins (e.g. show a loading indicator)
    OnCompacting = () => Console.WriteLine("Compacting context…"),

    // Optional: callback invoked after compaction completes
    OnCompacted = result =>
        Console.WriteLine($"Compacted {result.TokensBefore} → {result.TokensAfter} tokens"),

    // Optional: durable Before/After snapshots for every compaction attempt
    OnCompactionCheckpointAsync = (checkpoint, _) =>
    {
        Console.WriteLine($"{checkpoint.Phase}: {checkpoint.Messages.Count} messages ({checkpoint.Reason})");
        return ValueTask.CompletedTask;
    }
};

Built-in Tools

Tool Description Enabled by
read_file Read file contents with line numbers and pagination EnableFileOps
write_file Create or overwrite files EnableFileWrites
edit_file Exact string replacement (single occurrence) EnableFileWrites
glob Find files by pattern (e.g. src/**/*.cs) EnableFileOps
grep Search file contents with regex EnableFileOps
execute_bash_command Run shell commands EnableBash
list_skills / load_skill Discover and load project skills EnableSkills

On Windows the command runs under PowerShell 7+ (pwsh) when it is installed, falling back to Windows PowerShell (powershell.exe), then to cmd.exe if neither is present. On Linux and macOS it uses bash found on PATH, falling back to /bin/sh. Shells are located via PATH, never via fixed install locations. The shell is resolved once when the agent is built; if the configured shell cannot be found, construction throws instead of failing on the first command. On PowerShell the command is executed with a UTF-8 console encoding prelude and a -EncodedCommand wrapper, so Unicode in the command and in output round-trips correctly and no shell quoting rules leak into your command text; output is UTF-8. Cmdlet error records are emitted by PowerShell as CLIXML on stderr (e.g. #< CLIXML), which is how PowerShell surfaces them when nobody is attached to the console — that is normal, not corruption. Prefer pwsh/PowerShell syntax (Get-ChildItem, ;) over cmd.exe syntax; &&/|| only work in PowerShell 7+. To force a specific shell set BashShell (SharpCoder.ShellPreference.Pwsh, PowerShell, Cmd, Bash, or Auto) — or BashShellPath for an arbitrary executable such as Git Bash or WSL bash. On cmd.exe the command tail is passed through verbatim after /d /s /c (cmd.exe does not understand .NET argument quoting). If you set BashShellArgsFormat, its output is split on whitespace with quote-grouping and no escape processing — it is not a shell-quoted string.

execute_bash_command accepts an optional timeout_ms tool argument: a positive integer in milliseconds for that invocation. If omitted or null, the instance-configured default applies (normally 120000 ms); for example, 900000 provides a 15-minute budget. Zero or negative values are rejected before process launch, and each invocation starts a fresh shell process. The original C# caller signature remains compatible. Each stdout and stderr stream is capped at about 50,000 characters; for full output, redirect it to a file and use grep or tail to inspect it. A valid tool call is:

{"command":"dotnet test --configuration Release", "timeout_ms":900000}

Home-directory guard (default on). BashHomeGuard makes execute_bash_command inspect every command before a shell process is created and refuse it (as a tool result, with an explanation and the work directory) if it assigns $HOME, $env:USERPROFILE, $env:HOMEDRIVE, $env:HOMEPATH, $env:HOME or $PSHOME, or combines a delete/clear/format verb with a home path ($HOME, ~, %USERPROFILE%, the literal user-profile path or its parent). PowerShell variable cmdlets/provider paths, cmd.exe set/setx and POSIX HOME=/export/unset forms are covered. This matters because PowerShell's $HOME is read-only and AllScope: $HOME = 'C:\Temp\scratch' fails with a non-terminating error, the script continues, and $HOME still points at the real user profile — a following Remove-Item -Recurse -Force $HOME deletes the whole profile. The same rules are placed in the system prompt and tool description, sub-agents inherit the setting, and SessionDiagnostics.BashHomeGuard reports it. The check is conservative and text-level, not a sandbox: dynamically constructed names or Invoke-Expression can bypass it. Because it errs on the side of refusing, a destructive command that spells out an absolute path beneath the profile (for example a workspace in C:\Users\<name>\source\…) is also refused — use a workspace-relative path such as ./bin instead. Set BashHomeGuard = false only in a disposable sandbox where managing the machine's home directory is intended.

Caller cancellation propagates an OperationCanceledException; it does not return a timeout transcript, and raw captured output is not promised on cancellation. The command deadline covers root-process exit and redirected-output draining. Native process-tree termination is attempted while the root process is still alive; descendants that escaped ancestry or were reparented after root exit cannot reliably be found or killed, so cleanup is not guaranteed to be complete. The fixed five-second cleanup allowance bounds managed waits only, not synchronous OS calls, and there is no public AgentOptions command-timeout setting or managed background-job API. Completed output remains available with incomplete-capture diagnostics when output was not fully captured, and actual exit status is reported, including silent nonzero exits.

Agent Result

ExecuteAsync and ExecuteStreamingAsync return an AgentResult with:

result.Status        // "Success", "MaxStepsReached", or "Error"
result.Message       // Final text response from the agent
result.Messages      // Full conversation history (all messages, tool calls, results)
result.ToolCallCount // Number of tool invocations made
result.ModelId       // Model that produced the response
result.FinishReason  // Why the model stopped (e.g. Stop, Length, ToolCalls)
result.Usage         // Provider/framework usage for the final response (may aggregate internal round trips)
result.TokenUsage    // Per-call usage for this execution, grouped by source and model
result.Diagnostics   // Snapshot of everything sent to the LLM (system prompt, tools, etc.)

Usage is the provider-returned usage for the final response; on FunctionInvokingChatClient paths it may aggregate that request's internal round trips. It does not include compaction or sub-agent calls and is not a consistent per-execution total. Use TokenUsage for SharpCoder's per-call totals across sources.

Usage accounting

AgentResult.TokenUsage is a detached, point-in-time snapshot of calls recorded for that execution. AgentSession.Usage is cumulative across calls recorded into the session and can be saved and loaded. Its Total sums all buckets, while Entries groups usage by source and model.

var agent = new CodingAgent(chatClient, new AgentOptions
{
    WorkDirectory = "/path/to/project",
    OnUsage = usageEvent =>
    {
        // Report each ended model call; events include source, model and usage.
        Console.WriteLine($"{usageEvent.Source}/{usageEvent.Model}: {usageEvent.Usage}");
    }
});

Thread safety: OnUsage may be invoked concurrently and may run after ExecuteAsync has returned, because background sub-agents forward calls as they finish. Protect shared handler state accordingly. Sub-agent calls are forwarded into the parent's accounting as SubAgent, with the sub-agent ID on the event; SubAgentInfo.Usage exposes each sub-agent's running totals. A supported SubAgentCompaction classification exists, though current sub-agent executions are stateless and do not compact.

The TokenUsage.Estimated breakdown contains estimates, not measurements, of input categories (system prompt, tool definitions, user and assistant text, tool calls and results, reasoning, and images) and output categories (text, tool calls, and reasoning). Category sums cover only calls that contributed an estimate; InputEstimatedCalls and OutputEstimatedCalls show that coverage. A sub-agent call that ends after the result is built updates AgentSession.Usage and invokes OnUsage, but does not update the already-returned AgentResult.TokenUsage snapshot.

Context Compaction

Long-running sessions can exceed model context limits. SharpCoder automatically compacts conversation history by summarizing older messages while preserving recent context:

  • Triggered when tokens exceed CompactionThreshold × MaxContextTokens

  • Uses exact token counts from the most recent API round-trip (LastKnownContextTokens) when available; falls back to heuristic estimate (~4 chars per token) before the first API call. When tools are invoked, the token count reflects the final round's context size — not the sum across all internal tool-call round-trips.

  • Two-stage: old tool-result bodies and attachments are first elided (replaced by a one-line stub naming the tool, its arguments and the payload size — re-run the tool to recover the content). If elision alone brings the history back under the threshold, no summarization call is made at all; otherwise the remaining old messages are summarized into a single [CONTEXT SUMMARY] message

  • Recent messages are kept verbatim within a token budget: as many newest messages as fit in CompactionRetainTokens (default 16,000, capped at half the compaction threshold), but always at least CompactionRetainRecent (default 2) messages, and never split mid tool-call/tool-result group

  • Leading system messages are preserved — all consecutive ChatRole.System messages at the start of the history are kept intact and are never included in the summary. Callers do not need to re-add the system prompt after compaction.

  • Key decisions, findings, and file paths are preserved in the summary

  • Automatic recovery — If an API call fails due to context overflow (model_max_prompt_tokens_exceeded), the agent force-compacts the session and retries once

  • Mid-loop compaction — During streaming with tool calls, compaction occurs between tool rounds to handle large tool results (e.g., web search returning 50K tokens). Session history is synchronized from the authoritative messages list after compaction to prevent duplicate entries.

  • Disable with EnableAutoCompaction = false if you manage context manually.

  • Use OnCompacting / OnCompacted callbacks to hook into the compaction lifecycle — e.g. to show a loading indicator before the summarisation call starts.

  • Durable checkpoints — OnCompactionCheckpointAsync is an additive async hook fired for threshold, mid-loop, overflow-recovery, host-triggered and elision-only compactions. Its Before phase receives a deep copy of the authoritative live history (leading system prompts stripped) and a detached, directly saveable AgentSession with the session identity, counters, usage and timestamps. Its After phase carries the compacted history and CompactionResult; an After with a null Result and bounded Error marks a failed/cancelled attempt. Hook exceptions are logged and never fail the agent turn, and existing synchronous UI callbacks are unchanged.

  • Separate compaction model — Configure CompactionClient to use a cheaper/smaller model (e.g., llama3.2 via Ollama) just for context compaction summaries. When not set, the main IChatClient is used (backward compatible).

  • Chunked compaction — When CompactionMaxTokens is set and old messages exceed that budget, they are split into token-budgeted chunks and each chunk is summarized separately. The per-chunk summaries are concatenated into one summary message. This prevents the compaction model from overflowing when it has a smaller context window than the main model. When CompactionMaxTokens is null (default), all old messages are summarized in a single call (existing behavior).

  • Cancellation — When a summarization call throws OperationCanceledException while the caller's token is cancelled, compaction rethrows it without changing history or LastKnownContextTokens or invoking OnCompacted; the attempted call is still recorded in usage, and chunked summarization stops without fallback text. Exceptions from OnCompacting/OnCompacted are not covered by this guarantee. No-op paths (such as auto-compaction disabled or too few messages) may still return false with a cancelled token; client-originated cancellation/timeout failures while the caller's token is not cancelled are handled by path: single-call summarization logs and returns false; automatic chunked paths log and substitute fallback text, while chunked CompactOldestPercentAsync/ForceCompactAsync return false without logging or fallback text.

  • Partial compaction — CompactOldestPercentAsync(session, options, percent, ct) summarizes only the oldest X% of tokens, keeping the newest portion verbatim. Gentler than full compaction — preserves more recent context with full fidelity while reducing token usage.

Skills

The agent can discover and load project-specific skills from .github/skills/. Each skill is a Markdown file with YAML frontmatter:

---
name: build
description: How to build this project
---

# Build Instructions

Run `dotnet build` to compile the solution.

The agent calls list_skills to discover what's available and load_skill to read the full instructions.

Command-line interface

The repository includes a terminal front-end over the library, in src/SharpCoder.Cli. It is published to NuGet as the SharpCoder.Cli .NET tool (command sharpcoder), alongside the SharpCoder and SharpCoder.Providers libraries. It streams responses live, renders tool calls inline, shows per-turn and cumulative token/tool usage, automatically resumes a managed session for the current workdir, and supports the same providers as SharpCoder.Providers. All CLI output is rendered through Spectre.Console widgets, including plain diagnostics and transient terminal frames; single-key confirmations use Spectre's IAnsiConsoleInput port, while the REPL line reader stays Console.ReadLine to preserve piped stdin/EOF and the custom ANSI input row.

Install the .NET tool

A .NET 11 SDK is required to install and run .NET tools. Install it with dotnet tool install, not dotnet add package (that is for the SharpCoder library):

dotnet tool install --global SharpCoder.Cli
sharpcoder --help                              # list all flags
sharpcoder "fix the build"                     # one-shot task
sharpcoder chat                                # interactive REPL (default)

Prerelease develop builds: dotnet tool install -g SharpCoder.Cli --prerelease (or pin --version 0.25.0-beta.N). Run once without installing on SDK 10+: dnx SharpCoder.Cli -- --help. To pin a version per repository, use dotnet new tool-manifest + dotnet tool install SharpCoder.Cli + dotnet tool run sharpcoder. Update or remove with dotnet tool update -g SharpCoder.Cli / dotnet tool uninstall -g SharpCoder.Cli. The tool package bundles the library and provider assemblies, so it has no NuGet dependency on the library packages. Full install notes and requirements are in src/SharpCoder.Cli/README.md, which is also the package readme on NuGet.

Standalone binaries (GitHub Releases)

Every vX.Y.Z tag also publishes six self-contained, single-file archives on the GitHub Releases page, built by .github/workflows/github-release.yml. The archives are named sharpcoder-<version>-<rid>.zip for win-x64, win-arm64, linux-x64, linux-arm64, osx-x64 and osx-arm64. Each contains one executable (sharpcoder.exe or sharpcoder), the CLI readme and the MIT license. No .NET SDK or runtime is needed — extract it and put the binary on your PATH:

unzip sharpcoder-0.25.0-linux-x64.zip
chmod +x sharpcoder        # if the archive did not preserve the executable bit
./sharpcoder --help

Verify downloads with the release's SHA256SUMS asset (sha256sum -c SHA256SUMS). These binaries bundle the runtime, so they are ~85–95 MB each (a framework-dependent single file would be ~12 MB but needs .NET 11 installed); use the .NET tool when size matters more than a standalone install. The binaries are currently unsigned: Windows SmartScreen may warn, and macOS Gatekeeper may require xattr -d com.apple.quarantine sharpcoder before the first run. develop prereleases are published to NuGet only — zips are produced for tags, or on demand via the workflow's workflow_dispatch input with an existing tag. Code signing/notarization and OS package-manager manifests are follow-up work.

Run from source
dotnet run --project src/SharpCoder.Cli -- \
    --model ollama-local/llama3 "Summarize this repository"

# interactive session (default)
dotnet run --project src/SharpCoder.Cli

Examples below use the source binary name SharpCoder.Cli; substitute sharpcoder when using the installed .NET tool.

In interactive mode the banner is followed by a prompt; /help lists the slash commands (/new, /fork, /session, /config, /markdown, /verbose, /clear, /exit). On interactive ANSI terminals each REPL input line is highlighted with a subdued dark-navy background and bright-white typed text, so the prompt and the text you type stand out from earlier output without reducing readability. After Enter, the following row is cleared back to the terminal's default background and one blank line is written before subsequent output, so the highlight stays on the input line only; raw/redirected, non-interactive, non-ANSI, and no-color consoles keep a plain prompt. A task given without a subcommand runs once as a one-shot (SharpCoder.Cli "fix the build" is shorthand for SharpCoder.Cli run "fix the build"). Useful options: --env <file> for a dotenv file, --config <file> for YAML settings, --home <dir> for the managed-session/config home, --new [name] / --new=<name> to start a fresh session, --fork [name] / --fork=<name> to branch the current session, --open <name> to switch to an existing one, --no-session-history for an in-memory run, --workdir, --max-steps, --reasoning, --bash (with --shell auto|pwsh|powershell|cmd|bash to pick the shell), --read-only/--no-writes to disable write_file/edit_file and omit write_session_artifact/delete_session_artifact, --confirm-tools auto|always|never (or -y/--yes) to control consent prompts for workspace writes, session-artifact writes/deletes, bash and web tools, --no-web-tools to disable web_search/web_fetch, --verbose (or /verbose) for full tool-call panels, --bash-timeout <ms> for the default bash timeout, --no-env-context to skip the startup environment snapshot, -m|--model for provider-prefixed model ids (copilot/…, github/…, ollama-local/…, ollama-cloud/…), --context-tokens for the model's context window, --retain-tokens for the verbatim tail kept on compaction, and --markdown for how assistant output is rendered. Credentials come from the same environment variables as SharpCoder.Providers (GITHUB_TOKEN/GH_TOKEN, OLLAMA_API_KEY, OLLAMA_URL, LLM_PROVIDER) or from --env. Repeated CLI settings can be stored in YAML configuration files; the current startup folder always remains the workdir. The latest managed session for that workdir resumes by default; see managed sessions.

Environment files

Use -e, --env <file> (or --env=<file>) to load KEY=value pairs before the CLI parses options or constructs a provider:

# .env — keep this file out of version control
GH_TOKEN=github_pat_...
OLLAMA_API_KEY=ollama_...
LLM_PROVIDER=ollama-cloud
OLLAMA_URL=http://localhost:11434
SharpCoder.Cli --env .env --model ollama-cloud/gpt-oss:120b "Review this repository"

Every KEY=value pair in the file is applied to the process environment, so provider tokens, URLs, model defaults (OLLAMA_MODEL, GITHUB_MODEL, COPILOT_MODEL), OLLAMA_WEB_URL, SHARPCODER_HOME, SHARPCODER_NO_SESSION_HISTORY, SHARPCODER_SESSION_RETENTION_DAYS, SHARPCODER_SESSION_MAX_CHECKPOINTS, SHARPCODER_DIAGNOSTICS_DIR, and other variables all work without being exported in the shell. Existing non-blank process environment variables take precedence; blank or missing values are filled from the file. A command-line --env is applied before home/default-config resolution, so it can set SHARPCODER_HOME; --home still wins over that variable. The startup table reports the resolved file path and applied/skipped counts, but never displays values.

Blank lines and whole-line #/; comments are ignored. An optional export prefix, single/double quotes, = inside values, and trailing # comment / ; comment are supported. Double-quoted values understand \n, \r, \t, \\, and \". Shell-style $VAR expansion and multi-line values are deliberately not performed. Relative paths are resolved from the current directory; ~/… is expanded to the user profile. Missing files, malformed lines, duplicate keys, and unsupported escapes fail startup with an actionable error that does not echo file values. Help and version requests skip loading entirely.

YAML configuration files

<home>/config.yaml is loaded automatically when it exists; a missing default file is not an error. The home resolves from --home <dir>, SHARPCODER_HOME, then ~/.sharpcoder. Use --config <file> (or --config=<file>) to select another file. Bare filenames such as work.yaml resolve under the effective home; paths containing a separator and ~/… paths are resolved as written. An explicitly selected missing file fails startup, and help/version requests skip config loading. The startup table shows the active path and whether it was loaded.

YAML is parsed with YamlDotNet. Config values are translated into equivalent CLI arguments and placed before the real command line, so explicit CLI flags win. --no-bash, --no-verbose/--compact, --writes, --web-tools, --env-context, and --hide-cursor turn config-file settings back off. A command-line --env also wins over the config file's env entry. System-wide retention keys are read directly as defaults so SHARPCODER_SESSION_RETENTION_DAYS / SHARPCODER_SESSION_MAX_CHECKPOINTS and the matching CLI flags still override config.yaml.

/config shows the active config file, the effective session home/source and history mode, plus effective, non-secret values with their source (repl, cli, env, config, or default). /config save [file] writes only non-default effective settings, including live /markdown and /verbose changes and system-wide retention values, using the nested model: shape; it never persists session-specific state such as the home, a session name/path or per-session identity. If the target folder does not exist, the CLI asks with a single-key y/N prompt on the question line; y accepts, any other key or EOF keeps the default no, and no Enter is needed. Bare save filenames resolve under the effective home, while explicit paths resolve as written. Saves are atomic.

The current startup folder always remains the workdir and is deliberately not stored in the config. Session-specific state — tasks, session/save/home paths, session names, per-session identity, secrets — and the config path itself are also excluded; put secrets in an env file and choose the home with --home or SHARPCODER_HOME instead. System-wide retention policy is the exception: session-retention-days and session-max-checkpoints apply to every session and are valid keys. Unknown keys, duplicate keys, invalid values, and accidental workdir/session-specific/home/secret entries are rejected, and values are validated through the same parser as CLI flags. model.context-tokens and model.retain-tokens accept plain numbers or the CLI's k/m suffixes.

YAML key CLI equivalent Notes
env -e, --env <file> Relative to the config file's directory; --env on the command line wins.
model.name -m, --model <model> Provider-prefixed model id or bare model id.
model.reasoning --reasoning <level> none, low, medium, high, or extra-high.
model.max-steps -n, --max-steps <n> Tool-call iteration budget per execution.
model.context-tokens --context-tokens <n> Model context window; 200k and 1m are accepted.
model.retain-tokens --retain-tokens <n> Verbatim tail kept during compaction; 8k is accepted.
markdown --markdown <mode> auto, live, full, or raw.
verbose --verbose Full tool-call panels. Override with --no-verbose/--compact.
bash --bash Enables the bash tool. Override with --no-bash.
read-only --read-only / --no-writes Removes write/edit tools. Override with --writes.
shell --shell <shell> auto, pwsh, powershell, cmd, or bash.
bash-timeout --bash-timeout <ms> Default whole-capture bash timeout.
no-env-context --no-env-context Omits startup environment digest. Override with --env-context.
no-web-tools --no-web-tools Disables web tools. Override with --web-tools.
confirm-tools --confirm-tools <mode> auto, always, or never.
show-cursor --show-cursor Keeps the cursor visible. Override with --hide-cursor.
session-retention-days --session-retention <days> System-wide age limit for retained context snapshots/events; 0 disables age pruning.
session-max-checkpoints --session-max-checkpoints <n> System-wide cap on retained completed pre-compaction snapshots; 0 disables count pruning.

Example (env: .env resolves to <home>/.env; only non-default values are needed):

env: .env
model:
  name: copilot/claude-sonnet-4.6
  reasoning: high
  max-steps: 40
  context-tokens: 200k
  retain-tokens: 8k
markdown: raw
bash: true
shell: pwsh
no-web-tools: true
confirm-tools: never
show-cursor: true
session-retention-days: 30
session-max-checkpoints: 20
SharpCoder.Cli --config work.yaml chat
# In the REPL:
/config
/config save experiments.yaml

When saving to another config directory, the env entry is rewritten as a path relative to that target directory.

Managed sessions

Sessions are managed automatically per workdir. On startup the CLI reads <home>/workspaces.json, maps the canonical current workdir to its latest session, and loads <home>/sessions/<name>/latest.json with AgentSession.LoadAsync. A first run creates a timestamped session folder (yyyyMMdd-HHmmss, with -2, -3, … suffixes for same-second collisions) and writes the registry entry. Different workdirs never share a latest session. The folder layout is:

<home>/
  config.yaml
  workspaces.json
  sessions/
    20261130-150713/
      session.json             # metadata only (name, immutable session id, workdir, timestamps)
      latest.json             # current AgentSession JSON, directly loadable
      context/000000-initial.json
      context/000001-pre-compaction.json  # one per compaction attempt
      context/000002-fork-source.json     # exact source latest.json at a branch point
      checkpoints.jsonl       # pending / compacted / aborted / fork-source metadata
      events.jsonl            # bounded turn, compaction, lifecycle and artifact write/delete records
      artifacts/             # bounded .md/.txt/.json plan/review/report files
      .lock                   # PID/process-start owner while a CLI is active

latest.json is atomically replaced after every turn, after a successful compaction and at exit, including Ctrl+C and REPL EOF. Writes use a sibling temp file and File.Move(overwrite: true), so an interrupted write leaves either the previous complete state or the new complete state. Missing, corrupt or mismatched registry/state is preserved: the CLI warns, starts a new session and points the workdir at it. A live .lock owner fails startup with an actionable message rather than racing writes. Home, session directories and transcripts get user-only Unix modes; Windows relies on the inherited user ACL.

Before each compaction attempt, the CLI writes one numbered, directly loadable context/NNNNNN-pre-compaction.json snapshot of the authoritative live history (including in-flight tool-loop messages) and a pending record in checkpoints.jsonl. Success atomically replaces latest.json with the compacted state and appends a compacted record with the reduction statistics; there is deliberately no numbered post-compaction file. Failure or cancellation appends aborted, keeps the pre-compaction snapshot and leaves latest.json unchanged. Numbering is monotonic from session.json, so repeated mid-loop compactions in one turn are supported. Bounded, control-character-sanitized turn, lifecycle and compaction records are appended to events.jsonl; full transcript bodies remain in latest.json and the numbered snapshots. Checkpoint/event I/O failures produce a plain stderr warning and never fail an agent turn.

--fork [name] / --fork=<name> and /fork [name] branch a session into a new folder and identity. All regular source files are recursively duplicated into a hidden temp sibling, excluding only transient .lock and *.tmp files; relative paths, timestamps and user-only modes are preserved. The source latest.json is copied verbatim to a monotonic context/NNNNNN-fork-source.json snapshot and indexed with a fork-source row in checkpoints.jsonl plus a bounded session_forked record in events.jsonl. The fork's own latest.json is an AgentSession.Fork() state: deep-copied message history, a new immutable session ID, fresh timestamps, zeroed cumulative token/usage counters, and the source's LastKnownContextTokens. session.json records the source name/ID and fork time, workspaces.json points the current workdir at the fork, and the source folder remains unchanged. There is no numbered post-fork file: after the branch-point snapshot, latest.json is the current state.

The agent also gets five bounded, CLI-only tools registered through AgentOptions.CustomTools: list_session_artifacts, read_session_artifact, write_session_artifact, delete_session_artifact and search_session_history. Artifact files stay inside <session>/artifacts/; the existing read_file/write_file/glob/grep workdir confinement is unchanged. Only relative .md, .txt and .json paths are accepted. Traversal, absolute paths, terminal-control characters and symlink/reparse-point escapes are rejected, and file/content size, list entries, read lines, search results and returned characters are capped. write_session_artifact uses an atomic private write; delete_session_artifact removes one regular file after the same path/reparse-point checks and appends a bounded artifact_deleted event. Both write and delete are guarded by tool confirmation and omitted with --read-only; deletion never recurses into directories, and all five tools are disabled by --no-session-history. Every model-facing result is explicitly labeled UNTRUSTED DATA. search_session_history returns bounded checkpoint/event metadata snippets with IDs and numbered snapshot filenames only — it never rehydrates full transcripts into context. Custom instructions expose the active session name, artifact directory and registered tool names but never file contents, and are refreshed before each turn so REPL session switches are reflected. /session artifacts prints a bounded metadata table through Spectre widgets.

--home <dir> overrides SHARPCODER_HOME, which overrides the default ~/.sharpcoder; a command-line --env file may supply the variable. --no-session-history or SHARPCODER_NO_SESSION_HISTORY=1 skips every registry/session read and write (use --session-history to override the variable for one run), and is mutually exclusive with --new, --fork, --open, /new, /fork and the managed /session verbs — bare /session statistics still work in memory. The startup table, /config and /session show the effective name, folder, home and source. The legacy --session, --save and /save forms are removed; passing them produces an actionable error. --no-session-history also disables the dedicated artifact and session-history tools.

System-wide retention is configured in config.yaml with session-retention-days and session-max-checkpoints, overridden by SHARPCODER_SESSION_RETENTION_DAYS / SHARPCODER_SESSION_MAX_CHECKPOINTS and then by --session-retention / --session-max-checkpoints (assigned =<value> forms are also accepted); 0 disables a rule. The effective values are stored in session.json as a retention snapshot. /session checkpoints shows bounded metadata for numbered snapshots and compaction status; /session prune applies the policy after a single-key y/N confirmation. Pruning protects latest.json, session.json, initial/fork-source snapshots and pending compactions, and atomically rewrites checkpoints.jsonl/events.jsonl alongside the files it removes. Retention also runs automatically at startup when a policy is configured.

Start, switch and inspect sessions explicitly:

SharpCoder.Cli --new chat                                  # fresh timestamped session
SharpCoder.Cli --new review-1 chat                         # fresh named session
SharpCoder.Cli --new=review-1 run "Fix the failing test"    # unambiguous name + one-shot task
SharpCoder.Cli --new run "Fix the failing test"             # `run` is never read as a name
SharpCoder.Cli --fork chat                                 # branch the current session (timestamped)
SharpCoder.Cli --fork branch chat                          # named branch
SharpCoder.Cli --fork=review-2 run "Explore an alternative" # unambiguous name + one-shot task
SharpCoder.Cli --open 20261130-150713 --fork branch chat   # choose the fork source
SharpCoder.Cli --open 20261130-150713 chat                 # make an existing session current

--new ignores --open and never touches the workdir's previous session folder; its files stay available on disk. --fork uses --open <name> as its source when supplied; otherwise it branches the workdir's current session (or the live REPL session). If no persisted or active source exists, it fails with an actionable --new hint. --open when used alone takes a session name, not a file path, and points the current workdir's registry entry at that folder. --new and --fork are mutually exclusive. Session names are single tokens: no whitespace, path separators, ./.., control characters, trailing dots/spaces or Windows reserved device names. Unicode is allowed (the canonical folder name and the display spelling are stored separately), and an explicit-name collision fails with an actionable error suggesting /session list. The space-separated --new <name> and --fork <name> forms use strict lookahead so flags, run/chat, quoted tasks and another option's required value are never mistaken for names; --new=<name> and --fork=<name> are always unambiguous. A single-word bare task immediately after --new or --fork is interpreted as the optional name, so use --new run "<task>", --fork run "<task>", --new=<name> "<task>" or --fork=<name> "<task>" for one-shot runs.

Inside the REPL, /new [name] finalizes the current session and starts a new one; /fork [name] finalizes it, then copies all regular files into a new branch, adds the fork-source snapshot and lineage/checkpoint/event records, assigns a fresh AgentSession.Fork() identity, points the workdir registry at the fork and leaves the source folder unchanged. Startup --fork uses the persisted source state, while REPL /fork finalizes the live transcript first. /session open <name> switches to an existing session; /session rename <name> moves the active folder, updates session.json and every workspaces.json entry pointing at the old name, and leaves sessionId unchanged; /session list [all] lists sessions for the current workdir (or every workdir) from metadata only; /session path prints the active folder, /session artifacts lists bounded artifact metadata, /session checkpoints shows numbered checkpoint/compaction metadata, and /session prune applies configured retention after confirmation. A switch finalizes latest.json first, releases the old .lock and acquires the new one. Opening or creating a session from a different workdir intentionally keeps that folder's original metadata while the registry now points at it.

Transcripts, session artifacts, duplicated fork history, and numbered pre-compaction/fork-source snapshots are stored unencrypted and can contain source snippets, secrets, tool output and retrieved web content. Every fork duplicates that history and its artifacts into another folder. Artifact contents and history snippets are untrusted data, never instructions. Protect the SharpCoder home, avoid committing it, and use --no-session-history for sensitive or ephemeral runs.

Web search and fetch

When OLLAMA_API_KEY is set, the CLI registers web_search and web_fetch regardless of the selected chat model provider. They call Ollama's cloud web API at https://ollama.com/ with a request-scoped bearer credential; set OLLAMA_WEB_URL to an absolute HTTPS URL (optionally with a path prefix) to use another backend. The credential is re-read for every call and is never displayed or logged. Use --no-web-tools to remove both tools. Queries and URLs chosen by the model are sent to the external backend, and retrieved pages are untrusted data, so these calls are guarded by tool confirmation and remote control characters are stripped before results reach the model or terminal. A malformed OLLAMA_WEB_URL fails at startup; the configuration table shows the effective backend authority.

REPL commands
Command Description
/help Show the in-REPL command table
/new [name] Finalize the current session and start a new one (timestamped by default)
/fork [name] Copy the current session into a new fork with its own identity and history
/session Show the active managed session: name, id, folder, home, history mode and session statistics
/session open <name> Switch to an existing managed session and make it current for this workdir
/session rename <name> Rename/move the active folder, updating the manifest and workdir registry
/session list [all] List sessions for this workdir (or all workdirs) from metadata only
/session path Print the active session folder
/session artifacts List bounded metadata for this session's .md/.txt/.json artifact files
/session checkpoints Show bounded numbered checkpoint and compaction metadata
/session prune Apply configured session retention after a single-key confirmation
/config Show the active config file, effective settings, and their source (repl, cli, env, config, default)
/config save [file] Save non-default settings to the active file or another YAML file
/markdown [mode] Show or set markdown rendering (auto, live, full, raw)
/verbose [on\|off] Show or set tool display: compact one-liners (default) or full panels
/clear Clear the screen (does not clear the conversation history)
/exit, /quit, /q Finalize the managed session and exit

Managed per-turn autosaves are silent and automatic; /save is removed. latest.json is written atomically (temp file + replace), so an interrupted save cannot leave a truncated, unloadable JSON file.

Structured tool updates

The CLI renders tool calls in two modes, switched with /verbose [on|off] (or --verbose at startup):

  • Compact (default) — one line per call (two for bash), driven by structured ToolCallFacts rather than by scraping result text. Each line is two columns: the icon, label and subject (a filename, search pattern or skill name) flush left, and the metrics + elapsed time flush right at the terminal margin. This keeps the numbers in a fixed column across a stream of calls, so they are easy to scan. A width-aware path emphasises the filename and elides directories from the left when needed. Examples at 80 columns:

    🔧 ✓ Read  src/SharpCoder.Cli/ConsoleUi.cs     138–210 · 4,182 chars · 8ms
    🔧 ✓ Edit  src/SharpCoder.Cli/Program.cs          1× · −27/+41 chars · 4ms
    🔧 ✓ Write CHANGELOG.md                                 2,910 chars · 2ms
    🔧 ✓ Grep  FlushPending  *.cs               7 matches in 3 files · 41ms
    🔧 ✓ Skill build                                                   1ms
    🔧 ✓ Bash  ⏱ 2m (default) timeout                        1.4s · exit 0
                dotnet build SharpCoder.slnx --nologo -v q
    

    read_file shows the line range and characters read; edit_file shows occurrences replaced plus characters removed/added; glob/grep show match and file counts; load_skill/list_skills show the skill name or count; bash shows the effective timeout (human-readable, "(default)" when it came from --bash-timeout) on the left and elapsed time + exit code on the right, with the command on a second line. Unknown/custom tools fall back to a generic one-liner. On very narrow terminals whole metric segments are dropped (keeping the elapsed time) so the filename never vanishes and the line never wraps. Errors are red with ✗.

    While a compact call is running, the CLI shows the same styled line with a yellow spinner and Ns · running in the right column (Bash reserves its two-row preview). The preview is repainted in place at the shared 80 ms heartbeat and cleared before the permanent result. Context compaction is separated from the surrounding output by blank lines and a cyan ↻ context compacted rule carrying the before/after statistics.

  • Verbose — one Spectre panel per call with all arguments, the full untruncated result, running/success/error status, elapsed time, and a round/step progress line. Useful for build/test logs.

In --markdown raw mode (redirected output) neither mode writes anything, so SharpCoder.Cli run "..." > out.txt contains only the model's text. The compact/verbose choice applies only to tool-call display; markdown rendering of assistant prose is controlled separately by --markdown.

These come from the library's additive AgentOptions.EmitStructuredToolUpdates flag. When enabled on the manual streaming tool loop, CodingAgent emits StreamingUpdateKind.ToolCallStarted, ToolCallCompleted and RoundProgress updates carrying ToolCallUpdate (full arguments, untruncated result, error flag, elapsed time) and RoundProgressUpdate. The flag defaults to false; the pre-existing markdown text narration is still emitted unchanged, so existing hosts that only read TextDelta see exactly the same output:

var options = new AgentOptions
{
    ShowToolCallsInStream = true,
    EmitStructuredToolUpdates = true,
};

await foreach (var update in agent.ExecuteStreamingAsync(session, task))
{
    if (update.Kind == StreamingUpdateKind.ToolCallCompleted && update.ToolCall is { } t)
        Console.WriteLine($"{t.Name}: {t.Result} ({t.Elapsed.TotalMilliseconds:n0} ms, error={t.IsError})");
}

The flag has no effect on the default streaming path, where FunctionInvokingChatClient owns the tool loop and individual invocations are not observable.

Tool confirmation

By default the CLI asks for consent before write_file, edit_file, write_session_artifact, delete_session_artifact, execute_bash_command, web_search and web_fetch run. The prompt is a rounded cyan panel whose header shows the friendly tool label (e.g. Bash) and the actual tool name; arguments appear as an indented block, with simple shell syntax highlighting for Bash commands (the panel border frames the preview, so no literal markdown fences are printed). Answer y to allow once, n to deny once (the default), a to allow all remaining calls in the session, or s to deny all remaining calls. Local read/search tools, artifact list/read and history search, and skills are never prompted; web tools are guarded because they disclose model-chosen inputs to an external service and return untrusted content. A denial is returned to the agent as a refusal — the tool does not run and no file, command, or web request is affected.

--confirm-tools selects the mode:

Mode Behavior
auto (default) Prompt on an interactive terminal; auto-allow when input or output is redirected, so SharpCoder.Cli run … > out.txt never hangs
always Prompt even when redirected; EOF / no answer denies (fail closed)
never Allow all guarded calls without asking — for CI and trusted batches

-y / --yes is an alias for never. The startup configuration table shows the effective mode. Note that --read-only and --no-writes remove the workspace and session-artifact write/delete tools entirely, which is a stronger guarantee than prompting.

Startup environment context

By default the CLI adds a compact environment context block to the agent's system prompt so the model knows its surroundings without probing: OS/architecture, .NET runtime and SDK version, work directory, git branch / status / last commit, a bounded top-level workspace listing, and the enabled tool set (including the resolved shell and read-only state). It is a startup snapshot — the agent should re-check with a tool if state may have changed. Everything is best-effort with short timeouts (a missing toolchain or a non-git directory reports unavailable) and the output is capped (20 git-status lines, 40 workspace entries, 4,000 characters per command), so it cannot consume a meaningful share of the context window. Use --no-env-context to disable it; the startup configuration table shows the effective setting.

Markdown rendering

Assistant output is rendered as markdown in the terminal. The CLI renders complete blocks as they finish arriving, so output still streams live; tool-call notes are shown as dim one-liners. It understands headings, paragraphs, bold/italic/strikethrough, inline code, fenced code blocks (with language label), ordered/unordered/task lists, blockquotes, tables, links, and horizontal rules.

--markdown selects how much processing happens. It defaults to auto, which uses live on an interactive terminal and raw when output is redirected or piped (so SharpCoder.Cli … > out.txt stays plain text):

Mode Behavior
live Render each block as soon as it is complete (default on a TTY)
full Buffer the whole turn and render once at the end
raw No processing; the model's bytes are written verbatim
auto live on a TTY, raw otherwise (default)

/markdown in the interactive REPL shows or changes the mode for the rest of the session.

The CLI sets the context window used for compaction decisions to 1,000,000 tokens by default (the library default is 100,000), and keeps up to 16,000 tokens of recent conversation verbatim when compacting (--retain-tokens); older tool results are first replaced with one-line elision stubs, and only if that is not enough is the remainder summarized. Override it with --context-tokens — accepts a raw number or a k/m suffix (e.g. --context-tokens 200000, --context-tokens 200k, --context-tokens 1m). Compaction triggers at 80% of the configured window. Set this to your model's real window: set it too low and the agent compacts long before it needs to; set it too high and a smaller model fails with context-overflow errors (the agent then force-compacts and retries once, at the cost of the failed request and a more aggressive compaction than pre-emptive one).

The source build produces a SharpCoder.Cli binary; the published .NET tool is invoked as sharpcoder. The CLI targets net11.0 and is included in SharpCoder.slnx, so CI builds, tests and packs it with the .NET 11 SDK. dotnet pack src/SharpCoder.Cli produces the SharpCoder.Cli tool package; before publishing, CI installs that package from a local feed and runs sharpcoder --version as a smoke test. Build the whole solution with dotnet build SharpCoder.slnx, or build the CLI directly with dotnet build src/SharpCoder.Cli.

Security

  • Path traversal protection — all file operations are confined to WorkDirectory
  • Bash disabled by default — opt in explicitly with EnableBash = true (CLI: --bash)
  • Web tools require a credential and guarded egress — the CLI registers web_search/web_fetch only when OLLAMA_API_KEY is non-blank (in the process environment or --env), uses HTTPS with redirects disabled, and asks for consent under --confirm-tools; use --no-web-tools to remove them. Remote results are sanitized but remain untrusted data subject to prompt-injection policy.
  • File writes are enabled by default, but confirmed interactively — the CLI registers write_file/edit_file/write_session_artifact/delete_session_artifact and asks for consent via AuthorizeTool on an interactive terminal (see Tool confirmation). In redirected/scripted runs auto mode allows them without prompting, so use --confirm-tools always, -y/--yes deliberately, or --read-only/--no-writes (which removes the workspace and session-artifact write/delete tools entirely). The library itself has no confirmation prompt: hosts must set AgentOptions.AuthorizeTool or EnableFileWrites = false themselves. The CLI's startup configuration table shows the effective settings. Only enable writes in trusted or sandboxed environments.
  • Home-directory guard for bash (best-effort, not a sandbox) — execute_bash_command refuses a command before launching the shell if it assigns $HOME (or $env:USERPROFILE, $env:HOMEDRIVE, $env:HOMEPATH, $env:HOME, $PSHOME) or combines a delete/clear/format verb with a home path ($HOME, ~, %USERPROFILE%, the literal profile path or its parent). PowerShell's $HOME is read-only and AllScope: $HOME = 'C:\Temp\scratch' fails with a non-terminating error while $HOME still resolves to the real user profile, so a following Remove-Item -Recurse -Force $HOME can erase the entire profile (SSH/PGP keys, credentials, documents). The refusal is returned to the model as a tool result so it can rewrite the command with an explicit workspace-relative path. Enabled by default through AgentOptions.BashHomeGuard; the CLI never disables it, so it still applies with --confirm-tools never/-y. The same rules are in the system prompt and tool description. This is a conservative text-level check, not a sandbox: dynamically built variable names, Invoke-Expression and other indirection can get past it.
  • No sandboxing for bash — apart from the guard above, when enabled the agent has full shell access with the process's privileges. Only enable in trusted environments (containers, CI runners)

License

MIT

Product Compatible and additional computed target framework versions.
.NET net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.26.0-beta.212 0 12/2/2026
0.26.0-beta.211 0 12/2/2026
0.26.0-beta.210 0 12/2/2026
0.25.0 0 12/1/2026
0.25.0-beta.208 10 12/1/2026
0.25.0-beta.207 10 12/1/2026
0.25.0-beta.206 10 12/1/2026
0.25.0-beta.205 52 11/30/2026
0.25.0-beta.204 55 11/30/2026
0.25.0-beta.203 56 11/30/2026
0.25.0-beta.200 50 11/30/2026
0.25.0-beta.199 55 11/30/2026
0.25.0-beta.198 60 11/30/2026
0.25.0-beta.197 54 11/30/2026
0.25.0-beta.196 53 11/30/2026
0.24.0-beta.195 56 11/30/2026
0.24.0-beta.194 58 11/30/2026
0.24.0-beta.193 57 11/30/2026
0.24.0-beta.192 58 11/29/2026
0.24.0-beta.191 61 11/29/2026
Loading failed