Something went wrong. Try again.
A monorepo for writing specs and other serious text on the AT Protocol.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195// How a document is shown to an assistant and how its answer comes back.//// The document goes out as text with every block and section prefixed by// its id in brackets; the answer is JSON: a message for the writer and a// list of ops (see ops.ts) that address blocks by id and text by quoting// it. Anything else in the answer is treated as message text.import type { Node as PMNode } from '@tiptap/pm/model';import { blocksOf } from '../doc.ts';import { OP_NAMES, type Op } from './ops.ts';import { validatePart } from './outline.ts';
/** A note the assistant names for the next step: its title in the writer's vault, the section it is for, and why. */export type NamedNote = { title: string; for?: string; why?: string };
export type AssistantReply = { message: string; ops: Op[]; /** The vault notes it would draw on next, when it named any. */ named?: NamedNote[] };
/** The document as the assistant reads it. */export function docForAssistant(doc: PMNode, title?: string): string { const lines: string[] = []; if (title) lines.push(`# ${title}`, ''); for (const b of blocksOf(doc)) { const tag = `[${b.id}]`; switch (b.type) { case 'section': { const target = Number(b.node.attrs.target); lines.push(`${tag} ${'#'.repeat(b.depth + 2)} ${b.text}${target > 0 ? ` (target: ${target} words)` : ''}`); break; } case 'codeBlock': { const lang = String(b.node.attrs.language ?? ''); lines.push(`${tag} \`\`\`${lang}`, ...b.text.split('\n'), '```'); break; } case 'blockMath': lines.push(`${tag} $$ ${b.text} $$`); break; case 'figure': lines.push(`${tag} [image${b.text ? `: ${b.text}` : ''}]`); break; case 'bulletList': case 'orderedList': case 'definitionList': { // an outline list: the points a paragraph will make, one per sentence const head = b.node.attrs.outline ? `${tag} (outline)` : tag; const [first, ...rest] = b.text.split('\n'); lines.push(`${head} ${first ?? ''}`, ...rest.map((l) => `${' '.repeat(head.length + 1)}${l}`)); break; } case 'paragraph': lines.push(b.node.attrs.outline ? `${tag} (outline) ${b.text}` : `${tag} ${b.text}`); break; default: lines.push(`${tag} ${b.text}`); } lines.push(''); } return lines.join('\n').trimEnd() + '\n';}
/** * Material that goes beside the document for context only: the other * chapters of the same work, notes the writer attached. It carries no ids, * so nothing in it can be addressed by an op. */export function contextForAssistant(items: { label: string; text: string }[]): string { if (!items.length) return ''; const parts = items.map((it) => `### ${it.label}\n\n${it.text.trim()}`); return `For context only. What follows is not part of the document you are editing and has no block ids: read it, draw on it, quote it where that helps, but never write an operation against it.\n\n${parts.join('\n\n')}`;}
/** What to tell a model so it answers in the protocol. */export const ASSISTANT_INSTRUCTIONS = `You are helping edit a document. It is given to you as blocks, each prefixed with its id in square brackets: sections read like Markdown headings ([id] ## Title), paragraphs are plain text, code blocks are fenced, lists are indented under their id.
Answer with a single JSON object and nothing else:
{"message": "<a short note to the writer>", "ops": [ ...operations... ]}
Every operation names the block it touches by id and quotes the exact text it works on; never use offsets. Keep quoted text short but unambiguous (a phrase, a sentence). Operations:
- {"op":"replace","block":"<id>","find":"<exact text>","with":"<new text>","note":"<why>"}- {"op":"insert","block":"<id>","text":"<text>","after":"<exact text>"} (or "before"; neither means the end of the block)- {"op":"delete","block":"<id>","find":"<exact text>","note":"<why>"}- {"op":"format","block":"<id>","find":"<exact text>","mark":"bold|italic|code|dfn|dfnRef"} ("remove":true takes it off)- {"op":"retitle","block":"<section id>","title":"<new title>"}- {"op":"delete-block","block":"<id>","note":"<why>"}- {"op":"insert-block","after":"<id>","text":"<text>","type":"paragraph|code|math|list|ordered|section"} ("before" or "in":"<section id>" instead of "after"; sections take "title" and may take "target", a word count; code takes "language"; a list is one item per line; "outline":true makes the paragraph, or a new section's paragraphs, outline notes; several insert-blocks after the same block land in the order you give them; "draws":["<note title>", ...] names the writer's vault notes the block was written from, when any)- {"op":"target","block":"<section id>","words":<number>} (the word target of a section; 0 removes it)- {"op":"move-block","block":"<id>","after":"<id>"} (or "before")- {"op":"split-block","block":"<id>","at":"<the text after which to split>"}- {"op":"merge-block","block":"<id>"} (joins it with the block after it)- {"op":"comment","block":"<id>","text":"<the comment>","find":"<exact text, optional>"}- {"op":"outline","in":"<section id>","parts":[ ...parts... ]} (the structure proposed at one level, as outline notes, not prose: the writer takes it part by part. "in" puts the parts inside a section; "after" or "before" a block puts them beside it; "block" names an outline note they break down, which then goes; none of these means the top of the document. A part is one of: {"title":"<a section's title>","note":"<what it will argue or cover>","target":<words>,"parts":[ ...its own parts... ]} for a section; {"note":"<what one paragraph will say>"} for a paragraph to be written; {"note":"<what the paragraph says>","points":["<what its first sentence says>","<the second>", ...]} for a paragraph planned down to its sentences. Any part may carry "draws":["<note title>", ...], the writer's vault notes it draws on.)
Add "nth": 2 when the quoted text occurs more than once and you mean a later occurrence. Text you write may use **bold**, *italic* and \`code\`. Prefer a few precise operations to a rewrite; the writer accepts or rejects each one separately. When asked to tighten, shorten or rewrite, change the words that need changing: delete a filler phrase, replace a wordy clause with a short one. Do not quote a whole passage and give it back nearly as it was, and never give "with" text that is the same as "find" (such a replace is dropped, as is one that differs only in quote marks or spacing). If nothing should change, return an empty "ops" list and say why in "message".
A paragraph shown as (outline) is an outline note: a sentence or two saying what its section, or that one paragraph, will say, not prose for the reader; a list shown as (outline) gives the points the paragraph before it will make, one per sentence. Outlining is the writer's way of working out the argument before writing it, level by level and ever finer, and the writer writes the prose: when asked to outline, answer with one outline op at the level asked, at the granularity asked, and no prose. Asked for chapters or sections, give parts with a "title", a "note" on what each will argue or cover, and a "target" in words so that they add up to the whole's (a section shown with (target: N words) is meant to run to about that many; set one on an existing section with the target op where it helps); nest a part's own "parts" only where the writer asks for them or a section plainly needs them. Asked for subsections, the same "in" the section named. Asked for paragraphs, give a part with a "note" for each paragraph to be written, in order, "in" the section (or "block" the note being broken down). Asked for sentences, give each paragraph as a part with its "note" and its "points", one per sentence, in order; for one note, "block" it with a single part holding the "points" (the note stays as the paragraph's gist). Revise the outline notes already at that level rather than adding beside them: delete-block the ones the new parts replace. Follow the writer's guidance on what to cover, the angle and the order. When asked to expand or write out a section, a note, or the outline as a whole, write the prose each outline note calls for as new paragraphs placed after that note (insert-block, "after" the note's id, several ops for several paragraphs, in reading order) and then delete-block the note; a note followed by an (outline) list is one paragraph, its sentences as listed, and both go once it is written (delete-block the list, then the note); keep to what the note promises, to the section's target and to the document's style; leave sections without outline notes alone unless asked.
The writer may give you other material for context: the other chapters of the same work, or notes and reading they attached. It is marked as such and carries no block ids. Use it to keep what you write consistent with the rest and to draw on the writer's own notes and sources, quoting them where it helps; never try to edit it. Some of it comes from the writer's vault of notes, each marked as a note from the vault with its title. When a block or a part you write draws on one, say so with "draws" and the note's exact title. And name the notes to read next: add "named" to your reply, a list of up to five {"title":"<the note's exact title>","for":"<the section it serves, by its title or number>","why":"<a line on what it brings>"}, taken from the notes you were shown or ones the writer named; leave "named" out when there are none.`;
const STRING_FIELDS: Record<string, string[]> = { replace: ['block', 'find', 'with'], insert: ['block', 'text'], delete: ['block', 'find'], format: ['block', 'find', 'mark'], retitle: ['block', 'title'], 'delete-block': ['block'], 'insert-block': ['text'], 'move-block': ['block'], 'split-block': ['block', 'at'], 'merge-block': ['block'], comment: ['block', 'text'], target: ['block'], outline: [],};
/** One candidate op, checked for shape. */export function validateOp(v: unknown): { op: Op } | { error: string } { if (!v || typeof v !== 'object') return { error: 'not an object' }; const o = v as Record<string, unknown>; const name = o.op; if (typeof name !== 'string' || !(OP_NAMES as readonly string[]).includes(name)) return { error: `unknown op "${String(name)}"` }; for (const f of STRING_FIELDS[name] ?? []) { if (typeof o[f] !== 'string') return { error: `${name} needs a string "${f}"` }; } if (name === 'format' && !['bold', 'italic', 'code', 'dfn', 'dfnRef'].includes(String(o.mark))) return { error: `format: unknown mark "${String(o.mark)}"` }; if (name === 'insert-block' && o.type !== undefined && !['paragraph', 'code', 'math', 'list', 'ordered', 'section'].includes(String(o.type))) return { error: `insert-block: unknown type "${String(o.type)}"` }; if (o.nth !== undefined && (typeof o.nth !== 'number' || o.nth < 1)) return { error: `${name}: nth must be a positive number` }; if (name === 'target' && (typeof o.words !== 'number' || o.words < 0)) return { error: 'target needs a number of "words"' }; if (name === 'insert-block' && o.target !== undefined && typeof o.target !== 'number') return { error: 'insert-block: "target" must be a number of words' }; if (name === 'insert-block' && o.draws !== undefined && (!Array.isArray(o.draws) || o.draws.some((x) => typeof x !== 'string'))) return { error: 'insert-block: "draws" must be a list of note titles' }; if (name === 'outline') { if (!Array.isArray(o.parts) || !o.parts.length) return { error: 'outline needs a list of "parts"' }; for (const f of ['in', 'after', 'before', 'block']) if (o[f] !== undefined && typeof o[f] !== 'string') return { error: `outline: "${f}" must be a block id` }; for (const p of o.parts) { const err = validatePart(p); if (err) return { error: `outline: ${err}` }; } } return { op: o as unknown as Op };}
/** * Read an assistant's answer: the JSON object (possibly inside a code * fence or surrounded by prose), or, failing that, the text as the message. */export function parseReply(text: string): { reply: AssistantReply; errors: string[] } { const errors: string[] = []; const raw = extractJson(text); if (!raw) return { reply: { message: text.trim(), ops: [] }, errors }; let parsed: unknown; try { parsed = JSON.parse(raw); } catch (err) { errors.push(`invalid JSON: ${err instanceof Error ? err.message : String(err)}`); return { reply: { message: text.trim(), ops: [] }, errors }; } const obj = (parsed && typeof parsed === 'object' ? parsed : {}) as Record<string, unknown>; const ops: Op[] = []; const list = Array.isArray(obj.ops) ? obj.ops : Array.isArray(parsed) ? (parsed as unknown[]) : []; list.forEach((v, i) => { const r = validateOp(v); if ('op' in r) ops.push(r.op); else errors.push(`op ${i + 1}: ${r.error}`); }); const message = typeof obj.message === 'string' ? obj.message : ops.length ? `${ops.length} suggestion${ops.length === 1 ? '' : 's'}.` : text.trim(); const named = parseNamed(obj.named); return { reply: { message, ops, ...(named.length ? { named } : {}) }, errors };}
/** The notes a reply names, those that have a title; the rest is ignored. */export function parseNamed(v: unknown): NamedNote[] { if (!Array.isArray(v)) return []; const out: NamedNote[] = []; for (const n of v) { if (!n || typeof n !== 'object') continue; const o = n as Record<string, unknown>; const title = typeof o.title === 'string' ? o.title.trim() : ''; if (!title) continue; out.push({ title, ...(typeof o.for === 'string' && o.for.trim() ? { for: o.for.trim() } : {}), ...(typeof o.why === 'string' && o.why.trim() ? { why: o.why.trim() } : {}) }); } return out;}
function extractJson(text: string): string | null { const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(text); if (fenced?.[1]) return fenced[1].trim(); const start = text.indexOf('{'); const end = text.lastIndexOf('}'); if (start >= 0 && end > start) return text.slice(start, end + 1); const a = text.indexOf('['); const b = text.lastIndexOf(']'); if (a >= 0 && b > a) return text.slice(a, b + 1); return null;}