lattedit-cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,9 +13,13 @@ Projects live in the user's browser (IndexedDB). Optional Supabase sign-in syncs
13
13
 
14
14
  ## What works
15
15
 
16
+ - Landing page (`web/src/pages/Home.tsx`, `web/src/styles/home.css`): a browser's first visit to `/` shows it once; after that, and for anyone who already has projects, `/` opens the project dashboard at `/projects`. `/welcome` always shows the landing page. The desktop app skips it.
16
17
  - Project dashboard: templates (Article, Blank, Thesis, Slides), import from `.zip` (including Overleaf downloads, and Overleaf's multi-project download, which becomes one project per inner zip), rename, duplicate, download `.zip`, delete.
17
18
  - Editor: CodeMirror 6 with LaTeX highlighting in the design system's colours, autocomplete for commands, environments, `\ref` labels, `\cite` keys and file names, search and replace, a formatting toolbar, and autosave to the browser.
19
+ - Project search: the **Search** tab beside Files and Outline (Ctrl/⌘ Shift F, starting from the selected text) finds text in every file, with match case, whole word and regular expressions; click a result to select it in the editor. **Replace all** changes every file at once after saving a History version (`web/src/lib/projectSearch.ts`).
20
+ - Images: paste or drop an image into the editor and lattedit saves it in `figures/` (or the project's existing images folder), inserts a `figure` with `\includegraphics` and a label, and adds `\usepackage{graphicx}` if nothing loads it. Screenshots are named `pasted-1.png`, `pasted-2.png`…; GIF, WebP and SVG are converted to PNG. Hover an image in the file tree to preview it (`web/src/lib/figures.ts`).
18
21
  - Math preview: hover over inline or display math to see it typeset (KaTeX, loaded on first use), with simple `\newcommand` and `\DeclareMathOperator` macros from the project.
22
+ - Citations: a personal citation library. Add an entry by pasting BibTeX, typing it in, or pasting a DOI, arXiv ID or link: the browser looks it up on Crossref (journal and conference DOIs) or DataCite (arXiv and other DOIs) and builds the BibTeX entry, with a Google Scholar style key (`web/src/lib/citeLookup.ts`).
19
23
  - Table editor: build a table as a grid (alignment, booktabs or grid rules, header row, caption and label), or put the cursor in an existing table and edit it the same way. lattedit adds `\usepackage{booktabs}` when the rules need it.
20
24
  - Files: folders, upload by button or drag and drop (images, PDFs, `.bib`, `.sty`…), rename, delete, set the main document.
21
25
  - Compiling: pdfLaTeX, XeLaTeX or LuaLaTeX; BibTeX and Biber run automatically through latexmk; Ctrl/⌘ Enter or Ctrl/⌘ S; optional auto compile; stop on first error; cancel.
@@ -28,7 +32,8 @@ Projects live in the user's browser (IndexedDB). Optional Supabase sign-in syncs
28
32
  - GitHub: import a repository or one folder of it, connect a project to a branch, pull, and push commits, all from the browser through the GitHub API. Public repositories import without a token; private ones and pushing need a fine-grained token with Contents read and write. The token stays in the browser. A push is refused while GitHub has commits the project hasn't pulled, and only deletes files the project had at the last sync. The link is kept per browser.
29
33
  - Latte (light) and Espresso (dark) themes, resizable panes, and a one-pane layout with a file drawer on phones.
30
34
 
31
- - Coding agents: Claude Code, Codex, Cursor or any MCP client can read, edit and compile projects with the person's own model (**Coding agents** in the header). Locally, `npx lattedit-cli mcp` is a stdio MCP server (`cli/mcp.mjs`) that the open tab or desktop app connects to on `127.0.0.1:47824`; or the person makes a private link, `https://lattedit.xyz/mcp/agent/<secret>`, which `web/proxy.js` answers and relays through the compile server (`server/src/agentRelay.js`) to the tab. The tools run in the tab (`web/src/lib/agentTools.ts`, `agentBridge.ts`), so edits go through the editor live, and a History version is saved before an agent's first change.
35
+ - Coding agents: Claude Code, Codex, Cursor or any MCP client can read, edit and compile projects with the person's own model (**Coding agents** in the header). `npx lattedit-cli mcp` is a stdio MCP server (`cli/mcp.mjs`) that the open tab or desktop app connects to on `127.0.0.1:47824`. The tools run in the tab (`web/src/lib/agentTools.ts`, `agentBridge.ts`), so edits go through the editor live, and a History version is saved before an agent's first change. While an agent works, the editor switches to workspace mode: an **Agents** sidebar opens by itself on the agent's first call and shows each agent's current step, its run step by step with diffs, and Follow (the editor opens what the agent touches), Keep and **Undo run** (puts back every file the run changed); the lines an agent changed are tinted in its colour with its name (`web/src/components/AgentWorkspace.tsx`, `web/src/lib/agentRuns.ts`).
36
+ - Peer-review council: the person's agent reviews the paper as a council: Ultron (skeptic), Friday (methods), U (clarity), Edith (related work) and Dumb-E (ideas), with Vision as area chair, plus Jarvis (submission checks), Karen (ethics), Pepper (framing) and custom members on request, all on the same model, over MCP only (`council_*` tools, the `council_review` prompt, and `council_run` for clients with sampling). The harness in `web/src/lib/council.ts` hands out each role's brief, checks every note against the source, runs the debate and chair rounds, and writes `reviews/council-<date>.md` plus comments. Advisory: the paper is never edited. Settings live in `reviews/council.json`; the Council panel over the PDF shows it live. See [docs/peer-review-council.md](docs/peer-review-council.md).
32
37
 
33
38
  Without sign-in, users move projects between devices with the `.zip` download and import, or through GitHub.
34
39
 
@@ -59,7 +64,7 @@ docker build -t lattedit-compile server
59
64
  docker run --rm -p 8080:8080 -e ALLOWED_ORIGINS=http://localhost:5173 lattedit-compile
60
65
  ```
61
66
 
62
- Tests: `npm test` at the root (the local MCP server, end to end), in `server/` (path safety, validation, limits, SyncTeX output, word count) and in `web/` (log parser, SyncTeX, tables, math detection, arXiv comments, GitHub links).
67
+ Tests: `npm test` at the root (the local MCP server and the council's prompts and sampling runner, end to end), in `server/` (path safety, validation, limits, SyncTeX output, word count) and in `web/` (log parser, SyncTeX, tables, math detection, arXiv comments, GitHub links, the council harness and its tools).
63
68
 
64
69
  ## Deploy
65
70
 
@@ -0,0 +1,163 @@
1
+ /**
2
+ * council_run: drive a whole peer-review council from this server, asking the client's
3
+ * model for each role's answer through MCP sampling (sampling/createMessage).
4
+ *
5
+ * This is the same harness an agent walks through by hand (council_start → council_brief
6
+ * → council_submit_* in web/src/lib/council.ts); here the server plays the agent:
7
+ *
8
+ * council_start
9
+ * for each phase (review, then debate if on):
10
+ * for each role: council_brief (json, complete) → sample(system, task) → parse JSON → council_submit_*
11
+ * on a rejected submission, send the model the error and ask again
12
+ * chair (if on): council_brief chair → sample → council_submit_meta
13
+ *
14
+ * Each role is its own sampling request with only its brief, so roles are isolated by
15
+ * construction. The client decides which model answers and may ask the person first.
16
+ */
17
+
18
+ /** Tries per role before giving up on it: the first answer plus corrections. */
19
+ export const MAX_ATTEMPTS = 3;
20
+
21
+ /**
22
+ * The JSON object in a model's reply: plain JSON, a ```json fence, or the first
23
+ * balanced {...} in prose. Throws if there isn't one.
24
+ */
25
+ export function extractJson(text) {
26
+ if (typeof text !== 'string' || !text.trim()) throw new Error('The reply was empty.');
27
+ const t = text.trim();
28
+ const candidates = [];
29
+ const fence = /```(?:json)?\s*\n([\s\S]*?)```/i.exec(t);
30
+ if (fence) candidates.push(fence[1]);
31
+ candidates.push(t);
32
+ const start = t.indexOf('{');
33
+ if (start >= 0) {
34
+ let depth = 0, inString = false, escaped = false;
35
+ for (let i = start; i < t.length; i++) {
36
+ const ch = t[i];
37
+ if (inString) {
38
+ if (escaped) escaped = false;
39
+ else if (ch === '\\') escaped = true;
40
+ else if (ch === '"') inString = false;
41
+ continue;
42
+ }
43
+ if (ch === '"') inString = true;
44
+ else if (ch === '{') depth++;
45
+ else if (ch === '}' && --depth === 0) { candidates.push(t.slice(start, i + 1)); break; }
46
+ }
47
+ }
48
+ for (const c of candidates) {
49
+ try {
50
+ const v = JSON.parse(c);
51
+ if (v && typeof v === 'object' && !Array.isArray(v)) return v;
52
+ } catch { /* next */ }
53
+ }
54
+ throw new Error('The reply did not contain a JSON object.');
55
+ }
56
+
57
+ /** The text of a sampling result (content may be one block or a list). */
58
+ export function sampledText(result) {
59
+ const c = result?.content;
60
+ const blocks = Array.isArray(c) ? c : c ? [c] : [];
61
+ return blocks.filter((b) => b?.type === 'text').map((b) => b.text).join('\n');
62
+ }
63
+
64
+ const SUBMIT = { review: 'council_submit_review', debate: 'council_submit_debate', chair: 'council_submit_meta' };
65
+
66
+ /** Read "Reviewers (n):\n- id: Name. …" from council_start's answer. */
67
+ export function rolesFrom(startText) {
68
+ const block = /Reviewers \(\d+\):\n((?:- .*\n?)+)/.exec(startText);
69
+ if (!block) return [];
70
+ return [...block[1].matchAll(/^- ([a-z][a-z0-9-]*): /gm)].map((m) => m[1]);
71
+ }
72
+
73
+ export function phaseFrom(statusText) {
74
+ return /Phase: (\w+)/.exec(statusText)?.[1] ?? null;
75
+ }
76
+
77
+ /**
78
+ * Run the council.
79
+ * deps.call(name, args) → { text, isError } a lattedit tool, as an agent would call it
80
+ * deps.sample(params) → MCP CreateMessageResult (throws if the client refuses)
81
+ * deps.progress?(done, total, message)
82
+ */
83
+ export async function runCouncil(args, deps) {
84
+ const { maxTokens = 8000, ...startArgs } = args ?? {};
85
+ const started = await deps.call('council_start', startArgs);
86
+ if (started.isError) return started;
87
+ const sessionId = /Started council (\S+) on/.exec(started.text)?.[1];
88
+ if (!sessionId) return { text: `council_start answered in a way this runner doesn't understand:\n${started.text}`, isError: true };
89
+ const roles = rolesFrom(started.text);
90
+ const debate = /Debate round: on/.test(started.text);
91
+ const chair = /Area chair: on/.test(started.text);
92
+ const total = roles.length * (debate ? 2 : 1) + (chair ? 1 : 0);
93
+ let done = 0;
94
+ let samples = 0;
95
+ const log = [];
96
+
97
+ const runRole = async (role, phase) => {
98
+ // complete: the sampled model has no tools, so it can't read_file what a normal brief leaves out.
99
+ const b = await deps.call('council_brief', { sessionId, role, format: 'json', complete: true });
100
+ if (b.isError) throw new Error(`council_brief for ${role}: ${b.text}`);
101
+ const brief = JSON.parse(b.text);
102
+ if (brief.omitted?.length) {
103
+ throw new Error(`The brief for ${role} leaves out ${brief.omitted.join(', ')}, and a sampled model can't read them; run the council with council_start instead.`);
104
+ }
105
+ if (brief.phase !== phase) throw new Error(`Expected the ${phase} round for ${role}, but the session is in the ${brief.phase} round.`);
106
+ const tool = SUBMIT[phase];
107
+ const messages = [{
108
+ role: 'user',
109
+ content: {
110
+ type: 'text',
111
+ text: `${brief.task}\n\nAnswer with only the JSON arguments for ${tool}: one JSON object, no prose before or after it.`,
112
+ },
113
+ }];
114
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
115
+ deps.progress?.(done, total, `${phase === 'chair' ? 'Area chair' : role}: ${phase}${attempt > 1 ? ` (try ${attempt})` : ''}`);
116
+ const result = await deps.sample({
117
+ messages,
118
+ systemPrompt: brief.system,
119
+ includeContext: 'none',
120
+ maxTokens,
121
+ temperature: phase === 'chair' ? 0.2 : 0.4,
122
+ modelPreferences: { intelligencePriority: 0.9, speedPriority: 0.2, costPriority: 0.2 },
123
+ metadata: { lattedit: 'council', sessionId, role, phase },
124
+ });
125
+ samples++;
126
+ const reply = sampledText(result);
127
+ let submitted;
128
+ try {
129
+ const parsed = extractJson(reply);
130
+ submitted = await deps.call(tool, { ...parsed, sessionId, ...(phase === 'chair' ? {} : { role }) });
131
+ } catch (e) {
132
+ submitted = { text: e.message, isError: true };
133
+ }
134
+ if (!submitted.isError) {
135
+ done++;
136
+ log.push(`${phase === 'chair' ? 'Area chair' : role}: ${submitted.text.split('\n')[0]}`);
137
+ return submitted;
138
+ }
139
+ if (attempt === MAX_ATTEMPTS) throw new Error(`${role} (${phase}) failed after ${MAX_ATTEMPTS} tries: ${submitted.text}`);
140
+ messages.push({ role: 'assistant', content: { type: 'text', text: reply || '(empty)' } });
141
+ messages.push({ role: 'user', content: { type: 'text', text: `lattedit rejected that:\n${submitted.text}\n\nSend the corrected JSON object only.` } });
142
+ }
143
+ throw new Error('unreachable');
144
+ };
145
+
146
+ let last = started;
147
+ try {
148
+ for (const role of roles) last = await runRole(role, 'review');
149
+ let status = await deps.call('council_status', { sessionId });
150
+ if (phaseFrom(status.text) === 'debate') {
151
+ for (const role of roles) last = await runRole(role, 'debate');
152
+ status = await deps.call('council_status', { sessionId });
153
+ }
154
+ if (phaseFrom(status.text) === 'chair') last = await runRole('chair', 'chair');
155
+ } catch (e) {
156
+ await deps.call('council_cancel', { sessionId });
157
+ return { text: `The council stopped: ${e.message}\nNothing was written to the project.${log.length ? `\n\nFiled before it stopped:\n${log.map((l) => `- ${l}`).join('\n')}` : ''}`, isError: true };
158
+ }
159
+ deps.progress?.(total, total, 'Done');
160
+ return {
161
+ text: [`Ran the council (session ${sessionId}) with ${samples} sampling request${samples === 1 ? '' : 's'}.`, ...log.map((l) => `- ${l}`), '', last.text].join('\n'),
162
+ };
163
+ }
package/cli/lattedit.mjs CHANGED
@@ -50,7 +50,7 @@ async function request(url, init) {
50
50
  async function main() {
51
51
  const args = process.argv.slice(2);
52
52
  if (args.length === 0 || args.includes('--help') || args.includes('-h')) return usage();
53
- if (args.includes('--version') || args.includes('-v')) return console.log('0.2.0');
53
+ if (args.includes('--version') || args.includes('-v')) return console.log('0.3.0');
54
54
 
55
55
  const command = args[0];
56
56
  if (command === 'mcp') {
package/cli/mcp-tools.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The tools lattedit offers coding agents over MCP. The lattedit tab carries them
3
- * out (web/src/lib/agentTools.ts); web/mcp-tools.js is a copy for the hosted relay,
4
- * and web/test/agentTools.test.ts checks that the copies match.
3
+ * out (web/src/lib/agentTools.ts), and web/test/agentTools.test.ts checks that
4
+ * each one has a handler there.
5
5
  */
6
6
 
7
7
  const projectId = {
@@ -13,7 +13,8 @@ const path = { type: 'string', description: 'Path inside the project, e.g. "main
13
13
  export const INSTRUCTIONS = `lattedit is a LaTeX editor. These tools read and change the person's lattedit projects in their open lattedit tab or desktop app, and compile them.
14
14
  Start with get_editor_context (what the person has open and selected) or list_projects. Read a file before editing it, and prefer edit_file (exact text replacement) over rewriting whole files.
15
15
  The person may be typing in the same files, and your edits appear live in their editor; re-read a file if an edit can't find its text. After changing LaTeX, run compile and fix the errors it reports.
16
- lattedit saves a version to History before your first edit in a while, so the person can undo your changes.`;
16
+ lattedit saves a version to History before your first edit in a while, so the person can undo your changes.
17
+ To review a paper rather than edit it, use the peer-review council: council_start, then follow the steps its answer gives (the council_review prompt does this for you).`;
17
18
 
18
19
  export const TOOLS = [
19
20
  {
@@ -158,3 +159,215 @@ export const TOOLS = [
158
159
  annotations: { readOnlyHint: true },
159
160
  },
160
161
  ];
162
+
163
+ /* ---------- the peer-review council (web/src/lib/council.ts) ---------- */
164
+
165
+ const sessionId = { type: 'string', description: 'The council session, from council_start.' };
166
+ const recommendation = { type: 'string', enum: ['ready', 'minor-revision', 'major-revision', 'not-ready'], description: 'Readiness for submission.' };
167
+ const roleId = { type: 'string', description: 'A council member\'s id from council_start: ultron (skeptic), friday (methods), u (clarity), edith (related work), dumb-e (ideas), jarvis, karen, pepper or a custom one; "vision" (the area chair) for council_brief. Names and jobs work too ("Ultron", "skeptic", "chair").' };
168
+
169
+ const councilOptions = {
170
+ projectId,
171
+ scope: { type: 'string', enum: ['document', 'section'], description: 'Review the whole document (default) or one section.' },
172
+ section: { type: 'string', description: 'With scope "section": the section title (partial is fine), its label (sec:methods) or its number (3, 3.2).' },
173
+ roles: { type: 'array', items: { type: 'string' }, description: 'Council members to seat, in order, by id, name or job: ultron (skeptic), friday (methods), u (clarity), edith (related work), dumb-e (ideas), and the optional jarvis (submission checker), karen (ethics), pepper (framing). Defaults to the project\'s council settings (reviews/council.json), else the first five.' },
174
+ debate: { type: 'boolean', description: 'Add a round where reviewers answer each other before the area chair. Defaults to on.' },
175
+ chair: { type: 'boolean', description: 'End with Vision, the area chair, writing the meta-review. Defaults to on.' },
176
+ venue: { type: 'string', description: 'Judge against this venue\'s standards, e.g. "NeurIPS" or "a PhD thesis".' },
177
+ focus: { type: 'string', description: 'What the person wants the council to pay attention to, in their words.' },
178
+ };
179
+
180
+ export const COUNCIL_TOOLS = [
181
+ {
182
+ name: 'council_start',
183
+ title: 'Start a peer-review council',
184
+ description: 'Start a peer-review council on a lattedit project: several reviewers played by you, each with one job (Ultron the skeptic, Friday on methods, U on clarity, Edith on related work, Dumb-E on ideas), then Vision\'s meta-review as area chair. Advisory: nothing in the paper changes. The answer is a step-by-step protocol; follow it.',
185
+ inputSchema: {
186
+ type: 'object',
187
+ properties: { ...councilOptions, restart: { type: 'boolean', description: 'Stop a council that is already running on this project and start over.' } },
188
+ additionalProperties: false,
189
+ },
190
+ },
191
+ {
192
+ name: 'council_brief',
193
+ title: 'Get a council role\'s brief',
194
+ description: 'The brief for one council role in the current round: its system prompt and the paper as numbered source (plus the other reviews in the debate round, and everything for the chair). Hand it to a subagent verbatim, or take on the role yourself.',
195
+ inputSchema: {
196
+ type: 'object',
197
+ required: ['sessionId', 'role'],
198
+ properties: {
199
+ sessionId,
200
+ role: roleId,
201
+ format: { type: 'string', enum: ['text', 'json'], default: 'text', description: '"json" returns {system, task, omitted} separately.' },
202
+ complete: { type: 'boolean', default: false, description: 'Include all the source however long, instead of leaving the largest files to read_file. For readers that cannot call tools.' },
203
+ },
204
+ additionalProperties: false,
205
+ },
206
+ annotations: { readOnlyHint: true },
207
+ },
208
+ {
209
+ name: 'council_submit_review',
210
+ title: 'Submit a council review',
211
+ description: 'File one reviewer\'s independent review. Every note with a location must give the file path, the line number from the numbered source and a quote copied exactly from that line. A new submission for the same role replaces the old one.',
212
+ inputSchema: {
213
+ type: 'object',
214
+ required: ['sessionId', 'role', 'summary', 'notes'],
215
+ properties: {
216
+ sessionId,
217
+ role: roleId,
218
+ summary: { type: 'string', description: '2–4 sentences: the overall assessment from this role\'s point of view.' },
219
+ strengths: { type: 'array', items: { type: 'string' }, maxItems: 6 },
220
+ recommendation,
221
+ notes: {
222
+ type: 'array',
223
+ items: {
224
+ type: 'object',
225
+ required: ['severity', 'title', 'body'],
226
+ properties: {
227
+ severity: { type: 'string', enum: ['major', 'minor', 'idea'] },
228
+ title: { type: 'string', description: 'One line.' },
229
+ body: { type: 'string', description: 'What is wrong and why it matters.' },
230
+ path: { type: 'string', description: 'File the note is about, e.g. "chapters/methods.tex".' },
231
+ line: { type: 'integer', minimum: 1, description: 'Line number from the numbered source.' },
232
+ quote: { type: 'string', description: 'Exact text from that line.' },
233
+ suggestion: { type: 'string', description: 'A concrete fix.' },
234
+ },
235
+ additionalProperties: false,
236
+ },
237
+ },
238
+ },
239
+ additionalProperties: false,
240
+ },
241
+ },
242
+ {
243
+ name: 'council_submit_debate',
244
+ title: 'Submit debate responses',
245
+ description: 'File one reviewer\'s answers to the other reviewers\' notes in the debate round: agree, disagree, refine, or withdraw (own notes only).',
246
+ inputSchema: {
247
+ type: 'object',
248
+ required: ['sessionId', 'role', 'responses'],
249
+ properties: {
250
+ sessionId,
251
+ role: roleId,
252
+ responses: {
253
+ type: 'array',
254
+ items: {
255
+ type: 'object',
256
+ required: ['noteId', 'stance', 'comment'],
257
+ properties: {
258
+ noteId: { type: 'string', description: 'e.g. "UL-1".' },
259
+ stance: { type: 'string', enum: ['agree', 'disagree', 'refine', 'withdraw'] },
260
+ comment: { type: 'string' },
261
+ },
262
+ additionalProperties: false,
263
+ },
264
+ },
265
+ },
266
+ additionalProperties: false,
267
+ },
268
+ },
269
+ {
270
+ name: 'council_submit_meta',
271
+ title: 'Submit the meta-review',
272
+ description: 'File the area chair\'s meta-review. lattedit then writes the full review to reviews/council-<date>.md and comments on the lines it points at, as the council settings say.',
273
+ inputSchema: {
274
+ type: 'object',
275
+ required: ['sessionId', 'summary', 'recommendation', 'items'],
276
+ properties: {
277
+ sessionId,
278
+ summary: { type: 'string', description: '3–6 sentences.' },
279
+ recommendation,
280
+ items: {
281
+ type: 'array',
282
+ items: {
283
+ type: 'object',
284
+ required: ['priority', 'title', 'body', 'noteIds'],
285
+ properties: {
286
+ priority: { type: 'string', enum: ['must', 'should', 'consider'] },
287
+ title: { type: 'string' },
288
+ body: { type: 'string', description: 'What the author should do.' },
289
+ noteIds: { type: 'array', items: { type: 'string' }, minItems: 1 },
290
+ path: { type: 'string', description: 'Optional: where to comment; defaults to the first note\'s location.' },
291
+ line: { type: 'integer', minimum: 1 },
292
+ },
293
+ additionalProperties: false,
294
+ },
295
+ },
296
+ dismissed: {
297
+ type: 'array',
298
+ items: {
299
+ type: 'object', required: ['noteId', 'reason'],
300
+ properties: { noteId: { type: 'string' }, reason: { type: 'string' } },
301
+ additionalProperties: false,
302
+ },
303
+ },
304
+ },
305
+ additionalProperties: false,
306
+ },
307
+ },
308
+ {
309
+ name: 'council_status',
310
+ title: 'Council status',
311
+ description: 'Where a council stands: who has filed, the phase, and what to do next. Without sessionId, the latest council on the open project.',
312
+ inputSchema: { type: 'object', properties: { sessionId, projectId }, additionalProperties: false },
313
+ annotations: { readOnlyHint: true },
314
+ },
315
+ {
316
+ name: 'council_cancel',
317
+ title: 'Stop a council',
318
+ description: 'Stop a running council. Nothing is written to the project.',
319
+ inputSchema: { type: 'object', required: ['sessionId'], properties: { sessionId }, additionalProperties: false },
320
+ },
321
+ ];
322
+
323
+ TOOLS.push(...COUNCIL_TOOLS);
324
+
325
+ /**
326
+ * Tools this server carries out itself instead of passing them to the tab.
327
+ * council_run drives a whole council through MCP sampling (cli/council-run.mjs), when the client offers it.
328
+ */
329
+ export const LOCAL_TOOLS = [
330
+ {
331
+ name: 'council_run',
332
+ title: 'Run the whole council',
333
+ description: 'Run a complete peer-review council in one call, with each role answered through MCP sampling by the model your client chooses. Only works in clients that support sampling; otherwise use the council_review prompt, or council_start and the steps it gives.',
334
+ inputSchema: {
335
+ type: 'object',
336
+ properties: { ...councilOptions, restart: { type: 'boolean' }, maxTokens: { type: 'integer', minimum: 1000, maximum: 32000, default: 8000, description: 'Token limit for each role\'s answer.' } },
337
+ additionalProperties: false,
338
+ },
339
+ },
340
+ ];
341
+
342
+ /** MCP prompts: in Claude Code they show up as /mcp__lattedit__council_review. */
343
+ export const PROMPTS = [
344
+ {
345
+ name: 'council_review',
346
+ title: 'Peer-review council',
347
+ description: 'Review the paper open in lattedit with the council: Ultron (skeptic), Friday (methods), U (clarity), Edith (related work), Dumb-E (ideas), and Vision as area chair. Advisory: the paper is not changed.',
348
+ arguments: [
349
+ { name: 'section', description: 'Review only this section (title, label or number). Leave empty for the whole document.', required: false },
350
+ { name: 'focus', description: 'Anything the council should pay attention to.', required: false },
351
+ { name: 'venue', description: 'Judge against this venue, e.g. "NeurIPS".', required: false },
352
+ ],
353
+ },
354
+ ];
355
+
356
+ /** The text of a prompt, filled in with its arguments. */
357
+ export function promptMessages(name, args = {}) {
358
+ if (name !== 'council_review') return null;
359
+ const opts = {};
360
+ if (args.section?.trim()) { opts.scope = 'section'; opts.section = args.section.trim(); }
361
+ if (args.focus?.trim()) opts.focus = args.focus.trim();
362
+ if (args.venue?.trim()) opts.venue = args.venue.trim();
363
+ const text = [
364
+ `Run lattedit's peer-review council on the paper open in lattedit${opts.section ? `, section "${opts.section}"` : ''}.`,
365
+ '',
366
+ `1. Call the lattedit tool council_start with ${Object.keys(opts).length ? JSON.stringify(opts) : 'no arguments'}. If it says a council is already running, ask me whether to continue it or restart.`,
367
+ '2. Its answer is a protocol. Follow it step by step: briefs, submissions, the debate round and the area chair, until lattedit says the review is written.',
368
+ '3. Keep the roles isolated. With subagents, start one per role and give it only the instruction the protocol quotes. Without them, do one role at a time from its brief alone.',
369
+ '4. If a submission comes back with problems (a quote not found, a line out of range, too many notes), fix exactly those and submit again.',
370
+ '5. When it is done, tell me the recommendation and the must-address items, each with its file and line, and where the full review is. Do not change the paper unless I ask.',
371
+ ].join('\n');
372
+ return { description: 'Peer-review council', messages: [{ role: 'user', content: { type: 'text', text } }] };
373
+ }
package/cli/mcp.mjs CHANGED
@@ -22,9 +22,10 @@ import { createServer } from 'node:http';
22
22
  import { createHash, randomUUID } from 'node:crypto';
23
23
  import { mkdir, writeFile } from 'node:fs/promises';
24
24
  import { dirname, resolve } from 'node:path';
25
- import { INSTRUCTIONS, TOOLS } from './mcp-tools.mjs';
25
+ import { INSTRUCTIONS, LOCAL_TOOLS, PROMPTS, TOOLS, promptMessages } from './mcp-tools.mjs';
26
+ import { runCouncil } from './council-run.mjs';
26
27
 
27
- const VERSION = '0.2.0';
28
+ const VERSION = '0.3.0';
28
29
  const PORT = Number(process.env.LATTEDIT_BRIDGE_PORT) || 47824;
29
30
  const ORIGINS = new Set([
30
31
  'https://lattedit.xyz', 'https://www.lattedit.xyz',
@@ -36,6 +37,8 @@ const ORIGINS = new Set([
36
37
  const CONNECT_WAIT_MS = 10_000;
37
38
  const CALL_TIMEOUT_MS = 30_000;
38
39
  const COMPILE_TIMEOUT_MS = 200_000;
40
+ /** A sampling request waits on a model, and maybe on the person approving it. */
41
+ const SAMPLING_TIMEOUT_MS = 10 * 60_000;
39
42
  const MAX_MESSAGE = 96 * 1024 * 1024;
40
43
 
41
44
  const log = (...a) => console.error('[lattedit mcp]', ...a);
@@ -288,10 +291,52 @@ async function call(name, args) {
288
291
 
289
292
  /* ---------- MCP over stdio ---------- */
290
293
 
291
- function reply(id, result) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\n'); }
292
- function fail(id, code, message) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: id ?? null, error: { code, message } }) + '\n'); }
294
+ function send(msg) { process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...msg }) + '\n'); }
295
+ function reply(id, result) { send({ id, result }); }
296
+ function fail(id, code, message) { send({ id: id ?? null, error: { code, message } }); }
293
297
 
294
- async function runTool(name, args) {
298
+ /* Requests this server sends the client (sampling), and their answers. */
299
+ let clientCapabilities = {};
300
+ let nextRequest = 0;
301
+ const clientPending = new Map();
302
+
303
+ function requestClient(method, params, timeoutMs = SAMPLING_TIMEOUT_MS) {
304
+ const id = `lattedit-${++nextRequest}`;
305
+ return new Promise((done, failed) => {
306
+ const timer = setTimeout(() => { clientPending.delete(id); failed(new Error(`The client didn't answer ${method} in time.`)); }, timeoutMs);
307
+ clientPending.set(id, { done, failed, timer });
308
+ send({ id, method, params });
309
+ });
310
+ }
311
+
312
+ function onClientResponse(msg) {
313
+ const p = clientPending.get(msg.id);
314
+ if (!p) return;
315
+ clientPending.delete(msg.id);
316
+ clearTimeout(p.timer);
317
+ if (msg.error) p.failed(new Error(msg.error.message || 'The client refused the request.'));
318
+ else p.done(msg.result);
319
+ }
320
+
321
+ async function runLocalTool(name, args, progressToken) {
322
+ if (name !== 'council_run') return { text: `Unknown tool: ${name}`, isError: true };
323
+ if (!clientCapabilities.sampling) {
324
+ return {
325
+ text: 'This MCP client does not offer sampling, so lattedit cannot ask your model for each role directly. '
326
+ + 'Run the council yourself instead: call council_start and follow the steps it returns (or use the council_review prompt).',
327
+ isError: true,
328
+ };
329
+ }
330
+ return runCouncil(args, {
331
+ call: (tool, a) => call(tool, a),
332
+ sample: (params) => requestClient('sampling/createMessage', params),
333
+ progress: progressToken === undefined ? undefined
334
+ : (progress, total, message) => send({ method: 'notifications/progress', params: { progressToken, progress, total, message } }),
335
+ });
336
+ }
337
+
338
+ async function runTool(name, args, progressToken) {
339
+ if (LOCAL_TOOLS.some((t) => t.name === name)) return runLocalTool(name, args, progressToken);
295
340
  if (!TOOLS.some((t) => t.name === name)) return { text: `Unknown tool: ${name}`, isError: true };
296
341
  if (name !== 'compile' || !args.savePdfTo) return call(name, args);
297
342
  const { savePdfTo, ...rest } = args;
@@ -308,24 +353,31 @@ async function runTool(name, args) {
308
353
 
309
354
  async function handle(msg) {
310
355
  const { id, method, params } = msg;
356
+ if (method === undefined && id !== undefined) return onClientResponse(msg);
311
357
  if (method === 'initialize') {
312
358
  const client = params?.clientInfo;
359
+ clientCapabilities = params?.capabilities ?? {};
313
360
  myAgent = client?.title || client?.name || 'agent';
314
361
  if (relay?.readyState === 1) relay.send(JSON.stringify({ type: 'hello', agent: myAgent }));
315
362
  announceAgents();
316
363
  const asked = params?.protocolVersion;
317
364
  return reply(id, {
318
365
  protocolVersion: ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'].includes(asked) ? asked : '2025-06-18',
319
- capabilities: { tools: { listChanged: false } },
366
+ capabilities: { tools: { listChanged: false }, prompts: { listChanged: false } },
320
367
  serverInfo: { name: 'lattedit', title: 'lattedit', version: VERSION },
321
368
  instructions: INSTRUCTIONS,
322
369
  });
323
370
  }
324
371
  if (method === 'ping') return reply(id, {});
325
- if (method === 'tools/list') return reply(id, { tools: TOOLS });
372
+ if (method === 'tools/list') return reply(id, { tools: [...TOOLS, ...LOCAL_TOOLS] });
373
+ if (method === 'prompts/list') return reply(id, { prompts: PROMPTS });
374
+ if (method === 'prompts/get') {
375
+ const p = promptMessages(params?.name, params?.arguments ?? {});
376
+ return p ? reply(id, p) : fail(id, -32602, `Unknown prompt: ${params?.name}`);
377
+ }
326
378
  if (method === 'tools/call') {
327
379
  try {
328
- const r = await runTool(params?.name, params?.arguments ?? {});
380
+ const r = await runTool(params?.name, params?.arguments ?? {}, params?._meta?.progressToken);
329
381
  return reply(id, { content: [{ type: 'text', text: r.text }], isError: !!r.isError });
330
382
  } catch (e) {
331
383
  return reply(id, { content: [{ type: 'text', text: e.message }], isError: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lattedit-cli",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Official command-line client and MCP server for lattedit: compile LaTeX, and let coding agents edit your lattedit projects",
5
5
  "type": "module",
6
6
  "bin": {
@@ -9,10 +9,11 @@
9
9
  "files": [
10
10
  "cli/lattedit.mjs",
11
11
  "cli/mcp.mjs",
12
- "cli/mcp-tools.mjs"
12
+ "cli/mcp-tools.mjs",
13
+ "cli/council-run.mjs"
13
14
  ],
14
15
  "scripts": {
15
- "test": "node --test cli/mcp.test.mjs"
16
+ "test": "node --test cli/mcp.test.mjs cli/council-run.test.mjs"
16
17
  },
17
18
  "keywords": [
18
19
  "latex",