lattedit-cli 0.0.0-stage → 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
@@ -1,3 +1,152 @@
1
- # Temporary Holding Version
1
+ # lattedit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An online LaTeX editor: write source on the left, read the PDF on the right. *LaTeX, freshly compiled.*
4
+
5
+ ```
6
+ web/ React + Vite frontend → Vercel
7
+ server/ Node + TeX Live compile service (Docker) → Render
8
+ desktop/ Tauri shell around web/ for Linux, macOS and Windows (see desktop/README.md)
9
+ render.yaml Render Blueprint for server/
10
+ ```
11
+
12
+ Projects live in the user's browser (IndexedDB). Optional Supabase sign-in syncs a copy across devices. For fast editing, the compile server keeps a bounded, short-lived workspace identified by a random tab-local key. It reuses LaTeX auxiliary state for edits and skips TeX entirely for an exact repeat. Workspaces expire after ten minutes and disappear whenever Render restarts or redeploys.
13
+
14
+ ## What works
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.
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.
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`).
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`).
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.
24
+ - Files: folders, upload by button or drag and drop (images, PDFs, `.bib`, `.sty`…), rename, delete, set the main document.
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.
26
+ - Logs: errors, warnings and bad boxes parsed with plain-language hints, gutter markers in the editor, and a click to jump to the line (across files).
27
+ - PDF: pdf.js preview with paging, zoom and fit, rendering only the pages in view; the last PDF is cached per project.
28
+ - SyncTeX: double-click the PDF to open that line of the source; Ctrl Alt J (⌘ ⌥ J) or the locate button shows the cursor's line in the PDF. The compile server returns the `.synctex.gz` and the browser reads it (`web/src/lib/synctex.ts`).
29
+ - Word count: texcount on the server (`POST /wordcount`, same body as `/compile`), with totals and words per section.
30
+ - History: lattedit saves versions in the browser as you work (every ten minutes while editing, after a successful compile, before restores, pulls and AI changes) and when you name one. Compare any version with the project now, restore all of it or one file, or download it. File contents are stored once and shared between versions; named versions are kept, plus the last 60 others.
31
+ - Downloads: source `.zip`, PDF, an arXiv-ready `.zip` (comments removed from `.tex` files, the `.bbl` beside the main file), the compile log and the `.bbl`.
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.
33
+ - Latte (light) and Espresso (dark) themes, resizable panes, and a one-pane layout with a file drawer on phones.
34
+
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).
37
+
38
+ Without sign-in, users move projects between devices with the `.zip` download and import, or through GitHub.
39
+
40
+ ## Run locally
41
+
42
+ Requires Node 20+ and a TeX Live install with `latexmk` (or Docker).
43
+
44
+ ```bash
45
+ cd server && npm install && npm run dev
46
+ ```
47
+
48
+ ```bash
49
+ cd web && npm install && npm run dev
50
+ ```
51
+
52
+ Configuration comes from environment variables. Keep them in `.env` files, which git ignores and the repository doesn't include:
53
+
54
+ - `web/.env.local` (and the build environment, such as Vercel): `VITE_COMPILE_URL` (the compile server, no trailing slash, for example `http://localhost:8080`), and optionally `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY` (the browser-safe publishable key), `VITE_AUTH_ENABLED` and `VITE_CLARITY_ID`.
55
+ - `server/.env` (and the Render dashboard): `ALLOWED_ORIGINS` (comma-separated), `PORT`, `COMPILE_TIMEOUT_MS`, `MAX_CONCURRENT`, `MAX_QUEUE`, `RATE_PER_MINUTE`, `MAX_BODY`, `MAX_FILES`; for the AI agent `SARVAM_API_KEY` (secret), `SUPABASE_URL`, `SUPABASE_ANON_KEY` and `AI_DAILY_LIMIT`.
56
+
57
+ The editor opens at http://localhost:5173 and compiles against `VITE_COMPILE_URL`. To run the server with the same TeX Live as production instead:
58
+
59
+ ```bash
60
+ docker build -t lattedit-compile server
61
+ ```
62
+
63
+ ```bash
64
+ docker run --rm -p 8080:8080 -e ALLOWED_ORIGINS=http://localhost:5173 lattedit-compile
65
+ ```
66
+
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).
68
+
69
+ ## Deploy
70
+
71
+ **Everything on Render:** `render.yaml` deploys both the compile server and the web app (as a static site) on the free plan. In Render choose **New → Blueprint**, pick this repo, and apply. The steps below are for the split setup (server on Render, web on Vercel).
72
+
73
+ ### 1. Compile server on Render
74
+
75
+ 1. Push this repository to the Git provider connected to Render.
76
+ 2. In Render, choose **New → Blueprint** and pick the repo; it reads `render.yaml`.
77
+ 3. When asked for `ALLOWED_ORIGINS`, enter your Vercel URL (you can come back and add a custom domain later, comma-separated).
78
+ 4. The first build takes a while: the image carries TeX Live (a few GB).
79
+ 5. Check `https://<your-service>.onrender.com/health`. It should return `{"ok":true,...}`.
80
+
81
+ The Blueprint uses the **Free** plan. Free instances sleep when idle, so the first compile after a break can take about a minute while the server wakes; opening the dashboard or editor starts waking it immediately.
82
+
83
+ ### 2. Frontend on Vercel
84
+
85
+ 1. In Vercel, import the same repo and set **Root Directory** to `web`. Vite is detected; `web/vercel.json` sets the build and the single-page-app rewrite.
86
+ 2. Add the environment variable `VITE_COMPILE_URL` = `https://<your-service>.onrender.com` (no trailing slash).
87
+ 3. Deploy. If you change the URL later, redeploy, because Vite bakes it in at build time.
88
+
89
+ ### 3. Optional account sync
90
+
91
+ Run `supabase/schema.sql` in the Supabase SQL editor (it is safe to run again to upgrade; run it again after updating to allow live co-editing). It creates `lattedit_projects`, `lattedit_files`, `lattedit_members` and `lattedit_comments`, enables row level security, and adds the tables to Supabase Realtime.
92
+
93
+ Signed-in owners can share a project from **Share**: invite people by the email they sign in with, as **Can view**, **Can comment** or **Can edit**, up to 7 people per project including the owner. General access is **Private** (only invited people) or **Public** (anyone with the link can view, signed in or not; only invited editors can edit). The database enforces all of this: roles, the 7-person cap, and that only the owner shares or changes visibility. Everyone on a project but viewers can comment: select text and press **Add comment** (Ctrl Alt M, ⌘ ⌥ M on a Mac), reply, and resolve threads. Comments stay attached to the quoted text as lines move, and the database only lets authors edit their own comments (authors and the owner can delete). People who open a public link don't see comments. The AI agent runs on the compile server with Sarvam (`sarvam-105b`). The model answers with SEARCH/REPLACE edits rather than JSON, so LaTeX reaches the file exactly as written; the server then adds any missing `\usepackage` lines for well-known commands, checks environments, braces and Unicode, compiles the edited project, and sends what's still wrong back to the model for up to two repair rounds (`AI_MAX_REPAIRS`) before answering (`server/src/ai.js`). It is for signed-in people only, with 15 prompts per person per day (`AI_DAILY_LIMIT`), counted in `lattedit_ai_usage` and reset at midnight UTC; only answered prompts count. The compile server needs `SARVAM_API_KEY` (secret, Render dashboard) and `SUPABASE_URL` / `SUPABASE_ANON_KEY` (the same public values as the web app) to check sign-ins. Collaborators see each other's saves and who else has the project open, live. People who can edit a project also share what they type as they type it: each open project has a Yjs document carried over a private Realtime broadcast channel (`lattedit:collab:<project id>`, owners and editors only; see `supabase/schema.sql`), so edits to the same file merge and everyone sees the others' cursors (`web/src/lib/collab.ts`). Files are still saved as before; if the channel can't be joined (for example before the schema is upgraded), editing falls back to file-by-file merging, where the newest save of a file wins. Set `VITE_SUPABASE_URL` and `VITE_SUPABASE_ANON_KEY` in Vercel using the project URL and a browser-safe publishable key. Do not use the secret or service-role key.
94
+
95
+ Set the Supabase Auth Site URL to the production origin and allow the origins used by the app as redirect URLs. After configuring the Google provider, set `VITE_AUTH_ENABLED=true` in Vercel and redeploy. Until then, the sign-in control stays hidden, no Supabase client or session handling runs, and projects remain entirely in the browser.
96
+
97
+ ### 4. Optional analytics
98
+
99
+ Set `VITE_CLARITY_ID` to a Microsoft Clarity project ID in Vercel and redeploy. Analytics then loads automatically on every page. Use Strict masking in the Clarity project so document text is never sent in session recordings.
100
+
101
+ ## Server settings
102
+
103
+ | Variable | Default | What it does |
104
+ | --- | --- | --- |
105
+ | `ALLOWED_ORIGINS` | `http://localhost:5173` | Comma-separated origins allowed to call the API |
106
+ | `COMPILE_TIMEOUT_MS` | `120000` | A compile is killed after this |
107
+ | `MAX_CONCURRENT` | `2` | Compiles running at once; more wait in a queue |
108
+ | `MAX_QUEUE` | `8` | Waiting compiles before the server answers 503 |
109
+ | `WORKSPACE_TTL_MS` | `600000` | Idle time before incremental build state is removed |
110
+ | `MAX_WORKSPACES` | `12` | Maximum short-lived workspaces retained per instance |
111
+ | `RATE_PER_MINUTE` | `20` | Compiles per IP per minute |
112
+ | `MAX_BODY` | `25mb` | Largest project upload |
113
+ | `MAX_FILES` | `300` | Most files in one project |
114
+
115
+ ## Security notes
116
+
117
+ - Shell escape is off (`shell_escape=f`), and TeX may only read and write inside the project folder (`openin_any=p`, `openout_any=p`).
118
+ - File paths are checked: no absolute paths, no `..`, no dot-files (so no `.latexmkrc`).
119
+ - Each browser tab compiles as the unprivileged `node` user in an isolated, randomly keyed temp folder. The server retains at most 12 folders for 10 minutes and kills timed-out process groups.
120
+ - CORS limits which sites can call the API, but anyone can still script requests directly. The per-IP rate limit and the queue keep that bounded. Add an auth token or a proxy if abuse becomes a problem.
121
+
122
+ ## Storage notes
123
+
124
+ Browsers can evict site data under storage pressure. The app asks for persistent storage and shows usage on the dashboard, but the `.zip` download is the real backup. Tell users that clearing site data deletes their projects.
125
+
126
+ ## API
127
+
128
+ The stable compile API is served from `https://lattedit.xyz/api/v1` and described by the machine-readable [OpenAPI 3.1 contract](https://lattedit.xyz/openapi.json). It requires no API key. `POST /api/v1/compile` accepts:
129
+
130
+ ```json
131
+ {
132
+ "compiler": "pdflatex",
133
+ "main": "main.tex",
134
+ "workspaceKey": "random-browser-generated-capability",
135
+ "stopOnFirstError": false,
136
+ "files": [
137
+ { "path": "main.tex", "content": "\\documentclass{article}...", "encoding": "utf8" },
138
+ { "path": "figures/plot.png", "content": "<base64>", "encoding": "base64" }
139
+ ]
140
+ }
141
+ ```
142
+
143
+ The response is `{ status, pdf, log, durationMs, syncMs, engineMs, cache }`. `cache` is `cold`, `incremental`, `exact`, or `none`; an exact response does not start TeX. `status` is `success`, `error` (compiled with errors; a PDF may still exist), `failure` (no PDF), or `timeout`. `pdf` is base64 or `null`. Bad requests use RFC 9457 problem details with stable `code`, `detail`, and `resolution` fields.
144
+
145
+ `GET /api/v1/health` returns `{ ok, tex, busy, queued }`.
146
+
147
+ The zero-dependency CLI is included for local use:
148
+
149
+ ```bash
150
+ node cli/lattedit.mjs health
151
+ node cli/lattedit.mjs compile project.json --output paper.pdf
152
+ ```
@@ -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
+ }
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFile, writeFile } from 'node:fs/promises';
4
+ import { basename, resolve } from 'node:path';
5
+
6
+ const DEFAULT_API = 'https://lattedit.xyz/api/v1';
7
+
8
+ function usage() {
9
+ console.log(`lattedit - compile LaTeX through the lattedit API
10
+
11
+ Usage:
12
+ lattedit health [--api URL]
13
+ lattedit compile PROJECT.json [--output FILE.pdf] [--api URL]
14
+ lattedit mcp
15
+
16
+ PROJECT.json follows https://lattedit.xyz/openapi.json. It must contain main
17
+ and files; compiler, workspaceKey, and stopOnFirstError are optional.
18
+
19
+ mcp runs an MCP server (stdio) that lets a coding agent read, edit and compile
20
+ your lattedit projects in your open lattedit tab or desktop app. Add it to your
21
+ agent, then turn on Coding agents in lattedit's account menu:
22
+ claude mcp add lattedit -- npx -y lattedit-cli mcp
23
+ codex mcp add lattedit -- npx -y lattedit-cli mcp
24
+
25
+ Examples:
26
+ lattedit health
27
+ lattedit compile project.json --output paper.pdf`);
28
+ }
29
+
30
+ function option(args, name) {
31
+ const index = args.indexOf(name);
32
+ if (index === -1) return null;
33
+ if (!args[index + 1] || args[index + 1].startsWith('--')) throw new Error(`${name} needs a value.`);
34
+ return args[index + 1];
35
+ }
36
+
37
+ async function request(url, init) {
38
+ const response = await fetch(url, init);
39
+ const text = await response.text();
40
+ let body;
41
+ try { body = JSON.parse(text); } catch { throw new Error(`The server returned non-JSON (${response.status}).`); }
42
+ if (!response.ok) {
43
+ const detail = body.detail || body.message || response.statusText;
44
+ const resolution = body.resolution ? ` ${body.resolution}` : '';
45
+ throw new Error(`${body.code || `http_${response.status}`}: ${detail}${resolution}`);
46
+ }
47
+ return body;
48
+ }
49
+
50
+ async function main() {
51
+ const args = process.argv.slice(2);
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.3.0');
54
+
55
+ const command = args[0];
56
+ if (command === 'mcp') {
57
+ const { serveMcp } = await import('./mcp.mjs');
58
+ return serveMcp();
59
+ }
60
+ const api = (option(args, '--api') || process.env.LATTEDIT_API || DEFAULT_API).replace(/\/$/, '');
61
+
62
+ if (command === 'health') {
63
+ const health = await request(`${api}/health`);
64
+ console.log(JSON.stringify(health, null, 2));
65
+ return;
66
+ }
67
+
68
+ if (command === 'compile') {
69
+ const inputPath = args[1];
70
+ if (!inputPath || inputPath.startsWith('--')) throw new Error('compile needs a PROJECT.json file.');
71
+ const project = JSON.parse(await readFile(resolve(inputPath), 'utf8'));
72
+ const result = await request(`${api}/compile`, {
73
+ method: 'POST',
74
+ headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
75
+ body: JSON.stringify(project),
76
+ });
77
+ const output = resolve(option(args, '--output') || `${basename(inputPath, '.json')}.pdf`);
78
+ if (result.pdf) {
79
+ await writeFile(output, Buffer.from(result.pdf, 'base64'));
80
+ console.log(`PDF: ${output}`);
81
+ }
82
+ console.log(`Status: ${result.status}`);
83
+ console.log(`Compile: ${result.durationMs} ms (${result.cache} cache, ${result.engineMs} ms TeX)`);
84
+ if (result.status !== 'success') {
85
+ if (result.log) console.error(result.log);
86
+ process.exitCode = 2;
87
+ }
88
+ return;
89
+ }
90
+
91
+ throw new Error(`Unknown command: ${command}`);
92
+ }
93
+
94
+ main().catch((error) => {
95
+ console.error(`lattedit: ${error.message}`);
96
+ process.exitCode = 1;
97
+ });
@@ -0,0 +1,373 @@
1
+ /**
2
+ * The tools lattedit offers coding agents over MCP. The lattedit tab carries them
3
+ * out (web/src/lib/agentTools.ts), and web/test/agentTools.test.ts checks that
4
+ * each one has a handler there.
5
+ */
6
+
7
+ const projectId = {
8
+ type: 'string',
9
+ description: 'The project to work on (see list_projects). Defaults to the project open in the lattedit editor.',
10
+ };
11
+ const path = { type: 'string', description: 'Path inside the project, e.g. "main.tex" or "chapters/intro.tex".' };
12
+
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
+ 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
+ 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.
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).`;
18
+
19
+ export const TOOLS = [
20
+ {
21
+ name: 'get_editor_context',
22
+ title: 'What the person has open',
23
+ description: 'The project and file open in the lattedit editor, the cursor line and the selected text. Call this first when the person refers to "this", "here" or "the selection".',
24
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
25
+ annotations: { readOnlyHint: true },
26
+ },
27
+ {
28
+ name: 'list_projects',
29
+ title: 'List projects',
30
+ description: 'All lattedit projects with their ids, main documents and which one is open in the editor.',
31
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
32
+ annotations: { readOnlyHint: true },
33
+ },
34
+ {
35
+ name: 'open_project',
36
+ title: 'Open a project',
37
+ description: 'Open a project in the lattedit editor so the person can watch the changes.',
38
+ inputSchema: { type: 'object', required: ['projectId'], properties: { projectId }, additionalProperties: false },
39
+ },
40
+ {
41
+ name: 'create_project',
42
+ title: 'Create a project',
43
+ description: 'Create a new lattedit project, optionally with files, and open it. Without files it starts from a blank article.',
44
+ inputSchema: {
45
+ type: 'object',
46
+ required: ['name'],
47
+ properties: {
48
+ name: { type: 'string', description: 'Project name.' },
49
+ files: {
50
+ type: 'array',
51
+ description: 'Text files to create.',
52
+ items: {
53
+ type: 'object', required: ['path', 'content'], additionalProperties: false,
54
+ properties: { path, content: { type: 'string' } },
55
+ },
56
+ },
57
+ mainFile: { type: 'string', description: 'The document to compile. Defaults to main.tex or the first .tex file.' },
58
+ compiler: { type: 'string', enum: ['pdflatex', 'xelatex', 'lualatex'], default: 'pdflatex' },
59
+ open: { type: 'boolean', default: true, description: 'Open it in the editor.' },
60
+ },
61
+ additionalProperties: false,
62
+ },
63
+ },
64
+ {
65
+ name: 'list_files',
66
+ title: 'List files',
67
+ description: 'The files in a project, with sizes, and which one is the main document.',
68
+ inputSchema: { type: 'object', properties: { projectId }, additionalProperties: false },
69
+ annotations: { readOnlyHint: true },
70
+ },
71
+ {
72
+ name: 'read_file',
73
+ title: 'Read a file',
74
+ description: 'Read a text file as it is now, including unsaved typing in the editor. Long files: pass offset (1-based line) and limit.',
75
+ inputSchema: {
76
+ type: 'object',
77
+ required: ['path'],
78
+ properties: {
79
+ projectId, path,
80
+ offset: { type: 'integer', minimum: 1, description: 'First line to read.' },
81
+ limit: { type: 'integer', minimum: 1, description: 'Number of lines to read.' },
82
+ },
83
+ additionalProperties: false,
84
+ },
85
+ annotations: { readOnlyHint: true },
86
+ },
87
+ {
88
+ name: 'edit_file',
89
+ title: 'Edit a file',
90
+ description: 'Replace exact text in a file. old_string must match the file exactly (whitespace included) and occur once, unless replace_all is set.',
91
+ inputSchema: {
92
+ type: 'object',
93
+ required: ['path', 'old_string', 'new_string'],
94
+ properties: {
95
+ projectId, path,
96
+ old_string: { type: 'string', description: 'The text to replace.' },
97
+ new_string: { type: 'string', description: 'The replacement.' },
98
+ replace_all: { type: 'boolean', default: false },
99
+ },
100
+ additionalProperties: false,
101
+ },
102
+ },
103
+ {
104
+ name: 'write_file',
105
+ title: 'Write a file',
106
+ description: 'Create a text file, or replace all of one. Prefer edit_file for changes to an existing file.',
107
+ inputSchema: {
108
+ type: 'object',
109
+ required: ['path', 'content'],
110
+ properties: { projectId, path, content: { type: 'string' } },
111
+ additionalProperties: false,
112
+ },
113
+ },
114
+ {
115
+ name: 'delete_file',
116
+ title: 'Delete a file',
117
+ description: 'Delete a file from a project. The main document cannot be deleted.',
118
+ inputSchema: { type: 'object', required: ['path'], properties: { projectId, path }, additionalProperties: false },
119
+ annotations: { destructiveHint: true },
120
+ },
121
+ {
122
+ name: 'rename_file',
123
+ title: 'Rename or move a file',
124
+ description: 'Rename or move a file inside a project.',
125
+ inputSchema: {
126
+ type: 'object',
127
+ required: ['from', 'to'],
128
+ properties: { projectId, from: path, to: path },
129
+ additionalProperties: false,
130
+ },
131
+ },
132
+ {
133
+ name: 'update_project',
134
+ title: 'Change project settings',
135
+ description: 'Rename a project, set its main document, or switch its compiler.',
136
+ inputSchema: {
137
+ type: 'object',
138
+ properties: {
139
+ projectId,
140
+ name: { type: 'string' },
141
+ mainFile: path,
142
+ compiler: { type: 'string', enum: ['pdflatex', 'xelatex', 'lualatex'] },
143
+ },
144
+ additionalProperties: false,
145
+ },
146
+ },
147
+ {
148
+ name: 'compile',
149
+ title: 'Compile',
150
+ description: 'Compile the project as the editor does (the PDF pane updates) and report the status with each error and warning by file and line.',
151
+ inputSchema: {
152
+ type: 'object',
153
+ properties: {
154
+ projectId,
155
+ savePdfTo: { type: 'string', description: 'Local server only: also save the PDF to this path on this computer.' },
156
+ },
157
+ additionalProperties: false,
158
+ },
159
+ annotations: { readOnlyHint: true },
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 ADDED
@@ -0,0 +1,408 @@
1
+ /**
2
+ * `lattedit mcp`: an MCP server (stdio) that lets a coding agent such as Claude Code,
3
+ * Codex or Cursor read, edit and compile the person's lattedit projects.
4
+ *
5
+ * Projects live in the person's lattedit tab (or the desktop app), so this server is
6
+ * a bridge. It listens on 127.0.0.1:47824; the tab connects to it once the person
7
+ * turns on "Coding agents" in lattedit, and each tool call is carried out there
8
+ * (web/src/lib/agentTools.ts), live in the editor.
9
+ *
10
+ * Several agents can run at once: the first server owns the port (the hub) and the
11
+ * others connect to it and relay their calls through it. When the hub exits, the
12
+ * next one takes the port over.
13
+ *
14
+ * agent ── stdio ── lattedit mcp (hub) ── ws://127.0.0.1:47824/editor ── lattedit tab
15
+ * other agent ── stdio ── lattedit mcp ──┘ /agent
16
+ *
17
+ * Only the lattedit site (and the desktop app, and the dev server) may connect as an
18
+ * editor: browsers always send Origin, and the hub checks it. Relaying agents are
19
+ * local processes, which never send one.
20
+ */
21
+ import { createServer } from 'node:http';
22
+ import { createHash, randomUUID } from 'node:crypto';
23
+ import { mkdir, writeFile } from 'node:fs/promises';
24
+ import { dirname, resolve } from 'node:path';
25
+ import { INSTRUCTIONS, LOCAL_TOOLS, PROMPTS, TOOLS, promptMessages } from './mcp-tools.mjs';
26
+ import { runCouncil } from './council-run.mjs';
27
+
28
+ const VERSION = '0.3.0';
29
+ const PORT = Number(process.env.LATTEDIT_BRIDGE_PORT) || 47824;
30
+ const ORIGINS = new Set([
31
+ 'https://lattedit.xyz', 'https://www.lattedit.xyz',
32
+ 'http://localhost:5173', 'http://127.0.0.1:5173',
33
+ 'tauri://localhost', 'http://tauri.localhost', 'https://tauri.localhost',
34
+ ...(process.env.LATTEDIT_ORIGINS ?? '').split(',').map((s) => s.trim()).filter(Boolean),
35
+ ]);
36
+ /** How long a call waits for a lattedit tab to connect before giving up. */
37
+ const CONNECT_WAIT_MS = 10_000;
38
+ const CALL_TIMEOUT_MS = 30_000;
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;
42
+ const MAX_MESSAGE = 96 * 1024 * 1024;
43
+
44
+ const log = (...a) => console.error('[lattedit mcp]', ...a);
45
+
46
+ /* ---------- a minimal WebSocket server (RFC 6455), text frames only ---------- */
47
+
48
+ function frame(text, opcode = 1) {
49
+ const payload = Buffer.from(text);
50
+ const n = payload.length;
51
+ const head = n < 126 ? Buffer.from([0x80 | opcode, n])
52
+ : n < 65536 ? Buffer.from([0x80 | opcode, 126, n >> 8, n & 255])
53
+ : (() => { const b = Buffer.alloc(10); b[0] = 0x80 | opcode; b[1] = 127; b.writeBigUInt64BE(BigInt(n), 2); return b; })();
54
+ return Buffer.concat([head, payload]);
55
+ }
56
+
57
+ class Peer {
58
+ constructor(socket, onMessage, onClose) {
59
+ this.socket = socket;
60
+ this.buf = Buffer.alloc(0);
61
+ this.parts = [];
62
+ this.open = true;
63
+ socket.on('data', (d) => {
64
+ this.buf = Buffer.concat([this.buf, d]);
65
+ try { this.drain(onMessage); } catch (e) { log(e.message); this.close(); }
66
+ });
67
+ this.onClose = onClose;
68
+ this.ended = false;
69
+ socket.on('close', () => this.end());
70
+ socket.on('error', () => this.end());
71
+ }
72
+
73
+ /** The connection is gone, whichever side closed it: clean up once. */
74
+ end() {
75
+ this.open = false;
76
+ if (this.ended) return;
77
+ this.ended = true;
78
+ this.onClose();
79
+ }
80
+
81
+ drain(onMessage) {
82
+ for (;;) {
83
+ const b = this.buf;
84
+ if (b.length < 2) return;
85
+ const fin = b[0] & 0x80, opcode = b[0] & 0x0f, masked = b[1] & 0x80;
86
+ let len = b[1] & 0x7f, off = 2;
87
+ if (len === 126) { if (b.length < 4) return; len = b.readUInt16BE(2); off = 4; }
88
+ else if (len === 127) { if (b.length < 10) return; len = Number(b.readBigUInt64BE(2)); off = 10; }
89
+ if (len > MAX_MESSAGE) throw new Error('Message too large.');
90
+ const maskAt = off;
91
+ if (masked) off += 4;
92
+ if (b.length < off + len) return;
93
+ const payload = Buffer.from(b.subarray(off, off + len));
94
+ if (masked) for (let i = 0; i < len; i++) payload[i] ^= b[maskAt + (i & 3)];
95
+ this.buf = b.subarray(off + len);
96
+ if (opcode === 8) { this.close(); return; }
97
+ if (opcode === 9) { this.socket.write(frame(payload, 10)); continue; }
98
+ if (opcode === 10) continue;
99
+ this.parts.push(payload);
100
+ if (this.parts.reduce((s, p) => s + p.length, 0) > MAX_MESSAGE) throw new Error('Message too large.');
101
+ if (!fin) continue;
102
+ const text = Buffer.concat(this.parts).toString('utf8');
103
+ this.parts = [];
104
+ let msg;
105
+ try { msg = JSON.parse(text); } catch { continue; }
106
+ onMessage(msg);
107
+ }
108
+ }
109
+
110
+ send(msg) { if (this.open) this.socket.write(frame(JSON.stringify(msg))); }
111
+ close() {
112
+ if (this.open) {
113
+ this.open = false;
114
+ try { this.socket.end(frame('', 8)); } catch { /* gone */ }
115
+ this.socket.destroy();
116
+ }
117
+ this.end();
118
+ }
119
+ }
120
+
121
+ /* ---------- the hub: owns the port, talks to lattedit tabs ---------- */
122
+
123
+ /** Connected lattedit tabs; calls go to the one focused most recently. */
124
+ const editors = new Set();
125
+ /** Calls waiting on a tab, by id: { resolve, timer, editor }. */
126
+ const pending = new Map();
127
+ /** Other agents' servers relaying through this one. */
128
+ const agents = new Set();
129
+ const editorWaiters = new Set();
130
+ /** Agent names, for the tab to show who is connected. */
131
+ let myAgent = 'agent';
132
+
133
+ function currentEditor() {
134
+ let best = null;
135
+ for (const e of editors) if (!best || e.focusedAt > best.focusedAt) best = e;
136
+ return best;
137
+ }
138
+
139
+ function agentNames() {
140
+ return [...new Set([myAgent, ...[...agents].map((a) => a.name).filter(Boolean)])];
141
+ }
142
+
143
+ function announceAgents() {
144
+ for (const e of editors) e.peer.send({ type: 'agents', names: agentNames() });
145
+ }
146
+
147
+ function noEditorResult() {
148
+ return {
149
+ text: 'lattedit is not connected. Ask the person to open lattedit (https://lattedit.xyz or the desktop app) '
150
+ + 'and turn on Coding agents (account menu → Coding agents). Then try again.',
151
+ isError: true,
152
+ };
153
+ }
154
+
155
+ async function waitForEditor() {
156
+ if (currentEditor()) return currentEditor();
157
+ return new Promise((done) => {
158
+ const w = () => { clearTimeout(timer); editorWaiters.delete(w); done(currentEditor()); };
159
+ const timer = setTimeout(w, CONNECT_WAIT_MS);
160
+ editorWaiters.add(w);
161
+ });
162
+ }
163
+
164
+ /** Run a call on the focused tab (hub only). */
165
+ async function callEditor(name, args, agent) {
166
+ const editor = await waitForEditor();
167
+ if (!editor) return noEditorResult();
168
+ const id = randomUUID();
169
+ return new Promise((done) => {
170
+ const timer = setTimeout(() => {
171
+ pending.delete(id);
172
+ done({ text: `lattedit didn't answer ${name} in time. The tab may be in the background or busy; try again.`, isError: true });
173
+ }, name === 'compile' ? COMPILE_TIMEOUT_MS : CALL_TIMEOUT_MS);
174
+ pending.set(id, { done, timer, editor });
175
+ editor.peer.send({ type: 'call', id, name, args, agent });
176
+ });
177
+ }
178
+
179
+ function onEditorClose(editor) {
180
+ editors.delete(editor);
181
+ for (const [id, p] of pending) {
182
+ if (p.editor !== editor) continue;
183
+ clearTimeout(p.timer);
184
+ pending.delete(id);
185
+ p.done({ text: 'The lattedit tab closed or disconnected during the call.', isError: true });
186
+ }
187
+ }
188
+
189
+ function handleUpgrade(req, socket) {
190
+ const reject = (status) => { socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n\r\n`); };
191
+ // DNS rebinding: only answer to loopback names.
192
+ const host = (req.headers.host ?? '').replace(/:\d+$/, '');
193
+ if (!['127.0.0.1', 'localhost', '[::1]'].includes(host)) return reject('403 Forbidden');
194
+ const key = req.headers['sec-websocket-key'];
195
+ if (!key || req.headers.upgrade?.toLowerCase() !== 'websocket') return reject('400 Bad Request');
196
+ const origin = req.headers.origin;
197
+ const path = new URL(req.url, 'http://x').pathname;
198
+ if (path === '/editor' ? !origin || !ORIGINS.has(origin) : path === '/agent' ? !!origin : true) {
199
+ log(`refused a connection to ${path} from ${origin ?? 'a local process'}`);
200
+ return reject('403 Forbidden');
201
+ }
202
+ const accept = createHash('sha1').update(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64');
203
+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
204
+ socket.setNoDelay(true);
205
+
206
+ if (path === '/editor') {
207
+ const editor = { focusedAt: Date.now(), origin };
208
+ editor.peer = new Peer(socket, (msg) => {
209
+ if (msg.type === 'hello' || msg.type === 'focus') {
210
+ if (msg.type === 'focus' || msg.focused) editor.focusedAt = Date.now();
211
+ if (msg.type === 'hello') { editor.peer.send({ type: 'agents', names: agentNames() }); editorWaiters.forEach((w) => w()); }
212
+ } else if (msg.type === 'result') {
213
+ const p = pending.get(msg.id);
214
+ if (!p) return;
215
+ clearTimeout(p.timer);
216
+ pending.delete(msg.id);
217
+ p.done(msg.result ?? { text: 'Empty answer from lattedit.', isError: true });
218
+ }
219
+ }, () => onEditorClose(editor));
220
+ editors.add(editor);
221
+ log(`lattedit connected (${origin})`);
222
+ } else {
223
+ const agent = { name: '' };
224
+ agent.peer = new Peer(socket, async (msg) => {
225
+ if (msg.type === 'hello') { agent.name = msg.agent ?? ''; announceAgents(); return; }
226
+ if (msg.type !== 'call') return;
227
+ const result = await callEditor(msg.name, msg.args ?? {}, msg.agent);
228
+ agent.peer.send({ type: 'result', id: msg.id, result });
229
+ }, () => { agents.delete(agent); announceAgents(); });
230
+ agents.add(agent);
231
+ }
232
+ }
233
+
234
+ function listen() {
235
+ return new Promise((done) => {
236
+ const server = createServer((req, res) => {
237
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
238
+ res.end(JSON.stringify({ name: 'lattedit-mcp', version: VERSION, editors: editors.size }));
239
+ });
240
+ server.on('upgrade', handleUpgrade);
241
+ server.once('error', (e) => done(e.code === 'EADDRINUSE' ? null : (log(e.message), null)));
242
+ server.listen(PORT, '127.0.0.1', () => done(server));
243
+ });
244
+ }
245
+
246
+ /* ---------- relaying through another server's hub ---------- */
247
+
248
+ let hub = null;
249
+ let relay = null;
250
+ const relayPending = new Map();
251
+
252
+ function connectRelay() {
253
+ return new Promise((done) => {
254
+ let ws;
255
+ try { ws = new WebSocket(`ws://127.0.0.1:${PORT}/agent`); } catch { return done(null); }
256
+ ws.onopen = () => { ws.send(JSON.stringify({ type: 'hello', agent: myAgent })); done(ws); };
257
+ ws.onerror = () => done(null);
258
+ ws.onmessage = (e) => {
259
+ let msg;
260
+ try { msg = JSON.parse(e.data); } catch { return; }
261
+ const p = relayPending.get(msg.id);
262
+ if (msg.type === 'result' && p) { relayPending.delete(msg.id); p(msg.result); }
263
+ };
264
+ ws.onclose = () => {
265
+ if (relay === ws) relay = null;
266
+ for (const [id, p] of relayPending) { relayPending.delete(id); p({ text: 'The connection to lattedit dropped during the call; try again.', isError: true }); }
267
+ };
268
+ });
269
+ }
270
+
271
+ /** Own the port, or relay through whoever does. Re-run before each call so a lost hub is replaced. */
272
+ async function ensureBridge() {
273
+ if (hub || relay) return;
274
+ hub = await listen();
275
+ if (hub) { log(`waiting for lattedit on 127.0.0.1:${PORT}`); return; }
276
+ relay = await connectRelay();
277
+ if (!relay) log(`port ${PORT} is in use by something that isn't lattedit.`);
278
+ }
279
+
280
+ async function call(name, args) {
281
+ await ensureBridge();
282
+ if (hub) return callEditor(name, args, myAgent);
283
+ if (!relay) return { text: `lattedit's bridge port ${PORT} is busy. Set LATTEDIT_BRIDGE_PORT to use another.`, isError: true };
284
+ const id = randomUUID();
285
+ const ws = relay;
286
+ return new Promise((done) => {
287
+ relayPending.set(id, done);
288
+ ws.send(JSON.stringify({ type: 'call', id, name, args, agent: myAgent }));
289
+ });
290
+ }
291
+
292
+ /* ---------- MCP over stdio ---------- */
293
+
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 } }); }
297
+
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);
340
+ if (!TOOLS.some((t) => t.name === name)) return { text: `Unknown tool: ${name}`, isError: true };
341
+ if (name !== 'compile' || !args.savePdfTo) return call(name, args);
342
+ const { savePdfTo, ...rest } = args;
343
+ const result = await call(name, { ...rest, wantPdf: true });
344
+ if (result.pdf) {
345
+ const out = resolve(savePdfTo);
346
+ await mkdir(dirname(out), { recursive: true });
347
+ await writeFile(out, Buffer.from(result.pdf, 'base64'));
348
+ result.text += `\nSaved the PDF to ${out}.`;
349
+ }
350
+ delete result.pdf;
351
+ return result;
352
+ }
353
+
354
+ async function handle(msg) {
355
+ const { id, method, params } = msg;
356
+ if (method === undefined && id !== undefined) return onClientResponse(msg);
357
+ if (method === 'initialize') {
358
+ const client = params?.clientInfo;
359
+ clientCapabilities = params?.capabilities ?? {};
360
+ myAgent = client?.title || client?.name || 'agent';
361
+ if (relay?.readyState === 1) relay.send(JSON.stringify({ type: 'hello', agent: myAgent }));
362
+ announceAgents();
363
+ const asked = params?.protocolVersion;
364
+ return reply(id, {
365
+ protocolVersion: ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'].includes(asked) ? asked : '2025-06-18',
366
+ capabilities: { tools: { listChanged: false }, prompts: { listChanged: false } },
367
+ serverInfo: { name: 'lattedit', title: 'lattedit', version: VERSION },
368
+ instructions: INSTRUCTIONS,
369
+ });
370
+ }
371
+ if (method === 'ping') return reply(id, {});
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
+ }
378
+ if (method === 'tools/call') {
379
+ try {
380
+ const r = await runTool(params?.name, params?.arguments ?? {}, params?._meta?.progressToken);
381
+ return reply(id, { content: [{ type: 'text', text: r.text }], isError: !!r.isError });
382
+ } catch (e) {
383
+ return reply(id, { content: [{ type: 'text', text: e.message }], isError: true });
384
+ }
385
+ }
386
+ if (id === undefined) return; // a notification
387
+ return fail(id, -32601, `Method not found: ${method}`);
388
+ }
389
+
390
+ export async function serveMcp() {
391
+ // Start listening at once so a lattedit tab can connect before the first call.
392
+ await ensureBridge();
393
+ let buf = '';
394
+ process.stdin.setEncoding('utf8');
395
+ process.stdin.on('data', (chunk) => {
396
+ buf += chunk;
397
+ let nl;
398
+ while ((nl = buf.indexOf('\n')) !== -1) {
399
+ const line = buf.slice(0, nl).trim();
400
+ buf = buf.slice(nl + 1);
401
+ if (!line) continue;
402
+ let msg;
403
+ try { msg = JSON.parse(line); } catch { fail(null, -32700, 'Parse error'); continue; }
404
+ handle(msg).catch((e) => fail(msg.id, -32603, e.message));
405
+ }
406
+ });
407
+ process.stdin.on('end', () => process.exit(0));
408
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "lattedit-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Official command-line client and MCP server for lattedit: compile LaTeX, and let coding agents edit your lattedit projects",
5
+ "type": "module",
6
+ "bin": {
7
+ "lattedit": "cli/lattedit.mjs"
8
+ },
9
+ "files": [
10
+ "cli/lattedit.mjs",
11
+ "cli/mcp.mjs",
12
+ "cli/mcp-tools.mjs",
13
+ "cli/council-run.mjs"
14
+ ],
15
+ "scripts": {
16
+ "test": "node --test cli/mcp.test.mjs cli/council-run.test.mjs"
17
+ },
18
+ "keywords": [
19
+ "latex",
20
+ "mcp",
21
+ "claude-code",
22
+ "codex",
23
+ "overleaf",
24
+ "pdf"
25
+ ],
26
+ "homepage": "https://lattedit.xyz/developers",
27
+ "engines": {
28
+ "node": ">=22"
29
+ }
30
+ }