AgentEvent.fromJson constructor
Reads the shared JSON shape (kind plus its fields), as the browser's loop sends it.
Implementation
factory AgentEvent.fromJson(Map<String, Object?> json) {
T field<T>(String name) {
final value = json[name];
if (value is T) return value;
throw FormatException('agent event "${json['kind']}": bad "$name"');
}
switch (json['kind']) {
case 'piece':
return AgentPiece(field<String>('text'));
case 'tool_call':
return AgentToolCall(
callId: field<String>('call_id'),
name: field<String>('name'),
argumentsJson: field<String>('arguments_json'),
needsApproval: field<bool>('needs_approval'),
);
case 'approval_needed':
return AgentApprovalNeeded(field<String>('call_id'));
case 'tool_result':
return AgentToolResult(
callId: field<String>('call_id'),
ok: field<bool>('ok'),
contentJson: field<String>('content_json'),
error: field<String?>('error'),
);
case 'step':
final left = field<Map<String, Object?>>('budget_left');
int count(String name) {
final value = left[name];
if (value is int) return value;
throw FormatException('agent step: bad "budget_left.$name"');
}
return AgentStep(
index: field<int>('index'),
budgetLeft: AgentBudget(
steps: count('steps'),
tokens: count('tokens'),
millis: count('millis'),
),
);
case 'done':
final finish = field<String>('finish');
return AgentDone(
AgentFinish.values.firstWhere(
(f) => f.name == finish,
orElse: () =>
throw FormatException('agent done: unknown finish "$finish"'),
),
);
case 'failed':
return AgentFailed(
failureKind: field<String>('failure_kind'),
message: field<String>('message'),
);
default:
throw FormatException('unknown agent event kind "${json['kind']}"');
}
}