// 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> sessionStatus() async { final r = await _json('GET', '/auth/session'); return r; } Future> 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> listSessions({ int limit = 50, String? cursor, String order = 'desc', String? search, String? directory, bool? archived, }) async { final query = { '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)) .toList(); final cursorMap = r['cursor'] as Map?; return Page(data, next: cursorMap?['next'] as String?, previous: cursorMap?['previous'] as String?); } Future> activeSessions() async { final r = await _json('GET', '/api/session/active'); final data = r['data'] as Map? ?? {}; return data.keys.toSet(); } Future 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); } Future updateSession(String id, {String? title, bool? archived, Map? 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> listProjects() async { final list = await _jsonList('GET', '/api/project'); return [ for (final p in list) if (p is Map) ProjectInfo.fromJson(p), ]; } Future deleteSession(String id) async { await _json('DELETE', '/api/session/${Uri.encodeComponent(id)}'); } Future> listMessages(String id, {int limit = 30, String? cursor, String order = 'desc', String? directory, bool partShells = true}) async { final query = { '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)) .toList(); final cursorMap = r['cursor'] as Map?; return Page(data, next: cursorMap?['next'] as String?, previous: cursorMap?['previous'] as String?); } Future 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); } Future> 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)) .toList(); } Future> 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)) .toList(); } Future> 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)) .toList(); } Future 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}); } /// Sends a prompt. [delivery] is 'steer' or 'queue' on a running turn; with /// none the server starts a turn when idle. Returns the inbox item id. Future prompt(String sessionId, {String text = '', String? messageId, String? directory, String? delivery, List>? files, List? skillIds}) async { final r = await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/prompt', directory: directory, body: { if (text.isNotEmpty) 'text': text, if (messageId != null) 'id': messageId, if (delivery != null) 'delivery': delivery, if (files != null && files.isNotEmpty) 'files': files, if (skillIds != null && skillIds.isNotEmpty) 'skills': [ for (final id in skillIds) {'id': id}, ], }); final data = r['data']; return data is Map ? data['id'] as String? : null; } /// Prompts waiting in the session's inbox (queued or about to steer). Future> inbox(String sessionId, {String? directory}) async { final r = await _json('GET', '/api/session/${Uri.encodeComponent(sessionId)}/inbox', directory: directory); return [ for (final e in (r['data'] as List? ?? [])) if (e is Map && e['type'] == 'user') InboxItem.fromJson(e), ]; } /// Takes a waiting prompt out of the inbox. Future cancelInbox(String sessionId, String inboxId, {String? directory}) async { await _json('DELETE', '/api/session/${Uri.encodeComponent(sessionId)}/inbox/${Uri.encodeComponent(inboxId)}', directory: directory); } /// Moves a waiting prompt between `steer` and `queue`. Future updateInbox(String sessionId, String inboxId, String delivery, {String? directory}) async { await _json('PATCH', '/api/session/${Uri.encodeComponent(sessionId)}/inbox/${Uri.encodeComponent(inboxId)}', directory: directory, body: {'delivery': delivery}); } /// Runs a registered slash command (`/initialize`, `/review`, …). The /// server expands the command template and starts the turn. Future command(String sessionId, {required String name, String text = '', String? directory, List>? 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 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> 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) FormInfo.fromJson(f), ]; } Future replyForm(String sessionId, String formId, Map answer, {String? directory}) async { await _json( 'POST', '/api/session/${Uri.encodeComponent(sessionId)}/form/${Uri.encodeComponent(formId)}/reply', body: {'answer': answer}, directory: directory); } Future 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>> 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>> 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 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 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); } Future 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 commitRevert(String sessionId, {String? directory}) async { await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/revert/commit', directory: directory, body: const {}); } Future switchModel(String sessionId, ModelRef model, {String? directory}) async { // The route takes the reference under `model`; sending it at the top level // is rejected with "Missing key at [model]". await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/model', directory: directory, body: {'model': model.toJson()}); } /// The instance settings. `surface` selects a per-surface profile (a phone /// still shares every key that is not marked per-surface). Future> settings({String surface = 'mobile'}) async { return _json('GET', '/api/config/settings', query: {'surface': surface}); } /// Persists a partial settings patch and returns the updated settings. Future> saveSettings(Map patch, {String surface = 'mobile'}) async { return _json('PUT', '/api/config/settings', query: {'surface': surface}, body: patch); } Future switchAgent(String sessionId, String agent, {String? directory}) async { await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/agent', directory: directory, body: {'agent': agent}); } Future> 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 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> 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) FsEntry.fromJson(e), ]; } Future 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(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) return null; return FsStat.fromJson(data); } Future fsWrite(String path, String content, {String? directory}) async { await _json('POST', '/api/fs/write', body: {'path': path, 'content': content}, directory: directory, rawDirectory: true); } Future fsMkdir(String path, {String? directory}) async { await _json('POST', '/api/fs/mkdir', body: {'path': path}, directory: directory, rawDirectory: true); } Future 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> streamEvents({List? 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; 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(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 r) { final context = r['context']; return ProjectContext.fromJson( context is Map ? context : r); } Future 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 closeTerminal(String sessionId, {String? directory}) async { await _json( 'DELETE', '/api/terminal/${Uri.encodeComponent(sessionId)}', directory: directory); } /// The terminals the server still holds for [cwd] (or all of them when it is /// empty). The server keeps an unattached shell for half an hour, so a /// client that remembers its session id can reattach after a restart. Future> listTerminals({String? cwd}) async { final r = await _json('GET', '/api/terminal/sessions', query: {if (cwd != null && cwd.isNotEmpty) 'cwd': cwd}, directory: cwd); final raw = r['sessions']; if (raw is! List) return const []; return [ for (final entry in raw) if (entry is Map) ServerTerminal.fromJson(entry), ]; } /// The headers the terminal socket needs (auth, and the workspace the /// server routes the upgrade by). Map get eventHeaders => { 'user-agent': 'openchamber-native/0.3', if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token', }; // --------------------------------------------------------------- transport Future> _jsonList(String method, String path, {Map? 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> _json(String method, String path, {Map? query, Map? 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; 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; } catch (_) { throw ApiError(res.statusCode, 'invalid JSON'); } } Future<_Response> _request(String method, String path, {Map? query, Map? body, String? directory, bool partShells = false, bool rawDirectory = false, bool noCompression = false}) async { final headers = { '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 headers; final Stream> body; final void Function()? abort; _Response(this.statusCode, this.headers, this.body, [this.abort]); Future> collect() => body.fold>([], (a, b) => a..addAll(b)); }