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:
@@ -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 按钮文字
|
||||
};
|
||||
}
|
||||
|
||||
248
lib/data/model/opencode/models.dart
Normal file
248
lib/data/model/opencode/models.dart
Normal 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'],
|
||||
);
|
||||
}
|
||||
}
|
||||
388
lib/data/model/opencode/ssh_tunnel.dart
Normal file
388
lib/data/model/opencode/ssh_tunnel.dart
Normal 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");
|
||||
}
|
||||
}
|
||||
331
lib/data/provider/opencode/opencode.dart
Normal file
331
lib/data/provider/opencode/opencode.dart
Normal file
@@ -0,0 +1,331 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:fl_lib/fl_lib.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:server_box/data/model/opencode/models.dart';
|
||||
import 'package:server_box/data/model/opencode/ssh_tunnel.dart';
|
||||
import 'package:server_box/data/model/server/server_private_info.dart';
|
||||
import 'package:server_box/data/store/opencode_store.dart';
|
||||
|
||||
part 'opencode.g.dart';
|
||||
part 'opencode.freezed.dart';
|
||||
|
||||
/// Opencode 连接状态
|
||||
@freezed
|
||||
abstract class OpencodeConnectionState with _$OpencodeConnectionState {
|
||||
const factory OpencodeConnectionState({
|
||||
@Default(OpencodeConnectionStatus.disconnected) OpencodeConnectionStatus status,
|
||||
String? error,
|
||||
OpencodeInstallStatus? installStatus,
|
||||
String? serverId,
|
||||
}) = _OpencodeConnectionState;
|
||||
}
|
||||
|
||||
enum OpencodeConnectionStatus {
|
||||
disconnected,
|
||||
connecting,
|
||||
connected,
|
||||
checkingInstallation,
|
||||
installing,
|
||||
startingServer,
|
||||
error,
|
||||
}
|
||||
|
||||
/// Opencode 会话状态
|
||||
@freezed
|
||||
abstract class OpencodeSessionState with _$OpencodeSessionState {
|
||||
const factory OpencodeSessionState({
|
||||
OpencodeSession? currentSession,
|
||||
@Default([]) List<OpencodeSession> sessions,
|
||||
@Default(false) bool isLoading,
|
||||
String? error,
|
||||
}) = _OpencodeSessionState;
|
||||
}
|
||||
|
||||
/// 全局 Opencode 连接管理器
|
||||
@Riverpod(keepAlive: true)
|
||||
class OpencodeConnection extends _$OpencodeConnection {
|
||||
OpencodeSSHTunnel? _tunnel;
|
||||
OpencodeInstaller? _installer;
|
||||
OpencodeServerConfig? _config;
|
||||
Spi? _spi;
|
||||
|
||||
@override
|
||||
OpencodeConnectionState build() {
|
||||
return const OpencodeConnectionState();
|
||||
}
|
||||
|
||||
OpencodeSSHTunnel? get tunnel => _tunnel;
|
||||
bool get isConnected => _tunnel?.isConnected ?? false;
|
||||
|
||||
Future<void> connect(Spi spi, {String? privateKey, String? passphrase}) async {
|
||||
state = state.copyWith(
|
||||
status: OpencodeConnectionStatus.connecting,
|
||||
serverId: spi.id,
|
||||
);
|
||||
|
||||
try {
|
||||
await disconnect();
|
||||
|
||||
_tunnel = OpencodeSSHTunnel();
|
||||
_spi = spi;
|
||||
|
||||
await _tunnel!.connect(spi, privateKey: privateKey, passphrase: passphrase);
|
||||
_installer = OpencodeInstaller(_tunnel!);
|
||||
|
||||
state = state.copyWith(status: OpencodeConnectionStatus.connected);
|
||||
} catch (e) {
|
||||
state = state.copyWith(
|
||||
status: OpencodeConnectionStatus.error,
|
||||
error: e.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> checkAndInstall({OpencodeServerConfig? config}) async {
|
||||
if (_tunnel == null || !_tunnel!.isConnected) {
|
||||
state = state.copyWith(
|
||||
status: OpencodeConnectionStatus.error,
|
||||
error: 'Not connected',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
_config = config ?? OpencodeServerConfig(serverId: _spi!.id);
|
||||
|
||||
state = state.copyWith(status: OpencodeConnectionStatus.checkingInstallation);
|
||||
|
||||
try {
|
||||
final installStatus = await _tunnel!.checkInstallation(_config!.opencodePath);
|
||||
|
||||
if (installStatus == OpencodeInstallStatus.installed) {
|
||||
state = state.copyWith(
|
||||
status: OpencodeConnectionStatus.connected,
|
||||
installStatus: installStatus,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
state = state.copyWith(status: OpencodeConnectionStatus.installing);
|
||||
|
||||
final success = await _installer!.fullInstall(
|
||||
config: _config!,
|
||||
onStatus: (status) {},
|
||||
);
|
||||
|
||||
if (success) {
|
||||
state = state.copyWith(
|
||||
status: OpencodeConnectionStatus.connected,
|
||||
installStatus: OpencodeInstallStatus.installed,
|
||||
);
|
||||
|
||||
await OpencodeConfigStore().saveConfig(_config!);
|
||||
} else {
|
||||
state = state.copyWith(
|
||||
status: OpencodeConnectionStatus.error,
|
||||
error: 'Installation failed',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
state = state.copyWith(
|
||||
status: OpencodeConnectionStatus.error,
|
||||
error: e.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> startAPIServer() async {
|
||||
if (_tunnel == null || _config == null) return;
|
||||
|
||||
state = state.copyWith(status: OpencodeConnectionStatus.startingServer);
|
||||
|
||||
try {
|
||||
await _tunnel!.startAPIServer(
|
||||
opencodePath: _config!.opencodePath,
|
||||
configPath: _config!.configPath,
|
||||
port: _config!.apiPort,
|
||||
apiKey: _config!.apiKey,
|
||||
envVars: _config!.envVars,
|
||||
);
|
||||
|
||||
state = state.copyWith(status: OpencodeConnectionStatus.connected);
|
||||
} catch (e) {
|
||||
state = state.copyWith(
|
||||
status: OpencodeConnectionStatus.error,
|
||||
error: e.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> disconnect() async {
|
||||
if (_tunnel != null) {
|
||||
await _tunnel!.disconnect();
|
||||
_tunnel = null;
|
||||
}
|
||||
_installer = null;
|
||||
_config = null;
|
||||
_spi = null;
|
||||
|
||||
state = const OpencodeConnectionState();
|
||||
}
|
||||
|
||||
Future<void> sendMessage(OpencodeMessage message, List<OpencodeMessage> history) async {
|
||||
if (_tunnel == null || _config == null) {
|
||||
throw Exception('Not connected');
|
||||
}
|
||||
|
||||
await _tunnel!.sendMessage(
|
||||
port: _config!.apiPort,
|
||||
message: message,
|
||||
history: history,
|
||||
apiKey: _config!.apiKey,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Opencode 会话管理器
|
||||
@Riverpod(keepAlive: true)
|
||||
class OpencodeSessionManager extends _$OpencodeSessionManager {
|
||||
late final OpencodeSessionStore _store;
|
||||
|
||||
@override
|
||||
OpencodeSessionState build() {
|
||||
_store = OpencodeSessionStore();
|
||||
_loadSessions();
|
||||
return const OpencodeSessionState();
|
||||
}
|
||||
|
||||
Future<void> _loadSessions() async {
|
||||
state = state.copyWith(isLoading: true);
|
||||
try {
|
||||
final sessions = _store.getAllSessions();
|
||||
state = state.copyWith(
|
||||
sessions: sessions,
|
||||
isLoading: false,
|
||||
);
|
||||
} catch (e) {
|
||||
state = state.copyWith(
|
||||
isLoading: false,
|
||||
error: e.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<OpencodeSession> createSession({
|
||||
required String serverId,
|
||||
required String serverName,
|
||||
String? title,
|
||||
}) async {
|
||||
final session = OpencodeSession.create(
|
||||
serverId: serverId,
|
||||
serverName: serverName,
|
||||
title: title,
|
||||
);
|
||||
|
||||
await _store.saveSession(session);
|
||||
|
||||
final sessions = [...state.sessions, session];
|
||||
sessions.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
|
||||
|
||||
state = state.copyWith(
|
||||
sessions: sessions,
|
||||
currentSession: session,
|
||||
);
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
Future<void> loadSession(String sessionId) async {
|
||||
final session = _store.getSession(sessionId);
|
||||
if (session != null) {
|
||||
state = state.copyWith(currentSession: session);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteSession(String sessionId) async {
|
||||
await _store.deleteSession(sessionId);
|
||||
|
||||
final sessions = state.sessions.where((s) => s.id != sessionId).toList();
|
||||
|
||||
state = state.copyWith(
|
||||
sessions: sessions,
|
||||
currentSession: state.currentSession?.id == sessionId
|
||||
? null
|
||||
: state.currentSession,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> addMessage(OpencodeMessage message) async {
|
||||
final currentSession = state.currentSession;
|
||||
if (currentSession == null) return;
|
||||
|
||||
currentSession.addMessage(message);
|
||||
await _store.updateSessionMessages(currentSession);
|
||||
|
||||
final sessions = state.sessions.map((s) {
|
||||
if (s.id == currentSession.id) {
|
||||
return currentSession;
|
||||
}
|
||||
return s;
|
||||
}).toList();
|
||||
|
||||
sessions.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
|
||||
|
||||
state = state.copyWith(
|
||||
sessions: sessions,
|
||||
currentSession: currentSession,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> updateSessionTitle(String sessionId, String title) async {
|
||||
final session = _store.getSession(sessionId);
|
||||
if (session == null) return;
|
||||
|
||||
final updatedSession = OpencodeSession(
|
||||
id: session.id,
|
||||
serverId: session.serverId,
|
||||
serverName: session.serverName,
|
||||
messages: session.messages,
|
||||
createdAt: session.createdAt,
|
||||
updatedAt: DateTime.now(),
|
||||
title: title,
|
||||
);
|
||||
|
||||
await _store.saveSession(updatedSession);
|
||||
|
||||
final sessions = state.sessions.map((s) {
|
||||
if (s.id == sessionId) return updatedSession;
|
||||
return s;
|
||||
}).toList();
|
||||
|
||||
state = state.copyWith(
|
||||
sessions: sessions,
|
||||
currentSession: state.currentSession?.id == sessionId
|
||||
? updatedSession
|
||||
: state.currentSession,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> refresh() async {
|
||||
await _loadSessions();
|
||||
}
|
||||
}
|
||||
|
||||
@riverpod
|
||||
Stream<String> opencodeOutputStream(OpencodeOutputStreamRef ref) {
|
||||
final tunnel = ref.read(opencodeConnectionProvider.notifier).tunnel;
|
||||
if (tunnel == null) {
|
||||
return const Stream.empty();
|
||||
}
|
||||
return tunnel.outputStream;
|
||||
}
|
||||
|
||||
@riverpod
|
||||
Stream<OpencodeResponse> opencodeResponseStream(OpencodeResponseStreamRef ref) {
|
||||
final tunnel = ref.read(opencodeConnectionProvider.notifier).tunnel;
|
||||
if (tunnel == null) {
|
||||
return const Stream.empty();
|
||||
}
|
||||
return tunnel.responseStream;
|
||||
}
|
||||
190
lib/data/store/opencode_store.dart
Normal file
190
lib/data/store/opencode_store.dart
Normal file
@@ -0,0 +1,190 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:fl_lib/fl_lib.dart';
|
||||
import 'package:server_box/data/model/opencode/models.dart';
|
||||
|
||||
/// Opencode 会话存储
|
||||
class OpencodeSessionStore {
|
||||
static const _boxName = 'opencode_sessions';
|
||||
late final Box<String> _box;
|
||||
|
||||
static final OpencodeSessionStore _instance = OpencodeSessionStore._internal();
|
||||
factory OpencodeSessionStore() => _instance;
|
||||
OpencodeSessionStore._internal();
|
||||
|
||||
Future<void> init() async {
|
||||
_box = await Hive.openBox<String>(_boxName);
|
||||
}
|
||||
|
||||
Future<void> saveSession(OpencodeSession session) async {
|
||||
final key = 'session_${session.id}';
|
||||
await _box.put(key, jsonEncode(session.toJson()));
|
||||
await _updateSessionList(session.id, add: true);
|
||||
}
|
||||
|
||||
OpencodeSession? getSession(String sessionId) {
|
||||
final key = 'session_$sessionId';
|
||||
final data = _box.get(key);
|
||||
if (data == null) return null;
|
||||
|
||||
try {
|
||||
final json = jsonDecode(data) as Map<String, dynamic>;
|
||||
return OpencodeSession.fromJson(json);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteSession(String sessionId) async {
|
||||
final key = 'session_$sessionId';
|
||||
await _box.delete(key);
|
||||
await _updateSessionList(sessionId, add: false);
|
||||
}
|
||||
|
||||
List<OpencodeSession> getAllSessions() {
|
||||
final sessionIds = _box.get('session_list')?.split(',') ?? [];
|
||||
final sessions = <OpencodeSession>[];
|
||||
|
||||
for (final id in sessionIds) {
|
||||
if (id.isEmpty) continue;
|
||||
final session = getSession(id);
|
||||
if (session != null) {
|
||||
sessions.add(session);
|
||||
}
|
||||
}
|
||||
|
||||
sessions.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
|
||||
return sessions;
|
||||
}
|
||||
|
||||
List<OpencodeSession> getSessionsByServer(String serverId) {
|
||||
return getAllSessions()
|
||||
.where((s) => s.serverId == serverId)
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<void> _updateSessionList(String sessionId, {required bool add}) async {
|
||||
final listStr = _box.get('session_list') ?? '';
|
||||
final list = listStr.split(',').where((s) => s.isNotEmpty).toList();
|
||||
|
||||
if (add) {
|
||||
if (!list.contains(sessionId)) {
|
||||
list.add(sessionId);
|
||||
}
|
||||
} else {
|
||||
list.remove(sessionId);
|
||||
}
|
||||
|
||||
await _box.put('session_list', list.join(','));
|
||||
}
|
||||
|
||||
Future<void> updateSessionMessages(OpencodeSession session) async {
|
||||
await saveSession(session);
|
||||
}
|
||||
|
||||
Future<void> clearAllSessions() async {
|
||||
await _box.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Opencode 服务器配置存储
|
||||
class OpencodeConfigStore {
|
||||
static const _boxName = 'opencode_configs';
|
||||
late final Box<String> _box;
|
||||
|
||||
static final OpencodeConfigStore _instance = OpencodeConfigStore._internal();
|
||||
factory OpencodeConfigStore() => _instance;
|
||||
OpencodeConfigStore._internal();
|
||||
|
||||
Future<void> init() async {
|
||||
_box = await Hive.openBox<String>(_boxName);
|
||||
}
|
||||
|
||||
Future<void> saveConfig(OpencodeServerConfig config) async {
|
||||
final key = 'config_${config.serverId}';
|
||||
await _box.put(key, jsonEncode(config.toJson()));
|
||||
}
|
||||
|
||||
OpencodeServerConfig getConfig(String serverId) {
|
||||
final key = 'config_$serverId';
|
||||
final data = _box.get(key);
|
||||
|
||||
if (data == null) {
|
||||
return OpencodeServerConfig(serverId: serverId);
|
||||
}
|
||||
|
||||
try {
|
||||
final json = jsonDecode(data) as Map<String, dynamic>;
|
||||
return OpencodeServerConfig.fromJson(json);
|
||||
} catch (e) {
|
||||
return OpencodeServerConfig(serverId: serverId);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteConfig(String serverId) async {
|
||||
final key = 'config_$serverId';
|
||||
await _box.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Opencode API 密钥存储
|
||||
class OpencodeKeyStore {
|
||||
static const _boxName = 'opencode_keys';
|
||||
late final Box<String> _box;
|
||||
|
||||
static final OpencodeKeyStore _instance = OpencodeKeyStore._internal();
|
||||
factory OpencodeKeyStore() => _instance;
|
||||
OpencodeKeyStore._internal();
|
||||
|
||||
Future<void> init() async {
|
||||
_box = await Hive.openBox<String>(_boxName);
|
||||
}
|
||||
|
||||
/// 保存服务器 API 密钥
|
||||
Future<void> saveServerKey(String serverId, {
|
||||
required String apiKey,
|
||||
String? description,
|
||||
}) async {
|
||||
final key = 'key_$serverId';
|
||||
final data = jsonEncode({
|
||||
'server_id': serverId,
|
||||
'api_key': apiKey, // 注意:这里存储明文密钥
|
||||
'description': description,
|
||||
'updated_at': DateTime.now().toIso8601String(),
|
||||
});
|
||||
await _box.put(key, data);
|
||||
}
|
||||
|
||||
/// 获取服务器密钥
|
||||
String? getServerKey(String serverId) {
|
||||
final key = 'key_$serverId';
|
||||
final data = _box.get(key);
|
||||
if (data == null) return null;
|
||||
|
||||
try {
|
||||
final json = jsonDecode(data) as Map<String, dynamic>;
|
||||
return json['api_key'] as String?;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取服务器密钥信息
|
||||
Map<String, dynamic>? getServerKeyInfo(String serverId) {
|
||||
final key = 'key_$serverId';
|
||||
final data = _box.get(key);
|
||||
if (data == null) return null;
|
||||
|
||||
try {
|
||||
return jsonDecode(data) as Map<String, dynamic>;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// 删除服务器密钥
|
||||
Future<void> deleteServerKey(String serverId) async {
|
||||
final key = 'key_$serverId';
|
||||
await _box.delete(key);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user