feat: a transport seam, image previews, native forms, a phone drawer
- lib/api/transport.dart: TransportRequest/TransportResponse/Transport, with DirectTransport holding the old behaviour (HTTP CONNECT, SOCKS5/socks5h, self-signed and pinned certificates). Client goes through it, so a relay tunnel only adds an implementation. - User rows decode the server's inline attachment data and open the shared image preview on tap; the local path stays the fallback. - The agent's native forms: models from @opencode/client, the form list, replies and cancels, form.* events, and a dock above the composer with when-rules and required-field validation (a switch must be on). - HomeScreen: the session list is the phone's left drawer and a persistent column from 840 px, the chat beside it; the newest session opens on start. - 0.3.10 (310).
This commit is contained in:
1 parent
9b53338908
commit
60d02083d3
11 files changed
+1272
-320
No files matched your search
+91
-233
@@ -4,11 +4,8 @@ library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:socks5_proxy/socks_client.dart';
|
||||
|
||||
import 'models.dart';
|
||||
import 'transport.dart';
|
||||
|
||||
class ApiError implements Exception {
|
||||
final int status;
|
||||
@@ -18,111 +15,23 @@ class ApiError implements Exception {
|
||||
String toString() => message.isEmpty ? 'HTTP $status' : message;
|
||||
}
|
||||
|
||||
/// A proxy as configured: an HTTP CONNECT proxy, or a SOCKS5 one.
|
||||
class _ProxyConfig {
|
||||
final String scheme; // http | https | socks5 | socks5h
|
||||
final String host;
|
||||
final int port;
|
||||
final String? username;
|
||||
final String? password;
|
||||
_ProxyConfig(this.scheme, this.host, this.port, [this.username, this.password]);
|
||||
|
||||
bool get socks => scheme.startsWith('socks');
|
||||
}
|
||||
|
||||
_ProxyConfig? _parseProxy(String? raw) {
|
||||
final s = raw?.trim() ?? '';
|
||||
if (s.isEmpty) return null;
|
||||
var normalized = s;
|
||||
if (!normalized.contains('://')) normalized = 'http://$normalized';
|
||||
final uri = Uri.tryParse(normalized);
|
||||
if (uri == null || uri.host.isEmpty) {
|
||||
throw ArgumentError('代理地址无效:$raw');
|
||||
}
|
||||
final scheme = uri.scheme.toLowerCase();
|
||||
final socks = scheme == 'socks' || scheme == 'socks5' || scheme == 'socks5h';
|
||||
final http = scheme == 'http' || scheme == 'https';
|
||||
if (!socks && !http) {
|
||||
throw ArgumentError('不支持的代理协议:$scheme(支持 http、https、socks5、socks5h)');
|
||||
}
|
||||
String? user;
|
||||
String? pass;
|
||||
if (uri.userInfo.isNotEmpty) {
|
||||
final i = uri.userInfo.indexOf(':');
|
||||
if (i >= 0) {
|
||||
user = Uri.decodeComponent(uri.userInfo.substring(0, i));
|
||||
pass = Uri.decodeComponent(uri.userInfo.substring(i + 1));
|
||||
} else {
|
||||
user = Uri.decodeComponent(uri.userInfo);
|
||||
}
|
||||
}
|
||||
final port = uri.hasPort ? uri.port : (socks ? 1080 : 8080);
|
||||
return _ProxyConfig(scheme, uri.host, port, user, pass);
|
||||
}
|
||||
|
||||
class Client {
|
||||
final Uri base;
|
||||
final String? proxy; // http://host:port or socks5://host:port
|
||||
final bool insecure;
|
||||
final String? fingerprint;
|
||||
|
||||
/// Every request and the event stream go through here; today a direct
|
||||
/// connection, later one that can also be a relay tunnel.
|
||||
final Transport transport;
|
||||
String? token;
|
||||
late HttpClient _http;
|
||||
_ProxyConfig? _proxyConfig;
|
||||
InternetAddress? _proxyAddress;
|
||||
|
||||
Client(
|
||||
this.base, {
|
||||
this.proxy,
|
||||
this.insecure = false,
|
||||
this.fingerprint,
|
||||
}) {
|
||||
_http = HttpClient();
|
||||
_http.connectionTimeout = const Duration(seconds: 20);
|
||||
_proxyConfig = _parseProxy(proxy);
|
||||
if (_proxyConfig != null && _proxyConfig!.socks) {
|
||||
// Dart's HttpClient has no SOCKS support in findProxy; the socks5_proxy
|
||||
// package tunnels the socket and hands a Socket back to the client.
|
||||
_http.connectionFactory = (uri, _, __) async {
|
||||
final address = await _resolveProxyAddress();
|
||||
final settings = ProxySettings(address, _proxyConfig!.port,
|
||||
username: _proxyConfig!.username, password: _proxyConfig!.password);
|
||||
final tunnel = SocksTCPClient.connect(
|
||||
[settings],
|
||||
// A unix-type address carries the host name, so the proxy resolves
|
||||
// it (socks5h semantics) instead of resolving it here.
|
||||
InternetAddress(uri.host, type: InternetAddressType.unix),
|
||||
uri.port,
|
||||
);
|
||||
if (uri.scheme == 'https') {
|
||||
final secure = tunnel.then(
|
||||
(s) => s.secure(uri.host, onBadCertificate: _badCertificate));
|
||||
return ConnectionTask.fromSocket(secure, () {});
|
||||
}
|
||||
return ConnectionTask.fromSocket(tunnel, () {});
|
||||
};
|
||||
} else if (_proxyConfig != null) {
|
||||
_http.findProxy = (_) => 'PROXY ${_proxyConfig!.host}:${_proxyConfig!.port}';
|
||||
}
|
||||
_http.badCertificateCallback = (cert, host, port) => _badCertificate(cert);
|
||||
}
|
||||
|
||||
Future<InternetAddress> _resolveProxyAddress() async {
|
||||
if (_proxyAddress != null) return _proxyAddress!;
|
||||
final addresses = await InternetAddress.lookup(_proxyConfig!.host);
|
||||
if (addresses.isEmpty) {
|
||||
throw const SocketException('无法解析代理主机');
|
||||
}
|
||||
return _proxyAddress = addresses.first;
|
||||
}
|
||||
|
||||
/// True for a certificate the app was told to accept: the user trusts any
|
||||
/// (insecure), or its SHA-256 matches the pinned fingerprint.
|
||||
bool _badCertificate(X509Certificate cert) {
|
||||
if (insecure) return true;
|
||||
final pinned = fingerprint?.replaceAll(':', '').toLowerCase();
|
||||
if (pinned == null || pinned.isEmpty) return false;
|
||||
return _sha256(cert.der) == pinned;
|
||||
}
|
||||
String? proxy,
|
||||
bool insecure = false,
|
||||
String? fingerprint,
|
||||
Transport? transport,
|
||||
}) : transport = transport ??
|
||||
DirectTransport(base,
|
||||
proxy: proxy, insecure: insecure, fingerprint: fingerprint);
|
||||
|
||||
String get baseUrl => base.toString();
|
||||
|
||||
@@ -290,6 +199,39 @@ class Client {
|
||||
return data is Map ? data['id'] as String? : null;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- forms
|
||||
|
||||
/// The agent's pending questions in this session.
|
||||
Future<List<FormInfo>> forms(String sessionId, {String? directory}) async {
|
||||
final r = await _json(
|
||||
'GET', '/api/session/${Uri.encodeComponent(sessionId)}/form',
|
||||
directory: directory);
|
||||
return [
|
||||
for (final f in (r['data'] as List? ?? []))
|
||||
if (f is Map<String, dynamic>) FormInfo.fromJson(f),
|
||||
];
|
||||
}
|
||||
|
||||
Future<void> replyForm(String sessionId, String formId,
|
||||
Map<String, Object?> answer, {String? directory}) async {
|
||||
await _json(
|
||||
'POST',
|
||||
'/api/session/${Uri.encodeComponent(sessionId)}/form/${Uri.encodeComponent(formId)}/reply',
|
||||
body: {'answer': answer},
|
||||
directory: directory);
|
||||
}
|
||||
|
||||
Future<void> cancelForm(String sessionId, String formId,
|
||||
{String? message, String? directory}) async {
|
||||
await _json(
|
||||
'DELETE',
|
||||
'/api/session/${Uri.encodeComponent(sessionId)}/form/${Uri.encodeComponent(formId)}',
|
||||
query: {
|
||||
if (message != null && message.isNotEmpty) 'message': message,
|
||||
},
|
||||
directory: directory);
|
||||
}
|
||||
|
||||
/// The commands this directory registers (`/api/command`).
|
||||
Future<List<Map<String, String>>> commands({String? directory}) async {
|
||||
final r = await _json('GET', '/api/command', directory: directory);
|
||||
@@ -357,10 +299,11 @@ class Client {
|
||||
},
|
||||
directory: directory,
|
||||
rawDirectory: true);
|
||||
final bytes = await res.collect();
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
throw ApiError(res.statusCode, utf8.decode(res.body, allowMalformed: true));
|
||||
throw ApiError(res.statusCode, utf8.decode(bytes, allowMalformed: true));
|
||||
}
|
||||
return res.body;
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ files
|
||||
@@ -383,7 +326,7 @@ class Client {
|
||||
Future<String> fsRead(String path, {String? directory}) async {
|
||||
final res = await _request('GET', '/api/fs/read',
|
||||
query: {'path': path}, directory: directory, rawDirectory: true);
|
||||
final text = utf8.decode(res.body, allowMalformed: true);
|
||||
final text = utf8.decode(await res.collect(), allowMalformed: true);
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
throw ApiError(res.statusCode, text.trim());
|
||||
}
|
||||
@@ -419,27 +362,29 @@ class Client {
|
||||
/// when the connection drops; the caller restarts it with backoff.
|
||||
Stream<Map<String, dynamic>> streamEvents({List<String>? types}) async* {
|
||||
// `types` repeats: a Map would keep only the last one.
|
||||
var uri = base.resolve('/api/event');
|
||||
if (types != null && types.isNotEmpty) {
|
||||
final q = types.map((t) => 'types=${Uri.encodeQueryComponent(t)}').join('&');
|
||||
uri = Uri.parse('$uri?$q');
|
||||
}
|
||||
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');
|
||||
final query = types == null || types.isEmpty
|
||||
? null
|
||||
: types.map((t) => 'types=${Uri.encodeQueryComponent(t)}').join('&');
|
||||
final res = await transport.send(TransportRequest(
|
||||
method: 'GET',
|
||||
path: '/api/event',
|
||||
rawQuery: query,
|
||||
headers: {
|
||||
'accept': 'text/event-stream',
|
||||
'cache-control': 'no-cache',
|
||||
'user-agent': 'openchamber-native/0.3',
|
||||
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
|
||||
},
|
||||
));
|
||||
if (res.status != 200) {
|
||||
throw ApiError(res.status, 'event stream failed');
|
||||
}
|
||||
String data = '';
|
||||
// The server sends a `: heartbeat` comment every few seconds; if nothing
|
||||
// at all arrives for a while the connection is dead and the caller should
|
||||
// reconnect rather than wait on a half-open socket.
|
||||
final lines = utf8.decoder
|
||||
.bind(res)
|
||||
.bind(res.body)
|
||||
.transform(const LineSplitter())
|
||||
.timeout(const Duration(seconds: 30));
|
||||
await for (final line in lines) {
|
||||
@@ -471,7 +416,7 @@ class Client {
|
||||
directory: directory,
|
||||
partShells: partShells,
|
||||
rawDirectory: rawDirectory);
|
||||
final text = utf8.decode(res.body, allowMalformed: true);
|
||||
final text = utf8.decode(await res.collect(), allowMalformed: true);
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
String msg = text;
|
||||
try {
|
||||
@@ -494,127 +439,40 @@ class Client {
|
||||
String? directory,
|
||||
bool partShells = false,
|
||||
bool rawDirectory = 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);
|
||||
// Every header must be set before the body, which finalizes them.
|
||||
req.headers.set('Accept', path == '/api/event' ? 'text/event-stream' : 'application/json');
|
||||
req.headers.set('User-Agent', 'openchamber-native/0.3');
|
||||
if (token != null && token!.isNotEmpty) {
|
||||
req.headers.set('Authorization', 'Bearer $token');
|
||||
}
|
||||
final headers = <String, String>{
|
||||
'accept': path == '/api/event' ? 'text/event-stream' : 'application/json',
|
||||
'user-agent': 'openchamber-native/0.3',
|
||||
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
|
||||
};
|
||||
if (directory != null && directory.isNotEmpty) {
|
||||
// The file routes compare this header with the workspace path, so they
|
||||
// need it as written; the rest of the API wants it URI-encoded.
|
||||
req.headers.set('x-opencode-directory',
|
||||
rawDirectory ? directory : Uri.encodeComponent(directory));
|
||||
if (!rawDirectory) {
|
||||
req.headers.set('x-opencode-directory-encoding', 'uri');
|
||||
}
|
||||
headers['x-opencode-directory'] =
|
||||
rawDirectory ? directory : Uri.encodeComponent(directory);
|
||||
if (!rawDirectory) headers['x-opencode-directory-encoding'] = 'uri';
|
||||
}
|
||||
if (partShells) {
|
||||
req.headers.set('x-openchamber-part-shells', 'v1');
|
||||
}
|
||||
if (path == '/api/event') {
|
||||
req.headers.set('Cache-Control', 'no-cache');
|
||||
}
|
||||
if (body != null) {
|
||||
req.headers.contentType = ContentType.json;
|
||||
req.write(jsonEncode(body));
|
||||
}
|
||||
final res = await req.close();
|
||||
final bodyBytes = await res.fold<List<int>>(<int>[], (a, b) => a..addAll(b));
|
||||
return _Response(res.statusCode, bodyBytes);
|
||||
if (partShells) headers['x-openchamber-part-shells'] = 'v1';
|
||||
if (path == '/api/event') headers['cache-control'] = 'no-cache';
|
||||
final bodyBytes = body == null ? null : utf8.encode(jsonEncode(body));
|
||||
if (bodyBytes != null) headers['content-type'] = 'application/json';
|
||||
final res = await transport.send(TransportRequest(
|
||||
method: method,
|
||||
path: path,
|
||||
query: query ?? const {},
|
||||
headers: headers,
|
||||
body: bodyBytes,
|
||||
));
|
||||
return _Response(res.status, res.body);
|
||||
}
|
||||
|
||||
void close() => _http.close();
|
||||
void close() => transport.close();
|
||||
}
|
||||
|
||||
class _Response {
|
||||
final int statusCode;
|
||||
final List<int> body;
|
||||
final Stream<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);
|
||||
Future<List<int>> collect() =>
|
||||
body.fold<List<int>>(<int>[], (a, b) => a..addAll(b));
|
||||
}
|
||||
Reference in new issue
Block a user