@mdedit/agent-client
Headless Node.js client for agents editing mdedit.ai articles. It joins the same Yjs
room as human editors when collaboration is enabled and transparently uses conditional
REST commits for non-collaborative articles.
Requires Node.js 20 or newer.
Install
npm install @mdedit/agent-client
Usage
import { openArticleSession } from '@mdedit/agent-client';
const session = await openArticleSession({
apiKey: process.env.MDEDIT_API_KEY!,
workspaceId: 'workspace-id',
articleId: 'article-id',
agent: { name: 'claude-code', onBehalfOf: 'vivek' },
});
console.log(session.mode);
console.log(session.read());
console.log(session.presence());
const result = await session.edit([
{
type: 'replace',
anchor: { quote: 'teh quick brown fox' },
text: 'the quick brown fox',
},
{
type: 'insert',
anchor: { afterHeading: '## Setup' },
text: '\nNew paragraph.\n',
},
]);
console.log(result.conflicts);
await session.review.addComment({
anchor: { quote: 'as everyone knows' },
body: 'Needs a citation.',
commandId: 'review-source-check-1',
});
await session.review.suggest({ anchor: { quote: 'teh' }, replace: 'the', note: 'Typo.' });
const openReview = await session.review.list({ status: 'open' });
console.log(openReview);
await session.close();
Hosted/server integrations can use createArticleReviewSession({ transport, ... })
to reuse the same review-session command path with an authenticated internal transport.
session.applyCommands(commands, { commandId }) submits a complete command batch under
one stable idempotency key.
Watch article and review events
session.events() is an async iterable. It emits an initial session.ready snapshot,
then article.updated, review.event, and review.updated records until the session is
closed or its abort signal fires:
const controller = new AbortController();
for await (const event of session.events({ signal: controller.signal })) {
console.log(event);
if (event.type === 'review.event') {
}
}
Live sessions observe Yjs and review changes directly. REST fallback polls the current
article package; set pollIntervalMs when a slower or faster interval is appropriate.
apiKey authenticates REST and collaborative websocket requests. Advanced callers can
provide websocketToken to override the websocket credential; normal agent sessions
only need the API key. When the override differs from the API key, the client omits its
own agent identity from presence() because the REST response cannot attest the actor
authenticated by that different websocket credential.
Quote anchors must match once. Use a one-based occurrence or exact adjacent
context: { before, after } to disambiguate. Heading anchors accept a heading name or
Markdown heading; beforeHeading and afterHeading resolve to insertion points, while
inSection resolves the body through the next heading of equal or higher rank.
Conflict semantics
Live edits are CRDT-merged, not race-free. edit() applies minimal character-level
splices after validating the complete operation batch against an isolated draft, waits
for the outgoing Yjs update to sync, and observes overlapping remote updates until a
short resettable quiet window elapses. A missing or ambiguous anchor rejects without
applying any operation in the batch. Successful edits return overlaps in conflicts;
callers should re-read and repair when the list is non-empty.
edit(operations, { ifContentHash }) checks a SHA-256 hash against the local replica
immediately before applying. This is only a best-effort local precondition: a human
update already accepted by the server may not have reached this replica yet, so the
agent update can still land. mdedit intentionally does not provide server-side
compare-and-apply for live article content.
REST fallback refreshes the article before every edit and uses the existing conditional
content commit. A concurrent REST change rejects with RestContentConflictError.
If collaboration is enabled after the REST session opens, the edit throws
CollaborationModeChangedError before uploading content. Close and reopen the session
to join the live room, then retry against the newly synced document.
Presence and reviews
Live awareness publishes display hints under
{ agent: { kind: "agent", agentName, onBehalfOf } }. These fields are client-visible
hints only; the collaboration server attests identity from websocket authentication.
session.presence() returns a sanitized snapshot of participant display fields and
server-attested agent fields. REST sessions return an empty list.
This package never mutates review.json. Every session.review mutation uses the
server-owned review-commands endpoint. list() reads the synced document when the
session is live and falls back to the review REST resource otherwise. Reuse an explicit
commandId when retrying after an unknown response so the server can deduplicate it.