feat(office): keep PDF support in bundled Python and the existing route

This commit is contained in:
yudshj authored and Yudong Han committed 2026-11-18 12:07:06 +01:00
1 parent 34a290150c
commit 2f93052188
153 files changed
+211 -528

No files matched your search

-69
View File
@@ -23,11 +23,6 @@ from pptx import Presentation
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Inches
from pypdf import PdfReader, PdfWriter
from pypdf.annotations import Text
from pypdf.errors import DependencyError
from pypdf.xmp import XmpInformation
from pypdf.generic import ArrayObject, DictionaryObject, FloatObject, NameObject, NumberObject, TextStringObject
def check_interpreters():
@@ -125,70 +120,6 @@ def main():
finally:
reopened_workbook.close()
assert pandas.read_excel(root / "workbook.xlsx")["Value"].iloc[0] == 42
pdf = PdfWriter()
pdf.add_blank_page(width=200, height=100)
pdf.add_blank_page(width=100, height=200).rotate(90)
pdf.add_metadata({"/Title": "Office PDF"})
xmp = XmpInformation.create()
xmp.dc_title = {"x-default": "Office PDF"}
pdf.xmp_metadata = xmp
pdf.add_attachment("data.csv", b"a,b")
pdf.add_attachment("data.csv", b"c,d")
pdf.set_page_label(0, 0, style="/r")
pdf.set_page_label(1, 1, style="/D", start=1)
pdf.write(root / "document.pdf")
reopened_pdf = PdfReader(root / "document.pdf")
assert len(reopened_pdf.pages) == 2
assert reopened_pdf.pages[1].rotation == 90
assert reopened_pdf.metadata.title == "Office PDF"
assert reopened_pdf.xmp_metadata.dc_title == {"x-default": "Office PDF"}
assert dict(reopened_pdf.attachments) == {"data.csv": [b"a,b", b"c,d"]}
assert reopened_pdf.page_labels == ["i", "1"]
form = PdfWriter()
form.add_blank_page(width=300, height=200)
field = form.add_annotation(0, DictionaryObject({
NameObject("/Subtype"): NameObject("/Widget"), NameObject("/FT"): NameObject("/Tx"),
NameObject("/T"): TextStringObject("name"), NameObject("/F"): NumberObject(4),
NameObject("/Rect"): ArrayObject([FloatObject(10), FloatObject(10), FloatObject(200), FloatObject(40)]),
NameObject("/DA"): TextStringObject("/Helv 12 Tf 0 g"),
}))
form.root_object[NameObject("/AcroForm")] = DictionaryObject({NameObject("/Fields"): ArrayObject([field.indirect_reference])})
form.add_annotation(0, Text(text="Review note", rect=(220, 150, 240, 170)))
form.write(root / "form.pdf")
filled = PdfWriter(clone_from=root / "form.pdf")
filled.update_page_form_field_values(None, {"name": "Ada Lovelace"}, auto_regenerate=False)
filled.remove_annotations(subtypes=["/Text"])
filled.write(root / "filled.pdf")
reopened_form = PdfReader(root / "filled.pdf")
assert reopened_form.get_fields()["name"].value == "Ada Lovelace"
assert reopened_form.trailer["/Root"]["/AcroForm"].get("/NeedAppearances") is not True
assert [annotation.get_object()["/Subtype"] for annotation in reopened_form.pages[0]["/Annots"]] == ["/Widget"]
assert "/AP" in reopened_form.pages[0]["/Annots"][0].get_object()
flattened = PdfWriter(clone_from=root / "form.pdf")
flattened.update_page_form_field_values(None, {"name": "Ada Lovelace"}, flatten=True)
flattened.remove_annotations(subtypes="/Widget")
del flattened.root_object["/AcroForm"]
flattened.write(root / "flattened.pdf")
reopened_flattened = PdfReader(root / "flattened.pdf")
assert reopened_flattened.get_fields() is None
assert "/Widget" not in [annotation.get_object()["/Subtype"] for annotation in reopened_flattened.pages[0].get("/Annots", [])]
assert reopened_flattened.pages[0].extract_text() == "Ada Lovelace"
# The payload omits cryptography, so only the RC4 algorithm named by the PDF skill is available.
try:
PdfWriter(clone_from=root / "document.pdf").encrypt("password", algorithm="AES-256")
except DependencyError:
pass
else:
raise AssertionError("AES encryption unexpectedly available")
protected = PdfWriter(clone_from=root / "document.pdf")
protected.encrypt("password", algorithm="RC4-128")
protected.write(root / "protected.pdf")
reopened_protected = PdfReader(root / "protected.pdf")
assert reopened_protected.is_encrypted and reopened_protected.decrypt("password")
assert len(reopened_protected.pages) == 2
print("Office runtime versions and document round trips passed.")
+1 -1
View File
@@ -997,7 +997,7 @@ def _smoke_sdk_authoring_cached(base_url: str, executable: Path, update_snapshot
assert len(requests) == 2, requests
prompt = json.dumps(requests[0], ensure_ascii=False)
assert ("- `office`:" in prompt) == (mode != "disabled"), mode
for name in ("office-docx", "office-pdf", "office-pptx", "office-xlsx"):
for name in ("office-docx", "office-pptx", "office-xlsx"):
assert (name in prompt) == (mode != "disabled"), (mode, name)
assert ("CUSTOM_OFFICE_DOCX" in prompt) == (mode == "replacement"), mode
tool_result = next(block for message in requests[1]["messages"]
@@ -1,14 +1,14 @@
{
"tool": {
"name": "load_workspace_dependencies",
"description": "Get absolute paths to bundled Python and library directories, plus bundled Python distribution versions. Node.js and pnpm paths are included when the payload provides them. Python includes numpy, pandas, python-docx, python-pptx, openpyxl, Pillow, lxml, XlsxWriter, and pypdf. Use these libraries for Office files unless the user or workspace instructions select another environment. When Node.js and pnpm paths are returned, run pnpm with that Node executable and pnpm script path. This does not change PATH or package-manager settings.",
"description": "Get absolute paths to bundled Python and library directories, plus bundled Python distribution versions. Node.js and pnpm paths are included when the payload provides them. Python includes numpy, pandas, python-docx, python-pptx, openpyxl, Pillow, lxml, and XlsxWriter. Use these libraries for Office files unless the user or workspace instructions select another environment. When Node.js and pnpm paths are returned, run pnpm with that Node executable and pnpm script path. This does not change PATH or package-manager settings.",
"input_schema": {
"type": "object",
"properties": {}
}
},
"catalogs": [
"Query the packaged Python environment for Office authoring.<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder><system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pdf`: Read, extract, inspect, split, merge, protect, or fill an existing PDF; PDF to Word (.pdf).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n</available_skills>\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n</system-reminder>Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."
"Query the packaged Python environment for Office authoring.<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder><system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n</available_skills>\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n</system-reminder>Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."
],
"result": {
"python": "{{python}}",
@@ -1,14 +1,14 @@
{
"tool": {
"name": "load_workspace_dependencies",
"description": "Get absolute paths to bundled Python and library directories, plus bundled Python distribution versions. Node.js and pnpm paths are included when the payload provides them. Python includes numpy, pandas, python-docx, python-pptx, openpyxl, Pillow, lxml, XlsxWriter, and pypdf. Use these libraries for Office files unless the user or workspace instructions select another environment. When Node.js and pnpm paths are returned, run pnpm with that Node executable and pnpm script path. This does not change PATH or package-manager settings.",
"description": "Get absolute paths to bundled Python and library directories, plus bundled Python distribution versions. Node.js and pnpm paths are included when the payload provides them. Python includes numpy, pandas, python-docx, python-pptx, openpyxl, Pillow, lxml, and XlsxWriter. Use these libraries for Office files unless the user or workspace instructions select another environment. When Node.js and pnpm paths are returned, run pnpm with that Node executable and pnpm script path. This does not change PATH or package-manager settings.",
"input_schema": {
"type": "object",
"properties": {}
}
},
"catalogs": [
"Query the packaged Python environment for Office authoring.<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder><system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `diagnose-windows-sandbox-acl`: Use on Windows for unexpected DSH sandbox access denials: workspace writes or listing fail, or an ordinarily readable path cannot be read. One bundled command inspects the path and every ancestor and repairs the ACL problems it proves in that same run. Expected confinement denials need no ACL repair.\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pdf`: Read, extract, inspect, split, merge, protect, or fill an existing PDF; PDF to Word (.pdf).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n</available_skills>\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n</system-reminder>Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."
"Query the packaged Python environment for Office authoring.<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder><system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `diagnose-windows-sandbox-acl`: Use on Windows for unexpected DSH sandbox access denials: workspace writes or listing fail, or an ordinarily readable path cannot be read. One bundled command inspects the path and every ancestor and repairs the ACL problems it proves in that same run. Expected confinement denials need no ACL repair.\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n</available_skills>\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n</system-reminder>Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."
],
"result": {
"python": "{{python}}",