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
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,20 @@ ACP agents can discover and read enabled MandoCode skills with `list_skills`, `l
reads are restricted to the selected skill folder and do not execute scripts. Native skill management and third-party
`mcpServers` settings remain separate; configure third-party servers through the adapter's own tooling.

ACP agents can run non-interactive builds, tests, and scripts in MandoCode-managed terminals. Adapters can use
ACP v1's `terminal/*` methods; agents can also use the bridge tools `create_terminal`, `get_terminal_output`,
`wait_for_terminal`, `kill_terminal`, and `release_terminal`. Pass an executable and literal arguments separately;
use an explicit shell executable when shell syntax is needed. Output appears live in an expandable command row,
including stdout, stderr, truncation, and exit status, and remains visible after release.

The working directory defaults to this pane's project; requested directories must stay inside it, including through
links. Commands use the ACP entry's environment rules and ordinary user permissions; execution is not a filesystem
sandbox. Each command has a ten-minute limit. Captured output defaults to 64 KiB and is capped at 1 MiB per terminal;
older output is dropped on UTF-8 boundaries. Each runtime allows eight running terminals and 32 retained terminal IDs.
Escape stops session command trees; `/clear`, restart, folder changes, and pane closure clean up owned terminals.
Released IDs cannot be reused. Set `"clientTerminals": false` on an ACP entry to disable both terminal routes.
The MCP route additionally requires `mandoCodeMcp` to be enabled. ACP v2 negotiation is not added by this feature.

When switching this pane between native and ACP agents, choose whether to carry a conversation recap. The agent
you are leaving generates it, and the next user message delivers it as reference context to the target. Declining
keeps the target's existing conversation without adding a recap; cancellation or a failed recap keeps the source
Expand Down
6 changes: 6 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ All notable changes to MandoCode will be documented in this file.

**Highlights**

- Run ACP builds, tests, and scripts through MandoCode-managed terminals, with live output and lifecycle cleanup via ACP v1 or the built-in MCP bridge.

- Collaborate between ACP and native Ollama agents with agent mentions, questions, background tasks, messages, and progress tracking.
- Discover enabled user/project skills and read their instructions and referenced text files from ACP through the built-in MandoCode MCP bridge.
- Create/import snapshots with Alt+C or `/context-snapshot`, and optionally carry a recap generated by the source agent when switching agent types.
Expand All @@ -23,6 +25,8 @@ All notable changes to MandoCode will be documented in this file.

### Added

- Run non-interactive commands in host-managed ACP terminals through the five ACP v1 `terminal/*` methods or the built-in MCP terminal tools. Stream bounded stdout/stderr into persistent command rows, report exit status, preserve displayed output after release, and isolate IDs by session. Cancel command trees on Escape and clean up on session clear, crash, restart, folder change, and closure. Apply configured ACP environment rules, validate working directories, and cap command duration, output, and terminal counts. Disable both routes per agent with `clientTerminals: false`; the reusable process backend does not require ACP v2.

- Offer a source-agent recap when switching between native and ACP agents, with opt-out and cancellation before changing runtimes.

- Share enabled user/project skills through read-only MCP discovery, instruction loading, and bounded text-resource reads inside the skill folder.
Expand Down Expand Up @@ -76,6 +80,8 @@ All notable changes to MandoCode will be documented in this file.

### Test coverage

- The ACP terminal update passed 2,038 tests with one existing skip on .NET 10 Release. Coverage includes all five ACP terminal methods, real MCP terminal calls, capability opt-out, active-session validation, literal arguments/environment, stdout/stderr and non-newline streaming, bounded UTF-8 tail output under a large flood, exit status, cancellation with child processes, per-pane isolation, and cleanup on clear, crash, and disposal. Terminal DTOs are checked against the vendored official v1 schema.

- The final ACP collaboration update passed 1,990 tests with one existing skip on .NET 10 Release. Real stdio MCP checks cover tool discovery, owning-pane identity, active-turn restrictions, call-loop prevention, cancellation, snapshot operations, skill precedence/disabled files, resource boundaries, and connection revocation. Component checks cover snapshots without Ollama, import retries and images, optional source-agent handoffs, compatible command spellings, and compact exchange rendering. A regression deliberately announces a command before the session/new response. Final focused checks and user testing also passed.

- Verify frame batching through the actual RazorConsole live canvas: a large-to-blank transition produces identical ANSI output in one underlying writer call. Cover fragmented frame markers, interrupted-frame shutdown, bounded buffering, and output restoration. All 59 selected rendering, workspace, and routing checks pass on both net8.0 and net10.0.
Expand Down
29 changes: 27 additions & 2 deletions src/MandoCode.Acp/Client/AcpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -314,10 +314,35 @@ private void RegisterHandlers()
(request, token) => _handler.WriteTextFileAsync(request, token));
}

// terminal/* is deliberately not registered: the capability is not advertised, so the connection
// answers "method not found".
if (capabilities.Terminal)
{
_connection.RegisterRequestHandler(AcpMethods.TerminalCreate, AcpJsonContext.Default.CreateTerminalRequest,
AcpJsonContext.Default.CreateTerminalResponse, (request, token) =>
{
if (!_sessions.TryGetValue(request.SessionId, out var session) || session.ActiveTurnToken is not { } turn)
throw new JsonRpcException(AcpErrorCodes.InvalidParams, "Terminal commands require an active request in this session.");
token.ThrowIfCancellationRequested();
return _handler.CreateTerminalAsync(request, turn);
});
_connection.RegisterRequestHandler(AcpMethods.TerminalOutput, AcpJsonContext.Default.TerminalOutputRequest,
AcpJsonContext.Default.TerminalOutputResponse, (request, token) => { RequireSession(request.SessionId); return _handler.TerminalOutputAsync(request, token); });
_connection.RegisterRequestHandler(AcpMethods.TerminalWaitForExit, AcpJsonContext.Default.WaitForTerminalExitRequest,
AcpJsonContext.Default.WaitForTerminalExitResponse, async (request, token) =>
{
var session = RequireSession(request.SessionId);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, session.ActiveTurnToken ?? CancellationToken.None);
return await _handler.WaitForTerminalExitAsync(request, linked.Token).ConfigureAwait(false);
});
_connection.RegisterRequestHandler(AcpMethods.TerminalKill, AcpJsonContext.Default.KillTerminalCommandRequest,
AcpJsonContext.Default.KillTerminalCommandResponse, (request, token) => { RequireSession(request.SessionId); return _handler.KillTerminalAsync(request, token); });
_connection.RegisterRequestHandler(AcpMethods.TerminalRelease, AcpJsonContext.Default.ReleaseTerminalRequest,
AcpJsonContext.Default.ReleaseTerminalResponse, (request, token) => { RequireSession(request.SessionId); return _handler.ReleaseTerminalAsync(request, token); });
}
}

private AcpSession RequireSession(string id) => _sessions.TryGetValue(id, out var session) ? session
: throw new JsonRpcException(AcpErrorCodes.InvalidParams, "Unknown ACP session.");

private async ValueTask<RequestPermissionResponse> HandlePermissionAsync(RequestPermissionRequest request, CancellationToken connectionToken)
{
var cancelled = new RequestPermissionResponse { Outcome = new CancelledPermissionOutcome() };
Expand Down
5 changes: 5 additions & 0 deletions src/MandoCode.Acp/Client/AcpSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,11 @@ internal void Adopt(SessionModeState? modes, IReadOnlyList<SessionConfigOption>?
}

/// <summary>The token a permission prompt must observe, or null when a cancel is already under way.</summary>
internal CancellationToken? ActiveTurnToken
{
get { lock (_gate) return _activeTurn is { CancelRequested: false } ? _permissionCancellation.Token : null; }
}

internal CancellationToken? BeginPermission()
{
lock (_gate)
Expand Down
20 changes: 20 additions & 0 deletions src/MandoCode.Acp/Client/IAcpClientHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,26 @@ ValueTask<ReadTextFileResponse> ReadTextFileAsync(ReadTextFileRequest request, C
/// <summary>Implements <c>fs/write_text_file</c> (only called when <see cref="Capabilities"/> advertises it).</summary>
ValueTask<WriteTextFileResponse> WriteTextFileAsync(WriteTextFileRequest request, CancellationToken cancellationToken) =>
throw new JsonRpcException(AcpErrorCodes.MethodNotFound, "fs/write_text_file is not supported.");
/// <summary>Implements <c>terminal/create</c> when terminal support is advertised.</summary>
ValueTask<CreateTerminalResponse> CreateTerminalAsync(CreateTerminalRequest request, CancellationToken cancellationToken) =>
throw new JsonRpcException(AcpErrorCodes.MethodNotFound, "terminal/create is not supported.");

/// <summary>Implements <c>terminal/output</c> when terminal support is advertised.</summary>
ValueTask<TerminalOutputResponse> TerminalOutputAsync(TerminalOutputRequest request, CancellationToken cancellationToken) =>
throw new JsonRpcException(AcpErrorCodes.MethodNotFound, "terminal/output is not supported.");

/// <summary>Implements <c>terminal/wait_for_exit</c> when terminal support is advertised.</summary>
ValueTask<WaitForTerminalExitResponse> WaitForTerminalExitAsync(WaitForTerminalExitRequest request, CancellationToken cancellationToken) =>
throw new JsonRpcException(AcpErrorCodes.MethodNotFound, "terminal/wait_for_exit is not supported.");

/// <summary>Implements <c>terminal/kill</c> when terminal support is advertised.</summary>
ValueTask<KillTerminalCommandResponse> KillTerminalAsync(KillTerminalCommandRequest request, CancellationToken cancellationToken) =>
throw new JsonRpcException(AcpErrorCodes.MethodNotFound, "terminal/kill is not supported.");

/// <summary>Implements <c>terminal/release</c> when terminal support is advertised.</summary>
ValueTask<ReleaseTerminalResponse> ReleaseTerminalAsync(ReleaseTerminalRequest request, CancellationToken cancellationToken) =>
throw new JsonRpcException(AcpErrorCodes.MethodNotFound, "terminal/release is not supported.");

}

/// <summary>A handler that advertises nothing and refuses every permission request. Used by connection probes.</summary>
Expand Down
6 changes: 6 additions & 0 deletions src/MandoCode.Acp/Protocol/AcpConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ public static class AcpProtocol
/// <summary>JSON-RPC method names used by ACP v1 (stable methods only).</summary>
public static class AcpMethods
{
public const string TerminalCreate = "terminal/create";
public const string TerminalOutput = "terminal/output";
public const string TerminalWaitForExit = "terminal/wait_for_exit";
public const string TerminalKill = "terminal/kill";
public const string TerminalRelease = "terminal/release";

// Client -> agent
public const string Initialize = "initialize";
public const string Authenticate = "authenticate";
Expand Down
11 changes: 11 additions & 0 deletions src/MandoCode.Acp/Protocol/AcpJsonContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@ namespace MandoCode.Acp.Protocol;
[JsonSerializable(typeof(ReadTextFileResponse))]
[JsonSerializable(typeof(WriteTextFileRequest))]
[JsonSerializable(typeof(WriteTextFileResponse))]
[JsonSerializable(typeof(CreateTerminalRequest))]
[JsonSerializable(typeof(CreateTerminalResponse))]
[JsonSerializable(typeof(TerminalOutputRequest))]
[JsonSerializable(typeof(TerminalOutputResponse))]
[JsonSerializable(typeof(WaitForTerminalExitRequest))]
[JsonSerializable(typeof(WaitForTerminalExitResponse))]
[JsonSerializable(typeof(KillTerminalCommandRequest))]
[JsonSerializable(typeof(KillTerminalCommandResponse))]
[JsonSerializable(typeof(ReleaseTerminalRequest))]
[JsonSerializable(typeof(ReleaseTerminalResponse))]
[JsonSerializable(typeof(TerminalExitStatus))]
// unions (the converters deserialize concrete variants through these)
[JsonSerializable(typeof(ContentBlock))]
[JsonSerializable(typeof(TextContent))]
Expand Down
40 changes: 40 additions & 0 deletions src/MandoCode.Acp/Protocol/Terminals.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System.Text.Json.Serialization;

namespace MandoCode.Acp.Protocol;

public sealed record CreateTerminalRequest : AcpObject
{
[JsonPropertyName("sessionId")] public string SessionId { get; set; } = "";
[JsonPropertyName("command")] public string Command { get; set; } = "";
[JsonPropertyName("args")] public IReadOnlyList<string> Args { get; set; } = [];
[JsonPropertyName("cwd")] public string? Cwd { get; set; }
[JsonPropertyName("env")] public IReadOnlyList<EnvVariable> Env { get; set; } = [];
[JsonPropertyName("outputByteLimit")] public ulong? OutputByteLimit { get; set; }
}
public sealed record CreateTerminalResponse : AcpObject
{
[JsonPropertyName("terminalId")] public string TerminalId { get; set; } = "";
}
public record TerminalRequest : AcpObject
{
[JsonPropertyName("sessionId")] public string SessionId { get; set; } = "";
[JsonPropertyName("terminalId")] public string TerminalId { get; set; } = "";
}
public sealed record TerminalOutputRequest : TerminalRequest;
public sealed record WaitForTerminalExitRequest : TerminalRequest;
public sealed record KillTerminalCommandRequest : TerminalRequest;
public sealed record ReleaseTerminalRequest : TerminalRequest;
public record TerminalExitStatus : AcpObject
{
[JsonPropertyName("exitCode")] public uint? ExitCode { get; set; }
[JsonPropertyName("signal")] public string? Signal { get; set; }
}
public sealed record TerminalOutputResponse : AcpObject
{
[JsonPropertyName("output")] public string Output { get; set; } = "";
[JsonPropertyName("truncated")] public bool Truncated { get; set; }
[JsonPropertyName("exitStatus")] public TerminalExitStatus? ExitStatus { get; set; }
}
public sealed record WaitForTerminalExitResponse : TerminalExitStatus;
public sealed record KillTerminalCommandResponse : AcpObject;
public sealed record ReleaseTerminalResponse : AcpObject;
10 changes: 7 additions & 3 deletions src/MandoCode/Components/Shell/App.Acp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,9 @@ private async Task<bool> StartAcpRuntimeAsync()
// The visible transcript already contains these messages during a folder change; don't replay them twice.
_acpHistory = resume is null || folderChange is not null ? null : new AcpHistoryCollector();
var holder = Pane.Services.GetRequiredService<AcpRuntimeHolder>();
var bridge = entry.MandoCodeMcp ? new AcpMcpBridge(Pane, Pane.Services.GetRequiredService<CliDelegations>(), Pane.Services.GetRequiredService<SnapshotStore>()) : null;
var clientHandler = CreateAcpClientHandler();
var bridge = entry.MandoCodeMcp ? new AcpMcpBridge(Pane, Pane.Services.GetRequiredService<CliDelegations>(),
Pane.Services.GetRequiredService<SnapshotStore>(), clientHandler.Terminals, () => _requestCts?.Token ?? new CancellationToken(true)) : null;
holder.Bridge = bridge;
var runtime = new AcpAgentRuntime(
name, entry, ProjectRoot.ProjectRoot,
Expand All @@ -102,7 +104,7 @@ private async Task<bool> StartAcpRuntimeAsync()
try { return await ConfirmAcpLaunchAsync(plan); }
finally { Spinner.Start($"Starting {name}..."); }
},
handler: CreateAcpClientHandler(),
handler: clientHandler,
extensionDump: (method, content) =>
{
// Debug only (MANDOCODE_ACP_DEBUG_EXT): on screen, never in a file.
Expand Down Expand Up @@ -179,7 +181,9 @@ private AcpClientHandler CreateAcpClientHandler()
},
requested: call => { tools.Apply(call); tools.Permission(call.ToolCallId, null); });

return new AcpClientHandler(prompter, files);
var entry = AcpEntry ?? new AcpAgentConfig();
return new AcpClientHandler(prompter, files, entry.ClientTerminals
? new AcpTerminalHandler(root, entry, tools.TerminalChanged, tools.TrackHostTerminal) : null);
}

/// <summary>Brings the spinner back after a question, unless the request ended meanwhile.</summary>
Expand Down
4 changes: 4 additions & 0 deletions src/MandoCode/Models/MandoCodeConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -891,6 +891,10 @@ public class McpServerConfig
/// </summary>
public class AcpAgentConfig
{
/// <summary>Offer host-managed command terminals through ACP v1 and the built-in MCP bridge.</summary>
[JsonPropertyName("clientTerminals")]
public bool ClientTerminals { get; set; } = true;

/// <summary>Expose MandoCode collaboration and saved snapshots to this ACP agent.</summary>
[JsonPropertyName("mandoCodeMcp")]
public bool MandoCodeMcp { get; set; } = true;
Expand Down
14 changes: 11 additions & 3 deletions src/MandoCode/Services/Acp/AcpAgentRuntime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -245,11 +245,12 @@ public async Task ConnectAsync(CancellationToken cancellationToken)
}
: null,
});
_ = client.Completion.ContinueWith(_ =>
_ = client.Completion.ContinueWith(async _ =>
{
if (Status == AcpRuntimeStatus.Ready)
SetStatus(AcpRuntimeStatus.Failed);
}, TaskScheduler.Default);
if (_handler is AcpClientHandler host) await host.DisposeAsync().ConfigureAwait(false);
}, TaskScheduler.Default).Unwrap();

var initialized = await client.ConnectAsync(cancellationToken).ConfigureAwait(false);
Volatile.Write(ref _title, DescribeAgent(initialized));
Expand Down Expand Up @@ -319,6 +320,8 @@ public async Task<bool> NewConversationAsync(CancellationToken cancellationToken
if (old.IsBusy)
throw new InvalidOperationException("A request is still running.");

if (_handler is AcpClientHandler { Terminals: { } terminals } && _session is { } previous)
await terminals.StopSessionAsync(previous.SessionId, release: true).ConfigureAwait(false);
var closed = false;
if (Support.CanClose)
{
Expand Down Expand Up @@ -451,7 +454,11 @@ public IAcpTurn Prompt(IReadOnlyList<ContentBlock> prompt)
public async Task<bool> CancelAsync()
{
var session = _session;
return session is null || await session.CancelAsync().ConfigureAwait(false);
if (session is null) return true;
var cancelled = await session.CancelAsync().ConfigureAwait(false);
if (_handler is AcpClientHandler { Terminals: { } terminals })
await terminals.StopSessionAsync(session.SessionId, release: true).ConfigureAwait(false);
return cancelled;
}

public async ValueTask DisposeAsync()
Expand All @@ -466,6 +473,7 @@ public async ValueTask DisposeAsync()

_session = null;
await DisposeQuietlyAsync(client).ConfigureAwait(false);
if (_handler is AcpClientHandler host) await host.DisposeAsync().ConfigureAwait(false);
// The agent is gone, so nothing writes to its log files any more; release them.
_stderrLog?.Close();
_traceLog?.Close();
Expand Down
Loading
Loading