odforge 0.3.0__py3-none-any.whl
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.
- odforge/__init__.py +1 -0
- odforge/benchmark.py +287 -0
- odforge/check.py +416 -0
- odforge/cli.py +1027 -0
- odforge/components.py +270 -0
- odforge/critic.py +1260 -0
- odforge/docfonts.py +104 -0
- odforge/editor_api.py +33 -0
- odforge/editor_launch.py +134 -0
- odforge/editor_routes.py +131 -0
- odforge/extract.py +478 -0
- odforge/feedback.py +86 -0
- odforge/fontembed.py +166 -0
- odforge/ir.py +1181 -0
- odforge/layoutcheck.py +602 -0
- odforge/llm.py +1865 -0
- odforge/localguard.py +42 -0
- odforge/mcp_server.py +552 -0
- odforge/media.py +352 -0
- odforge/odpedit.py +1219 -0
- odforge/package.py +114 -0
- odforge/pagefacts.py +388 -0
- odforge/preview.py +104 -0
- odforge/references.py +153 -0
- odforge/render/__init__.py +40 -0
- odforge/render/odp.py +5687 -0
- odforge/render/ods.py +155 -0
- odforge/render/odt.py +223 -0
- odforge/scene.py +657 -0
- odforge/setup_agents.py +274 -0
- odforge/skills/odforge-design/SKILL.md +298 -0
- odforge/skills/odforge-design/themes/academic.md +52 -0
- odforge/skills/odforge-design/themes/clay.md +53 -0
- odforge/skills/odforge-design/themes/color-system.md +59 -0
- odforge/skills/odforge-design/themes/crimson.md +53 -0
- odforge/skills/odforge-design/themes/dark.md +53 -0
- odforge/skills/odforge-design/themes/forest.md +54 -0
- odforge/skills/odforge-design/themes/gold.md +53 -0
- odforge/skills/odforge-design/themes/minimal.md +53 -0
- odforge/skills/odforge-design/themes/navy.md +56 -0
- odforge/skills/odforge-design/themes/plum.md +53 -0
- odforge/skills/odforge-design/themes/sky.md +53 -0
- odforge/skills/odforge-design/themes/slate.md +53 -0
- odforge/skills/odforge-design/themes/teal.md +53 -0
- odforge/skills/odforge-design/themes/violet.md +56 -0
- odforge/templates.py +250 -0
- odforge/textmetrics.py +616 -0
- odforge/textutil.py +24 -0
- odforge/themes.py +886 -0
- odforge/validate.py +403 -0
- odforge/watch.py +266 -0
- odforge/webapi.py +2617 -0
- odforge/webui/assets/editor-CjpYXM1a.css +1 -0
- odforge/webui/assets/editor-DPToJGio.js +3 -0
- odforge/webui/assets/jsx-runtime-C7KMcVI_.js +8 -0
- odforge/webui/assets/main-BLOs7Hnk.js +7 -0
- odforge/webui/assets/main-D21yFVE6.css +1 -0
- odforge/webui/editor.html +14 -0
- odforge/webui/index.html +25 -0
- odforge/xmlsafe.py +46 -0
- odforge/zipguard.py +91 -0
- odforge-0.3.0.dist-info/METADATA +95 -0
- odforge-0.3.0.dist-info/RECORD +66 -0
- odforge-0.3.0.dist-info/WHEEL +4 -0
- odforge-0.3.0.dist-info/entry_points.txt +3 -0
- odforge-0.3.0.dist-info/licenses/LICENSE +21 -0
odforge/localguard.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Keep a local tool's HTTP API to the browser tab it opened.
|
|
2
|
+
|
|
3
|
+
Binding to 127.0.0.1 stops other machines, not other web pages: any site the
|
|
4
|
+
user visits can send requests to ``http://127.0.0.1:<port>``, and a DNS-rebinding
|
|
5
|
+
attack can even read the answers. So every request must name this server in its
|
|
6
|
+
Host header, and anything that changes state must come from this server's own
|
|
7
|
+
origin. Requests without an Origin header (curl, scripts) are not cross-site
|
|
8
|
+
browser requests and pass.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from typing import Iterable
|
|
14
|
+
|
|
15
|
+
from fastapi import FastAPI
|
|
16
|
+
from starlette.requests import Request
|
|
17
|
+
from starlette.responses import PlainTextResponse
|
|
18
|
+
|
|
19
|
+
_SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def local_hosts(port: int) -> set[str]:
|
|
23
|
+
return {f"127.0.0.1:{port}", f"localhost:{port}", f"[::1]:{port}"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def add_local_guard(app: FastAPI, hosts: Iterable[str]) -> None:
|
|
27
|
+
allowed_hosts = {h.lower() for h in hosts}
|
|
28
|
+
allowed_origins = {f"http://{h}" for h in allowed_hosts}
|
|
29
|
+
|
|
30
|
+
@app.middleware("http")
|
|
31
|
+
async def guard(request: Request, call_next):
|
|
32
|
+
host = request.headers.get("host", "").lower()
|
|
33
|
+
if host not in allowed_hosts:
|
|
34
|
+
return PlainTextResponse("forbidden host", status_code=403)
|
|
35
|
+
origin = request.headers.get("origin")
|
|
36
|
+
if (
|
|
37
|
+
request.method not in _SAFE_METHODS
|
|
38
|
+
and origin is not None
|
|
39
|
+
and origin.lower() not in allowed_origins
|
|
40
|
+
):
|
|
41
|
+
return PlainTextResponse("forbidden origin", status_code=403)
|
|
42
|
+
return await call_next(request)
|
odforge/mcp_server.py
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
"""ODForge MCP server — expose the deterministic ODF rendering engine as tools.
|
|
2
|
+
|
|
3
|
+
This server is a *pure rendering engine*. The calling AI assistant is itself the
|
|
4
|
+
content author: it produces the Document IR (a JSON object) and hands it to a
|
|
5
|
+
``forge_*`` tool, which renders a native ``.odt`` / ``.odp`` / ``.ods`` file and
|
|
6
|
+
validates it. There is no prompt, no LLM call and no API key here — this module
|
|
7
|
+
deliberately never imports ``odforge.llm``.
|
|
8
|
+
|
|
9
|
+
Tools registered on the ``mcp`` app:
|
|
10
|
+
|
|
11
|
+
* ``forge_text_document(document, out_path)`` — render a text document to ``.odt``
|
|
12
|
+
* ``forge_presentation(document, out_path)`` — render a presentation to ``.odp``
|
|
13
|
+
* ``forge_spreadsheet(document, out_path)`` — render a spreadsheet to ``.ods``
|
|
14
|
+
* ``inspect_odf(path)`` — validate an existing ODF file
|
|
15
|
+
* ``preview_odf(path, out_dir)`` — rasterise an ODF file to one PNG per page
|
|
16
|
+
|
|
17
|
+
What a caller gets, and what it is responsible for
|
|
18
|
+
--------------------------------------------------
|
|
19
|
+
ODForge guarantees the *format*: every ``forge_*`` call renders spec-compliant
|
|
20
|
+
ODF XML and then runs the same three format gates the CLI runs (zip layout, XML
|
|
21
|
+
well-formedness, and a real LibreOffice round-trip when LibreOffice is
|
|
22
|
+
installed), plus the deterministic layout-budget check that reports text which
|
|
23
|
+
will overrun its frame.
|
|
24
|
+
|
|
25
|
+
The caller — the AI assistant — owns the *content*: it writes the Document IR,
|
|
26
|
+
and when a budget warning comes back it is the one that shortens the text and
|
|
27
|
+
forges again. ``preview_odf`` closes the loop by handing back one PNG per page,
|
|
28
|
+
so an agent can look at what it made rather than assume.
|
|
29
|
+
|
|
30
|
+
Every tool returns a plain string and **never raises**: any failure is reported
|
|
31
|
+
as a string beginning with ``"error:"``. Raising inside an MCP tool would surface
|
|
32
|
+
as a protocol-level error to the client, so all exceptions are converted to text.
|
|
33
|
+
|
|
34
|
+
Run as a stdio MCP server with ``odforge-mcp`` (installed console script) or
|
|
35
|
+
``python -m odforge.mcp_server``.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
from __future__ import annotations
|
|
39
|
+
|
|
40
|
+
import json
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
|
|
43
|
+
try: # mcp >= 2.0 renamed FastMCP to MCPServer and moved it.
|
|
44
|
+
from mcp.server.mcpserver import MCPServer as _Server
|
|
45
|
+
except ModuleNotFoundError: # pragma: no cover - exercised by the other major
|
|
46
|
+
from mcp.server.fastmcp import FastMCP as _Server
|
|
47
|
+
|
|
48
|
+
from odforge.ir import Presentation, parse_ir
|
|
49
|
+
from odforge.layoutcheck import LayoutReport, check_layout
|
|
50
|
+
from odforge.preview import PreviewUnavailable, render_pages
|
|
51
|
+
from odforge.render import render
|
|
52
|
+
from odforge.textmetrics import check_budget, deck_warnings
|
|
53
|
+
from odforge.textutil import concise
|
|
54
|
+
from odforge.themes import resolve_design, resolve_style
|
|
55
|
+
from odforge.validate import find_soffice, validate_odf
|
|
56
|
+
|
|
57
|
+
# Sent to the client on connect, so every MCP host shows it to its model — the
|
|
58
|
+
# one piece of guidance that reaches an agent which never opens the README or
|
|
59
|
+
# the skill. Kept short: the skill is where the depth lives.
|
|
60
|
+
INSTRUCTIONS = """\
|
|
61
|
+
ODForge 把 Document IR(JSON)渲染成原生 ODF 簡報/文件/試算表(.odp/.odt/.ods)。
|
|
62
|
+
|
|
63
|
+
- 做簡報前先讀 odforge-design skill(有訪談、大綱、版型欄位與主題規格);沒有載入 skill 時,
|
|
64
|
+
至少照工具說明的欄位寫 IR,產出後一定用 inspect_odf 檢查跑版。
|
|
65
|
+
- 使用者在旁邊時:forge_presentation 成功後網頁編輯器會自動打開;接著反覆呼叫 wait_for_feedback,
|
|
66
|
+
照留言用 edit_odp 修改,回 done 才結束。看/改既有 .odp 先 open_editor,再 outline_odp 看元素代號。
|
|
67
|
+
- 每個工具只回字串:開頭是 ok: 才算成功,error: 要修好再重來。
|
|
68
|
+
- 不要叫使用者打開 LibreOffice;它只在背景當渲染器。
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
# One object either way: ``.tool()`` and ``.run()`` are identical across both
|
|
72
|
+
# majors, so the shim above is the whole migration. Without it, `pip install
|
|
73
|
+
# odforge` on a machine that resolves mcp 2.x installed an MCP server that
|
|
74
|
+
# crashed on the first line of `odforge-mcp` — and the failure was invisible here
|
|
75
|
+
# because this repo's venv happened to be pinned at 1.28 from an earlier install.
|
|
76
|
+
mcp = _Server("odforge", instructions=INSTRUCTIONS)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _budget_warnings(ir: object) -> list[str]:
|
|
80
|
+
"""Layout-budget check: which frames will overrun their box, and by how much.
|
|
81
|
+
|
|
82
|
+
This is the deterministic half of the design gate, and until now it was
|
|
83
|
+
missing from the MCP path entirely — it lived only in ``llm.py`` (where it
|
|
84
|
+
drives a retry) and ``cli.py`` (where it prints a warning). An agent driving
|
|
85
|
+
``forge_presentation`` could hand over twelve bullets, get back a cheerful
|
|
86
|
+
``"ok:"``, and ship a deck with text running off the page.
|
|
87
|
+
|
|
88
|
+
The division of labour here is the whole point of MCP: **ODForge measures,
|
|
89
|
+
the calling agent rewrites.** So this returns actionable text naming the page
|
|
90
|
+
and the frame, not a pass/fail flag.
|
|
91
|
+
|
|
92
|
+
Presentations only — ``.odt`` reflows and ``.ods`` has no fixed frames, so
|
|
93
|
+
neither has a layout budget to blow.
|
|
94
|
+
"""
|
|
95
|
+
if not isinstance(ir, Presentation):
|
|
96
|
+
return []
|
|
97
|
+
theme = resolve_design(ir)
|
|
98
|
+
style = resolve_style(ir)
|
|
99
|
+
warnings: list[str] = []
|
|
100
|
+
for n, slide in enumerate(ir.slides, start=1):
|
|
101
|
+
warnings.extend(f"第 {n} 頁:{message}" for message in check_budget(slide, theme, style))
|
|
102
|
+
warnings.extend(deck_warnings(ir.slides))
|
|
103
|
+
return warnings
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _layout_bullets(layout: LayoutReport) -> list[str]:
|
|
107
|
+
label = {"ok": "OK", "overflow": "跑版"}.get(layout.status, "略過")
|
|
108
|
+
return [f"- layout: {label} — {layout.message}"] + [
|
|
109
|
+
f" - {finding.describe()}" for finding in layout.findings
|
|
110
|
+
]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _forge(document: dict, out_path: str, doc_type: str) -> str:
|
|
114
|
+
"""Shared pipeline: inject type -> parse_ir -> render -> validate -> budget.
|
|
115
|
+
|
|
116
|
+
Returns a human-readable string. On success it starts with ``"ok"`` and
|
|
117
|
+
lists the absolute output path plus a one-line summary per validation gate;
|
|
118
|
+
if any text overruns its frame, an explicit ``warning:`` block follows.
|
|
119
|
+
On any failure it returns ``"error: <reason>"``. Never raises.
|
|
120
|
+
|
|
121
|
+
LibreOffice runs here when it is installed, so an MCP-forged file gets the
|
|
122
|
+
same three format gates as one made by the CLI. It previously ran only two
|
|
123
|
+
(``with_soffice=False`` was hard-coded), which meant "ok" from this tool was
|
|
124
|
+
a weaker claim than "ok" from ``odforge new`` while reading identically.
|
|
125
|
+
"""
|
|
126
|
+
try:
|
|
127
|
+
# Override the caller-supplied ``type`` to the type this tool renders,
|
|
128
|
+
# preventing type confusion (a payload mislabelled by the caller/LLM).
|
|
129
|
+
payload = dict(document)
|
|
130
|
+
payload["type"] = doc_type
|
|
131
|
+
|
|
132
|
+
ir = parse_ir(payload)
|
|
133
|
+
|
|
134
|
+
out = Path(out_path)
|
|
135
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
136
|
+
|
|
137
|
+
render(ir, out)
|
|
138
|
+
|
|
139
|
+
soffice = find_soffice()
|
|
140
|
+
report = validate_odf(out, with_soffice=soffice is not None)
|
|
141
|
+
gates = "; ".join(
|
|
142
|
+
f"{name}: {'OK' if passed else 'FAIL'} — {message}"
|
|
143
|
+
for name, (passed, message) in report.gates.items()
|
|
144
|
+
)
|
|
145
|
+
if not report.ok:
|
|
146
|
+
return f"error: validation failed for {out.resolve()} — {gates}"
|
|
147
|
+
|
|
148
|
+
result = f"ok: wrote {out.resolve()} — {gates}"
|
|
149
|
+
warnings = _budget_warnings(ir)
|
|
150
|
+
if warnings:
|
|
151
|
+
# Not an error: the file exists and is a valid ODF package. But
|
|
152
|
+
# "valid" and "readable" are different claims, and reporting only the
|
|
153
|
+
# first one is how an overset deck ships under a clean bill of health.
|
|
154
|
+
result += (
|
|
155
|
+
"\n\nwarning: 版面預算超載——檔案已產出且格式有效,但下列內容會溢出"
|
|
156
|
+
"版面。請縮短這些頁面的文字後重新 forge:\n" + "\n".join(f"- {w}" for w in warnings)
|
|
157
|
+
)
|
|
158
|
+
if doc_type != "spreadsheet" and soffice is not None:
|
|
159
|
+
# The budget above is an estimate made before rendering; this is
|
|
160
|
+
# where LibreOffice actually put the text. They usually agree, and
|
|
161
|
+
# when they do not, the rendered one is the one the reader sees.
|
|
162
|
+
layout = check_layout(out, soffice)
|
|
163
|
+
if layout.findings:
|
|
164
|
+
result += (
|
|
165
|
+
"\n\nwarning: 跑版——LibreOffice 實際排版後,下列文字超出框或頁面。"
|
|
166
|
+
"請縮短或拆頁後重新 forge:\n"
|
|
167
|
+
+ "\n".join(f"- {f.describe()}" for f in layout.findings)
|
|
168
|
+
)
|
|
169
|
+
return result
|
|
170
|
+
except Exception as exc:
|
|
171
|
+
return f"error: {type(exc).__name__}: {concise(str(exc))}"
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@mcp.tool()
|
|
175
|
+
def forge_text_document(document: dict, out_path: str) -> str:
|
|
176
|
+
"""Render a text document (Document IR) to a native ``.odt`` file.
|
|
177
|
+
|
|
178
|
+
``document`` is the IR for a text document (``odforge.ir.TextDoc``). Key
|
|
179
|
+
fields:
|
|
180
|
+
|
|
181
|
+
* ``title`` (str, required) — document title.
|
|
182
|
+
* ``lang`` (str) — language tag, e.g. ``"zh-TW"``.
|
|
183
|
+
* ``blocks`` (list) — body content; each block has a ``kind`` discriminator:
|
|
184
|
+
``heading`` (``level`` 1-6, ``text``), ``paragraph`` (``text``, ``style``:
|
|
185
|
+
body/quote/note), ``list`` (``ordered``, ``items``), ``table`` (``header``,
|
|
186
|
+
``rows``), ``toc``, ``pagebreak``.
|
|
187
|
+
|
|
188
|
+
The ``type`` field is forced to ``"text"``. ``out_path`` is the target file
|
|
189
|
+
path; missing parent directories are created. Returns an ``"ok: ..."`` string
|
|
190
|
+
with the absolute path and per-gate validation summary, or ``"error: ..."``.
|
|
191
|
+
See ``odforge.ir.TextDoc.model_json_schema()`` for the full schema.
|
|
192
|
+
"""
|
|
193
|
+
return _forge(document, out_path, "text")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
@mcp.tool()
|
|
197
|
+
def forge_presentation(document: dict, out_path: str) -> str:
|
|
198
|
+
"""Render a presentation (Document IR) to a native ``.odp`` file.
|
|
199
|
+
|
|
200
|
+
``document`` is an ``odforge.ir.Presentation`` (full schema:
|
|
201
|
+
``Presentation.model_json_schema()``). You write the content; the engine
|
|
202
|
+
owns geometry, so a good deck comes from rich, well-structured IR.
|
|
203
|
+
|
|
204
|
+
**Deck-level fields**
|
|
205
|
+
|
|
206
|
+
* ``title`` (required); ``theme`` — one of 13 curated palettes: academic,
|
|
207
|
+
minimal, dark, teal, forest, navy, violet, crimson, slate, gold, sky,
|
|
208
|
+
plum, clay (light grounds except dark/violet/slate/gold).
|
|
209
|
+
* ``style`` — the composition, pick by occasion: ``passport`` (審查、計畫書、
|
|
210
|
+
成果報告 — white framed cards, the takeaway as a dark right-hand panel;
|
|
211
|
+
the densest, most formal look), ``report`` (顧問式匯報、議會、商業提案),
|
|
212
|
+
``academic`` (口試、課堂), ``editorial`` (人文、設計), ``keynote``
|
|
213
|
+
(演講、發表; pair with a dark theme), ``zen`` (品牌、極簡), ``classic``.
|
|
214
|
+
Styles change cards, heading marks, dividers and the takeaway band — two
|
|
215
|
+
decks in different styles should not look like one template.
|
|
216
|
+
|
|
217
|
+
**Every content page** (not title/section/closing/quote) should carry:
|
|
218
|
+
``kicker`` (chapter tag, e.g. "02 研究方法"), ``title`` written as a
|
|
219
|
+
full-sentence conclusion (10–22 字, not a topic noun), ``subtitle`` (a
|
|
220
|
+
15–40 字 lede under the title), and — on about a third of the pages,
|
|
221
|
+
where the page really concludes something — ``takeaway`` (≤30 字 "so
|
|
222
|
+
what", drawn as a band at the foot or, in ``passport``, a dark side panel
|
|
223
|
+
(the panel only where the body still fits two-thirds of the width: 2 or 4
|
|
224
|
+
cards, ≤3 metrics, two-col / comparison / title-content / big-fact /
|
|
225
|
+
diagram — 3 cards or 4 metrics keep the band)
|
|
226
|
+
on cards / title-content / two-col / comparison / metrics / big-fact /
|
|
227
|
+
diagram pages — wide layouts keep the band).
|
|
228
|
+
A takeaway must add something the title does not say (a number, an
|
|
229
|
+
impact, a next step); one that paraphrases the title is noise.
|
|
230
|
+
|
|
231
|
+
**Layouts** (``slide.layout``) and what each needs:
|
|
232
|
+
|
|
233
|
+
* ``title`` — title, subtitle, kicker (the occasion, e.g. 「期末審查」),
|
|
234
|
+
bullets (2–4 cover facts — 單位、報告人、日期 — shown as the cover's
|
|
235
|
+
info card). ``closing`` — title, subtitle, bullets
|
|
236
|
+
(3–4 next steps as ``{"text", "children"}``), optional kicker
|
|
237
|
+
(「結語」「請求事項」, drawn above the message).
|
|
238
|
+
* ``cards`` — bullets: 2–4 ``{"text": 4–14 字小標, "children": [1–2 句
|
|
239
|
+
具體說明]}``. ``dashboard`` — metrics (2–4; value + label only, a
|
|
240
|
+
metric's detail is not drawn in the dashboard strip) + bullets (2–3
|
|
241
|
+
cards, each with ONE short child ≤12 字 — the cards sit under the strip
|
|
242
|
+
and have room for a single line).
|
|
243
|
+
* ``process`` — steps: 2–5 ``{"title", "detail"}``. ``timeline`` —
|
|
244
|
+
events: 2–5 ``{"label", "title", "detail"}``. ``metrics`` — metrics:
|
|
245
|
+
2–4 ``{"value", "label", "detail"}``.
|
|
246
|
+
* ``table`` — table: ``{"columns": [2–5], "rows": [[...], ...] (≤6; ≤5
|
|
247
|
+
with a takeaway), "highlight": row index}``. ``comparison`` — left/right, first item of
|
|
248
|
+
each is the column header. ``two-col`` — left/right.
|
|
249
|
+
* ``diagram`` — diagram: ``{"kind": "hub"|"hierarchy", "nodes": [{"id",
|
|
250
|
+
"title", "detail", "emphasis"}], "edges": [{"source", "target",
|
|
251
|
+
"label"}]}``. ``chart`` — chart: ``{"labels", "values", "unit",
|
|
252
|
+
"highlight"}``, real data only.
|
|
253
|
+
* ``big-fact`` — title (what the number means — never the number
|
|
254
|
+
itself), fact (the number), subtitle (the baseline: 相較去年、全國平均),
|
|
255
|
+
bullets (one caption line); at most one big-fact per ten pages — a
|
|
256
|
+
lone number is emphasis, not a page type. ``quote`` — quote,
|
|
257
|
+
attribution (at most one quote page per deck).
|
|
258
|
+
* ``title-content`` — bullets (at most 2 such pages per deck);
|
|
259
|
+
``agenda`` — bullets, un-numbered (the page numbers them; only for decks
|
|
260
|
+
≥ 15 pages); ``section`` — title, with ``kicker`` "02 章節名" (only
|
|
261
|
+
for decks ≥ 20 pages, at most 2 — 3 from 30 pages — otherwise put the
|
|
262
|
+
chapter in the next page's ``kicker``). The divider's big numeral is
|
|
263
|
+
taken from that kicker in classic / report / keynote / editorial /
|
|
264
|
+
passport; ``academic`` draws its divider between two rules and ``zen``
|
|
265
|
+
under a dot — no numeral, by design. Agenda, dividers, quotes and
|
|
266
|
+
big-facts together stay under ~18% of the deck, and no card layout
|
|
267
|
+
(cards / process / timeline / metrics) should carry more than a fifth
|
|
268
|
+
of the pages — a table, chart, diagram or comparison says the same
|
|
269
|
+
thing without the deck reading as one page repeated. A count in a
|
|
270
|
+
title (「三項」「五個建議」) must match the items the page shows. The
|
|
271
|
+
tool reports all of these as warnings.
|
|
272
|
+
|
|
273
|
+
Practical lengths (longer text is shrunk, then cut with "…"): cards (3
|
|
274
|
+
across) title ≤10 字, each child ≤22 字; process 4 steps title ≤7 字 /
|
|
275
|
+
detail ≤18 字 (5 steps: 5 / 14); timeline 5 events title ≤6 字 / detail
|
|
276
|
+
≤18 字 (4 events: 8 / 24); metric value ≤7 字 incl. unit, label ≤10 字;
|
|
277
|
+
chart labels ≤5 字; diagram node title ≤6 字 / detail ≤10 字; table ≤5
|
|
278
|
+
columns, cells ≤12 字; closing text ≤10 字 (4 items: ≤6), child ≤20 字. Beside a
|
|
279
|
+
``passport`` side panel the body is two-thirds wide: card titles ≤6 字.
|
|
280
|
+
``two-col`` columns have no header — for 「改善前/改善後」 use
|
|
281
|
+
``comparison`` (its left[0] / right[0] are the column headers).
|
|
282
|
+
|
|
283
|
+
Write insights, not topics ("誤判率從 32% 降到 8%" beats "降低誤判"); fill
|
|
284
|
+
every ``detail``; never use the same layout on two adjacent pages. Any
|
|
285
|
+
slide may carry ``notes`` (speaker notes).
|
|
286
|
+
|
|
287
|
+
The ``type`` field is forced to ``"presentation"``. ``out_path`` is the target
|
|
288
|
+
file path; missing parent directories are created. Returns an ``"ok: ..."``
|
|
289
|
+
string with the absolute path and per-gate validation summary, or
|
|
290
|
+
``"error: ..."``.
|
|
291
|
+
|
|
292
|
+
**If any text will overrun its frame**, the ``"ok: ..."`` string is followed
|
|
293
|
+
by a ``warning:`` block naming each page and frame. The file is valid ODF and
|
|
294
|
+
was written — but it will look wrong. Shorten the flagged pages and call this
|
|
295
|
+
tool again; do not present an overset deck as finished. Then call
|
|
296
|
+
``preview_odf`` and look at the pages before handing the deck over.
|
|
297
|
+
"""
|
|
298
|
+
result = _forge(document, out_path, "presentation")
|
|
299
|
+
if result.startswith("ok"):
|
|
300
|
+
from odforge.editor_launch import editor_note
|
|
301
|
+
|
|
302
|
+
note = editor_note(Path(out_path))
|
|
303
|
+
if note:
|
|
304
|
+
result += "\n\n" + note
|
|
305
|
+
return result
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
@mcp.tool()
|
|
309
|
+
def forge_spreadsheet(document: dict, out_path: str) -> str:
|
|
310
|
+
"""Render a spreadsheet (Document IR) to a native ``.ods`` file.
|
|
311
|
+
|
|
312
|
+
``document`` is the IR for a spreadsheet (``odforge.ir.Spreadsheet``). Key
|
|
313
|
+
fields:
|
|
314
|
+
|
|
315
|
+
* ``title`` (str, required) — workbook title.
|
|
316
|
+
* ``sheets`` (list) — each sheet has ``name``, ``columns`` (header labels),
|
|
317
|
+
``rows`` (list of rows; cells are str/int/float) and optional ``formulas``
|
|
318
|
+
(each ``{"cell": "B5", "formula": "of:=SUM([.B2:.B4])"}`` — formulas must
|
|
319
|
+
use the ``of:=`` OpenFormula prefix).
|
|
320
|
+
|
|
321
|
+
The ``type`` field is forced to ``"spreadsheet"``. ``out_path`` is the target
|
|
322
|
+
file path; missing parent directories are created. Returns an ``"ok: ..."``
|
|
323
|
+
string with the absolute path and per-gate validation summary, or
|
|
324
|
+
``"error: ..."``. See ``odforge.ir.Spreadsheet.model_json_schema()``.
|
|
325
|
+
"""
|
|
326
|
+
return _forge(document, out_path, "spreadsheet")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
@mcp.tool()
|
|
330
|
+
def inspect_odf(path: str) -> str:
|
|
331
|
+
"""Validate an existing ODF file and report each gate as markdown.
|
|
332
|
+
|
|
333
|
+
Runs ODForge's validation gates over the file at ``path``: ``structure``
|
|
334
|
+
(zip layout, stored mimetype, manifest) and ``xml`` (well-formedness), plus
|
|
335
|
+
``soffice`` (a LibreOffice round-trip) when LibreOffice is installed. Returns
|
|
336
|
+
one markdown bullet per gate — ``- {gate}: {OK|FAIL} — {message}`` — then a
|
|
337
|
+
``- layout: ...`` bullet for ``.odp``/``.odt``: text that LibreOffice laid
|
|
338
|
+
out beyond its frame, the right margin or the page (跑版), one sub-bullet per
|
|
339
|
+
place. ``"error: file not found: {path}"`` when the file does not exist.
|
|
340
|
+
Never raises.
|
|
341
|
+
"""
|
|
342
|
+
try:
|
|
343
|
+
target = Path(path)
|
|
344
|
+
if not target.exists():
|
|
345
|
+
return f"error: file not found: {path}"
|
|
346
|
+
soffice = find_soffice()
|
|
347
|
+
report = validate_odf(target, with_soffice=soffice is not None)
|
|
348
|
+
lines = [
|
|
349
|
+
f"- {name}: {'OK' if passed else 'FAIL'} — {message}"
|
|
350
|
+
for name, (passed, message) in report.gates.items()
|
|
351
|
+
]
|
|
352
|
+
if target.suffix.lower() in (".odp", ".odt"):
|
|
353
|
+
lines.extend(_layout_bullets(check_layout(target, soffice)))
|
|
354
|
+
return "\n".join(lines)
|
|
355
|
+
except Exception as exc:
|
|
356
|
+
return f"error: {type(exc).__name__}: {concise(str(exc))}"
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
@mcp.tool()
|
|
360
|
+
def preview_odf(path: str, out_dir: str) -> str:
|
|
361
|
+
"""Rasterise an ODF file to one PNG per page for an agent's visual QA loop.
|
|
362
|
+
|
|
363
|
+
Converts the ODF at ``path`` to PDF via a headless LibreOffice round-trip and
|
|
364
|
+
renders each page to a zero-padded PNG (``page-01.png``, ``page-02.png``, ...)
|
|
365
|
+
in ``out_dir``, which is created if missing. This hands the QA harness's
|
|
366
|
+
rendering capability to any calling agent: after forging a deck, preview it
|
|
367
|
+
and *look* at the PNGs to catch overflow, contrast or layout problems that
|
|
368
|
+
``inspect_odf`` (structure/XML validation) cannot see.
|
|
369
|
+
|
|
370
|
+
On success returns a JSON string ``{"pages": [<png path>, ...], "count": N}``
|
|
371
|
+
with the absolute PNG paths in page order. When LibreOffice is not installed
|
|
372
|
+
it returns ``"error: preview unavailable: <reason>"``; any other failure
|
|
373
|
+
returns ``"error: <reason>"``. Never raises (an exception inside an MCP tool
|
|
374
|
+
would surface as a protocol-level error).
|
|
375
|
+
"""
|
|
376
|
+
try:
|
|
377
|
+
pages = render_pages(Path(path), Path(out_dir))
|
|
378
|
+
return json.dumps({"pages": [str(p.resolve()) for p in pages], "count": len(pages)})
|
|
379
|
+
except PreviewUnavailable as exc:
|
|
380
|
+
return f"error: preview unavailable: {concise(str(exc))}"
|
|
381
|
+
except Exception as exc:
|
|
382
|
+
return f"error: {type(exc).__name__}: {concise(str(exc))}"
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _outline_text(path: Path) -> str:
|
|
386
|
+
from odforge.scene import scene_of
|
|
387
|
+
|
|
388
|
+
scene = scene_of(path)
|
|
389
|
+
size = f"{scene['width']:g} × {scene['height']:g} cm"
|
|
390
|
+
lines = [f"{path.name}: {len(scene['pages'])} 頁,頁面 {size}"]
|
|
391
|
+
for index, page in enumerate(scene["pages"]):
|
|
392
|
+
lines.append(f"\n第 {index + 1} 頁(page={index})")
|
|
393
|
+
for el in page["elements"]:
|
|
394
|
+
if el["kind"] == "line":
|
|
395
|
+
where = f"({el['x1']:.2f},{el['y1']:.2f})→({el['x2']:.2f},{el['y2']:.2f})"
|
|
396
|
+
else:
|
|
397
|
+
where = f"x={el['x']:.2f} y={el['y']:.2f} w={el['w']:.2f} h={el['h']:.2f}"
|
|
398
|
+
detail = ""
|
|
399
|
+
text = el.get("text")
|
|
400
|
+
if text:
|
|
401
|
+
paragraphs = ["".join(r["text"] for r in p["runs"]) for p in text["paragraphs"]]
|
|
402
|
+
first = next((r for p in text["paragraphs"] for r in p["runs"]), {})
|
|
403
|
+
size = f" {first.get('size'):g}pt" if first.get("size") else ""
|
|
404
|
+
detail = f"{size} 「" + " / ".join(paragraphs)[:120] + "」"
|
|
405
|
+
elif el.get("fill"):
|
|
406
|
+
detail = f" 填色 {el['fill']}"
|
|
407
|
+
lines.append(f" [{el['id']}] {el['kind']} {where}{detail}")
|
|
408
|
+
for comment in page.get("comments", []):
|
|
409
|
+
about = f"關於 [{comment['target']}]" if comment["target"] else "整頁"
|
|
410
|
+
text = comment["text"].replace("\n", " / ")
|
|
411
|
+
lines.append(f" 留言 [{comment['id']}] {about}:{text}")
|
|
412
|
+
pending = sum(len(p.get("comments", [])) for p in scene["pages"])
|
|
413
|
+
if pending:
|
|
414
|
+
lines.insert(1, f"待處理留言 {pending} 則(照留言改完後,用 comment_delete 刪掉該則留言)")
|
|
415
|
+
return "\n".join(lines)
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
@mcp.tool()
|
|
419
|
+
def outline_odp(path: str) -> str:
|
|
420
|
+
"""List every element of an existing ``.odp``: its id, kind, box and text.
|
|
421
|
+
|
|
422
|
+
Use this before ``edit_odp``: the ids it prints (``"page/index"``, e.g.
|
|
423
|
+
``"7/2"``) are what ``edit_odp`` operations refer to. Coordinates are in cm
|
|
424
|
+
from the slide's top-left corner. Works on any .odp, not only ODForge's.
|
|
425
|
+
Returns ``"error: ..."`` on failure; never raises.
|
|
426
|
+
"""
|
|
427
|
+
try:
|
|
428
|
+
target = Path(path)
|
|
429
|
+
if not target.is_file():
|
|
430
|
+
return f"error: file not found: {path}"
|
|
431
|
+
return _outline_text(target)
|
|
432
|
+
except Exception as exc:
|
|
433
|
+
return f"error: {type(exc).__name__}: {concise(str(exc))}"
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
@mcp.tool()
|
|
437
|
+
def edit_odp(path: str, ops: list) -> str:
|
|
438
|
+
"""Edit an existing ``.odp`` in place — the same operations the web editor uses.
|
|
439
|
+
|
|
440
|
+
Prefer this over re-forging a whole deck when the user has already edited the
|
|
441
|
+
file by hand (``odforge edit``): it changes only what you name, so their edits
|
|
442
|
+
survive. If the user has the editor open, they see your change within a second.
|
|
443
|
+
|
|
444
|
+
``ops`` is a list applied atomically (all or nothing); ids come from
|
|
445
|
+
``outline_odp`` and refer to positions *before* this batch:
|
|
446
|
+
|
|
447
|
+
* ``{"op": "text", "id": "7/2", "paragraphs": ["第一段", "第二段\n段內換行"]}``
|
|
448
|
+
— replace text, keeping each paragraph's style. A paragraph may instead be
|
|
449
|
+
``{"runs": [{"text": "...", "weight": 700, "italic": true, "underline": true,
|
|
450
|
+
"color": "#C62828", "size": 20, "family": "Noto Serif TC"}], "align": "center"}``.
|
|
451
|
+
* ``{"op": "geom", "id": "7/2", "x": 2, "y": 3, "w": 10, "h": 2}`` (cm; any
|
|
452
|
+
subset). Lines take ``x1/y1/x2/y2``.
|
|
453
|
+
* ``{"op": "add_text", "page": 0, "x": 2, "y": 2, "w": 10, "h": 1.5, "text": "..."}``,
|
|
454
|
+
``{"op": "add_rect", "page": 0, "x": .., "y": .., "w": .., "h": ..}``
|
|
455
|
+
* ``{"op": "delete", "id": "7/2"}``, ``{"op": "duplicate", "id": "7/2", "dx": 0.5, "dy": 0.5}``,
|
|
456
|
+
``{"op": "order", "id": "7/2", "to": "front" | "back" | "forward" | "backward"}``
|
|
457
|
+
* ``{"op": "page_add", "after": 3}``, ``{"op": "page_duplicate", "page": 3}``,
|
|
458
|
+
``{"op": "page_delete", "page": 3}``, ``{"op": "page_move", "page": 3, "to": 0}``
|
|
459
|
+
* ``{"op": "comment_delete", "comment": "c7/0"}`` — remove a comment once it is
|
|
460
|
+
handled (comments are listed by ``outline_odp``); ``{"op": "comment_add",
|
|
461
|
+
"id": "7/2", "text": "..."}`` to leave one for the user.
|
|
462
|
+
|
|
463
|
+
When the user asks you to apply their comments (照留言改): read them with
|
|
464
|
+
``outline_odp``, make each change, and delete each comment you resolved in the
|
|
465
|
+
same ``edit_odp`` call — the open editor then shows the page without it.
|
|
466
|
+
|
|
467
|
+
Deleting several elements of one page: list them from the highest index down,
|
|
468
|
+
or later ids shift. Returns ``"ok: ..."`` with the ids of anything created, then
|
|
469
|
+
the new outline of the pages touched; ``"error: ..."`` if any op was refused.
|
|
470
|
+
"""
|
|
471
|
+
try:
|
|
472
|
+
from odforge.odpedit import Document, EditError
|
|
473
|
+
|
|
474
|
+
target = Path(path)
|
|
475
|
+
if not target.is_file():
|
|
476
|
+
return f"error: file not found: {path}"
|
|
477
|
+
if not isinstance(ops, list) or not ops:
|
|
478
|
+
return "error: ops must be a non-empty list"
|
|
479
|
+
try:
|
|
480
|
+
state = Document(target).apply(ops)
|
|
481
|
+
except EditError as exc:
|
|
482
|
+
return f"error: {exc}"
|
|
483
|
+
created = state["created"]
|
|
484
|
+
result = f"ok: applied {len(ops)} operation(s) to {target.resolve()}"
|
|
485
|
+
if created:
|
|
486
|
+
result += f"; created: {', '.join(created)}"
|
|
487
|
+
return result + "\n\n" + _outline_text(target)
|
|
488
|
+
except Exception as exc:
|
|
489
|
+
return f"error: {type(exc).__name__}: {concise(str(exc))}"
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
@mcp.tool()
|
|
493
|
+
def open_editor(path: str) -> str:
|
|
494
|
+
"""Open an existing ``.odp`` in the ODForge web editor in the user's browser.
|
|
495
|
+
|
|
496
|
+
``forge_presentation`` already does this for decks it makes; use this for a
|
|
497
|
+
file that already exists (the user asks to look at or change a deck). Reuses
|
|
498
|
+
the editor already serving the file. Then call ``wait_for_feedback(path)``.
|
|
499
|
+
"""
|
|
500
|
+
try:
|
|
501
|
+
from odforge.editor_launch import ensure_editor
|
|
502
|
+
|
|
503
|
+
target = Path(path)
|
|
504
|
+
if not target.is_file() or target.suffix.lower() != ".odp":
|
|
505
|
+
return f"error: not an .odp file: {path}"
|
|
506
|
+
url = ensure_editor(target)
|
|
507
|
+
return (
|
|
508
|
+
f"ok: 已在瀏覽器打開 {url}。使用者可以在網頁上留言、按「交給 AI 修改」;"
|
|
509
|
+
f'接著呼叫 wait_for_feedback("{target.resolve()}")。'
|
|
510
|
+
)
|
|
511
|
+
except Exception as exc:
|
|
512
|
+
return f"error: {type(exc).__name__}: {concise(str(exc))}"
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
@mcp.tool()
|
|
516
|
+
async def wait_for_feedback(path: str, timeout_seconds: int = 50) -> str:
|
|
517
|
+
"""Wait for the person to hand you comments from the web editor, then return them.
|
|
518
|
+
|
|
519
|
+
Use after opening the editor for them (``odforge edit deck.odp``, which opens
|
|
520
|
+
their browser). They pin comments on the slides and press「交給 AI 修改」;
|
|
521
|
+
this returns those comments (``feedback: ...``) with the element each one is
|
|
522
|
+
about. Apply them with ``edit_odp`` — deleting each handled comment in the same
|
|
523
|
+
call — then call this again to wait for the next batch.
|
|
524
|
+
|
|
525
|
+
Returns ``waiting: ...`` when nothing arrived within ``timeout_seconds`` (keep
|
|
526
|
+
calling; the person may still be writing), or ``done: ...`` when they pressed
|
|
527
|
+
「完成」, which ends the loop. Never raises.
|
|
528
|
+
"""
|
|
529
|
+
try:
|
|
530
|
+
from odforge.feedback import wait_for_feedback as wait
|
|
531
|
+
|
|
532
|
+
target = Path(path)
|
|
533
|
+
if not target.is_file():
|
|
534
|
+
return f"error: file not found: {path}"
|
|
535
|
+
return await wait(target, float(max(1, min(timeout_seconds, 3600))))
|
|
536
|
+
except Exception as exc:
|
|
537
|
+
return f"error: {type(exc).__name__}: {concise(str(exc))}"
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def main() -> None: # pragma: no cover
|
|
541
|
+
"""Console-script entry point (``odforge-mcp``): run the stdio MCP server.
|
|
542
|
+
|
|
543
|
+
Exists so that ``pip install odforge`` yields a *command* an MCP host can be
|
|
544
|
+
pointed at. Without it, wiring ODForge into Claude Code / Cursor / any other
|
|
545
|
+
host meant knowing the module path and which interpreter to use — a barrier
|
|
546
|
+
that had nothing to do with the tool's capabilities.
|
|
547
|
+
"""
|
|
548
|
+
mcp.run()
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
if __name__ == "__main__": # pragma: no cover
|
|
552
|
+
main()
|