Files
openchamber-android-native/lib/api/client.dart
T
blumia b65498d73e feat: stats page, and the client becomes Chamber Go
- 全部功能 gains 统计 (Stats): ranges Today/7/30/90 days/all time, a
  project scope (reusing the shared project sheet, plus "All projects"),
  session/prompt/token/cost/active-days/streak tiles, a daily activity
  chart (weekly past 92 days), token composition, efficiency tiles, model
  ranking by tokens/cost/steps and on-request tool-call stats; data comes
  from /api/experimental/session/stats and the day buckets use the device's
  IANA zone (a small platform channel; desktop falls back to UTC)
- the model bars draw a full-width track with a left-aligned fill, so a
  small token share reads as a sliver instead of an empty bar
- AI token strings read 词元 (not 令牌) in Chinese
- the client's display name is Chamber Go (launcher, iOS, Linux window,
  About), package unchanged; pairing/login labels and the user-agent
  follow, so a newly paired device shows "Chamber Go" on the web client's
  "Connect to this server" list
- bump to 0.5.6
2026-11-26 17:18:09 +08:00

1105 lines
41 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 '../version.dart';
import 'models.dart';
import 'scheduled_tasks.dart';
import 'usage_stats.dart';
import 'shells.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;
}
/// What the server sees in request headers; the connect page's device name
/// comes from the pairing label below, not from this.
String _userAgent() =>
'chamber-go/${appVersion.isEmpty ? '0.0' : appVersion}';
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;
/// The bearer this client authenticates with. A relay transport is told too,
/// because it must mint URL-scoped tokens for WebSocket upgrades.
String? get token => _token;
set token(String? value) {
_token = value;
transport.setBearerToken(value);
}
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();
/// Redeems a pairing link's one-time secret over whichever transport this
/// client uses, and returns the device token.
Future<({String token, Map<String, dynamic> response})> redeemPairing({
required String pairingId,
required String secret,
required String installId,
String clientLabel = 'Chamber Go',
String clientKind = 'mobile',
String? deviceName,
}) async {
final r = await _json('POST', '/api/client-auth/pairing/redeem', body: {
'pairingId': pairingId,
'secret': secret,
'clientLabel': clientLabel,
'clientKind': clientKind,
'deviceName': deviceName ?? clientLabel,
'devicePlatform': 'android',
'dedupeKey': installId,
'appVersion': appVersion,
});
return (token: r['clientToken'] as String? ?? '', response: r);
}
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 = 'Chamber Go', 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,
String? parentID,
}) 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',
if (parentID != null && parentID.isNotEmpty) 'parentID': parentID,
};
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<Session> getSession(String id, {String? directory}) async {
final r = await _json('GET', '/api/session/${Uri.encodeComponent(id)}',
directory: directory);
return Session.fromJson(r['data'] as Map<String, dynamic>);
}
/// The versions behind the server. Each endpoint is optional: an older
/// server answers neither, and the about page then says it could not tell.
Future<ServerVersions> serverVersions() async {
var opencode = '';
var openchamber = '';
try {
final info = await _json('GET', '/api/info');
final v = info['version'];
if (v is String) opencode = v;
} catch (_) {}
try {
final version = await _json('GET', '/api/version');
final v = version['openchamberVersion'];
if (v is String) openchamber = v;
} catch (_) {}
return ServerVersions(opencode: opencode, openchamber: openchamber);
}
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),
];
}
/// The server's home and chats root. Sessions filed under a chats root are
/// the "聊天" group, not a project; the root can be relocated away from the
/// home config directory, so it must come from the server.
Future<FsHomeInfo> fsHome() async {
final r = await _json('GET', '/api/fs/home');
return FsHomeInfo.fromJson(r);
}
/// The project's chosen/auto icon image. [projectId] is the OpenChamber
/// settings id; SVG icons are recoloured by the server for [theme] and
/// [iconColor].
Future<Uint8List?> projectIconBytes(String projectId,
{String? theme, String? iconColor}) async {
try {
final res = await _request(
'GET', '/api/projects/${Uri.encodeComponent(projectId)}/icon',
query: {
if (theme != null && theme.isNotEmpty) 'theme': theme,
if (iconColor != null && iconColor.isNotEmpty)
'iconColor': iconColor,
});
if (res.statusCode != 200) return null;
final bytes = await res.collect();
return bytes.isEmpty ? null : Uint8List.fromList(bytes);
} catch (_) {
return null;
}
}
Future<void> deleteSession(String id) async {
await _json('DELETE', '/api/session/${Uri.encodeComponent(id)}');
}
/// The session statistics report. [from] is milliseconds since the epoch and
/// omitted for all time; [project] is the OpenCode project id (not the
/// settings row id); [timezone] is an IANA name and decides how the server
/// buckets days. Tool details cost a scan of every message, so they are only
/// read when [tools] is true.
Future<UsageStats> sessionStats({
int? from,
int? to,
String? project,
required String timezone,
bool tools = false,
String? directory,
}) async {
final r = await _json('GET', '/api/experimental/session/stats',
query: {
if (from != null) 'from': '$from',
if (to != null) 'to': '$to',
if (project != null && project.isNotEmpty) 'project': project,
'timezone': timezone,
'tools': tools ? 'detail' : 'none',
},
directory: directory);
return UsageStats.fromJson(r['data'] as Map<String, dynamic>? ?? const {});
}
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();
}
/// The models that generate or edit images (`types=image`), for the image
/// tool's model choice in 设置 → 通用.
Future<List<ModelInfo>> imageModels(String directory) async {
final r = await _json('GET', '/api/model', query: {
'types': 'image',
if (directory.isNotEmpty) 'location[directory]': directory,
});
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});
}
/// 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<String?> prompt(String sessionId,
{String text = '',
String? messageId,
String? directory,
String? delivery,
List<Map<String, String>>? files,
List<String>? 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<List<InboxItem>> 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<String, dynamic> && e['type'] == 'user')
InboxItem.fromJson(e),
];
}
/// Takes a waiting prompt out of the inbox.
Future<void> cancelInbox(String sessionId, String inboxId, {String? directory}) async {
await _json('DELETE',
'/api/session/${Uri.encodeComponent(sessionId)}/inbox/${Uri.encodeComponent(inboxId)}',
directory: directory);
}
/// The shells started in [directory], running ones and ones that just
/// exited (the list keeps an exited shell for a while). A background command
/// is one the transcript marks with `{status: running, shellID}`.
Future<List<ShellTask>> listShells({String? directory}) async {
final r = await _json('GET', '/api/shell', directory: directory);
return shellTasksFromList(r);
}
/// The running jobs of a session (and its children with [descendants]):
/// shell commands opencode detached, plus unrelated kinds the caller
/// filters out. Empty on an opencode without the experimental endpoint
/// (404).
Future<List<ShellTask>> listShellJobs(String sessionId,
{bool descendants = true}) async {
final r = await _json('GET', '/api/experimental/job', query: {
'sessionID': sessionId,
if (descendants) 'descendants': 'true',
'status': 'running',
});
return shellTasksFromJobs(r);
}
/// One page of a shell's output. Without [cursor] the server reads from the
/// start; [size] in the answer says how much there is, so the first call can
/// ask again from `size - tail` for a long command.
Future<ShellOutputPage> shellOutput(String shellId,
{int? cursor, int? limit, String? directory}) async {
final query = <String, String>{
if (cursor != null) 'cursor': '$cursor',
if (limit != null) 'limit': '$limit',
};
final r = await _json(
'GET', '/api/shell/${Uri.encodeComponent(shellId)}/output',
query: query.isEmpty ? null : query, directory: directory);
return ShellOutputPage.fromJson(r);
}
/// One shell by id; null when the server no longer knows it (removed).
Future<ShellTask?> shell(String shellId, {String? directory}) async {
try {
final r = await _json(
'GET', '/api/shell/${Uri.encodeComponent(shellId)}',
directory: directory);
return ShellTask.fromWire(r['data']);
} on ApiError catch (e) {
if (e.status == 404) return null;
rethrow;
}
}
/// Stops a background shell (SIGTERM through its pid). The command's
/// completion notice then reports a `Shell.NotFoundError`-like failure, so
/// [syntheticNote] tells the model that the user stopped it.
Future<void> stopShell(String shellId, {String? directory}) async {
await _json('DELETE', '/api/shell/${Uri.encodeComponent(shellId)}',
directory: directory);
}
/// Writes a note into the session without starting a turn: how the model
/// learns that a command was stopped by the user (or anything else the
/// client did), as the first-party client does.
Future<void> syntheticNote(String sessionId,
{required String text,
String? description,
Map<String, dynamic>? metadata,
String? directory}) async {
await _json('POST',
'/api/session/${Uri.encodeComponent(sessionId)}/synthetic',
directory: directory,
body: {
'text': text,
if (description != null) 'description': description,
if (metadata != null) 'metadata': metadata,
'resume': false,
});
}
// ------------------------------------------------------ scheduled tasks
/// The project id the scheduled-tasks API uses for sessions outside any
/// project: the web client's chats scope.
static const scheduledChatsScope = 'openchamber:chats';
static String _scheduledTasksPath(String projectId) =>
'/api/projects/${Uri.encodeComponent(projectId)}/scheduled-tasks';
static List<ScheduledTask> _scheduledTasks(Map<String, dynamic> r) => [
for (final task in r['tasks'] as List? ?? const [])
if (task is Map<String, dynamic>) ScheduledTask.fromJson(task),
];
Future<List<ScheduledTask>> scheduledTasks(String projectId) async =>
_scheduledTasks(await _json('GET', _scheduledTasksPath(projectId)));
/// Creates or replaces [task]; the server answers with the project's tasks.
Future<List<ScheduledTask>> saveScheduledTask(
String projectId, ScheduledTask task) async {
final r = await _json('PUT', _scheduledTasksPath(projectId),
body: {'task': task.toJson()});
return _scheduledTasks(r);
}
Future<List<ScheduledTask>> deleteScheduledTask(
String projectId, String taskId) async {
final r = await _json('DELETE',
'${_scheduledTasksPath(projectId)}/${Uri.encodeComponent(taskId)}');
return _scheduledTasks(r);
}
/// Starts a run now; the run's task (with its new state) comes back.
Future<ScheduledTask?> runScheduledTask(
String projectId, String taskId) async {
final r = await _json('POST',
'${_scheduledTasksPath(projectId)}/${Uri.encodeComponent(taskId)}/run');
final task = r['task'];
return task is Map<String, dynamic> ? ScheduledTask.fromJson(task) : null;
}
/// Moves a waiting prompt between `steer` and `queue`.
Future<void> 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<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 {
// 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<Map<String, dynamic>> 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<Map<String, dynamic>> saveSettings(Map<String, dynamic> patch,
{String surface = 'mobile'}) async {
return _json('PUT', '/api/config/settings',
query: {'surface': surface}, body: patch);
}
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': _userAgent(),
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 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<List<ServerTerminal>> 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<String, dynamic>) ServerTerminal.fromJson(entry),
];
}
/// The headers the terminal socket needs (auth, and the workspace the
/// server routes the upgrade by).
Map<String, String> get eventHeaders => {
'user-agent': _userAgent(),
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': _userAgent(),
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));
}