Agents
You will learn how an agent works with a document: it reads the grammar from describe(), sends commands as JSON, dry-runs them with preview, and gets errors back as JSON it can act on.
dart
import 'dart:convert';
import 'package:vyuh_document/vyuh_document.dart';
import 'package:vyuh_document_elements/vyuh_document_elements.dart';
/// Lets an agent learn the grammar, then send commands as JSON.
void main() {
final configuration = notesConfiguration;
// Elements, content rules, attributes, traits and commands with their
// argument types: give this to the model as its tool description.
final grammar = jsonEncode(configuration.describe().toJson());
print(grammar.length);
final controller = DocumentController(
configuration,
author: const Author.agent('planner'),
);
// A command arrives as JSON. Decoding never throws.
final decoded = configuration.decodeCommand({
'command': 'InsertRwo', // a typo
'table': {'element': 'vyuh.document.block.table', 'id': 't1'},
'at': 2,
});
switch (decoded) {
case Done(:final value):
final result = controller.preview(value); // dry run first
print(result.isDone);
case Failed(:final error):
// UnknownCommand: "Did you mean InsertRow?" Return it to the agent.
print(jsonEncode(error.toJson()));
}
controller.close();
}The grammar
configuration.describe() returns a DocumentDescription: every element with its attributes and commands, the marks, and the shared commands. Put its toJson() (or toPrettyJson()) in the agent's tool description.
Commands as JSON
Every command has a generated JSON form: {"command": "InsertRow", ...arguments}.
| Call | Does |
|---|---|
command.toJson() | Serializes a typed command |
configuration.decodeCommand(json) | Result<Command>; UnknownCommand (with didYouMean) or InvalidDocument (with the argument path) |
controller.preview(command) | The resulting document, nothing applied |
controller.run(command) | Applies it, attributed to the controller's author |
error.toJson(), DocumentError.fromJson(json) | Errors as data |
References serialize as {"element": "vyuh.document.block.table", "id": "t1"}.
Patterns
- Give each agent its own controller with
Author.agent(name)andjoin; a person can undo their own edits without undoing the agent's. - Run a plan of several steps as one turn (
agent.turn): all or nothing, one undo. Preview a single command before running it. - Return
error.toJson()to the model verbatim:where,expected,foundandhintare written for it.
Wrap decodeCommand and run in your own tool handler.
An agent beside a person
An agent is a participant like any other: join it to the person's controller with Author.agent(name) and run its commands through your tool handler. The person keeps typing in their editor while it works.
- Each step addresses content by reference or position in the document as it is now; the person may have edited it since the agent last looked.
- A step whose target the person removed comes back as error JSON from
preview; hand it to the model and move on. - The agent's own
Undoreverts only its edits, and the person's only theirs. - Give the agent a mode:
join(author: ..., mode: DocumentInteractionMode.suggesting), oragent.setMode(...)later. In suggesting mode its edits are recorded as suggestions attributed to it (document.suggestions), which the person decides one at a time withAcceptSuggestion(id)andRejectSuggestion(id), or all at once withAcceptAllSuggestionsandRejectAllSuggestions, frompackage:vyuh_document/review.dart. Viewing, commenting and reviewing refuse content commands withNotAllowed; a command suggesting can't record yet (adding a table row, say) fails withUnsupported. - An agent in commenting mode reviews without editing: the comments family from
package:vyuh_document/comments.dart(AddComment,ReplyToComment,EditComment,ResolveComment,ReopenComment,DeleteComment) runs in every mode but viewing.AddCommentreturns the newCommentId; passid:to choose it and leavetextempty when the host keeps comment bodies elsewhere. A comment anchors text inside one block; any other range fails withNotAllowedwhosefoundismultiBlockAnchororemptyAnchor.
What the agent owns
Everything an agent does is bounded by what its controller owns (the full table); the types come from package:vyuh_document/participants.dart.
| Capability | For an agent |
|---|---|
| Mode | suggesting: its edits become suggestions the person decides |
| Grants | ParticipantGrants.contributor: it decides its own suggestions and changes its own comments, but nobody else's, and changes no settings |
| Write scope | WriteScope.section(heading): it may only write there |
| Turns | agent.turn(...): one tool call's steps are one change and one undo |
| Status | publishStatus(ParticipantStatus.thinking(...)) while the model works |
| Feed | othersChanges: react to what the person does |
dart
final summary = person.document.body.heading(text: 'Summary')!;
final agent = person.join(
author: const Author.agent('Reviewer'),
mode: DocumentInteractionMode.suggesting,
grants: ParticipantGrants.contributor,
writeScope: WriteScope.section(summary),
);
/// A tool call with several commands: decode them all, run them as one turn.
Object handleTurn(String intent, List<Map<String, Object?>> json) {
final commands = <Command<Object?>>[];
for (final command in json) {
switch (agent.configuration.decodeCommand(command)) {
case Done(:final value):
commands.add(value);
case Failed(:final error):
return error.toJson();
}
}
agent.publishStatus(ParticipantStatus.working(intent));
final result = agent.turn((turn) {
for (final command in commands) {
if (turn.run(command) is Failed) return;
}
}, label: intent);
agent.publishStatus(ParticipantStatus.idle);
return switch (result) {
Done() => {'applied': agent.state.revision},
// outsideWriteScope, decideSuggestions, deleteComments, ...: written
// for the model.
Failed(:final error) => error.toJson(),
};
}Every refusal is NotAllowed whose found says why: the mode's name, the missing grant (decideSuggestions, resolveComments, deleteComments, editComments), or outsideWriteScope. An unknown comment or suggestion id is NotFound and a comment id already taken is Conflict, each with the id as found. A turn that fails applies none of its steps, so the model can retry it whole.
dart
// The agent flags what it may not fix; a write scope admits comments
// anywhere protection does.
final id = agent.run(
AddComment(Range(Position(intro, offset: 6), Position(intro, offset: 17)),
text: 'Typo: "announcement".'),
).valueOrNull!; // CommentId
agent.run(DeleteComment(personsComment)); // Failed(NotAllowed): deleteCommentsThe agent beside you example runs a scripted model on a timer next to your editor: it may write only in the Summary, has contributor grants, works in turns (one "Undo agent" reverts a whole turn), flags the intro typo it may not fix with a comment, withdraws its own first suggestion with RejectSuggestion when it suggests, shows its status, reacts when you edit the intro, and has a "Show markup" switch for your view.
Next
- Commands: the full catalog.
- Loading and saving: persisting the JSON.