Skip to content
Open
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
99 changes: 99 additions & 0 deletions src/SharpClaw.Code.Acp/AcpLiveTurns.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,35 @@ internal sealed class AcpLiveTurns(ILiveTurnControlService? controls, Func<JsonO
{
private sealed record ActivePrompt(string Workspace, string SessionId, LiveTurnHandle Handle);
private readonly ConcurrentDictionary<string, ActivePrompt> active = new(StringComparer.Ordinal);
private sealed record OrdinaryPrompt(string Workspace, string SessionId, CancellationTokenSource Cancellation);
private readonly ConcurrentDictionary<string, OrdinaryPrompt> ordinary = new(StringComparer.Ordinal);

/// <summary>
/// Runs a prompt that did not opt into live turn control. It keeps the ordinary semantics (stdin EOF does not
/// cancel it) but is tracked so an id-less <c>session/cancel</c> notification for its session can stop it, in
/// which case it completes with <c>stopReason: "cancelled"</c>.
/// </summary>
internal async Task<JsonObject> RunOrdinaryAsync(JsonNode id, string? workspace, string? sessionId, Func<CancellationToken, Task<JsonObject>> run, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(workspace) || string.IsNullOrEmpty(sessionId))
return await run(cancellationToken).ConfigureAwait(false);

using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var key = id.ToJsonString();
var tracked = ordinary.TryAdd(key, new(Path.TrimEndingDirectorySeparator(workspace), sessionId, cancellation));
try
{
return await run(cancellation.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellation.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
return new JsonObject { ["stopReason"] = "cancelled" };
}
finally
{
if (tracked) ordinary.TryRemove(key, out _);
}
}

internal async Task<JsonObject> RunAsync(JsonNode id, string workspace, string sessionId, Func<CancellationToken, Task<JsonObject>> run)
{
Expand Down Expand Up @@ -67,6 +96,76 @@ internal JsonObject Control(string workspace, JsonNode? parameters, bool cancel)
return new JsonObject { ["accepted"] = cancel || target.Handle.TrySteer(text!) };
}

/// <summary>
/// Handles an id-less <c>session/cancel</c> notification. Cancels every live prompt of the named session
/// (optionally narrowed by <c>promptRequestId</c> and <c>cwd</c>); each cancelled prompt then completes with
/// <c>stopReason: "cancelled"</c>. Cancelling all of them is deterministic and matches the notification's
/// session-level intent.
/// </summary>
internal int CancelSession(JsonNode? parameters)
{
if (parameters?["sessionId"] is not JsonValue sessionValue
|| !sessionValue.TryGetValue<string>(out var sessionId)
|| string.IsNullOrEmpty(sessionId))
return 0;

// An omitted selector means "the whole session"; a present but malformed one cancels nothing.
string? promptRequestId = null;
if (parameters is JsonObject parameterObject && parameterObject.TryGetPropertyValue("promptRequestId", out var selector))
{
if (selector is not JsonValue requested
|| !(requested.TryGetValue<string>(out _) || requested.TryGetValue<long>(out _)))
return 0;
promptRequestId = requested.ToJsonString();
}

string? workspace = null;
if (parameters is JsonObject withCwd && withCwd.TryGetPropertyValue("cwd", out var cwdNode))
{
if (cwdNode is not JsonValue cwdValue || !cwdValue.TryGetValue<string>(out var cwd) || string.IsNullOrWhiteSpace(cwd))
return 0;
try
{
workspace = Path.GetFullPath(cwd);
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return 0;
}
}
var cancelled = 0;
foreach (var (key, target) in active)
{
if (target.SessionId != sessionId
|| (promptRequestId is not null && key != promptRequestId)
|| (workspace is not null && !string.Equals(target.Workspace, Path.TrimEndingDirectorySeparator(workspace),
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)))
continue;
target.Handle.Cancel();
cancelled++;
}

foreach (var (key, target) in ordinary)
{
if (target.SessionId != sessionId
|| (promptRequestId is not null && key != promptRequestId)
|| (workspace is not null && !string.Equals(target.Workspace, Path.TrimEndingDirectorySeparator(workspace),
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)))
continue;
try
{
target.Cancellation.Cancel();
cancelled++;
}
catch (ObjectDisposedException)
{
// The prompt finished concurrently.
}
}

return cancelled;
}

private static void AddPending(JsonObject result, IReadOnlyList<string> pending)
{
if (pending.Count == 0) return;
Expand Down
54 changes: 53 additions & 1 deletion src/SharpClaw.Code.Acp/AcpStdioHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,39 @@ public async Task RunAsync(TextReader stdin, TextWriter stdout, CancellationToke
private async Task ProcessRequestAsync(JsonObject requestObject, AcpLiveTurns live, TextWriter stdout, CancellationToken cancellationToken)
{
var id = requestObject["id"];
if (!requestObject.ContainsKey("id"))
Comment thread
Telli marked this conversation as resolved.
Resolved
{
// JSON-RPC 2.0: a well-formed message without an id is a notification and must never receive a
// response. A malformed one is still an invalid request, answered with a null id.
if (requestObject["jsonrpc"] is not JsonValue notificationVersion
|| !notificationVersion.TryGetValue<string>(out var notificationProtocol) || notificationProtocol != "2.0"
|| requestObject["method"] is not JsonValue notificationName
|| !notificationName.TryGetValue<string>(out var notificationMethod) || string.IsNullOrWhiteSpace(notificationMethod))
{
await WriteErrorAsync(stdout, null, -32600, "Invalid request.", cancellationToken).ConfigureAwait(false);
return;
}

try
{
if (notificationMethod == "session/cancel")
{
// ACP clients send cancellation as a notification naming the session.
live.CancelSession(requestObject["params"]);
}
else
{
logger.LogDebug("Ignoring ACP notification {Method}.", notificationMethod);
}
}
catch (Exception ex) when (ex is AcpRequestException or InvalidOperationException or FormatException or ArgumentException)
{
logger.LogDebug(ex, "Ignoring malformed ACP notification {Method}.", notificationMethod);
}

return;
Comment thread
Telli marked this conversation as resolved.
Resolved
}

if (requestObject["jsonrpc"] is not JsonValue version || !version.TryGetValue<string>(out var protocol) || protocol != "2.0"
|| requestObject["method"] is not JsonValue name || !name.TryGetValue<string>(out var method) || string.IsNullOrWhiteSpace(method)
|| id is not JsonValue)
Expand Down Expand Up @@ -147,7 +180,12 @@ private async Task ProcessRequestAsync(JsonObject requestObject, AcpLiveTurns li
"session/load" => await HandleSessionLoadAsync(parameters, cancellationToken).ConfigureAwait(false),
"session/prompt" when parameters?["liveTurnControl"]?.GetValue<bool>() == true =>
await live.RunAsync(id, RequireWorkspace(parameters), RequireSession(parameters), token => HandleSessionPromptAsync(parameters, stdout, token, id)).ConfigureAwait(false),
"session/prompt" => await HandleSessionPromptAsync(parameters, stdout, cancellationToken).ConfigureAwait(false),
"session/prompt" => await live.RunOrdinaryAsync(
id,
TryGetWorkspace(parameters),
parameters?["sessionId"] is JsonValue promptSession && promptSession.TryGetValue<string>(out var promptSessionId) ? promptSessionId : null,
token => HandleSessionPromptAsync(parameters, stdout, token),
cancellationToken).ConfigureAwait(false),
"session/steer" => live.Control(RequireWorkspace(parameters), parameters, cancel: false),
"session/cancel" => live.Control(RequireWorkspace(parameters), parameters, cancel: true),
"models/list" => await HandleModelsListAsync(cancellationToken).ConfigureAwait(false),
Expand Down Expand Up @@ -386,6 +424,20 @@ private async Task<JsonObject> HandleSessionPromptAsync(
return Task.FromResult<JsonNode?>(new JsonObject { ["resolved"] = resolved });
}

private string? TryGetWorkspace(JsonNode? parameters)
{
try
{
return parameters?["cwd"] is JsonValue cwd && cwd.TryGetValue<string>(out var value) && !string.IsNullOrWhiteSpace(value)
? pathService.GetFullPath(value)
: null;
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return null;
}
}

private string RequireWorkspace(JsonNode? parameters)
{
var cwd = parameters?["cwd"]?.GetValue<string>() ?? throw new InvalidOperationException("cwd is required.");
Expand Down
21 changes: 18 additions & 3 deletions src/SharpClaw.Code.Agents/Internal/ProviderBackedAgentKernel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,8 @@ internal async Task<ProviderInvocationResult> ExecuteAsync(
CreateProviderFailedEventMessage(provider.ProviderName, providerEvent));
}

if (!providerEvent.IsTerminal && !string.IsNullOrWhiteSpace(providerEvent.Content))
// Keep whitespace-only deltas (newlines, indentation): dropping them corrupts code blocks.
if (!providerEvent.IsTerminal && !string.IsNullOrEmpty(providerEvent.Content))
{
candidateTextSegments.Add(providerEvent.Content);
}
Expand Down Expand Up @@ -337,9 +338,22 @@ internal async Task<ProviderInvocationResult> ExecuteAsync(
break;
}

var iterationText = string.Concat(iterationTextSegments);
if (iteration + 1 >= options.MaxToolIterations)
{
// Final allowed iteration: executing these tools would cause side effects whose results the
// model can never observe, so stop here and report the loop as exhausted instead.
if (!string.IsNullOrEmpty(iterationText))
{
outputSegments.Add(iterationText);
}

iteration = options.MaxToolIterations;
break;
}

// Build assistant message with text + tool-use content blocks
var assistantBlocks = new List<ContentBlock>();
var iterationText = string.Concat(iterationTextSegments);
if (!string.IsNullOrEmpty(iterationText))
{
assistantBlocks.Add(new ContentBlock(ContentBlockKind.Text, iterationText, null, null, null, null));
Expand All @@ -352,7 +366,8 @@ internal async Task<ProviderInvocationResult> ExecuteAsync(
null,
toolUseEvent.ToolUseId,
toolUseEvent.ToolName,
toolUseEvent.ToolInputJson,
// Record exactly what the dispatcher executes; a blank input would round-trip as JSON null.
string.IsNullOrWhiteSpace(toolUseEvent.ToolInputJson) ? "{}" : toolUseEvent.ToolInputJson,
null));
}

Expand Down
2 changes: 1 addition & 1 deletion src/SharpClaw.Code.Agents/Internal/ToolCallDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public sealed class ToolCallDispatcher(
}

var toolName = toolUseEvent.ToolName;
var toolInputJson = toolUseEvent.ToolInputJson ?? "{}";
var toolInputJson = string.IsNullOrWhiteSpace(toolUseEvent.ToolInputJson) ? "{}" : toolUseEvent.ToolInputJson;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
var toolUseId = toolUseEvent.ToolUseId;

if (string.Equals(toolName, SubAgentToolContract.ToolName, StringComparison.OrdinalIgnoreCase))
Expand Down
37 changes: 30 additions & 7 deletions src/SharpClaw.Code.Git/Services/GitWorkspaceService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public async Task<GitWorkspaceSnapshot> GetSnapshotAsync(string workingDirectory
var repositoryRoot = NormalizeLine(repositoryRootResult.StandardOutput);
var currentBranchTask = RunGitAsync(workingDirectory, ["branch", "--show-current"], cancellationToken);
var headTask = RunGitAsync(workingDirectory, ["rev-parse", "HEAD"], cancellationToken);
var statusTask = RunGitAsync(workingDirectory, ["status", "--porcelain=v1", "--branch"], cancellationToken);
var statusTask = RunGitAsync(workingDirectory, ["status", "--porcelain=v1", "-z", "--branch"], cancellationToken);
var diffTask = RunGitAsync(workingDirectory, ["diff", "--no-ext-diff", "--stat"], cancellationToken);
var freshnessTask = RunGitAsync(workingDirectory, ["rev-list", "--left-right", "--count", "@{upstream}...HEAD"], cancellationToken);
var worktreeListTask = ListWorktreesCoreAsync(workingDirectory, repositoryRoot ?? workingDirectory, cancellationToken);
Expand Down Expand Up @@ -189,19 +189,42 @@ private async Task<GitWorktreeList> ListWorktreesCoreAsync(string workingDirecto

private static IReadOnlyList<GitStatusEntry> ParseStatusEntries(string output)
{
// `git status --porcelain=v1 -z` separates records with NUL, never C-quotes paths, and emits the original
// path of a rename/copy as an extra NUL-terminated field. Newline-separated output is accepted as a fallback.
var nulSeparated = output.Contains('\0', StringComparison.Ordinal);
var records = nulSeparated
? output.Split('\0')
: output.Split('\n').Select(static line => line.TrimEnd('\r')).ToArray();
var entries = new List<GitStatusEntry>();
foreach (var rawLine in output.Split('\n', StringSplitOptions.RemoveEmptyEntries))
for (var index = 0; index < records.Length; index++)
{
var line = rawLine.TrimEnd('\r');
if (line.StartsWith("##", StringComparison.Ordinal) || line.Length < 4)
var record = records[index];
if (record.StartsWith("##", StringComparison.Ordinal) || record.Length < 4)
{
continue;
}

var indexStatus = record[0];
var workingTreeStatus = record[1];
var path = record[3..];
if (nulSeparated && (indexStatus is 'R' or 'C' || workingTreeStatus is 'R' or 'C'))
{
// Skip the original-path field that follows a rename/copy record.
index++;
}
else if (!nulSeparated)
{
var arrow = path.IndexOf(" -> ", StringComparison.Ordinal);
if ((indexStatus is 'R' or 'C') && arrow >= 0)
{
path = path[(arrow + 4)..];
}
}

entries.Add(new GitStatusEntry(
Path: line[3..].Trim(),
IndexStatus: line[0].ToString(),
WorkingTreeStatus: line[1].ToString()));
Path: path,
IndexStatus: indexStatus.ToString(),
WorkingTreeStatus: workingTreeStatus.ToString()));
}

return entries;
Expand Down
Loading
Loading