Add Opencode (opencode.ai) integration via SSH tunnel

Features:
- Opencode AI chat interface
- SSH tunnel for secure API communication
- Auto-install Opencode on remote servers
- API key management with server-side storage
- Session history and management
- Integration with flutter_server_box server list
This commit is contained in:
root
2026-04-03 00:41:32 +08:00
parent 1d3534242c
commit 0f4fe33003
10 changed files with 2500 additions and 1 deletions

View File

@@ -13,7 +13,8 @@ enum ServerFuncBtn {
iperf(),
// pve(),
systemd(1058),
portForward(1340);
portForward(1340),
opencode(1352); // 添加 Opencode 按钮
final int? addedVersion;
@@ -36,6 +37,13 @@ enum ServerFuncBtn {
}
}
// 自动添加 Opencode 按钮
if (opencode.addedVersion != null && cur >= opencode.addedVersion!) {
if (!list.contains(opencode.index)) {
list.add(opencode.index);
}
}
if (list.length > originalLength) {
prop.put(list);
}
@@ -62,6 +70,7 @@ enum ServerFuncBtn {
iperf => Icons.speed,
systemd => MingCute.plugin_2_fill,
portForward => Icons.compare_arrows,
opencode => Icons.smart_toy, // Opencode 图标
};
String get toStr => switch (this) {
@@ -74,5 +83,6 @@ enum ServerFuncBtn {
iperf => 'iperf',
systemd => 'Systemd',
portForward => libL10n.portForward,
opencode => 'Opencode', // Opencode 按钮文字
};
}

View File

@@ -0,0 +1,248 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:dartssh2/dartssh2.dart';
import 'package:flutter/foundation.dart';
/// Opencode API 响应模型
class OpencodeResponse {
final String id;
final String? content;
final String? error;
final Map<String, dynamic>? toolCalls;
final bool isComplete;
final DateTime timestamp;
OpencodeResponse({
required this.id,
this.content,
this.error,
this.toolCalls,
this.isComplete = false,
DateTime? timestamp,
}) : timestamp = timestamp ?? DateTime.now();
factory OpencodeResponse.fromJson(Map<String, dynamic> json) {
return OpencodeResponse(
id: json['id'] ?? '',
content: json['content'],
error: json['error'],
toolCalls: json['tool_calls'],
isComplete: json['is_complete'] ?? false,
timestamp: json['timestamp'] != null
? DateTime.parse(json['timestamp'])
: DateTime.now(),
);
}
Map<String, dynamic> toJson() => {
'id': id,
'content': content,
'error': error,
'tool_calls': toolCalls,
'is_complete': isComplete,
'timestamp': timestamp.toIso8601String(),
};
}
/// Opencode 消息模型
class OpencodeMessage {
final String id;
final String role; // 'user', 'assistant', 'system'
final String content;
final DateTime timestamp;
final List<Map<String, dynamic>>? toolCalls;
final Map<String, dynamic>? toolResults;
OpencodeMessage({
required this.id,
required this.role,
required this.content,
DateTime? timestamp,
this.toolCalls,
this.toolResults,
}) : timestamp = timestamp ?? DateTime.now();
factory OpencodeMessage.user(String content) {
return OpencodeMessage(
id: _generateId(),
role: 'user',
content: content,
);
}
factory OpencodeMessage.assistant(String content) {
return OpencodeMessage(
id: _generateId(),
role: 'assistant',
content: content,
);
}
factory OpencodeMessage.system(String content) {
return OpencodeMessage(
id: _generateId(),
role: 'system',
content: content,
);
}
factory OpencodeMessage.fromJson(Map<String, dynamic> json) {
return OpencodeMessage(
id: json['id'] ?? _generateId(),
role: json['role'] ?? 'user',
content: json['content'] ?? '',
timestamp: json['timestamp'] != null
? DateTime.parse(json['timestamp'])
: DateTime.now(),
toolCalls: json['tool_calls'] != null
? List<Map<String, dynamic>>.from(json['tool_calls'])
: null,
toolResults: json['tool_results'],
);
}
Map<String, dynamic> toJson() => {
'id': id,
'role': role,
'content': content,
'timestamp': timestamp.toIso8601String(),
'tool_calls': toolCalls,
'tool_results': toolResults,
};
static String _generateId() {
return DateTime.now().millisecondsSinceEpoch.toString();
}
}
/// Opencode 会话配置
class OpencodeSession {
final String id;
final String serverId;
final String serverName;
final List<OpencodeMessage> messages;
final DateTime createdAt;
DateTime updatedAt;
String? title;
OpencodeSession({
required this.id,
required this.serverId,
required this.serverName,
this.messages = const [],
DateTime? createdAt,
DateTime? updatedAt,
this.title,
}) : createdAt = createdAt ?? DateTime.now(),
updatedAt = updatedAt ?? DateTime.now();
factory OpencodeSession.create({
required String serverId,
required String serverName,
String? title,
}) {
return OpencodeSession(
id: _generateId(),
serverId: serverId,
serverName: serverName,
title: title,
messages: [
OpencodeMessage.system(
'You are Opencode, a helpful AI assistant running inside an SSH session. '
'You have access to the server filesystem and can execute commands via tools.',
),
],
);
}
void addMessage(OpencodeMessage message) {
messages.add(message);
updatedAt = DateTime.now();
}
Map<String, dynamic> toJson() => {
'id': id,
'server_id': serverId,
'server_name': serverName,
'messages': messages.map((m) => m.toJson()).toList(),
'created_at': createdAt.toIso8601String(),
'updated_at': updatedAt.toIso8601String(),
'title': title,
};
factory OpencodeSession.fromJson(Map<String, dynamic> json) {
return OpencodeSession(
id: json['id'] ?? _generateId(),
serverId: json['server_id'] ?? '',
serverName: json['server_name'] ?? '',
messages: (json['messages'] as List?)
?.map((m) => OpencodeMessage.fromJson(m))
.toList() ??
[],
createdAt: json['created_at'] != null
? DateTime.parse(json['created_at'])
: DateTime.now(),
updatedAt: json['updated_at'] != null
? DateTime.parse(json['updated_at'])
: DateTime.now(),
title: json['title'],
);
}
static String _generateId() {
return DateTime.now().millisecondsSinceEpoch.toString();
}
}
/// Opencode 安装状态
enum OpencodeInstallStatus {
notInstalled,
installing,
installed,
error,
}
/// Opencode 服务器配置
class OpencodeServerConfig {
final String serverId;
String opencodePath;
String configPath;
String apiPort;
bool autoStart;
Map<String, String> envVars;
String? apiKey; // Opencode API Key
OpencodeServerConfig({
required this.serverId,
this.opencodePath = '/usr/local/bin/opencode',
this.configPath = '~/.config/opencode',
this.apiPort = '8080',
this.autoStart = true,
this.envVars = const {},
this.apiKey,
});
Map<String, dynamic> toJson() => {
'server_id': serverId,
'opencode_path': opencodePath,
'config_path': configPath,
'api_port': apiPort,
'auto_start': autoStart,
'env_vars': envVars,
'api_key': apiKey,
};
factory OpencodeServerConfig.fromJson(Map<String, dynamic> json) {
return OpencodeServerConfig(
serverId: json['server_id'] ?? '',
opencodePath: json['opencode_path'] ?? '/usr/local/bin/opencode',
configPath: json['config_path'] ?? '~/.config/opencode',
apiPort: json['api_port'] ?? '8080',
autoStart: json['auto_start'] ?? true,
envVars: Map<String, String>.from(json['env_vars'] ?? {}),
apiKey: json['api_key'],
);
}
}

View File

@@ -0,0 +1,388 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:dartssh2/dartssh2.dart';
import 'package:flutter/foundation.dart';
import 'package:server_box/data/model/opencode/models.dart';
import 'package:server_box/data/model/server/server_private_info.dart';
/// SSH 隧道管理器 - 用于通过 SSH 连接访问 Opencode API
class OpencodeSSHTunnel {
SSHClient? _client;
final StreamController<String> _outputController = StreamController<String>.broadcast();
final StreamController<OpencodeResponse> _responseController = StreamController<OpencodeResponse>.broadcast();
Stream<String> get outputStream => _outputController.stream;
Stream<OpencodeResponse> get responseStream => _responseController.stream;
bool get isConnected => _client != null && !_client!.isClosed;
/// 建立 SSH 连接
Future<void> connect(Spi spi, {String? privateKey, String? passphrase}) async {
try {
final socket = await SSHSocket.connect(spi.ip, spi.port);
SSHClient? client;
if (privateKey != null && privateKey.isNotEmpty) {
final keyPair = await _parsePrivateKey(privateKey, passphrase);
client = SSHClient(
socket,
username: spi.user,
identities: keyPair != null ? [keyPair] : [],
);
} else if (spi.pwd != null && spi.pwd!.isNotEmpty) {
client = SSHClient(
socket,
username: spi.user,
onPasswordRequest: () => spi.pwd!,
);
} else {
throw Exception('No authentication method available');
}
_client = client;
await client.authenticated;
if (kDebugMode) {
print('SSH tunnel connected to ${spi.name} (${spi.ip}:${spi.port})');
}
} catch (e) {
if (kDebugMode) {
print('SSH connection error: $e');
}
throw Exception('SSH connection failed: $e');
}
}
/// 解析私钥
Future<SSHKeyPair?\u003e _parsePrivateKey(String keyData, String? passphrase) async {
try {
if (keyData.contains('-----BEGIN OPENSSH PRIVATE KEY-----')) {
return OpenSSHKeyPair.fromPem(keyData, passphrase: passphrase);
} else if (keyData.contains('-----BEGIN RSA PRIVATE KEY-----')) {
return OpenSSHKeyPair.fromPem(keyData, passphrase: passphrase);
} else if (keyData.contains('-----BEGIN PRIVATE KEY-----') ||
keyData.contains('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {
return OpenSSHKeyPair.fromPem(keyData, passphrase: passphrase);
} else {
return OpenSSHKeyPair.fromPem(keyData, passphrase: passphrase);
}
} catch (e) {
if (kDebugMode) {
print('Private key parse error: $e');
}
return null;
}
}
/// 执行远程命令
Future<String> execute(String command) async {
if (_client == null || _client!.isClosed) {
throw Exception('SSH client not connected');
}
try {
final session = await _client!.execute(command);
final output = await session.stdout.join('');
final error = await session.stderr.join('');
await session.done;
if (error.isNotEmpty && output.isEmpty) {
throw Exception('Command failed: $error');
}
return output;
} catch (e) {
throw Exception('Command execution failed: $e');
}
}
/// 检查 Opencode 是否已安装
Future<OpencodeInstallStatus> checkInstallation(String opencodePath) async {
try {
final result = await execute('which $opencodePath');
if (result.trim().isNotEmpty) {
try {
final version = await execute('$opencodePath --version');
if (kDebugMode) {
print('Opencode version: $version');
}
return OpencodeInstallStatus.installed;
} catch (e) {
return OpencodeInstallStatus.installed;
}
}
return OpencodeInstallStatus.notInstalled;
} catch (e) {
return OpencodeInstallStatus.notInstalled;
}
}
/// 安装 Opencode
Future<void> installOpencode({
required String installPath,
String version = 'latest',
}) async {
try {
final unameResult = await execute('uname -s');
final osType = unameResult.trim().toLowerCase();
final archResult = await execute('uname -m');
final arch = archResult.trim();
String downloadUrl;
if (osType.contains('linux')) {
String archSuffix;
if (arch == 'x86_64') {
archSuffix = 'linux-x64';
} else if (arch == 'aarch64' || arch == 'arm64') {
archSuffix = 'linux-arm64';
} else {
throw Exception('Unsupported architecture: $arch');
}
downloadUrl = 'https://github.com/opencode-ai/opencode/releases/download/$version/opencode-$archSuffix';
} else if (osType.contains('darwin')) {
String archSuffix;
if (arch == 'x86_64') {
archSuffix = 'darwin-x64';
} else if (arch == 'aarch64' || arch == 'arm64') {
archSuffix = 'darwin-arm64';
} else {
throw Exception('Unsupported architecture: $arch');
}
downloadUrl = 'https://github.com/opencode-ai/opencode/releases/download/$version/opencode-$archSuffix';
} else {
throw Exception('Unsupported OS: $osType');
}
final installDir = installPath.substring(0, installPath.lastIndexOf('/'));
final commands = [
'mkdir -p $installDir',
'curl -L -o $installPath "$downloadUrl"',
'chmod +x $installPath',
];
for (final cmd in commands) {
await execute(cmd);
}
if (kDebugMode) {
print('Opencode installed successfully at $installPath');
}
} catch (e) {
if (kDebugMode) {
print('Opencode installation failed: $e');
}
throw Exception('Installation failed: $e');
}
}
/// 启动 Opencode API 服务器
Future<void> startAPIServer({
required String opencodePath,
required String configPath,
required String port,
String? apiKey,
Map<String, String>? envVars,
}) async {
try {
await execute('mkdir -p $configPath');
// 设置环境变量
final envPrefix = envVars?.entries
.map((e) => 'export ${e.key}="${e.value}"')
.join(' \u0026\u0026 ') ?? '';
// 配置 API Key
if (apiKey != null && apiKey.isNotEmpty) {
await execute('mkdir -p $configPath');
final escapedKey = apiKey.replaceAll("'", "'\\''");
await execute("echo '$escapedKey' \u003e $configPath/api_key.txt");
await execute('chmod 600 $configPath/api_key.txt');
}
// 启动 API 服务器
final startCmd = envPrefix.isNotEmpty
? '$envPrefix \u0026\u0026 nohup $opencodePath server --port $port \u003e /dev/null 2\u003e\u00261 \u0026'
: 'nohup $opencodePath server --port $port \u003e /dev/null 2\u003e\u00261 \u0026';
await execute(startCmd);
// 等待服务启动
await Future.delayed(const Duration(seconds: 2));
// 验证服务是否运行
final checkResult = await execute('curl -s http://localhost:$port/health || echo "not_running"');
if (checkResult.contains('not_running')) {
throw Exception('API server failed to start');
}
if (kDebugMode) {
print('Opencode API server started on port $port');
}
} catch (e) {
if (kDebugMode) {
print('Failed to start API server: $e');
}
throw Exception('Failed to start API server: $e');
}
}
/// 停止 Opencode API 服务器
Future<void> stopAPIServer(String port) async {
try {
await execute('pkill -f "opencode.*--port $port" || true');
if (kDebugMode) {
print('Opencode API server stopped');
}
} catch (e) {
// 忽略错误
}
}
/// 发送消息到 Opencode API
Future<void> sendMessage({
required String port,
required OpencodeMessage message,
required List<OpencodeMessage> history,
String? apiKey,
}) async {
if (_client == null || _client!.isClosed) {
throw Exception('SSH client not connected');
}
try {
// 构建请求体
final requestBody = jsonEncode({
'message': message.content,
'history': history.map((m) => m.toJson()).toList(),
'role': message.role,
if (apiKey != null) 'api_key': apiKey,
});
// 构建 curl 命令
final headers = ['Content-Type: application/json'];
if (apiKey != null) {
headers.add('Authorization: Bearer $apiKey');
}
final headerArgs = headers.map((h) => '-H "$h"').join(' ');
final command = '''
curl -s -X POST http://localhost:$port/api/v1/chat \\
$headerArgs \\
-d '${requestBody.replaceAll("'", "'\\''")}'
''';
final result = await execute(command);
try {
final responseData = jsonDecode(result);
final response = OpencodeResponse.fromJson(responseData);
_responseController.add(response);
} catch (e) {
_outputController.add(result);
}
} catch (e) {
_outputController.addError(Exception('Failed to send message: $e'));
}
}
/// 断开连接
Future<void> disconnect() async {
try {
_client?.close();
_client = null;
if (kDebugMode) {
print('SSH tunnel disconnected');
}
} catch (e) {
if (kDebugMode) {
print('Error disconnecting: $e');
}
}
}
/// 释放资源
void dispose() {
disconnect();
_outputController.close();
_responseController.close();
}
}
/// Opencode 安装器
class OpencodeInstaller {
final OpencodeSSHTunnel _tunnel;
OpencodeInstaller(this._tunnel);
/// 完整的安装流程
Future<bool> fullInstall({
required OpencodeServerConfig config,
void Function(String status)? onStatus,
}) async {
try {
onStatus?.call('Checking current installation...');
final status = await _tunnel.checkInstallation(config.opencodePath);
if (status == OpencodeInstallStatus.installed) {
onStatus?.call('Opencode already installed');
return true;
}
onStatus?.call('Installing Opencode...');
await _tunnel.installOpencode(
installPath: config.opencodePath,
);
onStatus?.call('Creating configuration...');
await _createConfig(config);
if (config.autoStart) {
onStatus?.call('Starting API server...');
await _tunnel.startAPIServer(
opencodePath: config.opencodePath,
configPath: config.configPath,
port: config.apiPort,
apiKey: config.apiKey,
envVars: config.envVars,
);
}
onStatus?.call('Installation complete!');
return true;
} catch (e) {
onStatus?.call('Installation failed: $e');
return false;
}
}
/// 创建配置文件
Future<void> _createConfig(OpencodeServerConfig config) async {
final configContent = '''
# Opencode Configuration
server:
port: ${config.apiPort}
host: 127.0.0.1
# API settings
api:
enabled: true
auth_required: ${config.apiKey != null}
# Logging
log:
level: info
path: ${config.configPath}/logs
''';
final escapedContent = configContent.replaceAll("'", "'\\''");
await _tunnel.execute('mkdir -p ${config.configPath}');
await _tunnel.execute("echo '$escapedContent' \u003e ${config.configPath}/config.yaml");
}
}