- Starting a session opens NewSessionScreen instead of a title sheet: a project chip (GET /api/project, one row per canonical), a model/agent chip, attachments and the composer. Nothing is created on the server until the first send, which posts the session with its directory, model and agent and then sends that message. - The draft lives in AppState (memory only): leaving it keeps it; the sidebar shows a draft row with its first line and a discard button; a failed create stays on the draft with its text. - The session list groups by project (chat folders under 聊天), dates the rows (今天/昨天/本周早些时候/更早), pins through session.metadata.openchamber.pinned, archives on demand, pages with "载入更多", and swipes to pin/archive/delete (flutter_slidable). - Child sessions are hidden; a parent's row shows its children's activity. - The chat app bar follows the live session list, so the title the server generates from the first message appears at once. - Attachments and the model picker move to shared widgets, used by the chat and the draft. - 0.3.13 (313).
793 lines
28 KiB
Dart
793 lines
28 KiB
Dart
// 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:typed_data';
|
|
|
|
import 'models.dart';
|
|
import 'terminal.dart';
|
|
import 'transport.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;
|
|
|
|
/// 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;
|
|
|
|
Client(
|
|
this.base, {
|
|
String? proxy,
|
|
bool insecure = false,
|
|
String? fingerprint,
|
|
Transport? transport,
|
|
}) : transport = transport ??
|
|
DirectTransport(base,
|
|
proxy: proxy, insecure: insecure, fingerprint: fingerprint);
|
|
|
|
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,
|
|
bool? archived,
|
|
}) 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,
|
|
if (archived != null) 'archived': '$archived',
|
|
};
|
|
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,
|
|
ModelRef? model,
|
|
String? agent}) async {
|
|
final r = await _json('POST', '/api/session', body: {
|
|
if (title != null && title.isNotEmpty) 'title': title,
|
|
if (directory != null && directory.isNotEmpty)
|
|
'location': {'directory': directory},
|
|
// The first turn runs on the draft's selection; no switch after create.
|
|
if (model != null) 'model': model.toJson(),
|
|
if (agent != null && agent.isNotEmpty) 'agent': agent,
|
|
});
|
|
return Session.fromJson(r['data'] as Map<String, dynamic>);
|
|
}
|
|
|
|
Future<void> updateSession(String id,
|
|
{String? title, bool? archived, Map<String, dynamic>? metadata}) async {
|
|
await _json('PATCH', '/api/session/${Uri.encodeComponent(id)}', body: {
|
|
if (title != null) 'title': title,
|
|
if (archived != null) 'archived': archived,
|
|
if (metadata != null) 'metadata': metadata,
|
|
});
|
|
}
|
|
|
|
/// The projects (checkouts and chat folders) an agent can open a session in.
|
|
Future<List<ProjectInfo>> listProjects() async {
|
|
final list = await _jsonList('GET', '/api/project');
|
|
return [
|
|
for (final p in list)
|
|
if (p is Map<String, dynamic>) ProjectInfo.fromJson(p),
|
|
];
|
|
}
|
|
|
|
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',
|
|
// The server rejects a cursor combined with order: the cursor already
|
|
// carries the direction.
|
|
if (cursor == null) '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['data'] as Map<String, dynamic>);
|
|
}
|
|
|
|
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,
|
|
List<String>? skillIds}) 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,
|
|
if (skillIds != null && skillIds.isNotEmpty)
|
|
'skills': [
|
|
for (final id in skillIds) {'id': id},
|
|
],
|
|
});
|
|
}
|
|
|
|
/// Runs a registered slash command (`/initialize`, `/review`, …). The
|
|
/// server expands the command template and starts the turn.
|
|
Future<void> command(String sessionId,
|
|
{required String name, String text = '', String? directory,
|
|
List<Map<String, String>>? files}) async {
|
|
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/command',
|
|
directory: directory,
|
|
body: {
|
|
'name': name,
|
|
'text': text,
|
|
if (files != null && files.isNotEmpty) 'files': files,
|
|
});
|
|
}
|
|
|
|
/// Asks the server to summarize the history into a compaction record.
|
|
/// Returns that record's message id, when the server names it.
|
|
Future<String?> compact(String sessionId, {String? directory}) async {
|
|
final r = await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/compact',
|
|
directory: directory, body: const {});
|
|
final data = r['data'];
|
|
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);
|
|
return [
|
|
for (final e in (r['data'] as List? ?? []))
|
|
if (e is Map)
|
|
{
|
|
'name': e['name'] as String? ?? '',
|
|
'description': e['description'] as String? ?? '',
|
|
},
|
|
];
|
|
}
|
|
|
|
/// The skills opencode knows in this directory (`/api/skill`).
|
|
Future<List<Map<String, String>>> skills({String? directory}) async {
|
|
final r = await _json('GET', '/api/skill', directory: directory);
|
|
return [
|
|
for (final e in (r['data'] as List? ?? []))
|
|
if (e is Map)
|
|
{
|
|
'id': e['id'] as String? ?? '',
|
|
'name': e['name'] as String? ?? '',
|
|
'description': e['description'] as String? ?? '',
|
|
},
|
|
];
|
|
}
|
|
|
|
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}) =>
|
|
downloadFile(path, directory: directory);
|
|
|
|
/// Downloads a file, reporting bytes as they arrive and letting the caller
|
|
/// cancel. A cancelled download throws [DownloadCancelled] and drops the
|
|
/// connection instead of reading it to the end.
|
|
Future<Uint8List> downloadFile(String path,
|
|
{String? directory,
|
|
void Function(int received, int? total)? onProgress,
|
|
CancelToken? cancel}) async {
|
|
final res = await _request('GET', '/api/fs/raw',
|
|
query: {
|
|
'path': path,
|
|
'allowOutsideWorkspace': 'true',
|
|
},
|
|
directory: directory,
|
|
rawDirectory: true,
|
|
// Gzip would leave the response chunked (no total to show) and count
|
|
// compressed bytes; a download wants the file as it is.
|
|
noCompression: true);
|
|
final total = int.tryParse(res.headers['content-length'] ?? '');
|
|
cancel?.attach(() => res.abort?.call());
|
|
try {
|
|
final bytes = BytesBuilder(copy: false);
|
|
try {
|
|
await for (final chunk in res.body) {
|
|
if (cancel?.isCancelled ?? false) throw const DownloadCancelled();
|
|
bytes.add(chunk);
|
|
onProgress?.call(bytes.length, total);
|
|
}
|
|
} catch (error) {
|
|
// Aborting the request surfaces as a socket error; the caller only
|
|
// asked to stop.
|
|
if (cancel?.isCancelled ?? false) throw const DownloadCancelled();
|
|
rethrow;
|
|
}
|
|
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
throw ApiError(
|
|
res.statusCode,
|
|
utf8.decode(bytes.takeBytes(), allowMalformed: true));
|
|
}
|
|
return bytes.takeBytes();
|
|
} finally {
|
|
cancel?.detach();
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------ files
|
|
|
|
Future<List<FsEntry>> fsList(String path,
|
|
{String? directory, bool respectGitignore = true}) async {
|
|
final r = await _json('GET', '/api/fs/list',
|
|
query: {
|
|
'path': path,
|
|
if (respectGitignore) 'respectGitignore': 'true',
|
|
},
|
|
directory: directory,
|
|
rawDirectory: true);
|
|
return [
|
|
for (final e in (r['entries'] as List? ?? []))
|
|
if (e is Map<String, dynamic>) FsEntry.fromJson(e),
|
|
];
|
|
}
|
|
|
|
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(await res.collect(), allowMalformed: true);
|
|
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
throw ApiError(res.statusCode, text.trim());
|
|
}
|
|
return text;
|
|
}
|
|
|
|
Future<FsStat?> fsStat(String path, {String? directory}) async {
|
|
final r = await _json('GET', '/api/fs/stat',
|
|
query: {'path': path}, directory: directory, rawDirectory: true);
|
|
final data = r['path'] == null ? r['data'] : r;
|
|
if (data is! Map<String, dynamic>) return null;
|
|
return FsStat.fromJson(data);
|
|
}
|
|
|
|
Future<void> fsWrite(String path, String content, {String? directory}) async {
|
|
await _json('POST', '/api/fs/write',
|
|
body: {'path': path, 'content': content},
|
|
directory: directory,
|
|
rawDirectory: true);
|
|
}
|
|
|
|
Future<void> fsMkdir(String path, {String? directory}) async {
|
|
await _json('POST', '/api/fs/mkdir',
|
|
body: {'path': path}, directory: directory, rawDirectory: true);
|
|
}
|
|
|
|
Future<void> fsDelete(String path, {String? directory}) async {
|
|
await _json('POST', '/api/fs/delete',
|
|
body: {'path': path}, directory: directory, rawDirectory: true);
|
|
}
|
|
|
|
/// 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* {
|
|
// `types` repeats: a Map would keep only the last one.
|
|
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.body)
|
|
.transform(const LineSplitter())
|
|
.timeout(const Duration(seconds: 30));
|
|
await for (final line in lines) {
|
|
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();
|
|
}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------ project knowledge
|
|
|
|
/// The project id the server derives from a checkout path: `path_` + the
|
|
/// path base64url-encoded, both ends agreeing on the encoding.
|
|
static String projectIdFor(String directory) {
|
|
final normalized = directory
|
|
.replaceAll('\\', '/')
|
|
.replaceAll(RegExp(r'/+$'), '')
|
|
.trim();
|
|
if (normalized.isEmpty) return '';
|
|
final encoded = base64Url
|
|
.encode(utf8.encode(normalized))
|
|
.replaceAll('=', '');
|
|
return 'path_$encoded';
|
|
}
|
|
|
|
Future<ProjectContext> projectContext(String projectId,
|
|
{String? directory}) async {
|
|
final r = await _json(
|
|
'GET', '/api/project-context/${Uri.encodeComponent(projectId)}',
|
|
directory: directory);
|
|
return ProjectContext.fromJson(r);
|
|
}
|
|
|
|
/// Every mutation answers with the whole context beside the record it
|
|
/// changed, so the panel refreshes from one reply.
|
|
static ProjectContext _contextOf(Map<String, dynamic> r) {
|
|
final context = r['context'];
|
|
return ProjectContext.fromJson(
|
|
context is Map<String, dynamic> ? context : r);
|
|
}
|
|
|
|
Future<ProjectContext> createNote(String projectId, String body,
|
|
{String? planId, String? directory}) async {
|
|
final r = await _json(
|
|
'POST', '/api/project-context/${Uri.encodeComponent(projectId)}/notes',
|
|
body: {
|
|
'body': body,
|
|
if (planId != null) 'planId': planId,
|
|
},
|
|
directory: directory);
|
|
return _contextOf(r);
|
|
}
|
|
|
|
Future<ProjectContext> updateNote(
|
|
String projectId, String noteId,
|
|
{String? body, bool? pinned, String? directory}) async {
|
|
final r = await _json(
|
|
'PATCH',
|
|
'/api/project-context/${Uri.encodeComponent(projectId)}/notes/${Uri.encodeComponent(noteId)}',
|
|
body: {
|
|
if (body != null) 'body': body,
|
|
if (pinned != null) 'pinned': pinned,
|
|
},
|
|
directory: directory);
|
|
return _contextOf(r);
|
|
}
|
|
|
|
Future<ProjectContext> deleteNote(String projectId, String noteId,
|
|
{String? directory}) async {
|
|
final r = await _json(
|
|
'DELETE',
|
|
'/api/project-context/${Uri.encodeComponent(projectId)}/notes/${Uri.encodeComponent(noteId)}',
|
|
directory: directory);
|
|
return _contextOf(r);
|
|
}
|
|
|
|
Future<ProjectContext> createTodo(String projectId, String text,
|
|
{String? planId, String? directory}) async {
|
|
final r = await _json(
|
|
'POST', '/api/project-context/${Uri.encodeComponent(projectId)}/todos',
|
|
body: {
|
|
'text': text,
|
|
if (planId != null) 'planId': planId,
|
|
},
|
|
directory: directory);
|
|
return _contextOf(r);
|
|
}
|
|
|
|
Future<ProjectContext> updateTodo(String projectId, String todoId,
|
|
{String? text, bool? completed, String? directory}) async {
|
|
final r = await _json(
|
|
'PATCH',
|
|
'/api/project-context/${Uri.encodeComponent(projectId)}/todos/${Uri.encodeComponent(todoId)}',
|
|
body: {
|
|
if (text != null) 'text': text,
|
|
if (completed != null) 'completed': completed,
|
|
},
|
|
directory: directory);
|
|
return _contextOf(r);
|
|
}
|
|
|
|
Future<ProjectContext> deleteTodo(String projectId, String todoId,
|
|
{String? directory}) async {
|
|
final r = await _json(
|
|
'DELETE',
|
|
'/api/project-context/${Uri.encodeComponent(projectId)}/todos/${Uri.encodeComponent(todoId)}',
|
|
directory: directory);
|
|
return _contextOf(r);
|
|
}
|
|
|
|
Future<ProjectContext> createPlan(String projectId,
|
|
{required String title, required String body, String? directory}) async {
|
|
final r = await _json(
|
|
'POST', '/api/project-context/${Uri.encodeComponent(projectId)}/plans',
|
|
body: {'title': title, 'body': body},
|
|
directory: directory);
|
|
return _contextOf(r);
|
|
}
|
|
|
|
Future<ProjectContext> savePlan(String projectId, String planId, String raw,
|
|
{String? directory}) async {
|
|
final r = await _json(
|
|
'PUT',
|
|
'/api/project-context/${Uri.encodeComponent(projectId)}/plans/${Uri.encodeComponent(planId)}',
|
|
body: {'raw': raw},
|
|
directory: directory);
|
|
return _contextOf(r);
|
|
}
|
|
|
|
Future<ProjectContext> setPlanPinned(
|
|
String projectId, String planId, bool pinned,
|
|
{String? directory}) async {
|
|
final r = await _json(
|
|
'PATCH',
|
|
'/api/project-context/${Uri.encodeComponent(projectId)}/plans/${Uri.encodeComponent(planId)}',
|
|
body: {'pinned': pinned},
|
|
directory: directory);
|
|
return _contextOf(r);
|
|
}
|
|
|
|
Future<ProjectContext> deletePlan(String projectId, String planId,
|
|
{String? directory}) async {
|
|
final r = await _json(
|
|
'DELETE',
|
|
'/api/project-context/${Uri.encodeComponent(projectId)}/plans/${Uri.encodeComponent(planId)}',
|
|
directory: directory);
|
|
return _contextOf(r);
|
|
}
|
|
|
|
Future<ProjectPlanContent> planContent(String projectId, String planId,
|
|
{String? directory}) async {
|
|
final r = await _json(
|
|
'GET',
|
|
'/api/project-context/${Uri.encodeComponent(projectId)}/plans/${Uri.encodeComponent(planId)}',
|
|
directory: directory);
|
|
return ProjectPlanContent.fromJson(r);
|
|
}
|
|
|
|
// ----------------------------------------------------------------- memory
|
|
|
|
/// Both memory scopes at once; null when the server has the feature switched
|
|
/// off (the route answers 404, which it also uses for a missing entry, but
|
|
/// this read has no entry id to miss).
|
|
Future<AgentMemorySnapshot?> agentMemory(String projectId,
|
|
{String? directory}) async {
|
|
try {
|
|
final r = await _json('GET', '/api/agent-memory/all',
|
|
query: {
|
|
if (projectId.isNotEmpty) 'projectId': projectId,
|
|
},
|
|
directory: directory);
|
|
return AgentMemorySnapshot.fromJson(r);
|
|
} on ApiError catch (error) {
|
|
if (error.status == 404) return null;
|
|
rethrow;
|
|
}
|
|
}
|
|
|
|
Future<void> updateMemory(String memoryId,
|
|
{required String scope,
|
|
String? projectId,
|
|
String? title,
|
|
String? body,
|
|
String? type,
|
|
String? directory}) async {
|
|
await _json(
|
|
'PATCH', '/api/agent-memory/${Uri.encodeComponent(memoryId)}',
|
|
query: {
|
|
'scope': scope,
|
|
if (scope == 'project' && projectId != null && projectId.isNotEmpty)
|
|
'projectId': projectId,
|
|
},
|
|
body: {
|
|
if (title != null) 'title': title,
|
|
if (body != null) 'body': body,
|
|
if (type != null) 'type': type,
|
|
},
|
|
directory: directory);
|
|
}
|
|
|
|
Future<void> deleteMemory(String memoryId,
|
|
{required String scope,
|
|
String? projectId,
|
|
String? directory}) async {
|
|
await _json(
|
|
'DELETE', '/api/agent-memory/${Uri.encodeComponent(memoryId)}',
|
|
query: {
|
|
'scope': scope,
|
|
if (scope == 'project' && projectId != null && projectId.isNotEmpty)
|
|
'projectId': projectId,
|
|
},
|
|
directory: directory);
|
|
}
|
|
|
|
// --------------------------------------------------------------- terminal
|
|
|
|
Future<TerminalSessionInfo> createTerminal(
|
|
{required String cwd, int cols = 80, int rows = 24}) async {
|
|
final r = await _json('POST', '/api/terminal/create',
|
|
body: {'cwd': cwd, 'cols': cols, 'rows': rows}, directory: cwd);
|
|
return TerminalSessionInfo.fromJson(r);
|
|
}
|
|
|
|
Future<void> resizeTerminal(String sessionId, int cols, int rows,
|
|
{String? directory}) async {
|
|
await _json('POST',
|
|
'/api/terminal/${Uri.encodeComponent(sessionId)}/resize',
|
|
body: {'cols': cols, 'rows': rows}, directory: directory);
|
|
}
|
|
|
|
Future<TerminalSessionInfo> restartTerminal(String sessionId,
|
|
{required String cwd, int cols = 80, int rows = 24}) async {
|
|
final r = await _json('POST',
|
|
'/api/terminal/${Uri.encodeComponent(sessionId)}/restart',
|
|
body: {'cwd': cwd, 'cols': cols, 'rows': rows}, directory: cwd);
|
|
return TerminalSessionInfo.fromJson(r);
|
|
}
|
|
|
|
Future<void> closeTerminal(String sessionId, {String? directory}) async {
|
|
await _json(
|
|
'DELETE', '/api/terminal/${Uri.encodeComponent(sessionId)}',
|
|
directory: directory);
|
|
}
|
|
|
|
/// The headers the terminal socket needs (auth, and the workspace the
|
|
/// server routes the upgrade by).
|
|
Map<String, String> get eventHeaders => {
|
|
'user-agent': 'openchamber-native/0.3',
|
|
if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
|
|
};
|
|
|
|
// --------------------------------------------------------------- transport
|
|
|
|
Future<List<dynamic>> _jsonList(String method, String path,
|
|
{Map<String, String>? query}) async {
|
|
final res = await _request(method, path, query: query);
|
|
final text = utf8.decode(await res.collect(), allowMalformed: true);
|
|
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
throw ApiError(res.statusCode, text.trim());
|
|
}
|
|
final decoded = jsonDecode(text);
|
|
return decoded is List ? decoded : const [];
|
|
}
|
|
|
|
Future<Map<String, dynamic>> _json(String method, String path,
|
|
{Map<String, String>? query,
|
|
Map<String, dynamic>? body,
|
|
String? directory,
|
|
bool partShells = false,
|
|
bool rawDirectory = false,
|
|
bool noCompression = false}) async {
|
|
final res = await _request(method, path,
|
|
query: query,
|
|
body: body,
|
|
directory: directory,
|
|
partShells: partShells,
|
|
rawDirectory: rawDirectory,
|
|
noCompression: noCompression);
|
|
final text = utf8.decode(await res.collect(), 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,
|
|
bool rawDirectory = false,
|
|
bool noCompression = false}) async {
|
|
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.
|
|
headers['x-opencode-directory'] =
|
|
rawDirectory ? directory : Uri.encodeComponent(directory);
|
|
if (!rawDirectory) headers['x-opencode-directory-encoding'] = 'uri';
|
|
}
|
|
if (partShells) headers['x-openchamber-part-shells'] = 'v1';
|
|
if (noCompression) headers['accept-encoding'] = 'identity';
|
|
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.headers, res.body, res.abort);
|
|
}
|
|
|
|
void close() => transport.close();
|
|
}
|
|
|
|
class _Response {
|
|
final int statusCode;
|
|
final Map<String, String> headers;
|
|
final Stream<List<int>> body;
|
|
final void Function()? abort;
|
|
_Response(this.statusCode, this.headers, this.body, [this.abort]);
|
|
|
|
Future<List<int>> collect() =>
|
|
body.fold<List<int>>(<int>[], (a, b) => a..addAll(b));
|
|
}
|