draftboard 0.0.1__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.
- draftboard/__init__.py +41 -0
- draftboard/__main__.py +225 -0
- draftboard/agent.py +104 -0
- draftboard/api.py +901 -0
- draftboard/measure.py +225 -0
- draftboard/models.py +407 -0
- draftboard/pptx_export.py +479 -0
- draftboard/render.py +80 -0
- draftboard/static/404.html +1 -0
- draftboard/static/__next.__PAGE__.txt +27 -0
- draftboard/static/__next._full.txt +22 -0
- draftboard/static/__next._tree.txt +3 -0
- draftboard/static/_next/static/0t_Cdsf-nvbYcwqDy78ch/_buildManifest.js +11 -0
- draftboard/static/_next/static/0t_Cdsf-nvbYcwqDy78ch/_clientMiddlewareManifest.js +1 -0
- draftboard/static/_next/static/0t_Cdsf-nvbYcwqDy78ch/_ssgManifest.js +1 -0
- draftboard/static/_next/static/chunks/0cz1d0mv5g_q7.js +1 -0
- draftboard/static/_next/static/chunks/0oheds1fsp9jx.js +1 -0
- draftboard/static/_next/static/chunks/1vsonpqt4u2rw.js +1 -0
- draftboard/static/_next/static/chunks/24xul4hawiu8l.js +1 -0
- draftboard/static/_next/static/chunks/2r7iycbt4s29o.js +22 -0
- draftboard/static/_next/static/chunks/2utugak-w5oge.css +1 -0
- draftboard/static/_next/static/chunks/39_j1bdzreq0m.js +1 -0
- draftboard/static/_next/static/chunks/3qfy96eoyh-ek.js +1 -0
- draftboard/static/_next/static/chunks/3u8gxd9uztfzl.js +4 -0
- draftboard/static/_next/static/chunks/3v_59l1qr_8dp.js +31 -0
- draftboard/static/_next/static/chunks/turbopack-2u1d16houkiyo.js +1 -0
- draftboard/static/_not-found/__next._full.txt +20 -0
- draftboard/static/_not-found/__next._not-found/__PAGE__.txt +26 -0
- draftboard/static/_not-found/__next._tree.txt +4 -0
- draftboard/static/_not-found.html +1 -0
- draftboard/static/_not-found.txt +20 -0
- draftboard/static/index.html +1 -0
- draftboard/static/index.txt +22 -0
- draftboard/static/p/__placeholder__/__next._full.txt +27 -0
- draftboard/static/p/__placeholder__/__next._tree.txt +5 -0
- draftboard/static/p/__placeholder__/__next.p/$d$id/__PAGE__.txt +34 -0
- draftboard/static/p/__placeholder__/preview/__next._full.txt +27 -0
- draftboard/static/p/__placeholder__/preview/__next._tree.txt +6 -0
- draftboard/static/p/__placeholder__/preview/__next.p/$d$id/preview/__PAGE__.txt +35 -0
- draftboard/static/p/__placeholder__/preview.html +1 -0
- draftboard/static/p/__placeholder__/preview.txt +27 -0
- draftboard/static/p/__placeholder__.html +1 -0
- draftboard/static/p/__placeholder__.txt +27 -0
- draftboard/storage.py +183 -0
- draftboard/tasks.py +464 -0
- draftboard/themes.py +213 -0
- draftboard/tools.py +723 -0
- draftboard-0.0.1.dist-info/METADATA +16 -0
- draftboard-0.0.1.dist-info/RECORD +51 -0
- draftboard-0.0.1.dist-info/WHEEL +4 -0
- draftboard-0.0.1.dist-info/entry_points.txt +2 -0
draftboard/tools.py
ADDED
|
@@ -0,0 +1,723 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Agent tools for the Draftboard workbench.
|
|
3
|
+
Each function is decorated with @function_tool so the OpenAI Agents SDK
|
|
4
|
+
can expose it to the model as a callable tool.
|
|
5
|
+
|
|
6
|
+
Dependency injection for storage root is provided via _storage_root module
|
|
7
|
+
variable (set in tests to redirect writes to a tmp directory).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import pathlib
|
|
11
|
+
import uuid
|
|
12
|
+
import xml.etree.ElementTree as ET
|
|
13
|
+
import zipfile
|
|
14
|
+
from typing import Optional
|
|
15
|
+
|
|
16
|
+
import pypdfium2 as pdfium
|
|
17
|
+
from agents import function_tool
|
|
18
|
+
|
|
19
|
+
from draftboard.models import (
|
|
20
|
+
Artifact,
|
|
21
|
+
AssetType,
|
|
22
|
+
EvidenceStatus,
|
|
23
|
+
ExportResult,
|
|
24
|
+
MaterialContent,
|
|
25
|
+
OutlineItem,
|
|
26
|
+
Outline,
|
|
27
|
+
ReadMaterialsOutput,
|
|
28
|
+
Slide,
|
|
29
|
+
SlideElement,
|
|
30
|
+
SlideLayout,
|
|
31
|
+
SourceFragment,
|
|
32
|
+
ValidationIssue,
|
|
33
|
+
ValidationLevel,
|
|
34
|
+
ValidationReport,
|
|
35
|
+
validate_ir,
|
|
36
|
+
validate_outline,
|
|
37
|
+
)
|
|
38
|
+
from draftboard.pptx_export import export_pptx
|
|
39
|
+
from draftboard.storage import STORAGE_ROOT, ProjectStorage
|
|
40
|
+
|
|
41
|
+
# Set to a pathlib.Path in tests to redirect storage to a temporary directory.
|
|
42
|
+
_storage_root: Optional[pathlib.Path] = None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _get_storage(project_id: str) -> ProjectStorage:
|
|
46
|
+
return ProjectStorage(project_id, storage_root=_storage_root)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
_W_NS = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _extract_docx_text(filepath: pathlib.Path) -> str:
|
|
53
|
+
"""Extract plain text from a .docx file using stdlib zipfile + ElementTree."""
|
|
54
|
+
try:
|
|
55
|
+
with zipfile.ZipFile(filepath) as zf:
|
|
56
|
+
if "word/document.xml" not in zf.namelist():
|
|
57
|
+
raise ValueError(f"DOCX 文件缺少 word/document.xml: {filepath.name}")
|
|
58
|
+
xml_bytes = zf.read("word/document.xml")
|
|
59
|
+
except zipfile.BadZipFile as exc:
|
|
60
|
+
raise ValueError(f"无法解析损坏的 DOCX 文件 '{filepath.name}'") from exc
|
|
61
|
+
|
|
62
|
+
try:
|
|
63
|
+
root = ET.fromstring(xml_bytes)
|
|
64
|
+
except ET.ParseError as exc:
|
|
65
|
+
raise ValueError(f"DOCX 文档 XML 结构损坏 '{filepath.name}'") from exc
|
|
66
|
+
|
|
67
|
+
lines: list[str] = []
|
|
68
|
+
body = root.find(f"{_W_NS}body")
|
|
69
|
+
container = body if body is not None else root
|
|
70
|
+
for elem in container:
|
|
71
|
+
if elem.tag == f"{_W_NS}p":
|
|
72
|
+
para = "".join(t.text or "" for t in elem.findall(f".//{_W_NS}t")).strip()
|
|
73
|
+
if para:
|
|
74
|
+
lines.append(para)
|
|
75
|
+
elif elem.tag == f"{_W_NS}tbl":
|
|
76
|
+
for row in elem.findall(f".//{_W_NS}tr"):
|
|
77
|
+
cells = []
|
|
78
|
+
for cell in row.findall(f"./{_W_NS}tc"):
|
|
79
|
+
cell_text = " ".join(
|
|
80
|
+
"".join(t.text or "" for t in p.findall(f".//{_W_NS}t")).strip()
|
|
81
|
+
for p in cell.findall(f".//{_W_NS}p")
|
|
82
|
+
).strip()
|
|
83
|
+
if cell_text:
|
|
84
|
+
cells.append(cell_text)
|
|
85
|
+
if cells:
|
|
86
|
+
lines.append(" | ".join(cells))
|
|
87
|
+
return "\n".join(lines)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _extract_pdf_pages(filepath: pathlib.Path) -> list[tuple[int, str]]:
|
|
91
|
+
"""Extract per-page plain text from a PDF file using pypdfium2."""
|
|
92
|
+
try:
|
|
93
|
+
doc = pdfium.PdfDocument(str(filepath))
|
|
94
|
+
except Exception as exc:
|
|
95
|
+
raise ValueError(f"无法解析 PDF 文件 '{filepath.name}'(可能已损坏或受密码保护)") from exc
|
|
96
|
+
|
|
97
|
+
pages: list[tuple[int, str]] = []
|
|
98
|
+
try:
|
|
99
|
+
page_count = len(doc)
|
|
100
|
+
for idx in range(page_count):
|
|
101
|
+
page = doc[idx]
|
|
102
|
+
textpage = page.get_textpage()
|
|
103
|
+
raw = textpage.get_text_range() or ""
|
|
104
|
+
cleaned = "\n".join(
|
|
105
|
+
line.strip() for line in raw.splitlines() if line.strip()
|
|
106
|
+
)
|
|
107
|
+
pages.append((idx + 1, cleaned))
|
|
108
|
+
finally:
|
|
109
|
+
doc.close()
|
|
110
|
+
return pages
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# ── Tool 1: read_materials ────────────────────────────────────────────────────
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@function_tool
|
|
117
|
+
def read_materials(
|
|
118
|
+
project_id: str,
|
|
119
|
+
asset_ids: Optional[list[str]] = None,
|
|
120
|
+
) -> ReadMaterialsOutput:
|
|
121
|
+
"""Read project materials (Markdown/TXT/DOCX/PDF files and images) from disk.
|
|
122
|
+
|
|
123
|
+
Scans ~/.draftboard/projects/{project_id}/assets/ for .md, .txt, .docx,
|
|
124
|
+
.pdf, .png, and .jpg files. Text content is returned verbatim and split
|
|
125
|
+
into 50-line (or per-page) source fragments. Images are represented as a
|
|
126
|
+
stub string of the form '[image: {filename}]' – the agent must NOT
|
|
127
|
+
fabricate any image analysis.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
project_id: Identifier of the project whose assets to read.
|
|
131
|
+
asset_ids: Optional list of asset filenames (without extension) to
|
|
132
|
+
restrict which assets are loaded. None means load all assets.
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
ReadMaterialsOutput containing materials and source fragments.
|
|
136
|
+
"""
|
|
137
|
+
storage = _get_storage(project_id)
|
|
138
|
+
assets_dir = storage.root / "assets"
|
|
139
|
+
assets_dir.mkdir(parents=True, exist_ok=True)
|
|
140
|
+
|
|
141
|
+
materials: list[MaterialContent] = []
|
|
142
|
+
fragments: list[SourceFragment] = []
|
|
143
|
+
|
|
144
|
+
# Collect candidate files
|
|
145
|
+
candidate_files: list[pathlib.Path] = []
|
|
146
|
+
for ext in ("*.md", "*.txt", "*.docx", "*.pdf", "*.png", "*.jpg", "*.jpeg"):
|
|
147
|
+
candidate_files.extend(assets_dir.glob(ext))
|
|
148
|
+
|
|
149
|
+
for filepath in sorted(candidate_files):
|
|
150
|
+
stem = filepath.stem
|
|
151
|
+
if asset_ids is not None and stem not in asset_ids:
|
|
152
|
+
continue
|
|
153
|
+
|
|
154
|
+
suffix = filepath.suffix.lower()
|
|
155
|
+
if suffix in (".md", ".txt", ".docx"):
|
|
156
|
+
if suffix == ".docx":
|
|
157
|
+
text = _extract_docx_text(filepath)
|
|
158
|
+
else:
|
|
159
|
+
text = filepath.read_text(encoding="utf-8", errors="replace")
|
|
160
|
+
materials.append(
|
|
161
|
+
MaterialContent(
|
|
162
|
+
asset_id=stem,
|
|
163
|
+
asset_type=AssetType.MARKDOWN,
|
|
164
|
+
content=text,
|
|
165
|
+
)
|
|
166
|
+
)
|
|
167
|
+
# Split into 50-line fragments
|
|
168
|
+
lines = text.splitlines()
|
|
169
|
+
chunk_size = 50
|
|
170
|
+
for chunk_start in range(0, max(len(lines), 1), chunk_size):
|
|
171
|
+
chunk_end = min(chunk_start + chunk_size, len(lines))
|
|
172
|
+
chunk_lines = lines[chunk_start:chunk_end]
|
|
173
|
+
frag_id = f"{stem}-L{chunk_start + 1}"
|
|
174
|
+
fragments.append(
|
|
175
|
+
SourceFragment(
|
|
176
|
+
source_id=frag_id,
|
|
177
|
+
asset_id=stem,
|
|
178
|
+
location=f"L{chunk_start + 1}-L{chunk_end}",
|
|
179
|
+
content_preview=" ".join(chunk_lines[:3])[:200] or None,
|
|
180
|
+
)
|
|
181
|
+
)
|
|
182
|
+
elif suffix == ".pdf":
|
|
183
|
+
pdf_pages = _extract_pdf_pages(filepath)
|
|
184
|
+
combined_parts: list[str] = []
|
|
185
|
+
if not pdf_pages:
|
|
186
|
+
fragments.append(
|
|
187
|
+
SourceFragment(
|
|
188
|
+
source_id=f"{stem}-P1",
|
|
189
|
+
asset_id=stem,
|
|
190
|
+
location="P1",
|
|
191
|
+
content_preview="[空 PDF 文档]",
|
|
192
|
+
)
|
|
193
|
+
)
|
|
194
|
+
for page_num, page_text in pdf_pages:
|
|
195
|
+
if page_text:
|
|
196
|
+
combined_parts.append(page_text)
|
|
197
|
+
lines = page_text.splitlines()
|
|
198
|
+
if len(lines) <= 50:
|
|
199
|
+
preview = (
|
|
200
|
+
" ".join(lines[:3])[:200]
|
|
201
|
+
if lines
|
|
202
|
+
else "[该页无可提取文本(可能为纯图片/扫描页)]"
|
|
203
|
+
)
|
|
204
|
+
fragments.append(
|
|
205
|
+
SourceFragment(
|
|
206
|
+
source_id=f"{stem}-P{page_num}",
|
|
207
|
+
asset_id=stem,
|
|
208
|
+
location=f"P{page_num}",
|
|
209
|
+
content_preview=preview,
|
|
210
|
+
)
|
|
211
|
+
)
|
|
212
|
+
else:
|
|
213
|
+
chunk_size = 50
|
|
214
|
+
for chunk_start in range(0, len(lines), chunk_size):
|
|
215
|
+
chunk_end = min(chunk_start + chunk_size, len(lines))
|
|
216
|
+
chunk_lines = lines[chunk_start:chunk_end]
|
|
217
|
+
fragments.append(
|
|
218
|
+
SourceFragment(
|
|
219
|
+
source_id=f"{stem}-P{page_num}-L{chunk_start + 1}",
|
|
220
|
+
asset_id=stem,
|
|
221
|
+
location=f"P{page_num} L{chunk_start + 1}-L{chunk_end}",
|
|
222
|
+
content_preview=" ".join(chunk_lines[:3])[:200] or None,
|
|
223
|
+
)
|
|
224
|
+
)
|
|
225
|
+
materials.append(
|
|
226
|
+
MaterialContent(
|
|
227
|
+
asset_id=stem,
|
|
228
|
+
asset_type=AssetType.MARKDOWN,
|
|
229
|
+
content="\n\n".join(combined_parts),
|
|
230
|
+
)
|
|
231
|
+
)
|
|
232
|
+
else:
|
|
233
|
+
# Image file
|
|
234
|
+
stub = f"[image: {filepath.name}]"
|
|
235
|
+
materials.append(
|
|
236
|
+
MaterialContent(
|
|
237
|
+
asset_id=stem,
|
|
238
|
+
asset_type=AssetType.IMAGE,
|
|
239
|
+
content=stub,
|
|
240
|
+
)
|
|
241
|
+
)
|
|
242
|
+
fragments.append(
|
|
243
|
+
SourceFragment(
|
|
244
|
+
source_id=f"{stem}-img",
|
|
245
|
+
asset_id=stem,
|
|
246
|
+
location=stem,
|
|
247
|
+
content_preview=None,
|
|
248
|
+
)
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
storage.save_sources(fragments)
|
|
252
|
+
return ReadMaterialsOutput(
|
|
253
|
+
project_id=project_id,
|
|
254
|
+
materials=materials,
|
|
255
|
+
source_fragments=fragments,
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
# ── Tool 2: propose_outline ───────────────────────────────────────────────────
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@function_tool
|
|
263
|
+
def propose_outline(
|
|
264
|
+
project_id: str,
|
|
265
|
+
material_snapshot_id: str,
|
|
266
|
+
items: list[OutlineItem],
|
|
267
|
+
) -> Outline:
|
|
268
|
+
"""Persist a draft outline proposed by the agent.
|
|
269
|
+
|
|
270
|
+
The agent should populate *items* based on its analysis of the materials.
|
|
271
|
+
This tool saves the outline with is_confirmed=False and returns it so the
|
|
272
|
+
user can review and approve.
|
|
273
|
+
|
|
274
|
+
Args:
|
|
275
|
+
project_id: Target project identifier.
|
|
276
|
+
material_snapshot_id: Identifier of the material snapshot used to
|
|
277
|
+
build this outline (for traceability).
|
|
278
|
+
items: List of OutlineItem objects the agent has prepared.
|
|
279
|
+
|
|
280
|
+
Returns:
|
|
281
|
+
The saved Outline with a generated outline_version.
|
|
282
|
+
|
|
283
|
+
Raises:
|
|
284
|
+
ValueError: If titles/summaries are empty, item IDs repeat, citations
|
|
285
|
+
reference unknown source fragments, or a layout cannot be built
|
|
286
|
+
from an outline. Nothing is saved on failure.
|
|
287
|
+
"""
|
|
288
|
+
storage = _get_storage(project_id)
|
|
289
|
+
errors = validate_outline(items, storage.load_source_ids())
|
|
290
|
+
if errors:
|
|
291
|
+
raise ValueError("Invalid outline:\n" + "\n".join(errors))
|
|
292
|
+
outline_version = f"v-{uuid.uuid4().hex[:8]}"
|
|
293
|
+
outline = Outline(
|
|
294
|
+
outline_version=outline_version,
|
|
295
|
+
project_id=project_id,
|
|
296
|
+
items=items,
|
|
297
|
+
is_confirmed=False,
|
|
298
|
+
)
|
|
299
|
+
storage.save_outline(outline)
|
|
300
|
+
return outline
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
# ── Tool 3: generate_slides ───────────────────────────────────────────────────
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
@function_tool
|
|
307
|
+
def generate_slides(
|
|
308
|
+
project_id: str,
|
|
309
|
+
approved_outline_version: str,
|
|
310
|
+
template_id: str = "default",
|
|
311
|
+
idempotency_key: str = "",
|
|
312
|
+
auto_fit: bool = False,
|
|
313
|
+
) -> Artifact:
|
|
314
|
+
"""Generate a slide artifact from an approved outline.
|
|
315
|
+
|
|
316
|
+
Requires the outline to be confirmed (is_confirmed=True). Checks the
|
|
317
|
+
idempotency cache first; if a previous call with the same key exists its
|
|
318
|
+
result is returned unchanged.
|
|
319
|
+
|
|
320
|
+
Args:
|
|
321
|
+
project_id: Target project identifier.
|
|
322
|
+
approved_outline_version: Outline version that has been confirmed by
|
|
323
|
+
the user.
|
|
324
|
+
template_id: Slide template/theme to apply (default: "default").
|
|
325
|
+
idempotency_key: Unique string; identical keys return the cached
|
|
326
|
+
artifact without re-generating slides.
|
|
327
|
+
auto_fit: When True, allow exporter to step font size down to floor
|
|
328
|
+
(body >= 14pt, cover title >= 28pt) before blocking on overflow.
|
|
329
|
+
|
|
330
|
+
Returns:
|
|
331
|
+
The generated (or cached) Artifact.
|
|
332
|
+
|
|
333
|
+
Raises:
|
|
334
|
+
ValueError: If the outline has not been confirmed.
|
|
335
|
+
"""
|
|
336
|
+
storage = _get_storage(project_id)
|
|
337
|
+
|
|
338
|
+
# Idempotency check
|
|
339
|
+
if idempotency_key:
|
|
340
|
+
cached = storage.load_idempotent_result(idempotency_key)
|
|
341
|
+
if cached is not None:
|
|
342
|
+
return Artifact.model_validate(cached)
|
|
343
|
+
|
|
344
|
+
# Load and validate outline
|
|
345
|
+
outline = storage.load_outline(approved_outline_version)
|
|
346
|
+
if not outline.is_confirmed:
|
|
347
|
+
raise ValueError(
|
|
348
|
+
f"Outline '{approved_outline_version}' has not been confirmed. "
|
|
349
|
+
"Ask the user to confirm the outline before generating slides."
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
# Build slides verbatim from the confirmed outline. Layout comes from
|
|
353
|
+
# the confirmed item, or the program default: first cover, last closing,
|
|
354
|
+
# others content. No model rewriting happens here.
|
|
355
|
+
n = len(outline.items)
|
|
356
|
+
slides: list[Slide] = []
|
|
357
|
+
for idx, item in enumerate(outline.items):
|
|
358
|
+
slide_id = f"slide-{idx + 1:03d}"
|
|
359
|
+
source_id = item.source_ids[0] if item.source_ids else None
|
|
360
|
+
layout = item.layout
|
|
361
|
+
if layout is None:
|
|
362
|
+
if idx == 0:
|
|
363
|
+
layout = SlideLayout.COVER
|
|
364
|
+
elif idx == n - 1:
|
|
365
|
+
layout = SlideLayout.CLOSING
|
|
366
|
+
else:
|
|
367
|
+
layout = SlideLayout.CONTENT
|
|
368
|
+
|
|
369
|
+
elements = [
|
|
370
|
+
SlideElement(
|
|
371
|
+
element_id=f"{slide_id}-title",
|
|
372
|
+
type="title",
|
|
373
|
+
content=item.title,
|
|
374
|
+
source_id=source_id,
|
|
375
|
+
)
|
|
376
|
+
]
|
|
377
|
+
if layout == SlideLayout.BULLETS:
|
|
378
|
+
lines = [ln for ln in item.summary.split("\n") if ln.strip()]
|
|
379
|
+
for bi, line in enumerate(lines, start=1):
|
|
380
|
+
elements.append(
|
|
381
|
+
SlideElement(
|
|
382
|
+
element_id=f"{slide_id}-bullet-{bi}",
|
|
383
|
+
type="bullet",
|
|
384
|
+
content=line,
|
|
385
|
+
source_id=source_id,
|
|
386
|
+
)
|
|
387
|
+
)
|
|
388
|
+
elif layout == SlideLayout.TWO_COLUMN:
|
|
389
|
+
elements.append(
|
|
390
|
+
SlideElement(
|
|
391
|
+
element_id=f"{slide_id}-column-left",
|
|
392
|
+
type="column_left",
|
|
393
|
+
content=item.summary,
|
|
394
|
+
source_id=source_id,
|
|
395
|
+
)
|
|
396
|
+
)
|
|
397
|
+
elements.append(
|
|
398
|
+
SlideElement(
|
|
399
|
+
element_id=f"{slide_id}-column-right",
|
|
400
|
+
type="column_right",
|
|
401
|
+
content=item.column_right or "",
|
|
402
|
+
source_id=source_id,
|
|
403
|
+
)
|
|
404
|
+
)
|
|
405
|
+
elif layout == SlideLayout.TEXT_IMAGE:
|
|
406
|
+
elements.append(
|
|
407
|
+
SlideElement(
|
|
408
|
+
element_id=f"{slide_id}-text",
|
|
409
|
+
type="text",
|
|
410
|
+
content=item.summary,
|
|
411
|
+
source_id=source_id,
|
|
412
|
+
)
|
|
413
|
+
)
|
|
414
|
+
elements.append(
|
|
415
|
+
SlideElement(
|
|
416
|
+
element_id=f"{slide_id}-image",
|
|
417
|
+
type="image",
|
|
418
|
+
content=item.image_asset_id or "",
|
|
419
|
+
source_id=source_id,
|
|
420
|
+
)
|
|
421
|
+
)
|
|
422
|
+
else:
|
|
423
|
+
role = {
|
|
424
|
+
SlideLayout.COVER: "subtitle",
|
|
425
|
+
SlideLayout.CONTENT: "text",
|
|
426
|
+
SlideLayout.CLOSING: "conclusion",
|
|
427
|
+
}[layout]
|
|
428
|
+
elements.append(
|
|
429
|
+
SlideElement(
|
|
430
|
+
element_id=f"{slide_id}-{role}",
|
|
431
|
+
type=role,
|
|
432
|
+
content=item.summary,
|
|
433
|
+
source_id=source_id,
|
|
434
|
+
)
|
|
435
|
+
)
|
|
436
|
+
slides.append(
|
|
437
|
+
Slide(
|
|
438
|
+
slide_id=slide_id,
|
|
439
|
+
layout=layout,
|
|
440
|
+
elements=elements,
|
|
441
|
+
speaker_notes=item.speaker_notes,
|
|
442
|
+
)
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
artifact_id = f"art-{uuid.uuid4().hex[:8]}"
|
|
446
|
+
artifact = Artifact(
|
|
447
|
+
artifact_id=artifact_id,
|
|
448
|
+
project_id=project_id,
|
|
449
|
+
artifact_revision=1,
|
|
450
|
+
slides=slides,
|
|
451
|
+
outline_version=approved_outline_version,
|
|
452
|
+
template_id=template_id,
|
|
453
|
+
auto_fit=auto_fit,
|
|
454
|
+
)
|
|
455
|
+
ir_errors = validate_ir(artifact)
|
|
456
|
+
if ir_errors:
|
|
457
|
+
raise ValueError("Generated IR is invalid:\n" + "\n".join(ir_errors))
|
|
458
|
+
storage.save_artifact(artifact)
|
|
459
|
+
|
|
460
|
+
if idempotency_key:
|
|
461
|
+
storage.save_idempotent_result(idempotency_key, artifact.model_dump())
|
|
462
|
+
|
|
463
|
+
return artifact
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
# ── Tool 4: patch_slide ───────────────────────────────────────────────────────
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
@function_tool
|
|
470
|
+
def patch_slide(
|
|
471
|
+
artifact_id: str,
|
|
472
|
+
slide_id: str,
|
|
473
|
+
expected_revision: int,
|
|
474
|
+
operation_type: str,
|
|
475
|
+
element_id: str,
|
|
476
|
+
new_content: str,
|
|
477
|
+
idempotency_key: str = "",
|
|
478
|
+
) -> Artifact:
|
|
479
|
+
"""Apply a targeted edit to a single slide element.
|
|
480
|
+
|
|
481
|
+
Checks the idempotency cache; if a matching cached result exists it is
|
|
482
|
+
returned unchanged. Otherwise, the artifact is loaded at
|
|
483
|
+
*expected_revision*, the element is patched, and the new revision is saved.
|
|
484
|
+
|
|
485
|
+
Supported operation_type values:
|
|
486
|
+
- replace_text – replace the text content of a text or title element
|
|
487
|
+
- replace_existing_image – replace the reference of an existing image element
|
|
488
|
+
|
|
489
|
+
Args:
|
|
490
|
+
artifact_id: Artifact to patch.
|
|
491
|
+
slide_id: ID of the slide containing the element.
|
|
492
|
+
expected_revision: Revision the caller believes is current; rejected
|
|
493
|
+
if it does not match the latest revision on disk.
|
|
494
|
+
operation_type: One of replace_text or replace_existing_image.
|
|
495
|
+
element_id: ID of the element to modify.
|
|
496
|
+
new_content: Replacement content string.
|
|
497
|
+
idempotency_key: Unique string; identical keys return the cached result.
|
|
498
|
+
|
|
499
|
+
Returns:
|
|
500
|
+
The new Artifact at the incremented revision.
|
|
501
|
+
|
|
502
|
+
Raises:
|
|
503
|
+
ValueError: On invalid operation_type or revision mismatch.
|
|
504
|
+
"""
|
|
505
|
+
# Determine project_id from artifact storage by locating the artifact directory.
|
|
506
|
+
# We need to search across all projects – but patch_slide requires knowing the
|
|
507
|
+
# project_id. To keep the tool simple, we embed project lookup via storage root.
|
|
508
|
+
# In practice the agent should track project_id; we derive it here by scanning.
|
|
509
|
+
storage_root = _storage_root or STORAGE_ROOT
|
|
510
|
+
|
|
511
|
+
# Find project that owns this artifact
|
|
512
|
+
project_id: Optional[str] = None
|
|
513
|
+
if storage_root.exists():
|
|
514
|
+
for proj_dir in storage_root.iterdir():
|
|
515
|
+
art_dir = proj_dir / "artifacts" / artifact_id
|
|
516
|
+
if art_dir.exists():
|
|
517
|
+
project_id = proj_dir.name
|
|
518
|
+
break
|
|
519
|
+
|
|
520
|
+
if project_id is None:
|
|
521
|
+
raise KeyError(f"Artifact '{artifact_id}' not found in any project.")
|
|
522
|
+
|
|
523
|
+
storage = _get_storage(project_id)
|
|
524
|
+
|
|
525
|
+
# Idempotency check
|
|
526
|
+
if idempotency_key:
|
|
527
|
+
cached = storage.load_idempotent_result(idempotency_key)
|
|
528
|
+
if cached is not None:
|
|
529
|
+
return Artifact.model_validate(cached)
|
|
530
|
+
|
|
531
|
+
# Validate operation type
|
|
532
|
+
allowed_ops = {"replace_text", "replace_existing_image"}
|
|
533
|
+
if operation_type not in allowed_ops:
|
|
534
|
+
raise ValueError(
|
|
535
|
+
f"Invalid operation_type '{operation_type}'. "
|
|
536
|
+
f"Must be one of: {', '.join(sorted(allowed_ops))}"
|
|
537
|
+
)
|
|
538
|
+
|
|
539
|
+
# Load artifact at expected revision
|
|
540
|
+
artifact = storage.load_artifact(artifact_id, expected_revision)
|
|
541
|
+
if artifact.artifact_revision != expected_revision:
|
|
542
|
+
raise ValueError(
|
|
543
|
+
f"Revision mismatch: expected {expected_revision}, "
|
|
544
|
+
f"found {artifact.artifact_revision}."
|
|
545
|
+
)
|
|
546
|
+
|
|
547
|
+
# Locate and patch element
|
|
548
|
+
patched = False
|
|
549
|
+
for slide in artifact.slides:
|
|
550
|
+
if slide.slide_id == slide_id:
|
|
551
|
+
for element in slide.elements:
|
|
552
|
+
if element.element_id == element_id:
|
|
553
|
+
element.content = new_content
|
|
554
|
+
patched = True
|
|
555
|
+
break
|
|
556
|
+
break
|
|
557
|
+
|
|
558
|
+
if not patched:
|
|
559
|
+
raise KeyError(
|
|
560
|
+
f"Element '{element_id}' not found in slide '{slide_id}' "
|
|
561
|
+
f"of artifact '{artifact_id}'."
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
# Increment revision and persist
|
|
565
|
+
new_revision = storage.next_revision(artifact_id)
|
|
566
|
+
artifact.artifact_revision = new_revision
|
|
567
|
+
storage.save_artifact(artifact)
|
|
568
|
+
|
|
569
|
+
if idempotency_key:
|
|
570
|
+
storage.save_idempotent_result(idempotency_key, artifact.model_dump())
|
|
571
|
+
|
|
572
|
+
return artifact
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
# ── Tool 5: validate_artifact ─────────────────────────────────────────────────
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
@function_tool
|
|
579
|
+
def validate_artifact(artifact_id: str, revision: int) -> ValidationReport:
|
|
580
|
+
"""Validate a slide artifact and return a structured report.
|
|
581
|
+
|
|
582
|
+
Checks applied:
|
|
583
|
+
- Each slide must contain at least one element with type 'title' (ERROR
|
|
584
|
+
if missing).
|
|
585
|
+
- Any element whose content is an empty string is flagged as WARNING.
|
|
586
|
+
|
|
587
|
+
Args:
|
|
588
|
+
artifact_id: Artifact to validate.
|
|
589
|
+
revision: Specific revision to validate.
|
|
590
|
+
|
|
591
|
+
Returns:
|
|
592
|
+
ValidationReport listing all issues found.
|
|
593
|
+
"""
|
|
594
|
+
storage_root = _storage_root or STORAGE_ROOT
|
|
595
|
+
|
|
596
|
+
project_id: Optional[str] = None
|
|
597
|
+
if storage_root.exists():
|
|
598
|
+
for proj_dir in storage_root.iterdir():
|
|
599
|
+
art_dir = proj_dir / "artifacts" / artifact_id
|
|
600
|
+
if art_dir.exists():
|
|
601
|
+
project_id = proj_dir.name
|
|
602
|
+
break
|
|
603
|
+
|
|
604
|
+
if project_id is None:
|
|
605
|
+
raise KeyError(f"Artifact '{artifact_id}' not found.")
|
|
606
|
+
|
|
607
|
+
storage = _get_storage(project_id)
|
|
608
|
+
artifact = storage.load_artifact(artifact_id, revision)
|
|
609
|
+
|
|
610
|
+
issues: list[ValidationIssue] = []
|
|
611
|
+
|
|
612
|
+
for msg in validate_ir(artifact):
|
|
613
|
+
issues.append(
|
|
614
|
+
ValidationIssue(
|
|
615
|
+
level=ValidationLevel.ERROR,
|
|
616
|
+
code="IR_INVALID",
|
|
617
|
+
message=msg,
|
|
618
|
+
)
|
|
619
|
+
)
|
|
620
|
+
|
|
621
|
+
for slide in artifact.slides:
|
|
622
|
+
has_title = any(el.type == "title" for el in slide.elements)
|
|
623
|
+
if not has_title:
|
|
624
|
+
issues.append(
|
|
625
|
+
ValidationIssue(
|
|
626
|
+
level=ValidationLevel.ERROR,
|
|
627
|
+
code="MISSING_TITLE",
|
|
628
|
+
message=f"Slide '{slide.slide_id}' has no title element.",
|
|
629
|
+
slide_id=slide.slide_id,
|
|
630
|
+
)
|
|
631
|
+
)
|
|
632
|
+
for element in slide.elements:
|
|
633
|
+
if element.content == "":
|
|
634
|
+
issues.append(
|
|
635
|
+
ValidationIssue(
|
|
636
|
+
level=ValidationLevel.WARNING,
|
|
637
|
+
code="EMPTY_CONTENT",
|
|
638
|
+
message=(
|
|
639
|
+
f"Element '{element.element_id}' in slide "
|
|
640
|
+
f"'{slide.slide_id}' has empty content."
|
|
641
|
+
),
|
|
642
|
+
slide_id=slide.slide_id,
|
|
643
|
+
)
|
|
644
|
+
)
|
|
645
|
+
|
|
646
|
+
return ValidationReport(
|
|
647
|
+
artifact_id=artifact_id,
|
|
648
|
+
artifact_revision=revision,
|
|
649
|
+
issues=issues,
|
|
650
|
+
)
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
# ── Tool 6: export_deck ───────────────────────────────────────────────────────
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def export_deck_impl(
|
|
657
|
+
project_id: str,
|
|
658
|
+
artifact_id: str,
|
|
659
|
+
revision: int,
|
|
660
|
+
idempotency_key: str = "",
|
|
661
|
+
) -> ExportResult:
|
|
662
|
+
"""Export a validated artifact revision to an editable PPTX file.
|
|
663
|
+
|
|
664
|
+
The program performs layout measurement, validation, and file writing;
|
|
665
|
+
success means the file exists on disk and all checks passed — never
|
|
666
|
+
trust a verbal claim of completion. The result and any blocking issues
|
|
667
|
+
are saved as a JSON report next to the file. On failure no PPTX is
|
|
668
|
+
written and the issues identify the affected slides and elements.
|
|
669
|
+
|
|
670
|
+
Args:
|
|
671
|
+
project_id: Project that owns the artifact.
|
|
672
|
+
artifact_id: Artifact to export.
|
|
673
|
+
revision: Revision to export.
|
|
674
|
+
idempotency_key: Unique key; identical keys return the cached
|
|
675
|
+
successful result without re-exporting.
|
|
676
|
+
|
|
677
|
+
Returns:
|
|
678
|
+
ExportResult with success flag, file path, and issue list.
|
|
679
|
+
"""
|
|
680
|
+
storage = _get_storage(project_id)
|
|
681
|
+
|
|
682
|
+
if idempotency_key:
|
|
683
|
+
cached = storage.load_idempotent_result(idempotency_key)
|
|
684
|
+
if cached is not None:
|
|
685
|
+
return ExportResult.model_validate(cached)
|
|
686
|
+
|
|
687
|
+
artifact = storage.load_artifact(artifact_id, revision)
|
|
688
|
+
exports_dir = storage.root / "exports"
|
|
689
|
+
exports_dir.mkdir(parents=True, exist_ok=True)
|
|
690
|
+
pptx_path = exports_dir / f"{artifact_id}-r{revision}.pptx"
|
|
691
|
+
|
|
692
|
+
try:
|
|
693
|
+
export_pptx(artifact, pptx_path, assets_dir=storage.root / "assets")
|
|
694
|
+
except (ValueError, FileNotFoundError) as e:
|
|
695
|
+
result = ExportResult(
|
|
696
|
+
success=False,
|
|
697
|
+
artifact_id=artifact_id,
|
|
698
|
+
artifact_revision=revision,
|
|
699
|
+
issues=[
|
|
700
|
+
ValidationIssue(
|
|
701
|
+
level=ValidationLevel.ERROR,
|
|
702
|
+
code="EXPORT_FAILED",
|
|
703
|
+
message=str(e),
|
|
704
|
+
)
|
|
705
|
+
],
|
|
706
|
+
)
|
|
707
|
+
storage.save_export_report(artifact_id, revision, result.model_dump())
|
|
708
|
+
return result
|
|
709
|
+
|
|
710
|
+
result = ExportResult(
|
|
711
|
+
success=True,
|
|
712
|
+
artifact_id=artifact_id,
|
|
713
|
+
artifact_revision=revision,
|
|
714
|
+
pptx_path=str(pptx_path),
|
|
715
|
+
slide_count=len(artifact.slides),
|
|
716
|
+
)
|
|
717
|
+
storage.save_export_report(artifact_id, revision, result.model_dump())
|
|
718
|
+
if idempotency_key:
|
|
719
|
+
storage.save_idempotent_result(idempotency_key, result.model_dump())
|
|
720
|
+
return result
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
export_deck = function_tool(export_deck_impl)
|