feat: port the client to Flutter (0.3.0)
Replace the MyGo/Go app with a Flutter client that keeps the feature set: - servers: saved servers, passwordless and password login, HTTP/SOCKS5 proxy via dart:io, self-signed certificates and pinning, tokens in flutter_secure_storage (Keystore) - sessions: list with live events, search, new/rename/archive/delete, instance sheet - chat: streaming Markdown (flutter_markdown), reasoning and tool rows, image previews, context usage ring and sheet, model/agent switching, fork/revert, attachments (file_picker), permissions - Android 7.0 (API 24)+, plain http:// works in release (Dart dials sockets directly) - build: China mirrors for Gradle/NDK, Aliyun Maven repositories, and the Gradle distribution pre-seeded; release signed with the test keystore Read-aloud is dropped as requested. Version 0.3.0.
This commit is contained in:
1 parent
24a311f234
commit
aee560172c
2616 files changed
+5810
-672083
No files matched your search
@@ -0,0 +1,415 @@
|
||||
// The OpenChamber HTTP client in Dart: same endpoints and headers as the
|
||||
// Go client (auth, sessions, messages, SSE, proxy, certificate pinning).
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'models.dart';
|
||||
|
||||
class ApiError implements Exception {
|
||||
final int status;
|
||||
final String message;
|
||||
ApiError(this.status, this.message);
|
||||
@override
|
||||
String toString() => message.isEmpty ? 'HTTP $status' : message;
|
||||
}
|
||||
|
||||
class Client {
|
||||
final Uri base;
|
||||
final String? proxy; // http://host:port or socks5://host:port
|
||||
final bool insecure;
|
||||
final String? fingerprint;
|
||||
String? token;
|
||||
late HttpClient _http;
|
||||
|
||||
Client(
|
||||
this.base, {
|
||||
this.proxy,
|
||||
this.insecure = false,
|
||||
this.fingerprint,
|
||||
}) {
|
||||
_http = HttpClient();
|
||||
_http.connectionTimeout = const Duration(seconds: 20);
|
||||
if (proxy != null && proxy!.isNotEmpty) {
|
||||
_http.findProxy = (uri) {
|
||||
final u = Uri.parse(proxy!);
|
||||
final scheme = u.scheme.toLowerCase();
|
||||
if (scheme == 'socks5' || scheme == 'socks') {
|
||||
return 'SOCKS ${u.host}:${u.port}';
|
||||
}
|
||||
return 'PROXY ${u.host}:${u.port}';
|
||||
};
|
||||
}
|
||||
if (insecure || (fingerprint != null && fingerprint!.isNotEmpty)) {
|
||||
_http.badCertificateCallback = (cert, host, port) {
|
||||
if (insecure) return true;
|
||||
final der = _sha256(cert.der);
|
||||
return der == fingerprint!.replaceAll(':', '');
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
String get baseUrl => base.toString();
|
||||
|
||||
Future<Map<String, dynamic>> sessionStatus() async {
|
||||
final r = await _json('GET', '/auth/session');
|
||||
return r;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> login(String password, String installId,
|
||||
{String label = 'OpenChamber Native', String clientKind = 'mobile'}) async {
|
||||
return _json('POST', '/auth/session', body: {
|
||||
'password': password,
|
||||
'trustDevice': true,
|
||||
'issueClientToken': true,
|
||||
'dedupeKey': installId,
|
||||
'clientLabel': label,
|
||||
'clientKind': clientKind,
|
||||
'devicePlatform': 'android',
|
||||
});
|
||||
}
|
||||
|
||||
Future<Page<Session>> listSessions({
|
||||
int limit = 50,
|
||||
String? cursor,
|
||||
String order = 'desc',
|
||||
String? search,
|
||||
String? directory,
|
||||
}) async {
|
||||
final query = <String, String>{
|
||||
'limit': '$limit',
|
||||
'order': order,
|
||||
if (cursor != null) 'cursor': cursor,
|
||||
if (search != null && search.isNotEmpty) 'search': search,
|
||||
if (directory != null && directory.isNotEmpty) 'directory': directory,
|
||||
};
|
||||
final r = await _json('GET', '/api/session', query: query, directory: directory);
|
||||
final data = (r['data'] as List? ?? [])
|
||||
.map((e) => Session.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
final cursorMap = r['cursor'] as Map<String, dynamic>?;
|
||||
return Page(data,
|
||||
next: cursorMap?['next'] as String?, previous: cursorMap?['previous'] as String?);
|
||||
}
|
||||
|
||||
Future<Set<String>> activeSessions() async {
|
||||
final r = await _json('GET', '/api/session/active');
|
||||
final data = r['data'] as Map<String, dynamic>? ?? {};
|
||||
return data.keys.toSet();
|
||||
}
|
||||
|
||||
Future<Session> createSession({String? title, String? directory}) async {
|
||||
final r = await _json('POST', '/api/session', body: {
|
||||
if (title != null && title.isNotEmpty) 'title': title,
|
||||
if (directory != null && directory.isNotEmpty)
|
||||
'location': {'directory': directory},
|
||||
});
|
||||
return Session.fromJson(r['data'] as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
Future<void> updateSession(String id, {String? title, bool? archived}) async {
|
||||
await _json('PATCH', '/api/session/${Uri.encodeComponent(id)}', body: {
|
||||
if (title != null) 'title': title,
|
||||
if (archived != null) 'archived': archived,
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> deleteSession(String id) async {
|
||||
await _json('DELETE', '/api/session/${Uri.encodeComponent(id)}');
|
||||
}
|
||||
|
||||
Future<Page<Message>> listMessages(String id,
|
||||
{int limit = 30, String? cursor, String order = 'desc', String? directory, bool partShells = true}) async {
|
||||
final query = <String, String>{
|
||||
'limit': '$limit',
|
||||
'order': order,
|
||||
if (cursor != null) 'cursor': cursor,
|
||||
};
|
||||
final r = await _json('GET', '/api/session/${Uri.encodeComponent(id)}/message',
|
||||
query: query, directory: directory, partShells: partShells);
|
||||
final data = (r['data'] as List? ?? [])
|
||||
.map((e) => Message.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
final cursorMap = r['cursor'] as Map<String, dynamic>?;
|
||||
return Page(data,
|
||||
next: cursorMap?['next'] as String?, previous: cursorMap?['previous'] as String?);
|
||||
}
|
||||
|
||||
Future<Message> getMessage(String sessionId, String messageId, {String? directory}) async {
|
||||
final r = await _json('GET',
|
||||
'/api/session/${Uri.encodeComponent(sessionId)}/message/${Uri.encodeComponent(messageId)}',
|
||||
directory: directory);
|
||||
return Message.fromJson(r);
|
||||
}
|
||||
|
||||
Future<List<ModelInfo>> models(String directory) async {
|
||||
final r = await _json('GET', '/api/model',
|
||||
query: directory.isNotEmpty ? {'location[directory]': directory} : null);
|
||||
return (r['data'] as List? ?? [])
|
||||
.map((e) => ModelInfo.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<List<AgentInfo>> agents(String directory) async {
|
||||
final r = await _json('GET', '/api/agent',
|
||||
query: directory.isNotEmpty ? {'location[directory]': directory} : null);
|
||||
return (r['data'] as List? ?? [])
|
||||
.map((e) => AgentInfo.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<List<PermissionRequest>> pendingPermissions(String directory) async {
|
||||
final r = await _json('GET', '/api/permission/request',
|
||||
query: directory.isNotEmpty ? {'directory': directory} : null);
|
||||
return (r['data'] as List? ?? [])
|
||||
.map((e) => PermissionRequest.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<void> replyPermission(String sessionId, String requestId, String decision,
|
||||
{String message = ''}) async {
|
||||
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/permission/${Uri.encodeComponent(requestId)}/reply',
|
||||
body: {'decision': decision, if (message.isNotEmpty) 'message': message});
|
||||
}
|
||||
|
||||
Future<void> prompt(String sessionId,
|
||||
{String text = '', String? messageId, String? directory, List<Map<String, String>>? files}) async {
|
||||
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/prompt', directory: directory,
|
||||
body: {
|
||||
if (text.isNotEmpty) 'text': text,
|
||||
if (messageId != null) 'id': messageId,
|
||||
if (files != null && files.isNotEmpty) 'files': files,
|
||||
});
|
||||
}
|
||||
|
||||
Future<bool> interrupt(String sessionId, {String? directory}) async {
|
||||
final r = await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/interrupt',
|
||||
directory: directory, body: const {});
|
||||
return r['interrupted'] as bool? ?? false;
|
||||
}
|
||||
|
||||
Future<Session> forkSession(String sessionId, {String? directory, String? before}) async {
|
||||
final r = await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/fork',
|
||||
directory: directory, body: {if (before != null && before.isNotEmpty) 'before': before});
|
||||
return Session.fromJson(r['data'] as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
Future<void> stageRevert(String sessionId, {String? directory, required String messageId}) async {
|
||||
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/revert/stage',
|
||||
directory: directory, body: {'messageID': messageId});
|
||||
}
|
||||
|
||||
Future<void> commitRevert(String sessionId, {String? directory}) async {
|
||||
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/revert/commit',
|
||||
directory: directory, body: const {});
|
||||
}
|
||||
|
||||
Future<void> switchModel(String sessionId, ModelRef model, {String? directory}) async {
|
||||
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/model',
|
||||
directory: directory, body: model.toJson());
|
||||
}
|
||||
|
||||
Future<void> switchAgent(String sessionId, String agent, {String? directory}) async {
|
||||
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/agent',
|
||||
directory: directory, body: {'agent': agent});
|
||||
}
|
||||
|
||||
Future<List<int>> rawFile(String path, {String? directory}) async {
|
||||
final res = await _request('GET', '/api/fs/raw',
|
||||
query: {
|
||||
'path': path,
|
||||
'allowOutsideWorkspace': 'true',
|
||||
},
|
||||
directory: directory);
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
throw ApiError(res.statusCode, utf8.decode(res.body, allowMalformed: true));
|
||||
}
|
||||
return res.body;
|
||||
}
|
||||
|
||||
/// Subscribes to GET /api/event, yielding each SSE event. The stream ends
|
||||
/// when the connection drops; the caller restarts it with backoff.
|
||||
Stream<Map<String, dynamic>> streamEvents({List<String>? types}) async* {
|
||||
final query = <String, String>{
|
||||
if (types != null) for (final t in types) 'types': t,
|
||||
};
|
||||
final uri = base.resolve('/api/event')
|
||||
.replace(queryParameters: query.isEmpty ? null : query);
|
||||
final req = await _http.openUrl('GET', uri);
|
||||
req.headers.set('Accept', 'text/event-stream');
|
||||
req.headers.set('Cache-Control', 'no-cache');
|
||||
if (token != null && token!.isNotEmpty) {
|
||||
req.headers.set('Authorization', 'Bearer $token');
|
||||
}
|
||||
final res = await req.close();
|
||||
if (res.statusCode != 200) {
|
||||
throw ApiError(res.statusCode, 'event stream failed');
|
||||
}
|
||||
String data = '';
|
||||
await for (final line in utf8.decoder.bind(res).transform(const LineSplitter())) {
|
||||
if (line.isEmpty) {
|
||||
if (data.isNotEmpty) {
|
||||
final ev = jsonDecode(data) as Map<String, dynamic>;
|
||||
data = '';
|
||||
yield ev;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith('data:')) {
|
||||
data = (data.isEmpty ? '' : data + '\n') + line.substring(5).trimLeft();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- transport
|
||||
|
||||
Future<Map<String, dynamic>> _json(String method, String path,
|
||||
{Map<String, String>? query,
|
||||
Map<String, dynamic>? body,
|
||||
String? directory,
|
||||
bool partShells = false}) async {
|
||||
final res = await _request(method, path,
|
||||
query: query, body: body, directory: directory, partShells: partShells);
|
||||
final text = utf8.decode(res.body, allowMalformed: true);
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
String msg = text;
|
||||
try {
|
||||
final j = jsonDecode(text) as Map<String, dynamic>;
|
||||
msg = (j['error'] as String?) ?? ((j['message'] as String?) ?? text);
|
||||
} catch (_) {}
|
||||
throw ApiError(res.statusCode, msg.trim());
|
||||
}
|
||||
if (text.isEmpty) return const {};
|
||||
try {
|
||||
return jsonDecode(text) as Map<String, dynamic>;
|
||||
} catch (_) {
|
||||
throw ApiError(res.statusCode, 'invalid JSON');
|
||||
}
|
||||
}
|
||||
|
||||
Future<_Response> _request(String method, String path,
|
||||
{Map<String, String>? query,
|
||||
Map<String, dynamic>? body,
|
||||
String? directory,
|
||||
bool partShells = false}) async {
|
||||
final q = Uri(queryParameters: query ?? {});
|
||||
final uri = base.resolve(path).replace(queryParameters: q.queryParameters.isEmpty ? null : q.queryParameters);
|
||||
final req = await _http.openUrl(method, uri);
|
||||
req.headers.set('Accept', 'application/json');
|
||||
req.headers.set('User-Agent', 'openchamber-native/0.3');
|
||||
if (body != null) {
|
||||
req.headers.contentType = ContentType.json;
|
||||
req.write(jsonEncode(body));
|
||||
}
|
||||
if (token != null && token!.isNotEmpty) {
|
||||
req.headers.set('Authorization', 'Bearer $token');
|
||||
}
|
||||
if (directory != null && directory.isNotEmpty) {
|
||||
req.headers.set('x-opencode-directory', Uri.encodeComponent(directory));
|
||||
req.headers.set('x-opencode-directory-encoding', 'uri');
|
||||
}
|
||||
if (partShells) {
|
||||
req.headers.set('x-openchamber-part-shells', 'v1');
|
||||
}
|
||||
if (path == '/api/event') {
|
||||
req.headers.set('Accept', 'text/event-stream');
|
||||
req.headers.set('Cache-Control', 'no-cache');
|
||||
}
|
||||
final res = await req.close();
|
||||
final bodyBytes = await res.fold<List<int>>(<int>[], (a, b) => a..addAll(b));
|
||||
return _Response(res.statusCode, bodyBytes);
|
||||
}
|
||||
|
||||
void close() => _http.close();
|
||||
}
|
||||
|
||||
class _Response {
|
||||
final int statusCode;
|
||||
final List<int> body;
|
||||
_Response(this.statusCode, this.body);
|
||||
}
|
||||
|
||||
String _sha256(List<int> bytes) {
|
||||
return _Digest.sha256Hex(bytes);
|
||||
}
|
||||
|
||||
// Minimal SHA-256, so the client has no native dependencies for pinning.
|
||||
class _Digest {
|
||||
static String sha256Hex(List<int> bytes) {
|
||||
final h = List<int>.from(const [
|
||||
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
||||
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
||||
]);
|
||||
final k = <int>[
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
];
|
||||
final m = List<int>.from(bytes);
|
||||
final bitLen = m.length * 8;
|
||||
m.add(0x80);
|
||||
while (m.length % 64 != 56) {
|
||||
m.add(0);
|
||||
}
|
||||
for (var i = 7; i >= 0; i--) {
|
||||
m.add((bitLen >> (8 * i)) & 0xff);
|
||||
}
|
||||
final words = List<int>.generate(m.length ~/ 4, (i) =>
|
||||
(m[i * 4] << 24) | (m[i * 4 + 1] << 16) | (m[i * 4 + 2] << 8) | m[i * 4 + 3]);
|
||||
var a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
|
||||
for (var i = 0; i < words.length; i += 16) {
|
||||
final w = List<int>.filled(64, 0);
|
||||
for (var j = 0; j < 16; j++) {
|
||||
w[j] = words[i + j];
|
||||
}
|
||||
for (var j = 16; j < 64; j++) {
|
||||
final s0 = _rotr(w[j - 15], 7) ^ _rotr(w[j - 15], 18) ^ (w[j - 15] >> 3);
|
||||
final s1 = _rotr(w[j - 2], 17) ^ _rotr(w[j - 2], 19) ^ (w[j - 2] >> 10);
|
||||
w[j] = (w[j - 16] + s0 + w[j - 7] + s1) & 0xffffffff;
|
||||
}
|
||||
var ta = a, tb = b, tc = c, td = d, te = e, tf = f, tg = g, th = hh;
|
||||
for (var j = 0; j < 64; j++) {
|
||||
final S1 = _rotr(te, 6) ^ _rotr(te, 11) ^ _rotr(te, 25);
|
||||
final ch = (te & tf) ^ ((~te) & tg);
|
||||
final t1 = (th + S1 + ch + k[j] + w[j]) & 0xffffffff;
|
||||
final S0 = _rotr(ta, 2) ^ _rotr(ta, 13) ^ _rotr(ta, 22);
|
||||
final maj = (ta & tb) ^ (ta & tc) ^ (tb & tc);
|
||||
final t2 = (S0 + maj) & 0xffffffff;
|
||||
th = tg;
|
||||
tg = tf;
|
||||
tf = te;
|
||||
te = (td + t1) & 0xffffffff;
|
||||
td = tc;
|
||||
tc = tb;
|
||||
tb = ta;
|
||||
ta = (t1 + t2) & 0xffffffff;
|
||||
}
|
||||
a = (a + ta) & 0xffffffff;
|
||||
b = (b + tb) & 0xffffffff;
|
||||
c = (c + tc) & 0xffffffff;
|
||||
d = (d + td) & 0xffffffff;
|
||||
e = (e + te) & 0xffffffff;
|
||||
f = (f + tf) & 0xffffffff;
|
||||
g = (g + tg) & 0xffffffff;
|
||||
hh = (hh + th) & 0xffffffff;
|
||||
}
|
||||
final out = List<int>.filled(32, 0);
|
||||
final vals = [a, b, c, d, e, f, g, hh];
|
||||
for (var i = 0; i < 8; i++) {
|
||||
out[i * 4] = (vals[i] >> 24) & 0xff;
|
||||
out[i * 4 + 1] = (vals[i] >> 16) & 0xff;
|
||||
out[i * 4 + 2] = (vals[i] >> 8) & 0xff;
|
||||
out[i * 4 + 3] = vals[i] & 0xff;
|
||||
}
|
||||
return out.map((e) => e.toRadixString(16).padLeft(2, '0')).join();
|
||||
}
|
||||
|
||||
static int _rotr(int x, int n) => (x >> n) | ((x << (32 - n)) & 0xffffffff);
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
// OpenChamber API models, ported from the Go client's protocol knowledge.
|
||||
library;
|
||||
|
||||
class ModelRef {
|
||||
final String id;
|
||||
final String providerId;
|
||||
final String? variant;
|
||||
ModelRef(this.id, this.providerId, [this.variant]);
|
||||
factory ModelRef.fromJson(Map<String, dynamic> j) =>
|
||||
ModelRef(j['id'] as String, j['providerID'] as String, j['variant'] as String?);
|
||||
Map<String, dynamic> toJson() =>
|
||||
{'id': id, 'providerID': providerId, if (variant != null) 'variant': variant};
|
||||
}
|
||||
|
||||
class TokenUsage {
|
||||
final int? total;
|
||||
final int input;
|
||||
final int output;
|
||||
final int reasoning;
|
||||
final int cacheRead;
|
||||
final int cacheWrite;
|
||||
TokenUsage({
|
||||
this.total,
|
||||
this.input = 0,
|
||||
this.output = 0,
|
||||
this.reasoning = 0,
|
||||
this.cacheRead = 0,
|
||||
this.cacheWrite = 0,
|
||||
});
|
||||
factory TokenUsage.fromJson(Map<String, dynamic> j) {
|
||||
final cache = j['cache'] as Map<String, dynamic>? ?? {};
|
||||
return TokenUsage(
|
||||
total: j['total'] as int?,
|
||||
input: (j['input'] as num?)?.toInt() ?? 0,
|
||||
output: (j['output'] as num?)?.toInt() ?? 0,
|
||||
reasoning: (j['reasoning'] as num?)?.toInt() ?? 0,
|
||||
cacheRead: (cache['read'] as num?)?.toInt() ?? 0,
|
||||
cacheWrite: (cache['write'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
int get used =>
|
||||
(total ?? 0) > 0 ? total! : input + output + reasoning + cacheRead + cacheWrite;
|
||||
}
|
||||
|
||||
class Location {
|
||||
final String directory;
|
||||
final String? projectId;
|
||||
Location(this.directory, [this.projectId]);
|
||||
factory Location.fromJson(Map<String, dynamic> j) =>
|
||||
Location(j['directory'] as String? ?? '', j['projectId'] as String?);
|
||||
}
|
||||
|
||||
class Session {
|
||||
final String id;
|
||||
final String title;
|
||||
final String agent;
|
||||
final ModelRef? model;
|
||||
final Location? location;
|
||||
final int created;
|
||||
final int updated;
|
||||
Session({
|
||||
required this.id,
|
||||
required this.title,
|
||||
this.agent = '',
|
||||
this.model,
|
||||
this.location,
|
||||
this.created = 0,
|
||||
this.updated = 0,
|
||||
});
|
||||
factory Session.fromJson(Map<String, dynamic> j) {
|
||||
final t = j['time'] as Map<String, dynamic>? ?? {};
|
||||
return Session(
|
||||
id: j['id'] as String,
|
||||
title: j['title'] as String? ?? '',
|
||||
agent: j['agent'] as String? ?? '',
|
||||
model: j['model'] == null ? null : ModelRef.fromJson(j['model'] as Map<String, dynamic>),
|
||||
location: j['location'] == null ? null : Location.fromJson(j['location'] as Map<String, dynamic>),
|
||||
created: (t['created'] as num?)?.toInt() ?? 0,
|
||||
updated: (t['updated'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
String get directory => location?.directory ?? '';
|
||||
}
|
||||
|
||||
class ContentPart {
|
||||
final String type;
|
||||
final String text;
|
||||
final String? id;
|
||||
final String? name;
|
||||
final ToolState? state;
|
||||
final String? mime;
|
||||
final String? url;
|
||||
final String? uri;
|
||||
final String? filename;
|
||||
ContentPart({
|
||||
this.type = '',
|
||||
this.text = '',
|
||||
this.id,
|
||||
this.name,
|
||||
this.state,
|
||||
this.mime,
|
||||
this.url,
|
||||
this.uri,
|
||||
this.filename,
|
||||
});
|
||||
factory ContentPart.fromJson(Map<String, dynamic> j) => ContentPart(
|
||||
type: j['type'] as String? ?? '',
|
||||
text: j['text'] as String? ?? '',
|
||||
id: j['id'] as String?,
|
||||
name: j['name'] as String?,
|
||||
state: j['state'] == null ? null : ToolState.fromJson(j['state'] as Map<String, dynamic>),
|
||||
mime: j['mime'] as String?,
|
||||
url: j['url'] as String?,
|
||||
uri: j['uri'] as String?,
|
||||
filename: j['filename'] as String?,
|
||||
);
|
||||
Map<String, dynamic> toJson() => {
|
||||
if (type.isNotEmpty) 'type': type,
|
||||
if (text.isNotEmpty) 'text': text,
|
||||
if (state != null) 'state': state!.toJson(),
|
||||
};
|
||||
}
|
||||
|
||||
class ToolState {
|
||||
String status;
|
||||
Map<String, dynamic> input;
|
||||
List<ContentPart> content;
|
||||
List<ContentPart> attachments;
|
||||
Map<String, dynamic>? metadata;
|
||||
String? error;
|
||||
ToolState({
|
||||
this.status = '',
|
||||
Map<String, dynamic>? input,
|
||||
List<ContentPart>? content,
|
||||
List<ContentPart>? attachments,
|
||||
this.metadata,
|
||||
this.error,
|
||||
}) : input = input ?? {},
|
||||
content = content ?? [],
|
||||
attachments = attachments ?? [];
|
||||
factory ToolState.fromJson(Map<String, dynamic> j) => ToolState(
|
||||
status: j['status'] as String? ?? '',
|
||||
input: j['input'] as Map<String, dynamic>? ?? {},
|
||||
content: (j['content'] as List?)
|
||||
?.map((e) => ContentPart.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
attachments: (j['attachments'] as List?)
|
||||
?.map((e) => ContentPart.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
metadata: j['metadata'] as Map<String, dynamic>?,
|
||||
error: j['error'] == null ? null : _jsonString(j['error']),
|
||||
);
|
||||
Map<String, dynamic> toJson() => {
|
||||
'status': status,
|
||||
if (input.isNotEmpty) 'input': input,
|
||||
if (content.isNotEmpty) 'content': content.map((e) => e.toJson()).toList(),
|
||||
if (metadata != null) 'metadata': metadata,
|
||||
};
|
||||
}
|
||||
|
||||
class Message {
|
||||
final String id;
|
||||
final String type;
|
||||
final int created;
|
||||
final int completed;
|
||||
final String agent;
|
||||
final ModelRef? model;
|
||||
final List<ContentPart> content;
|
||||
final String text;
|
||||
final List<FileAttachment> files;
|
||||
final String finish;
|
||||
final double cost;
|
||||
final TokenUsage? tokens;
|
||||
Message({
|
||||
required this.id,
|
||||
required this.type,
|
||||
this.created = 0,
|
||||
this.completed = 0,
|
||||
this.agent = '',
|
||||
this.model,
|
||||
this.content = const [],
|
||||
this.text = '',
|
||||
this.files = const [],
|
||||
this.finish = '',
|
||||
this.cost = 0,
|
||||
this.tokens,
|
||||
});
|
||||
factory Message.fromJson(Map<String, dynamic> j) {
|
||||
final t = j['time'] as Map<String, dynamic>? ?? {};
|
||||
return Message(
|
||||
id: j['id'] as String,
|
||||
type: j['type'] as String? ?? '',
|
||||
created: (t['created'] as num?)?.toInt() ?? 0,
|
||||
completed: (t['completed'] as num?)?.toInt() ?? 0,
|
||||
agent: j['agent'] as String? ?? '',
|
||||
model: j['model'] == null ? null : ModelRef.fromJson(j['model'] as Map<String, dynamic>),
|
||||
content: (j['content'] as List?)
|
||||
?.map((e) => ContentPart.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
const [],
|
||||
text: j['text'] as String? ?? '',
|
||||
files: (j['files'] as List?)
|
||||
?.map((e) => FileAttachment.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
const [],
|
||||
finish: j['finish'] as String? ?? '',
|
||||
cost: (j['cost'] as num?)?.toDouble() ?? 0,
|
||||
tokens: j['tokens'] == null ? null : TokenUsage.fromJson(j['tokens'] as Map<String, dynamic>),
|
||||
);
|
||||
}
|
||||
String get partText {
|
||||
final buf = StringBuffer();
|
||||
for (final p in content) {
|
||||
if (p.type == 'text' && p.text.isNotEmpty) buf.write(p.text);
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
}
|
||||
|
||||
class FileAttachment {
|
||||
final String name;
|
||||
final String mime;
|
||||
FileAttachment(this.name, this.mime);
|
||||
factory FileAttachment.fromJson(Map<String, dynamic> j) =>
|
||||
FileAttachment(j['name'] as String? ?? '', j['mime'] as String? ?? '');
|
||||
}
|
||||
|
||||
class Page<T> {
|
||||
final List<T> data;
|
||||
final String? next;
|
||||
final String? previous;
|
||||
Page(this.data, {this.next, this.previous});
|
||||
}
|
||||
|
||||
class AuthStatus {
|
||||
final bool authenticated;
|
||||
final bool disabled;
|
||||
final bool locked;
|
||||
AuthStatus(this.authenticated, this.disabled, this.locked);
|
||||
}
|
||||
|
||||
class ModelInfo {
|
||||
final String id;
|
||||
final String providerId;
|
||||
final String name;
|
||||
final int context;
|
||||
final int output;
|
||||
ModelInfo(this.id, this.providerId, this.name, this.context, this.output);
|
||||
factory ModelInfo.fromJson(Map<String, dynamic> j) {
|
||||
final lim = j['limit'] as Map<String, dynamic>? ?? {};
|
||||
return ModelInfo(
|
||||
j['id'] as String,
|
||||
j['providerID'] as String? ?? '',
|
||||
j['name'] as String? ?? (j['id'] as String? ?? ''),
|
||||
(lim['context'] as num?)?.toInt() ?? 0,
|
||||
(lim['output'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AgentInfo {
|
||||
final String id;
|
||||
final String name;
|
||||
final String mode;
|
||||
AgentInfo(this.id, this.name, this.mode);
|
||||
factory AgentInfo.fromJson(Map<String, dynamic> j) =>
|
||||
AgentInfo(j['id'] as String, j['name'] as String? ?? '', j['mode'] as String? ?? '');
|
||||
}
|
||||
|
||||
class PermissionRequest {
|
||||
final String id;
|
||||
final String sessionId;
|
||||
final String action;
|
||||
final List<String> resources;
|
||||
PermissionRequest(this.id, this.sessionId, this.action, this.resources);
|
||||
factory PermissionRequest.fromJson(Map<String, dynamic> j) => PermissionRequest(
|
||||
j['id'] as String,
|
||||
j['sessionID'] as String? ?? '',
|
||||
j['action'] as String? ?? '',
|
||||
(j['resources'] as List?)?.map((e) => e.toString()).toList() ?? const [],
|
||||
);
|
||||
}
|
||||
|
||||
String _jsonString(Object? o) {
|
||||
if (o is String) return o;
|
||||
return o.toString();
|
||||
}
|
||||
Reference in new issue
Block a user