A monorepo for writing specs and other serious text on the AT Protocol.
portent draft
4 folders · 8 files

demo
e2e
src
test
Caddyfile
compose.yaml
Dockerfile
package.json
README.md
service.json
tsconfig.json
vite.config.ts
README.md

draft #

A block editor for specs and serious writing. Reusable across hosts: each one says which block types exist in its context, where references come from, what metadata sits around the text, and which assistant (if any) sits in the sidebar.

import { Draft, FakeAssistant } from '@portent/draft';
import '@supramundane/supram/css/supram.css';
import '@portent/draft/styles';        // draft.css, on supram's tokens

const draft = new Draft({
  author: { id: 'me', name: 'Me', kind: 'human' },
  blocks: ['list', 'ordered', 'code', 'math', 'definitionList', 'figure', 'section'],
  references: { searchRefs, searchTerms },   // "[" and "@"
  upload, blobUrl,                            // figures
  assistant: new FakeAssistant(),             // or an HttpAssistant, or your own
  onChange: (json) => save(json),
});

Then <draft-editor .draft=${draft} .content=${json}>, <draft-sidebar .draft=${draft}>, and <draft-line> for single-line fields (title, abstract). Components render in light DOM so the host's stylesheet reaches them; draft.css styles the editor's own chrome.

The editor keeps a discreet note at the bottom left of the screen with the text's words and characters, counted as a reader would: outline notes, suggested deletions and comments are left out, and so is whatever metadata the host keeps around the text. counts: false turns the note off (a second editor on the same document, say); counts: (live) => lines says what it shows, each line a { label?, words, chars, target? }, for a host that adds the whole book's beside the chapter's; a line with a target reads "412 of 1,200 words" and carries a thin rule that fills as the words come (ruby past the target). A section can carry a word target of its own (the field beside its anchor, or the target op); sectionsAround and targetedSectionAt find the sections at a position, for a host that wants a line for the one the caret is in. countNode, countJson and countText are exported for hosts that count elsewhere.

Suggestions and comments #

Edits made while suggesting is on (or by an assistant, always) are tracked in the document as insertion, deletion and modification marks (from prosemirror-suggest-changes); who made them and why lives beside the document in SuggestionStore. Block changes are the same marks on whole blocks: a deleted block, an inserted one, a move (a deletion and an insertion under one id), a split or a merge, or an outline note written out (the note deleted, prose inserted). Each suggestion is accepted or rejected on its own (draft.accept(id), draft.reject(id)), or all at once, or per assistant reply. Clicking a suggestion in the text puts accept and reject in the margin beside it. Comments are a comment mark plus a thread in the store; they reply and resolve. In the editor each open comment is a note in the right margin, level with its text and clamped to a couple of lines; it opens in full (text, replies, a reply box, resolve) when the caret is in the commented text or the note is clicked, and the notes make way for the open one. With no room beside the text (a phone) only the open note is drawn, over the text.

A paragraph can be an outline note (outline: true on the node, /outline in the editor, or the block menu): a sentence or two on what its section, or that one paragraph, will say rather than prose, shown muted and italic; a list can be one too, the points a paragraph will make, one per sentence. The assistant sees them as (outline) and sections as ## Title (target: N words). Outlining goes through one op, outline: the structure proposed at one level as parts (a section with a title, a note and a target and its own parts; a paragraph as a note; a paragraph down to its sentences as a note with points), placed in a section, after or before a block, in place of a note (block) or at the top. outlineOps lays it out as block ops, nested by reference (ref on an insert-block, $ref where a later op names a block), and Draft.applyOps gives every part a suggestion of its own — the suggestion library would otherwise fold a run of inserted blocks into one — so the writer takes an outline part by part (listed in Changes as proposed section, outline note, the sentences). The protocol tells the model to outline at the grain asked (chapters, sections, subsections, paragraphs, sentences), to follow the writer's guidance and never to write the prose unasked; asked to write, it writes the prose each note calls for after it (a note and its points as one paragraph), listed as written out. draft.outlineNotes(id) and draft.setOutlineNotes(id, blocks) read and write the notes at a level (a section's own, or one note; paragraphs and lists) as plain changes, draft.setTarget sets a section's target, and draft.ask(text, { intercept }) lets a host take some of a reply's ops for itself (Natural turns a top-level outline into chapters that way). Several blocks inserted after the same block land in the order given. <draft-text> is a few paragraphs of rich text (paragraphs, lists, bold, italic, code) with blocks in and out, for a brief or a plan; textOfBlocks and blocksFromText turn such blocks into prose for a model and back.

Every control with a title gets a tooltip drawn by the page (installTooltips() once per page): shown at once on hover or focus, the name as text and the shortcut in the title's parenthesis as keys, with the native tooltip kept from showing. Suggesting is a switch (renderSwitch(label, on, toggle), a role="switch" with a track and a knob) rather than a pressed button. The sidebar's tabs carry icons (SidebarPanel.icon, a Lucide name from supram's set); when the sidebar is too narrow for icons and names both, the names drop and the tooltips carry them.

With collaboration: { doc: ydoc } the document is a Yjs fragment and the store's metadata lives in the same Y.Doc, so concurrent edits and suggestions from several people merge (the demo runs two editors on one document).

Assistants #

An assistant sees the document as text with every block prefixed by its id (docForAssistant) and answers with a message and a list of ops that address blocks by id and text by quoting it (replace, insert, delete, format, retitle, delete-block, insert-block, move-block, split-block, merge-block, comment; see ASSISTANT_INSTRUCTIONS for the exact contract a model is given). draft.applyOps turns each op into one suggestion (or one comment thread); a replace (or retitle) is applied as the word-level difference between the quoted text and the new text (suggestions/diff.ts), so a rewritten sentence reads as the few words that changed, new words keep the marks of what they replace, and a rewrite that changes nothing (or only quote marks and spacing) is refused rather than shown as the same text struck through and typed again; the sidebar shows the conversation and lets the writer accept or reject a reply's suggestions together or one by one, then ask again. FakeAssistant implements the same contract with rules instead of a model. ClaudeAssistant talks to Claude through the Anthropic SDK (structured outputs hold the reply to the protocol's shape; in a browser it takes the writer's own API key and sends it to Anthropic only). OpenAIAssistant talks to any OpenAI-compatible chat endpoint (a local llama.cpp, a LiteLLM gateway, a hosted provider), by one road or several (endpoints: each a base URL with its own key and headers, tried in order, the one that answers kept for the next request, and an error that says what each one said when none does; probeEndpoints asks every road for its models, which the picker's Check shows). halfmindEndpoints is the pair for Robin's box: the LAN, then the tunnel with its X-Auth-Token. HttpAssistant posts the request to any endpoint that answers in the protocol itself. The assistant is a signal on the draft (draft.assistant.set(...)), so a host can let the writer switch. "Copy for a model" puts the instructions and the document on the clipboard for use with any LLM by hand.

CodeAssistant is Claude Code run by the host: codePrompt turns a request into a system prompt (the protocol, the style, and a note that the document is stored beside it as a .nat and that it reads only) and a prompt (the conversation so far, the context, the document, the ask); the host's run hook does the running (Natural's sidecar starts claude -p) and gives back the text, parsed like any reply. PeerAssistant sends the same two prompts, with the document's name and text, to another Natural that lends its Claude Code behind a password (/ask with Authorization: Bearer <password>), and probePeer asks such a Natural whether it is there and the password right, for Check. The picker offers Claude Code on this machine only when the host says it can run it (canCode, with a codeCheck hook for Check).

A host can give the assistant more to read than the document: context in DraftConfig is a function returning labelled pieces of text (the other chapters of a book, notes the writer attached) that go with every ask, marked as context only (contextForAssistant): the model may draw on them and quote them, but they carry no block ids, so no op can touch them.

What the assistant is doing #

An assistant says what it does as it does it: the request carries onEvent, and the assistant reports AssistantEvents — a status step ("asking hm-write at home: 12,400 characters"), the reply as text deltas, the model's thinking when the road carries it, a tool an agent used with its input in a phrase and the tool-result it got back, and the usage at the end (tokens, cost, time). OpenAIAssistant asks for a stream and reads server-sent events (readSSE; a server that ignores stream is read whole), ClaudeAssistant streams through the SDK, FakeAssistant tells its steps and streams its reply in pieces, HttpAssistant only says when the request went. CodeAssistant and PeerAssistant read the lines Claude Code prints (--output-format stream-json), forwarded by the host or the lending Natural as JSON lines (readCodeStream; codeEventMapper turns each line into events, describeToolInput makes "Essays/Essay.nat" of a Read).

draft.ask folds the events into an Activity (activity.ts: a pure reducer, applyEvent, with summariseActivity for one line on the whole), published on draft.activity while the question is out and kept on the reply's Message afterwards; draft.stop() aborts the request through the signal every assistant is given. The sidebar shows the activity live — who is at it and for how long, the steps with the current one marked, the tools and what they answered, the words streaming in, a Stop — and folds it under the reply once it lands. While the assistant is in use (a question composed, out, or just answered) the sidebar carries the class wide and the layout gives it the room (.draft-layout.with-sidebar:has(draft-sidebar.wide)); back in the text it narrows again, unless the writer pins it wide.

Demo #

npm run demo (or npm run dev here) serves it on http://127.0.0.1:5174; npm run deploy:demo from the repo root publishes it at draft.stan.computer.