Files
openchamber-android-native/lib/api/models.dart
T
blumia c4de5e84d8 feat: watch background commands, open their output and stop them
A command the agent detached keeps running after its tool call returns;
the chat now shows it above the composer: one row per command with its
clock and a stop, folded under "正在执行 N 条命令" when there are
several, with a subagent tag for a child session's command.

Tapping a row opens the live output in a sheet (a page a second from
shell.output, tail kept), following the tail with a way back to the
newest line. The tool row that started it carries a 后台 tag and shows
the same output when expanded, falling back to the completion note once
the shell is gone; a command stopped from the app says so instead of
showing the Shell.NotFoundError it leaves behind.

The list comes from opencode's own shell jobs (experimental/job,
descendants included), so a foreground command never appears, and an
older server falls back to the shell list narrowed by the detached
calls in the transcript. Stopping confirms, removes the shell, and
leaves the model a note that the stop was the user's, as the
first-party client does.

0.4.14 (414).
2026-11-24 19:31:22 +08:00

1096 lines
33 KiB
Dart

// OpenChamber API models, ported from the Go client's protocol knowledge.
library;
import 'dart:convert';
class ModelRef {
final String id;
final String providerId;
final String? variant;
ModelRef(this.id, this.providerId, [this.variant]);
factory ModelRef.fromJson(Map<String, dynamic> j) =>
ModelRef(j['id'] as String, j['providerID'] as String, j['variant'] as String?);
Map<String, dynamic> toJson() =>
{'id': id, 'providerID': providerId, if (variant != null) 'variant': variant};
}
class TokenUsage {
final int? total;
final int input;
final int output;
final int reasoning;
final int cacheRead;
final int cacheWrite;
TokenUsage({
this.total,
this.input = 0,
this.output = 0,
this.reasoning = 0,
this.cacheRead = 0,
this.cacheWrite = 0,
});
factory TokenUsage.fromJson(Map<String, dynamic> j) {
final cache = j['cache'] as Map<String, dynamic>? ?? {};
return TokenUsage(
total: j['total'] as int?,
input: (j['input'] as num?)?.toInt() ?? 0,
output: (j['output'] as num?)?.toInt() ?? 0,
reasoning: (j['reasoning'] as num?)?.toInt() ?? 0,
cacheRead: (cache['read'] as num?)?.toInt() ?? 0,
cacheWrite: (cache['write'] as num?)?.toInt() ?? 0,
);
}
int get used =>
(total ?? 0) > 0 ? total! : input + output + reasoning + cacheRead + cacheWrite;
}
class Location {
final String directory;
final String? projectId;
Location(this.directory, [this.projectId]);
factory Location.fromJson(Map<String, dynamic> j) =>
Location(j['directory'] as String? ?? '', j['projectId'] as String?);
}
class Session {
final String id;
final String? parentID;
final String projectID;
final String title;
final String agent;
final ModelRef? model;
final Location? location;
final Map<String, dynamic> metadata;
final int created;
final int updated;
final int viewed;
final int archived;
Session({
required this.id,
required this.title,
this.parentID,
this.projectID = '',
this.agent = '',
this.model,
this.location,
this.metadata = const {},
this.created = 0,
this.updated = 0,
this.viewed = 0,
this.archived = 0,
});
factory Session.fromJson(Map<String, dynamic> j) {
final t = j['time'] as Map<String, dynamic>? ?? {};
return Session(
id: j['id'] as String,
parentID: j['parentID'] as String?,
projectID: j['projectID'] as String? ?? '',
title: j['title'] as String? ?? '',
agent: j['agent'] as String? ?? '',
model: j['model'] == null ? null : ModelRef.fromJson(j['model'] as Map<String, dynamic>),
location: j['location'] == null ? null : Location.fromJson(j['location'] as Map<String, dynamic>),
metadata: j['metadata'] is Map<String, dynamic>
? Map<String, dynamic>.from(j['metadata'] as Map<String, dynamic>)
: const {},
created: (t['created'] as num?)?.toInt() ?? 0,
updated: (t['updated'] as num?)?.toInt() ?? 0,
viewed: (t['viewed'] as num?)?.toInt() ?? 0,
archived: (t['archived'] as num?)?.toInt() ?? 0,
);
}
String get directory => location?.directory ?? '';
bool get isChild => parentID != null && parentID!.isNotEmpty;
bool get isArchived => archived > 0;
/// Pins live in the session's metadata (`openchamber.pinned`), so every
/// client of the server sees them.
bool get isPinned {
final openchamber = metadata['openchamber'];
return openchamber is Map && openchamber['pinned'] is Map;
}
int get pinnedAt {
final openchamber = metadata['openchamber'];
if (openchamber is! Map) return 0;
final pinned = openchamber['pinned'];
return pinned is Map && pinned['at'] is num ? (pinned['at'] as num).toInt() : 0;
}
Session copyWith({
String? title,
ModelRef? model,
String? agent,
Map<String, dynamic>? metadata,
int? viewed,
int? archived,
int? updated,
}) =>
Session(
id: id,
parentID: parentID,
projectID: projectID,
title: title ?? this.title,
agent: agent ?? this.agent,
model: model ?? this.model,
location: location,
metadata: metadata ?? this.metadata,
created: created,
updated: updated ?? this.updated,
viewed: viewed ?? this.viewed,
archived: archived ?? this.archived,
);
}
/// The server's home and managed chats roots (`GET /api/fs/home`).
class FsHomeInfo {
final String home;
final String chatsRoot;
final String? canonicalChatsRoot;
final String? canonicalLegacyChatsRoot;
const FsHomeInfo({
required this.home,
required this.chatsRoot,
this.canonicalChatsRoot,
this.canonicalLegacyChatsRoot,
});
factory FsHomeInfo.fromJson(Map<String, dynamic> j) {
String? nonEmpty(Object? value) =>
value is String && value.trim().isNotEmpty ? value.trim() : null;
return FsHomeInfo(
home: nonEmpty(j['home']) ?? '',
chatsRoot: nonEmpty(j['chatsRoot']) ?? '',
canonicalChatsRoot: nonEmpty(j['canonicalChatsRoot']),
canonicalLegacyChatsRoot: nonEmpty(j['canonicalLegacyChatsRoot']),
);
}
}
/// A project the server knows: a checkout (or chat folder) an agent can work
/// in. [canonical] is the directory a session there carries.
class ProjectInfo {
final String id;
final String canonical;
final String name;
final String vcs;
/// The OpenChamber settings row this project was decorated from. The icon
/// endpoint keys on this id, not the opencode project id.
final String metaId;
final String icon;
final String color;
final String iconBackground;
final String iconImageMime;
final int iconImageUpdatedAt;
const ProjectInfo({
required this.id,
required this.canonical,
this.name = '',
this.vcs = '',
this.metaId = '',
this.icon = '',
this.color = '',
this.iconBackground = '',
this.iconImageMime = '',
this.iconImageUpdatedAt = 0,
});
factory ProjectInfo.fromJson(Map<String, dynamic> j) => ProjectInfo(
id: j['id'] as String? ?? '',
canonical: j['canonical'] as String? ?? '',
name: j['name'] as String? ?? '',
vcs: j['vcs'] as String? ?? '',
);
bool get hasIconImage => metaId.isNotEmpty && iconImageUpdatedAt > 0;
/// Decorates the opencode project with its OpenChamber settings row: the
/// operator's label, icon key, colour and uploaded/auto icon image.
ProjectInfo withMeta(Map<String, dynamic>? meta) {
if (meta == null) return this;
String text(Object? value) => value is String ? value.trim() : '';
final label = text(meta['label']);
final image = meta['iconImage'];
var mime = '';
var updatedAt = 0;
if (image is Map) {
mime = text(image['mime']);
final updated = image['updatedAt'];
if (updated is num) updatedAt = updated.toInt();
}
return ProjectInfo(
id: id,
canonical: canonical,
name: label.isNotEmpty ? label : name,
vcs: vcs,
metaId: text(meta['id']),
icon: text(meta['icon']),
color: text(meta['color']),
iconBackground: text(meta['iconBackground']),
iconImageMime: mime,
iconImageUpdatedAt: updatedAt,
);
}
String get label {
if (name.trim().isNotEmpty) return name.trim();
return pathLeaf(canonical);
}
}
/// The last segment of a path, treating `\` and `/` alike: a Windows server
/// sends `C:\...` and a project has to read as its folder name, not the path.
String pathLeaf(String path) {
final trimmed = path.replaceAll(RegExp(r'[/\\]+$'), '');
final index = trimmed.lastIndexOf(RegExp(r'[/\\]'));
return index >= 0 ? trimmed.substring(index + 1) : trimmed;
}
/// A path with `\` written as `/` and no trailing slash, for comparing and
/// grouping directory names from a Windows or a POSIX server.
String slashPath(String path) =>
path.replaceAll('\\', '/').replaceAll(RegExp(r'/+$'), '');
/// A file inside [directory] shown without it: the tool row says
/// `lib/screens/chat_screen.dart`, as the first-party client does, so a phone
/// still sees the part of the path that matters. Paths elsewhere stay whole.
String relativePath(String path, String directory) {
final file = path.trim();
final dir = slashPath(directory.trim());
if (file.isEmpty || dir.isEmpty) return file;
final normalized = slashPath(file);
if (normalized == dir) return '.';
if (normalized.startsWith('$dir/')) return normalized.substring(dir.length + 1);
return file;
}
/// Whether [directory] is [root] or inside it. Separators are unified and a
/// Windows drive path compares case-insensitively, as [samePath] does.
bool isUnderDirectory(String directory, String root) {
final d = slashPath(directory);
final r = slashPath(root);
if (d.isEmpty || r.isEmpty) return false;
final windows = RegExp(r'^[A-Za-z]:').hasMatch(d) ||
RegExp(r'^[A-Za-z]:').hasMatch(r);
final dd = windows ? d.toLowerCase() : d;
final rr = windows ? r.toLowerCase() : r;
return dd == rr || dd.startsWith('$rr/');
}
/// Whether two directory paths name the same place. Separators are unified;
/// a drive-letter path compares case-insensitively, as Windows does.
bool samePath(String a, String b) {
final x = slashPath(a);
final y = slashPath(b);
if (x == y) return true;
final windows = RegExp(r'^[A-Za-z]:').hasMatch(x) ||
RegExp(r'^[A-Za-z]:').hasMatch(y);
return windows && x.toLowerCase() == y.toLowerCase();
}
class ContentPart {
final String type;
final String text;
final String? id;
final String? name;
final ToolState? state;
final String? mime;
final String? url;
final String? uri;
final String? filename;
ContentPart({
this.type = '',
this.text = '',
this.id,
this.name,
this.state,
this.mime,
this.url,
this.uri,
this.filename,
});
factory ContentPart.fromJson(Map<String, dynamic> j) => ContentPart(
type: j['type'] as String? ?? '',
text: j['text'] as String? ?? '',
id: j['id'] as String?,
name: j['name'] as String?,
state: j['state'] == null ? null : ToolState.fromJson(j['state'] as Map<String, dynamic>),
mime: j['mime'] as String?,
url: j['url'] as String?,
uri: j['uri'] as String?,
filename: j['filename'] as String?,
);
Map<String, dynamic> toJson() => {
if (type.isNotEmpty) 'type': type,
if (text.isNotEmpty) 'text': text,
if (state != null) 'state': state!.toJson(),
};
}
class ToolState {
String status;
Map<String, dynamic> input;
List<ContentPart> content;
List<ContentPart> attachments;
Map<String, dynamic>? metadata;
String? error;
ToolState({
this.status = '',
Map<String, dynamic>? input,
List<ContentPart>? content,
List<ContentPart>? attachments,
this.metadata,
this.error,
}) : input = input ?? {},
content = content ?? [],
attachments = attachments ?? [];
factory ToolState.fromJson(Map<String, dynamic> j) => ToolState(
status: j['status'] as String? ?? '',
input: j['input'] as Map<String, dynamic>? ?? {},
content: (j['content'] as List?)
?.map((e) => ContentPart.fromJson(e as Map<String, dynamic>))
.toList(),
attachments: (j['attachments'] as List?)
?.map((e) => ContentPart.fromJson(e as Map<String, dynamic>))
.toList(),
metadata: j['metadata'] as Map<String, dynamic>?,
error: j['error'] == null ? null : _jsonString(j['error']),
);
Map<String, dynamic> toJson() => {
'status': status,
if (input.isNotEmpty) 'input': input,
if (content.isNotEmpty) 'content': content.map((e) => e.toJson()).toList(),
if (metadata != null) 'metadata': metadata,
};
}
/// The error OpenCode recorded on a message (a failed step, a failed
/// compaction). `body` is the provider's raw response, when there was one.
/// One row of a directory listing (`/api/fs/list`).
class FsEntry {
final String name;
final String path;
final bool isDirectory;
const FsEntry({required this.name, required this.path, this.isDirectory = false});
factory FsEntry.fromJson(Map<String, dynamic> j) => FsEntry(
name: j['name'] as String? ?? '',
path: j['path'] as String? ?? '',
isDirectory: j['isDirectory'] as bool? ?? false,
);
String get extension {
final dot = name.lastIndexOf('.');
return dot <= 0 ? '' : name.substring(dot + 1).toLowerCase();
}
}
/// `/api/fs/stat` answer (only what the file browser uses).
class FsStat {
final String path;
final bool isFile;
final int size;
const FsStat({required this.path, this.isFile = false, this.size = 0});
factory FsStat.fromJson(Map<String, dynamic> j) => FsStat(
path: j['path'] as String? ?? '',
isFile: j['isFile'] as bool? ?? false,
size: (j['size'] as num?)?.toInt() ?? 0,
);
}
class MessageError {
final String type;
final String message;
final int? status;
final String? body;
const MessageError({this.type = '', this.message = '', this.status, this.body});
factory MessageError.fromJson(Map<String, dynamic> j) {
final data = j['data'];
final response = j['response'];
return MessageError(
type: (j['type'] ?? j['name'] ?? '') as String? ?? '',
message: (j['message'] as String?) ??
(data is Map ? data['message'] as String? : null) ??
'',
status: (j['status'] as num?)?.toInt(),
body: response is Map ? response['body'] as String? : null,
);
}
bool get isEmpty => type.isEmpty && message.isEmpty;
}
class Message {
final String id;
final String type;
final int created;
final int completed;
final String agent;
final ModelRef? model;
final List<ContentPart> content;
final String text;
final List<FileAttachment> files;
final String finish;
final double cost;
final TokenUsage? tokens;
/// Set when the step (or compaction) failed.
final MessageError? error;
/// Compaction messages: 'running' | 'completed' | 'failed'.
final String status;
/// Compaction messages: why it ran ('manual' | 'auto').
final String reason;
/// Compaction messages: the summary the model wrote for the new history.
final String summary;
/// What the server attached to the message: a synthetic note carries why it
/// was written (a stopped shell, a job report), the chat UI reads that.
final Map<String, dynamic>? metadata;
Message({
required this.id,
required this.type,
this.created = 0,
this.completed = 0,
this.agent = '',
this.model,
this.content = const [],
this.text = '',
this.files = const [],
this.finish = '',
this.cost = 0,
this.tokens,
this.error,
this.status = '',
this.reason = '',
this.summary = '',
this.metadata,
});
factory Message.fromJson(Map<String, dynamic> j) {
final t = j['time'] as Map<String, dynamic>? ?? {};
return Message(
id: j['id'] as String,
type: j['type'] as String? ?? '',
created: (t['created'] as num?)?.toInt() ?? 0,
completed: (t['completed'] as num?)?.toInt() ?? 0,
agent: j['agent'] as String? ?? '',
model: j['model'] == null ? null : ModelRef.fromJson(j['model'] as Map<String, dynamic>),
content: (j['content'] as List?)
?.map((e) => ContentPart.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
text: j['text'] as String? ?? '',
files: (j['files'] as List?)
?.map((e) => FileAttachment.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
finish: j['finish'] as String? ?? '',
cost: (j['cost'] as num?)?.toDouble() ?? 0,
tokens: j['tokens'] == null ? null : TokenUsage.fromJson(j['tokens'] as Map<String, dynamic>),
error: j['error'] == null
? null
: MessageError.fromJson(j['error'] as Map<String, dynamic>),
status: j['status'] as String? ?? '',
reason: j['reason'] as String? ?? '',
summary: j['summary'] as String? ?? '',
metadata: j['metadata'] as Map<String, dynamic>?,
);
}
String get partText {
final buf = StringBuffer();
for (final p in content) {
if (p.type == 'text' && p.text.isNotEmpty) buf.write(p.text);
}
return buf.toString();
}
}
class FileAttachment {
final String name;
final String mime;
/// Base64 of the file the user attached, as the server stores it.
final String data;
/// 'inline' | 'path' — where the bytes came from, when the server says.
final String source;
FileAttachment(this.name, this.mime, {this.data = '', this.source = ''});
bool get isImage => mime.startsWith('image/') && data.isNotEmpty;
factory FileAttachment.fromJson(Map<String, dynamic> j) => FileAttachment(
j['name'] as String? ?? '',
j['mime'] as String? ?? '',
data: j['data'] as String? ?? '',
// Stored messages carry `{type: 'inline'}` here; keep only text.
source: j['source'] is String ? j['source'] as String : '',
);
}
/// A prompt the server holds in the session's inbox until it is delivered:
/// `queue` waits for the running turn to end, `steer` joins it at its next
/// step. The message only enters the transcript when it is delivered.
class InboxItem {
final String id;
final String text;
/// 'steer' | 'queue'.
final String delivery;
final int created;
final List<FileAttachment> files;
const InboxItem({
required this.id,
required this.text,
required this.delivery,
this.created = 0,
this.files = const [],
});
/// Non-user inbox entries (compaction, moves, synthetic context) are the
/// server's own; only what the person typed is shown.
factory InboxItem.fromJson(Map<String, dynamic> j) {
final time = j['time'] as Map<String, dynamic>? ?? {};
final payload = j['payload'] as Map<String, dynamic>? ?? {};
return InboxItem(
id: j['id'] as String,
text: payload['text'] as String? ?? '',
delivery: j['delivery'] as String? ?? 'queue',
created: (time['created'] as num?)?.toInt() ?? 0,
files: (payload['files'] as List?)
?.map((e) => FileAttachment.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
);
}
/// An `enqueued` event carries the payload under `item` and the id beside
/// it, rather than in the item.
factory InboxItem.fromEvent(String id, Map<String, dynamic> j, int created) {
final payload = j['payload'] as Map<String, dynamic>? ?? {};
return InboxItem(
id: id,
text: payload['text'] as String? ?? '',
delivery: j['delivery'] as String? ?? 'queue',
created: created,
files: (payload['files'] as List?)
?.map((e) => FileAttachment.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
);
}
InboxItem withDelivery(String value) => InboxItem(
id: id,
text: text,
delivery: value,
created: created,
files: files,
);
}
/// One row of a native form's choice control.
class FormOption {
final String value;
final String label;
final String? description;
const FormOption(this.value, this.label, [this.description]);
factory FormOption.fromJson(Map<String, dynamic> j) => FormOption(
j['value'] as String? ?? '',
j['label'] as String? ?? j['value'] as String? ?? '',
j['description'] as String?,
);
}
/// `when` makes a field visible only while another field holds a value.
class FormWhen {
final String key;
final String op; // eq | neq
final Object? value;
const FormWhen(this.key, this.op, this.value);
factory FormWhen.fromJson(Map<String, dynamic> j) => FormWhen(
j['key'] as String? ?? '',
j['op'] as String? ?? 'eq',
j['value'],
);
}
/// A field of a form request: string, number, integer, boolean, multiselect
/// or external (a link the user acknowledges).
class AgentFormField {
final String key;
final String type;
final String? title;
final String? description;
final String? placeholder;
final String? format;
final String? url;
final bool required;
final bool hidden;
final bool custom;
final Object? defaultValue;
final num? minimum;
final num? maximum;
final int? minLength;
final int? maxLength;
final int? minItems;
final int? maxItems;
final List<FormOption> options;
final List<FormWhen> when;
const AgentFormField({
required this.key,
required this.type,
this.title,
this.description,
this.placeholder,
this.format,
this.url,
this.required = false,
this.hidden = false,
this.custom = false,
this.defaultValue,
this.minimum,
this.maximum,
this.minLength,
this.maxLength,
this.minItems,
this.maxItems,
this.options = const [],
this.when = const [],
});
factory AgentFormField.fromJson(Map<String, dynamic> j) {
num? numOf(Object? v) => v is num ? v : null;
return AgentFormField(
key: j['key'] as String? ?? '',
type: j['type'] as String? ?? 'string',
title: j['title'] as String?,
description: j['description'] as String?,
placeholder: j['placeholder'] as String?,
format: j['format'] as String?,
url: j['url'] as String?,
required: j['required'] as bool? ?? false,
hidden: j['hidden'] as bool? ?? false,
custom: j['custom'] as bool? ?? false,
defaultValue: j['default'],
minimum: numOf(j['minimum']),
maximum: numOf(j['maximum']),
minLength: (j['minLength'] as num?)?.toInt(),
maxLength: (j['maxLength'] as num?)?.toInt(),
minItems: (j['minItems'] as num?)?.toInt(),
maxItems: (j['maxItems'] as num?)?.toInt(),
options: [
for (final o in (j['options'] as List? ?? []))
if (o is Map<String, dynamic>) FormOption.fromJson(o),
],
when: [
for (final w in (j['when'] as List? ?? []))
if (w is Map<String, dynamic>) FormWhen.fromJson(w),
],
);
}
String get label => (title == null || title!.isEmpty) ? key : title!;
}
/// A blocking question from the agent. The client answers every visible field
/// at once; the answer map is keyed by field key.
class FormInfo {
final String id;
final String sessionID;
final String title;
final List<AgentFormField> fields;
const FormInfo({
required this.id,
required this.sessionID,
required this.title,
required this.fields,
});
factory FormInfo.fromJson(Map<String, dynamic> j) => FormInfo(
id: j['id'] as String? ?? '',
sessionID: j['sessionID'] as String? ?? '',
title: j['title'] as String? ?? '',
fields: [
for (final f in (j['fields'] as List? ?? []))
if (f is Map<String, dynamic>) AgentFormField.fromJson(f),
],
);
}
// -------------------------------------------------------- project knowledge
/// A saved note, as `/api/project-context` stores it.
class ProjectNote {
final String id;
final String body;
final int createdAt;
final int updatedAt;
final String source; // manual | selection | agent
final bool pinned;
final String? planId;
const ProjectNote({
required this.id,
required this.body,
this.createdAt = 0,
this.updatedAt = 0,
this.source = 'manual',
this.pinned = false,
this.planId,
});
factory ProjectNote.fromJson(Map<String, dynamic> j) => ProjectNote(
id: j['id'] as String? ?? '',
body: j['body'] as String? ?? '',
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
updatedAt: (j['updatedAt'] as num?)?.toInt() ?? 0,
source: j['source'] as String? ?? 'manual',
pinned: j['pinned'] as bool? ?? false,
planId: j['planId'] as String?,
);
String get firstLine {
final line = body.split('\n').firstWhere((l) => l.trim().isNotEmpty,
orElse: () => '');
return line.trim();
}
}
/// A todo item. [planId] links it to a plan; [dependsOn] lists the todos of
/// the same plan that must be completed first.
class ProjectTodo {
final String id;
final String text;
final bool completed;
final int createdAt;
final String? planId;
final List<String> dependsOn;
const ProjectTodo({
required this.id,
required this.text,
this.completed = false,
this.createdAt = 0,
this.planId,
this.dependsOn = const [],
});
factory ProjectTodo.fromJson(Map<String, dynamic> j) => ProjectTodo(
id: j['id'] as String? ?? '',
text: j['text'] as String? ?? '',
completed: j['completed'] as bool? ?? false,
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
planId: j['planId'] as String?,
dependsOn: [
for (final d in (j['dependsOn'] as List? ?? []))
if (d is String) d,
],
);
}
/// A plan the project lists: a manifest entry (personal) or a file from the
/// team's shared folder.
class ProjectPlanLink {
final String id;
final String file;
final String title;
final int createdAt;
final bool pinned;
final String source; // personal | shared
final int progressDone;
final int progressTotal;
final String? sessionId;
const ProjectPlanLink({
required this.id,
required this.file,
required this.title,
this.createdAt = 0,
this.pinned = false,
this.source = 'personal',
this.progressDone = 0,
this.progressTotal = 0,
this.sessionId,
});
factory ProjectPlanLink.fromJson(Map<String, dynamic> j) {
final progress = j['progress'];
final session = j['session'];
return ProjectPlanLink(
id: j['id'] as String? ?? '',
file: j['file'] as String? ?? '',
title: j['title'] as String? ?? '',
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
pinned: j['pinned'] as bool? ?? false,
source: j['source'] as String? ?? 'personal',
progressDone:
progress is Map ? (progress['done'] as num?)?.toInt() ?? 0 : 0,
progressTotal:
progress is Map ? (progress['total'] as num?)?.toInt() ?? 0 : 0,
sessionId: session is Map ? session['sessionId'] as String? : null,
);
}
bool get hasProgress => progressTotal > 0;
}
/// Everything the project knowledge panel shows for one directory.
class ProjectContext {
final List<ProjectNote> notes;
final List<ProjectTodo> todos;
final List<ProjectPlanLink> plans;
final String? sharedPlansDir;
const ProjectContext({
this.notes = const [],
this.todos = const [],
this.plans = const [],
this.sharedPlansDir,
});
factory ProjectContext.fromJson(Map<String, dynamic> j) => ProjectContext(
notes: [
for (final n in (j['notes'] as List? ?? []))
if (n is Map<String, dynamic>) ProjectNote.fromJson(n),
],
todos: [
for (final t in (j['todos'] as List? ?? []))
if (t is Map<String, dynamic>) ProjectTodo.fromJson(t),
],
plans: [
for (final p in (j['plans'] as List? ?? []))
if (p is Map<String, dynamic>) ProjectPlanLink.fromJson(p),
],
sharedPlansDir: j['sharedPlansDir'] as String?,
);
bool get isEmpty => notes.isEmpty && todos.isEmpty && plans.isEmpty;
}
/// One remembered fact, preference or reference. The agent writes these
/// through its memory tool; the panel reads, corrects and deletes them.
class AgentMemoryEntry {
final String id;
final String title;
final String body;
final String type; // fact | preference | reference
final int createdAt;
final int updatedAt;
final bool flagged;
final String? sessionId;
const AgentMemoryEntry({
required this.id,
required this.title,
required this.body,
this.type = 'fact',
this.createdAt = 0,
this.updatedAt = 0,
this.flagged = false,
this.sessionId,
});
factory AgentMemoryEntry.fromJson(Map<String, dynamic> j) => AgentMemoryEntry(
id: j['id'] as String? ?? '',
title: j['title'] as String? ?? '',
body: j['body'] as String? ?? '',
type: j['type'] as String? ?? 'fact',
createdAt: (j['createdAt'] as num?)?.toInt() ?? 0,
updatedAt: (j['updatedAt'] as num?)?.toInt() ?? 0,
flagged: j['flagged'] == true,
sessionId: j['sessionId'] as String?,
);
String get typeLabel => switch (type) {
'preference' => '偏好',
'reference' => '参考',
_ => '事实',
};
}
/// Both memory scopes in one read, as `/api/agent-memory/all` answers.
class AgentMemorySnapshot {
final List<AgentMemoryEntry> global;
final List<AgentMemoryEntry> project;
final bool globalFailed;
final bool projectFailed;
const AgentMemorySnapshot({
this.global = const [],
this.project = const [],
this.globalFailed = false,
this.projectFailed = false,
});
factory AgentMemorySnapshot.fromJson(Map<String, dynamic> j) =>
AgentMemorySnapshot(
global: [
for (final m in (j['global'] as List? ?? []))
if (m is Map<String, dynamic>) AgentMemoryEntry.fromJson(m),
],
project: [
for (final m in (j['project'] as List? ?? []))
if (m is Map<String, dynamic>) AgentMemoryEntry.fromJson(m),
],
globalFailed: j['globalFailed'] == true,
projectFailed: j['projectFailed'] == true,
);
bool get isEmpty => global.isEmpty && project.isEmpty;
}
/// A plan as the server reads it back: the link plus its Markdown.
class ProjectPlanContent {
final String id;
final String title;
final String body;
final String raw;
final String? path;
final String source;
const ProjectPlanContent({
required this.id,
required this.title,
required this.body,
this.raw = '',
this.path,
this.source = 'personal',
});
factory ProjectPlanContent.fromJson(Map<String, dynamic> j) =>
ProjectPlanContent(
id: j['id'] as String? ?? '',
title: j['title'] as String? ?? '',
body: j['body'] as String? ?? '',
raw: j['raw'] as String? ?? '',
path: j['path'] as String?,
source: j['source'] as String? ?? 'personal',
);
}
class Page<T> {
final List<T> data;
final String? next;
final String? previous;
Page(this.data, {this.next, this.previous});
}
class AuthStatus {
final bool authenticated;
final bool disabled;
final bool locked;
AuthStatus(this.authenticated, this.disabled, this.locked);
}
class ModelInfo {
final String id;
final String providerId;
final String name;
final int context;
final int output;
/// Thinking levels this model offers (`minimal`, `low`, `medium`, …), as
/// v2's model variants. Empty means the model has no effort choice.
final List<String> variants;
/// The provider says the model reasons; worth a mark in the picker.
final bool reasoning;
ModelInfo(this.id, this.providerId, this.name, this.context, this.output,
{this.variants = const [], this.reasoning = false});
factory ModelInfo.fromJson(Map<String, dynamic> j) {
final lim = j['limit'] as Map<String, dynamic>? ?? {};
final capabilities = j['capabilities'];
return ModelInfo(
j['id'] as String,
j['providerID'] as String? ?? '',
j['name'] as String? ?? (j['id'] as String? ?? ''),
(lim['context'] as num?)?.toInt() ?? 0,
(lim['output'] as num?)?.toInt() ?? 0,
variants: [
for (final v in (j['variants'] as List? ?? []))
if (v is Map && v['id'] is String) v['id'] as String,
],
reasoning:
capabilities is Map && capabilities['reasoning'] == true,
);
}
bool get hasEffort => variants.isNotEmpty;
}
class AgentInfo {
final String id;
final String name;
final String mode;
final bool hidden;
AgentInfo(this.id, this.name, this.mode, [this.hidden = false]);
factory AgentInfo.fromJson(Map<String, dynamic> j) => AgentInfo(
j['id'] as String,
j['name'] as String? ?? '',
j['mode'] as String? ?? '',
j['hidden'] as bool? ?? false,
);
}
class PermissionRequest {
final String id;
final String sessionId;
final String action;
final List<String> resources;
PermissionRequest(this.id, this.sessionId, this.action, this.resources);
factory PermissionRequest.fromJson(Map<String, dynamic> j) => PermissionRequest(
j['id'] as String,
j['sessionID'] as String? ?? '',
j['action'] as String? ?? '',
(j['resources'] as List?)?.map((e) => e.toString()).toList() ?? const [],
);
}
String _jsonString(Object? o) {
if (o is String) return o;
return o.toString();
}
/// The images an `openchamber_image` call saved. The first-party client lifts
/// such a call out of the folded run and shows the pictures in the chat; this
/// reads the call's result envelope (`{ok, action: image.generate, data:
/// {images: [{path}]}}`) to know which files those are.
List<String> generatedImagePaths(ContentPart part) {
const empty = <String>[];
if (part.type != 'tool' || part.name != 'openchamber_image') return empty;
final state = part.state;
if (state == null || state.status != 'completed') return empty;
final text = state.content
.where((c) => c.type == 'text')
.map((c) => c.text)
.join()
.trim();
if (text.isEmpty) return empty;
Object? decoded;
try {
decoded = jsonDecode(text);
} catch (_) {
return empty;
}
if (decoded is! Map) return empty;
if (decoded['ok'] != true || decoded['action'] != 'image.generate') {
return empty;
}
final data = decoded['data'];
if (data is! Map) return empty;
final images = data['images'];
if (images is! List) return empty;
final out = <String>[];
for (final image in images) {
if (image is! Map) continue;
final path = image['path'];
if (path is String && path.trim().isNotEmpty) out.add(path.trim());
}
return out;
}