flutter_acp 0.1.0 copy "flutter_acp: ^0.1.0" to clipboard
flutter_acp: ^0.1.0 copied to clipboard

A Flutter/Dart implementation of the Agent Client Protocol (ACP). Supports both Client and Agent roles for building AI coding assistants.

flutter_acp #

A Flutter/Dart implementation of the Agent Client Protocol (ACP) for building AI coding assistants. This library supports both Client and Agent roles, enabling you to build IDE integrations, AI assistants, or agent services.

Features #

  • Dual Role Support: Implement either the Client (editor/IDE) or Agent (AI assistant) role
  • Multiple Transports:
    • In-process transport for embedded usage
    • HTTP transport for remote communication
    • SSE (Server-Sent Events) transport for streaming updates
  • Session Management: Create, load, and manage conversation sessions
  • Streaming Updates: Real-time streaming of text deltas, diffs, tool calls, and diagnostics
  • Multimodal Content: Support for text, image, and audio content in prompts
  • Tool Integration: Built-in support for tool calls and results
  • Permission Handling: Request and manage user permissions for sensitive operations
  • Type-Safe API: Full Dart type safety with comprehensive data models

Installation #

Add flutter_acp to your pubspec.yaml:

dependencies:
  flutter_acp: ^0.1.0

Then run:

dart pub get

Or install via command line:

dart pub add flutter_acp

Quick Start #

Client Example #

Connect to an ACP agent and send prompts:

import 'package:flutter_acp/flutter_acp.dart';

Future<void> main() async {
  // Create a transport (use HttpTransport for remote agents)
  final transport = HttpTransport('http://localhost:8080');
  
  // Create the client
  final client = AcpClient(
    transport: transport,
    config: const ClientConfig(
      timeout: Duration(seconds: 30),
      autoReconnect: true,
    ),
  );

  // Connect and initialize
  await client.connect();
  
  final initResult = await client.initialize(
    protocolVersion: 1,
    capabilities: ClientCapabilities(
      fs: FsCapabilities(readTextFile: true, writeTextFile: true),
      terminal: true,
    ),
    clientInfo: ClientInfo(
      name: 'my_client',
      version: '1.0.0',
    ),
  );
  
  print('Connected to: ${initResult.agentInfo.name}');

  // Subscribe to streaming updates
  client.updates.listen((update) {
    switch (update.type) {
      case UpdateType.textDelta:
        print(update.content?['text']);
        break;
      case UpdateType.diff:
        // Handle code diffs
        break;
      case UpdateType.diagnostic:
        // Handle errors/warnings
        break;
      default:
        print('[${update.type.name}] ${update.content}');
    }
  });

  // Create a session and send a prompt
  final session = await client.createSession(
    config: SessionConfig(cwd: '/path/to/project'),
  );

  final result = await client.sendPrompt(
    sessionId: session.sessionId,
    contents: [
      PromptContent.text('Explain this code'),
      PromptContent.image(data: base64Image, mimeType: 'image/png'),
    ],
  );

  print('Status: ${result.status.name}');

  // Cleanup
  await client.closeSession(session.sessionId);
  await client.disconnect();
}

Agent Example #

Implement an ACP agent to handle client requests:

import 'package:flutter_acp/flutter_acp.dart';

class MyAgentHandler implements AgentHandler {
  @override
  Future<InitializeResult> onInitialize(InitializeParams params) async {
    return InitializeResult(
      protocolVersion: params.protocolVersion,
      agentCapabilities: AgentCapabilities(
        loadSession: true,
        promptCapabilities: PromptCapabilities(
          image: true,
          audio: false,
          embeddedContext: true,
        ),
      ),
      agentInfo: AgentInfo(
        name: 'my_agent',
        title: 'My AI Agent',
        version: '1.0.0',
      ),
    );
  }

  @override
  Future<AuthenticateResult>? onAuthenticate(AuthenticateParams params) {
    // Optional: implement authentication
    return null;
  }

  @override
  Future<Session> onCreateSession(SessionConfig? config) async {
    return Session(
      sessionId: 'session-${DateTime.now().millisecondsSinceEpoch}',
      state: SessionState.active,
      config: config,
    );
  }

  @override
  Future<Session>? onLoadSession(String sessionId) {
    // Optional: implement session persistence
    return null;
  }

  @override
  Future<PromptResult> onPrompt(PromptParams params) async {
    // Process the prompt with your AI model
    final userMessage = params.contents
        .where((c) => c.type == ContentType.text)
        .map((c) => c.text ?? '')
        .join('\n');

    return PromptResult(
      sessionId: params.sessionId,
      status: PromptStatus.completed,
      messages: [
        {'role': 'assistant', 'content': 'Response to: $userMessage'},
      ],
    );
  }

  @override
  void onCancel(String sessionId) {
    // Handle cancellation
  }
}

Future<void> main() async {
  final agent = AcpAgent(
    handler: MyAgentHandler(),
    config: AgentConfig(
      name: 'my_agent',
      version: '1.0.0',
    ),
  );

  // Start with HTTP transport for remote clients
  final transport = HttpTransport('http://localhost:8080');
  await agent.start(transport: transport);
  
  print('Agent running on http://localhost:8080');
}

API Overview #

Core Types #

Type Description
AcpClient Client for connecting to ACP agents
AcpAgent Agent implementation for handling client requests
AgentHandler Interface for implementing agent behavior
Transport Abstract transport layer (HTTP, SSE, in-process)
Session Represents a conversation session
PromptContent Content in a prompt (text, image, audio)
SessionUpdate Streaming update notification

Capabilities #

Client Capabilities:

  • FsCapabilities: File system read/write access
  • ClientCapabilities.terminal: Terminal operation support

Agent Capabilities:

  • AgentCapabilities.loadSession: Session persistence support
  • PromptCapabilities: Image, audio, and embedded context support
  • McpCapabilities: Model Context Protocol support

Update Types #

Type Description
textDelta Streaming text content
diff Code diff/patch
toolCall Tool invocation request
toolResult Tool execution result
diagnostic Error or warning message
permission Permission request

Examples #

Complete examples are available in the example/ directory:

  • client_example: Demonstrates connecting to an agent, creating sessions, and sending prompts
  • agent_example: Shows how to implement an agent with streaming responses

Run the examples:

# Run client example
cd example/client_example
dart run bin/client_example.dart

# Run agent example
cd example/agent_example
dart run bin/agent_example.dart

Architecture #

flutter_acp/
  lib/
    src/
      core/           # JSON-RPC, types, errors, capabilities
      transport/      # HTTP, SSE, in-process transports
      session/        # Session management
      client/         # AcpClient implementation
      agent/          # AcpAgent implementation

Contributing #

Contributions are welcome! Please follow these guidelines:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/my-feature)
  3. Write tests for new functionality
  4. Ensure all tests pass (dart test)
  5. Commit your changes (git commit -am 'Add my feature')
  6. Push to the branch (git push origin feature/my-feature)
  7. Open a Pull Request

Development Setup #

# Clone the repository
git clone https://github.com/xinuo/flutter_acp.git
cd flutter_acp

# Install dependencies
dart pub get

# Run tests
dart test

# Run tests with coverage
dart test --coverage=coverage

License #

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog #

See CHANGELOG.md for a list of changes.

0
likes
160
points
25
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A Flutter/Dart implementation of the Agent Client Protocol (ACP). Supports both Client and Agent roles for building AI coding assistants.

Homepage
Repository (GitHub)
View/report issues

Topics

#ai #agent #protocol #llm #coding-assistant

License

MIT (license)

Dependencies

async, http, meta, stream_transform, uuid

More

Packages that depend on flutter_acp