fix(office): 修复独立技能的 Python 依赖入口 (#229)

为 pptx 与 xlsx 提供标准库启动器,使用已准备的受管 XML 依赖,保留目标退出码并避免失败后重放编辑。

同步双语说明、目录版本和固定启动器合同测试。

Refs desirecore/desirecore#5335
This commit is contained in:
yige authored and GitHub committed 2026-10-28 10:24:31 +08:00
1 parent aa6a1a6348
commit 1b9e82d95d
12 files changed
+462 -38

No files matched your search

+5 -1
View File
@@ -48,7 +48,7 @@ jobs:
;; ;;
esac esac
changed=$(git diff --name-only "$range" || true) changed=$(git diff --name-only "$range" || true)
if echo "$changed" | grep -qE '^(skills/|agents/|teams/|schemas/|manifest\.json$|categories\.json$|scripts/i18n/|scripts/catalog/|scripts/gen-collection-children\.py$)'; then if echo "$changed" | grep -qE '^(skills/|agents/|teams/|schemas/|manifest\.json$|categories\.json$|scripts/i18n/|scripts/catalog/|scripts/office/|scripts/gen-collection-children\.py$)'; then
echo "relevant=true" >> "$GITHUB_OUTPUT" echo "relevant=true" >> "$GITHUB_OUTPUT"
else else
echo "relevant=false" >> "$GITHUB_OUTPUT" echo "relevant=false" >> "$GITHUB_OUTPUT"
@@ -62,6 +62,10 @@ jobs:
if: steps.changes.outputs.relevant == 'true' if: steps.changes.outputs.relevant == 'true'
run: uv run --quiet scripts/i18n/test_validate_i18n.py run: uv run --quiet scripts/i18n/test_validate_i18n.py
- name: Run Office launcher contract tests
if: steps.changes.outputs.relevant == 'true'
run: python3 -B scripts/office/test_runtime_launcher.py
- name: Run catalog validator unit tests - name: Run catalog validator unit tests
if: steps.changes.outputs.relevant == 'true' if: steps.changes.outputs.relevant == 'true'
run: | run: |
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "DesireCore Official Market", "name": "DesireCore Official Market",
"version": "1.5.15", "version": "1.5.16",
"schemaVersion": "1.1.0", "schemaVersion": "1.1.0",
"supportedLocales": [ "supportedLocales": [
"zh-CN", "zh-CN",
@@ -32,7 +32,7 @@
"totalAgents": 9, "totalAgents": 9,
"totalTeams": 2, "totalTeams": 2,
"totalSkills": 144, "totalSkills": 144,
"lastUpdated": "2026-10-27" "lastUpdated": "2026-10-28"
}, },
"features": [ "features": [
"curated-index", "curated-index",
+210
View File
@@ -0,0 +1,210 @@
#!/usr/bin/env python3
"""Standalone Office launcher contracts; standard library only, no installs/network.
Run: python -B scripts/office/test_runtime_launcher.py
"""
import contextlib
import io
from itertools import product
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import types
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[2]
SKILLS = ("pptx", "xlsx")
class RuntimeLauncherTests(unittest.TestCase):
def fixture(self, skill, directory):
scripts = Path(directory) / "isolated home 中文" / "skills" / skill / "scripts"
scripts.mkdir(parents=True)
launcher = scripts / "with-deps.py"
shutil.copyfile(ROOT / "skills" / skill / "scripts" / launcher.name, launcher)
module = types.ModuleType("launcher_" + skill)
module.__file__ = str(launcher)
# Avoid writing a .pyc beside the repository's installed skill.
exec(compile(launcher.read_bytes(), str(launcher), "exec"), module.__dict__)
target = scripts / "office" / "probe.py"
target.parent.mkdir()
target.write_text("raise SystemExit(0)\n", encoding="utf-8")
libs = Path(module._PYLIBS)
libs.mkdir(parents=True)
return module, launcher, target, libs
def test_relative_target_arguments_environment_and_cwd_are_preserved(self):
for skill in SKILLS:
with self.subTest(skill=skill), tempfile.TemporaryDirectory() as directory:
module, launcher, target, libs = self.fixture(skill, directory)
before = os.getcwd()
with patch.object(sys, "argv", [str(launcher), "office/probe.py", "file with spaces", "中文", "--validate", "false"]), \
patch.dict(os.environ, {"PYTHONPATH": "existing-path"}), \
patch.object(module.subprocess, "run", return_value=types.SimpleNamespace(returncode=17)) as run:
self.assertEqual(module.main(), 17)
command = run.call_args.args[0]
self.assertEqual(command[:2], [sys.executable, "-B"])
self.assertEqual(Path(command[2]), target)
self.assertEqual(command[3:], ["file with spaces", "中文", "--validate", "false"])
self.assertEqual(run.call_args.kwargs["env"]["PYTHONPATH"], str(libs) + os.pathsep + "existing-path")
self.assertEqual(run.call_args.kwargs["env"]["PYTHONDONTWRITEBYTECODE"], "1")
self.assertNotIn("cwd", run.call_args.kwargs)
self.assertNotIn("shell", run.call_args.kwargs)
self.assertEqual(os.getcwd(), before)
def test_absolute_target_prefers_prepared_interpreter(self):
for skill in SKILLS:
with self.subTest(skill=skill), tempfile.TemporaryDirectory() as directory:
module, launcher, target, _libs = self.fixture(skill, directory)
bundled = Path(module._BUNDLED)
bundled.parent.mkdir(parents=True)
bundled.write_bytes(b"fixture executable; subprocess is mocked")
with patch.object(sys, "argv", [str(launcher), str(target)]), \
patch.object(module.subprocess, "run", return_value=types.SimpleNamespace(returncode=0)) as run:
self.assertEqual(module.main(), 0)
self.assertEqual(run.call_args.args[0], [str(bundled), "-B", str(target)])
def test_current_python_option_keeps_external_packages_interpreter(self):
for skill in SKILLS:
with self.subTest(skill=skill), tempfile.TemporaryDirectory() as directory:
module, launcher, target, _libs = self.fixture(skill, directory)
bundled = Path(module._BUNDLED)
bundled.parent.mkdir(parents=True)
bundled.write_bytes(b"fixture executable; subprocess is mocked")
with patch.object(sys, "argv", [str(launcher), "--current-python", "office/probe.py", "output.pptx"]), \
patch.object(module.subprocess, "run", return_value=types.SimpleNamespace(returncode=0)) as run:
self.assertEqual(module.main(), 0)
command = run.call_args.args[0]
self.assertEqual(command[:2], [sys.executable, "-B"])
self.assertEqual(Path(command[2]), target)
self.assertEqual(command[3:], ["output.pptx"])
def test_current_python_never_silently_uses_python_39(self):
for skill in SKILLS:
with self.subTest(skill=skill), tempfile.TemporaryDirectory() as directory:
module, launcher, _target, _libs = self.fixture(skill, directory)
with patch.object(sys, "argv", [str(launcher), "office/probe.py"]), \
patch.object(sys, "version_info", (3, 9, 0)), \
patch.object(module.subprocess, "run") as run, contextlib.redirect_stderr(io.StringIO()) as error:
self.assertEqual(module.main(), 1)
run.assert_not_called()
self.assertIn("Python 3.10+", error.getvalue())
def test_old_bootstrap_can_start_prepared_interpreter(self):
for skill in SKILLS:
with self.subTest(skill=skill), tempfile.TemporaryDirectory() as directory:
module, launcher, _target, _libs = self.fixture(skill, directory)
bundled = Path(module._BUNDLED)
bundled.parent.mkdir(parents=True)
bundled.write_bytes(b"fixture executable; subprocess is mocked")
with patch.object(sys, "argv", [str(launcher), "office/probe.py"]), \
patch.object(sys, "version_info", (3, 9, 0)), \
patch.object(module.subprocess, "run", return_value=types.SimpleNamespace(returncode=0)) as run:
self.assertEqual(module.main(), 0)
self.assertEqual(run.call_args.args[0][0], str(bundled))
def test_only_process_start_failure_can_fall_back(self):
for skill in SKILLS:
with self.subTest(skill=skill), tempfile.TemporaryDirectory() as directory:
module, launcher, _target, _libs = self.fixture(skill, directory)
bundled = Path(module._BUNDLED)
bundled.parent.mkdir(parents=True)
bundled.write_bytes(b"fixture executable; subprocess is mocked")
with patch.object(sys, "argv", [str(launcher), "office/probe.py"]), \
patch.object(module.subprocess, "run", side_effect=[OSError("fixture start failure"), types.SimpleNamespace(returncode=7)]) as run, \
contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(module.main(), 7)
self.assertEqual(run.call_count, 2)
self.assertEqual(run.call_args_list[1].args[0][0], sys.executable)
def test_failed_prepared_start_cannot_fall_back_to_python_39(self):
for skill in SKILLS:
with self.subTest(skill=skill), tempfile.TemporaryDirectory() as directory:
module, launcher, _target, _libs = self.fixture(skill, directory)
bundled = Path(module._BUNDLED)
bundled.parent.mkdir(parents=True)
bundled.write_bytes(b"fixture executable; subprocess is mocked")
with patch.object(sys, "argv", [str(launcher), "office/probe.py"]), \
patch.object(sys, "version_info", (3, 9, 0)), \
patch.object(module.subprocess, "run", side_effect=OSError("fixture start failure")) as run, \
contextlib.redirect_stderr(io.StringIO()) as error:
self.assertEqual(module.main(), 1)
run.assert_called_once()
self.assertIn("Python 3.10+", error.getvalue())
def test_target_failures_and_signals_are_not_replayed_or_success(self):
for skill in SKILLS:
for code in (1, 126, 127, -9):
with self.subTest(skill=skill, code=code), tempfile.TemporaryDirectory() as directory:
module, launcher, _target, _libs = self.fixture(skill, directory)
bundled = Path(module._BUNDLED)
bundled.parent.mkdir(parents=True)
bundled.write_bytes(b"fixture executable; subprocess is mocked")
with patch.object(sys, "argv", [str(launcher), "office/probe.py"]), \
patch.object(module.subprocess, "run", return_value=types.SimpleNamespace(returncode=code)) as run:
self.assertEqual(module.main(), code)
run.assert_called_once()
def test_missing_target_or_option_without_target_has_no_side_effect(self):
for skill in SKILLS:
for arguments in ([], ["--current-python"], ["office/missing.py"]):
with self.subTest(skill=skill, arguments=arguments), tempfile.TemporaryDirectory() as directory:
module, launcher, _target, _libs = self.fixture(skill, directory)
with patch.object(sys, "argv", [str(launcher), *arguments]), \
patch.object(module.subprocess, "run") as run, contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(module.main(), 2)
run.assert_not_called()
def test_independently_installed_skill_resolves_own_libs_without_bytecode(self):
for skill, current_python in product(SKILLS, (False, True)):
with self.subTest(skill=skill, current_python=current_python), tempfile.TemporaryDirectory() as directory:
module, launcher, target, libs = self.fixture(skill, directory)
if current_python:
bundled = Path(module._BUNDLED)
bundled.parent.mkdir(parents=True)
bundled.write_bytes(b"must not be executed with --current-python")
(libs / "launcher_fixture_dependency.py").write_text("value = 'from prepared libs'\n", encoding="utf-8")
(target.parent / "local_helper.py").write_text("value = 'script directory'\n", encoding="utf-8")
target.write_text(
"import json, os, sys, launcher_fixture_dependency, local_helper\n"
"print(json.dumps({'argv': sys.argv[1:], 'name': __name__, 'cwd': os.getcwd(), "
"'dependency': launcher_fixture_dependency.__file__, 'local': local_helper.value}))\n",
encoding="utf-8",
)
environment = dict(os.environ)
environment.pop("PYTHONPATH", None)
environment["PYTHONNOUSERSITE"] = "1"
completed = subprocess.run(
[sys.executable, "-B", str(launcher), *(["--current-python"] if current_python else []), "office/probe.py", "spaced input", "中文"],
cwd=directory, env=environment, capture_output=True, text=True, check=True,
)
self.assertEqual(completed.stderr, "")
result = json.loads(completed.stdout)
self.assertEqual(result["argv"], ["spaced input", "中文"])
self.assertEqual(result["name"], "__main__")
self.assertEqual(Path(result["cwd"]).resolve(), Path(directory).resolve())
self.assertEqual(Path(result["dependency"]).resolve(), (libs / "launcher_fixture_dependency.py").resolve())
self.assertEqual(result["local"], "script directory")
self.assertFalse(list(Path(directory).rglob("*.pyc")))
def test_missing_dependency_is_a_real_nonzero_target_failure(self):
for skill in SKILLS:
with self.subTest(skill=skill), tempfile.TemporaryDirectory() as directory:
_module, launcher, target, _libs = self.fixture(skill, directory)
target.write_text("import unavailable_office_test_dependency_5335\n", encoding="utf-8")
completed = subprocess.run(
[sys.executable, "-B", str(launcher), "office/probe.py"],
cwd=directory, capture_output=True, text=True,
)
self.assertNotEqual(completed.returncode, 0)
self.assertIn("ModuleNotFoundError", completed.stderr)
if __name__ == "__main__":
unittest.main()
+18 -12
View File
@@ -13,7 +13,7 @@ description: >-
content afterward. If a .pptx file needs to be opened, created, or touched, content afterward. If a .pptx file needs to be opened, created, or touched,
use this skill. Use when 用户提到 PPT、演示文稿、幻灯片、演讲稿、汇报材料、 use this skill. Use when 用户提到 PPT、演示文稿、幻灯片、演讲稿、汇报材料、
pptx、创建演示、编辑幻灯片。 pptx、创建演示、编辑幻灯片。
version: 1.0.5 version: 1.0.6
type: procedural type: procedural
risk_level: low risk_level: low
status: enabled status: enabled
@@ -26,7 +26,7 @@ tags:
- office - office
metadata: metadata:
author: anthropic author: anthropic
updated_at: '2026-10-14' updated_at: '2026-10-28'
i18n: i18n:
default_locale: en-US default_locale: en-US
source_locale: zh-CN source_locale: zh-CN
@@ -39,7 +39,7 @@ metadata:
description: >- description: >-
Use this skill any time a .pptx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates, layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx filename, regardless of what they plan to do with the content afterward. If a .pptx file needs to be opened, created, or touched, use this skill. Use when 用户提到 PPT、演示文稿、幻灯片、演讲稿、汇报材料、 pptx、创建演示、编辑幻灯片。 Use this skill any time a .pptx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates, layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx filename, regardless of what they plan to do with the content afterward. If a .pptx file needs to be opened, created, or touched, use this skill. Use when 用户提到 PPT、演示文稿、幻灯片、演讲稿、汇报材料、 pptx、创建演示、编辑幻灯片。
body: ./SKILL.zh-CN.md body: ./SKILL.zh-CN.md
source_hash: sha256:a952bf5622ede8e0 source_hash: sha256:c8569b584e23df32
translated_by: human translated_by: human
en-US: en-US:
name: Presentation Processing name: Presentation Processing
@@ -47,7 +47,7 @@ metadata:
description: >- description: >-
Use this skill any time a .pptx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates, layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx filename, regardless of what they plan to do with the content afterward. If a .pptx file needs to be opened, created, or touched, use this skill. Use when the user mentions PPT, presentation, slides, speaker notes, briefing materials, pptx, creating presentations, or editing slides. Use this skill any time a .pptx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates, layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx filename, regardless of what they plan to do with the content afterward. If a .pptx file needs to be opened, created, or touched, use this skill. Use when the user mentions PPT, presentation, slides, speaker notes, briefing materials, pptx, creating presentations, or editing slides.
body: ./SKILL.md body: ./SKILL.md
source_hash: sha256:9d8c46a62ef8bfb8 source_hash: sha256:c8569b584e23df32
translated_by: human translated_by: human
market: market:
icon: >- icon: >-
@@ -95,16 +95,19 @@ pptx is a **Procedural Skill** providing full PowerPoint presentation processing
The Python scripts bundled with this skill live inside the skill installation directory. You **MUST use full paths** when invoking them — never use bare relative paths. The Python scripts bundled with this skill live inside the skill installation directory. You **MUST use full paths** when invoking them — never use bare relative paths.
The skill directory is provided by the `<skill-dir>` tag in the context. Prefix all `scripts/` commands accordingly: The skill directory is provided by the `<skill-dir>` tag in the context. Run Office XML scripts through the cross-platform `with-deps.py` launcher. It adds the client's prepared `runtime-deps/python-libs` and prefers the prepared `runtime-deps/python-runtime` interpreter, so XML editing needs no online package installation:
```bash ```bash
python "<skill-dir>/scripts/office/unpack.py" presentation.pptx unpacked/ python "<skill-dir>/scripts/with-deps.py" office/unpack.py presentation.pptx unpacked/
python "<skill-dir>/scripts/office/pack.py" unpacked/ output.pptx python "<skill-dir>/scripts/with-deps.py" office/pack.py unpacked/ output.pptx
python "<skill-dir>/scripts/with-deps.py" office/validate.py output.pptx
python "<skill-dir>/scripts/office/soffice.py" --headless --convert-to pdf output.pptx python "<skill-dir>/scripts/office/soffice.py" --headless --convert-to pdf output.pptx
python "<skill-dir>/scripts/thumbnail.py" presentation.pptx python "<skill-dir>/scripts/with-deps.py" --current-python thumbnail.py presentation.pptx
``` ```
**NEVER** run `python scripts/office/unpack.py` directly — that relative path does not exist in the user's working directory. Targets are relative to `scripts/` (absolute paths are also accepted), and arguments/workdir/exit codes are preserved. `--current-python` keeps the interpreter where Pillow is installed for thumbnails while adding the shared pure-Python XML dependency. The launcher does not install Pillow, markitdown, LibreOffice, or any package.
**NEVER** invoke Office XML scripts directly: a bare `scripts/` path is not relative to the user's workdir, and direct invocation bypasses the prepared dependencies. If no prepared interpreter can start, the current Python must be 3.10+; missing libraries or failed validation remain nonzero failures. Restore the client's prepared runtime rather than treating skipped validation as success. Child scripts do not write bytecode into the installed skill.
## Prerequisites ## Prerequisites
@@ -130,6 +133,8 @@ load the `nodejs-runtime` skill for Node.js (pptxgenjs) issues; load the `dev-en
### Python Package Dependencies ### Python Package Dependencies
Office XML scripts use `defusedxml` and `lxml` from the client's prepared runtime through `with-deps.py`; do not run `pip install` for these dependencies. Full PPTX validation requires the lxml profile. If it is unavailable, report the failure; do not claim complete validation or silently skip it.
This skill's Python operations depend on the following packages (checked on demand): This skill's Python operations depend on the following packages (checked on demand):
- `markitdown[pptx]` — PPTX content reading - `markitdown[pptx]` — PPTX content reading
@@ -163,10 +168,10 @@ When you create or modify a .pptx file, you **MUST** tell the user the absolute
python -m markitdown presentation.pptx python -m markitdown presentation.pptx
# Visual overview # Visual overview
python scripts/thumbnail.py presentation.pptx python "<skill-dir>/scripts/with-deps.py" --current-python thumbnail.py presentation.pptx
# Raw XML # Raw XML
python scripts/office/unpack.py presentation.pptx unpacked/ python "<skill-dir>/scripts/with-deps.py" office/unpack.py presentation.pptx unpacked/
``` ```
--- ---
@@ -349,7 +354,7 @@ Report ALL issues found, including minor ones.
Convert presentations to individual slide images for visual inspection: Convert presentations to individual slide images for visual inspection:
```bash ```bash
python scripts/office/soffice.py --headless --convert-to pdf output.pptx python "<skill-dir>/scripts/office/soffice.py" --headless --convert-to pdf output.pptx
pdftoppm -jpeg -r 150 output.pdf slide pdftoppm -jpeg -r 150 output.pdf slide
``` ```
@@ -365,6 +370,7 @@ pdftoppm -jpeg -r 150 -f N -l N output.pdf slide-fixed
## Dependencies ## Dependencies
- `defusedxml` + `lxml` — Office XML editing and full PPTX validation; supplied by the client's prepared runtime and consumed through `scripts/with-deps.py`, independently of the docx skill.
- `pip install "markitdown[pptx]"` - text extraction - `pip install "markitdown[pptx]"` - text extraction
- `pip install Pillow` - thumbnail grids - `pip install Pillow` - thumbnail grids
- `npm install -g pptxgenjs` - creating from scratch - `npm install -g pptxgenjs` - creating from scratch
+14 -8
View File
@@ -46,6 +46,8 @@ Node.js(pptxgenjs)相关问题加载 `nodejs-runtime` 技能;其他(系
### Python 包依赖 ### Python 包依赖
Office XML 脚本通过 `with-deps.py` 读取客户端运行时预装的 `defusedxml` 与 `lxml`,不要为这两项执行 `pip install`。PPTX 完整校验需要 lxml profile;不可用时如实报告失败,不得跳过后宣称完整校验通过。
本技能的 Python 操作依赖以下包(按需检测): 本技能的 Python 操作依赖以下包(按需检测):
- `markitdown[pptx]` — PPTX 内容读取 - `markitdown[pptx]` — PPTX 内容读取
@@ -62,16 +64,19 @@ python3 -c "import markitdown; import PIL" 2>/dev/null || echo "MISSING"
本技能自带的 Python 脚本位于技能安装目录内。执行时**必须使用完整路径**,不能使用相对路径。 本技能自带的 Python 脚本位于技能安装目录内。执行时**必须使用完整路径**,不能使用相对路径。
技能目录由上下文中的 `<skill-dir>` 标签提供。所有 `scripts/` 开头的命令都应拼接为: 技能目录由上下文中的 `<skill-dir>` 标签提供。Office XML 脚本统一经过跨平台 `with-deps.py` 启动器:它注入客户端已准备的 `runtime-deps/python-libs`,优先选择 `runtime-deps/python-runtime` 解释器,不需要在线安装 XML 依赖:
```bash ```bash
python "<skill-dir>/scripts/office/unpack.py" presentation.pptx unpacked/ python "<skill-dir>/scripts/with-deps.py" office/unpack.py presentation.pptx unpacked/
python "<skill-dir>/scripts/office/pack.py" unpacked/ output.pptx python "<skill-dir>/scripts/with-deps.py" office/pack.py unpacked/ output.pptx
python "<skill-dir>/scripts/with-deps.py" office/validate.py output.pptx
python "<skill-dir>/scripts/office/soffice.py" --headless --convert-to pdf output.pptx python "<skill-dir>/scripts/office/soffice.py" --headless --convert-to pdf output.pptx
python "<skill-dir>/scripts/thumbnail.py" presentation.pptx python "<skill-dir>/scripts/with-deps.py" --current-python thumbnail.py presentation.pptx
``` ```
**禁止**直接执行 `python scripts/office/unpack.py`——该相对路径在用户工作目录下不存在。 目标路径相对 `scripts/` 解析,也接受绝对路径;参数、工作目录与退出码保持不变。缩略图使用 `--current-python`,保留已安装 Pillow 的解释器,同时注入共享的纯 Python XML 依赖。启动器不会安装 Pillow、markitdown、LibreOffice 或任何包。
**禁止**直接执行 Office XML 脚本:裸 `scripts/` 路径不相对用户工作目录,直接调用还会绕过预装依赖。受控解释器无法启动时,当前 Python 必须为 3.10+;缺库或校验失败仍返回非零。应修复客户端运行时,不能把跳过校验当成功。子脚本不在已安装技能中生成字节码缓存。
## Output Rule ## Output Rule
@@ -94,10 +99,10 @@ When you create or modify a .pptx file, you **MUST** tell the user the absolute
python -m markitdown presentation.pptx python -m markitdown presentation.pptx
# Visual overview # Visual overview
python scripts/thumbnail.py presentation.pptx python "<skill-dir>/scripts/with-deps.py" --current-python thumbnail.py presentation.pptx
# Raw XML # Raw XML
python scripts/office/unpack.py presentation.pptx unpacked/ python "<skill-dir>/scripts/with-deps.py" office/unpack.py presentation.pptx unpacked/
``` ```
--- ---
@@ -280,7 +285,7 @@ Report ALL issues found, including minor ones.
Convert presentations to individual slide images for visual inspection: Convert presentations to individual slide images for visual inspection:
```bash ```bash
python scripts/office/soffice.py --headless --convert-to pdf output.pptx python "<skill-dir>/scripts/office/soffice.py" --headless --convert-to pdf output.pptx
pdftoppm -jpeg -r 150 output.pdf slide pdftoppm -jpeg -r 150 output.pdf slide
``` ```
@@ -296,6 +301,7 @@ pdftoppm -jpeg -r 150 -f N -l N output.pdf slide-fixed
## Dependencies ## Dependencies
- `defusedxml` + `lxml` — Office XML 编辑与 PPTX 完整校验;由客户端运行时预装,通过 `scripts/with-deps.py` 使用,不依赖 docx 技能目录。
- `pip install "markitdown[pptx]"` - text extraction - `pip install "markitdown[pptx]"` - text extraction
- `pip install Pillow` - thumbnail grids - `pip install Pillow` - thumbnail grids
- `npm install -g pptxgenjs` - creating from scratch - `npm install -g pptxgenjs` - creating from scratch
+2 -2
View File
@@ -30,13 +30,13 @@
}, },
"release": { "release": {
"state": "known", "state": "known",
"version": "1.0.5", "version": "1.0.6",
"versionScheme": "semver" "versionScheme": "semver"
}, },
"timestamps": { "timestamps": {
"catalogUpdatedAt": { "catalogUpdatedAt": {
"state": "known", "state": "known",
"value": "2026-10-14", "value": "2026-10-28",
"precision": "day" "precision": "day"
}, },
"releasePublishedAt": { "releasePublishedAt": {
+6 -6
View File
@@ -6,7 +6,7 @@ When using an existing presentation as a template:
1. **Analyze existing slides**: 1. **Analyze existing slides**:
```bash ```bash
python scripts/thumbnail.py template.pptx python "<skill-dir>/scripts/with-deps.py" --current-python thumbnail.py template.pptx
python -m markitdown template.pptx python -m markitdown template.pptx
``` ```
Review `thumbnails.jpg` to see layouts, and markitdown output to see placeholder text. Review `thumbnails.jpg` to see layouts, and markitdown output to see placeholder text.
@@ -26,7 +26,7 @@ When using an existing presentation as a template:
Match content type to layout style (e.g., key points → bullet slide, team info → multi-column, testimonials → quote slide). Match content type to layout style (e.g., key points → bullet slide, team info → multi-column, testimonials → quote slide).
3. **Unpack**: `python scripts/office/unpack.py template.pptx unpacked/` 3. **Unpack**: `python "<skill-dir>/scripts/with-deps.py" office/unpack.py template.pptx unpacked/`
4. **Build presentation** (do this yourself, not via delegation): 4. **Build presentation** (do this yourself, not via delegation):
- Delete unwanted slides (remove from `<p:sldIdLst>`) - Delete unwanted slides (remove from `<p:sldIdLst>`)
@@ -39,7 +39,7 @@ When using an existing presentation as a template:
6. **Clean**: `python scripts/clean.py unpacked/` 6. **Clean**: `python scripts/clean.py unpacked/`
7. **Pack**: `python scripts/office/pack.py unpacked/ output.pptx --original template.pptx` 7. **Pack**: `python "<skill-dir>/scripts/with-deps.py" office/pack.py unpacked/ output.pptx --original template.pptx`
--- ---
@@ -56,7 +56,7 @@ When using an existing presentation as a template:
### unpack.py ### unpack.py
```bash ```bash
python scripts/office/unpack.py input.pptx unpacked/ python "<skill-dir>/scripts/with-deps.py" office/unpack.py input.pptx unpacked/
``` ```
Extracts PPTX, pretty-prints XML, escapes smart quotes. Extracts PPTX, pretty-prints XML, escapes smart quotes.
@@ -81,7 +81,7 @@ Removes slides not in `<p:sldIdLst>`, unreferenced media, orphaned rels.
### pack.py ### pack.py
```bash ```bash
python scripts/office/pack.py unpacked/ output.pptx --original input.pptx python "<skill-dir>/scripts/with-deps.py" office/pack.py unpacked/ output.pptx --original input.pptx
``` ```
Validates, repairs, condenses XML, re-encodes smart quotes. Validates, repairs, condenses XML, re-encodes smart quotes.
@@ -89,7 +89,7 @@ Validates, repairs, condenses XML, re-encodes smart quotes.
### thumbnail.py ### thumbnail.py
```bash ```bash
python scripts/thumbnail.py input.pptx [output_prefix] [--cols N] python "<skill-dir>/scripts/with-deps.py" --current-python thumbnail.py input.pptx [output_prefix] [--cols N]
``` ```
Creates `thumbnails.jpg` with slide filenames as labels. Default 3 columns, max 12 per grid. Creates `thumbnails.jpg` with slide filenames as labels. Default 3 columns, max 12 per grid.
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Run Office XML scripts with the client's prepared Python dependencies.
Each installed skill carries this launcher so it works without another Office
skill. The bootstrap uses only the standard library, including on Python 3.9;
the target requires Python 3.10+ and prefers the runtime's prepared interpreter.
No packages are installed and target failures are never reported as success.
python "<skill-dir>/scripts/with-deps.py" office/unpack.py input.pptx unpacked/
"""
import os
import subprocess
import sys
_HERE = os.path.dirname(os.path.abspath(__file__))
# scripts -> skill -> skills -> the effective DesireCore data root
_ROOT = os.path.abspath(os.path.join(_HERE, "..", "..", ".."))
_PYLIBS = os.path.join(_ROOT, "runtime-deps", "python-libs")
_BUNDLED = os.path.join(
_ROOT,
"runtime-deps",
"python-runtime",
"python.exe" if os.name == "nt" else os.path.join("bin", "python3"),
)
def _current_python_supported():
if sys.version_info[:2] >= (3, 10):
return True
sys.stderr.write(
"with-deps.py: Office XML scripts require Python 3.10+. "
"Prepare the managed Python runtime in DesireCore and retry.\n"
)
return False
def main():
arguments = list(sys.argv[1:])
current_python = bool(arguments and arguments[0] == "--current-python")
if current_python:
arguments.pop(0)
if not arguments:
sys.stderr.write("usage: with-deps.py [--current-python] <script.py> [args...]\n")
return 2
argument = arguments[0]
target = argument if os.path.isabs(argument) else os.path.join(_HERE, argument)
if not os.path.isfile(target):
sys.stderr.write("with-deps.py: target not found: " + target + "\n")
return 2
interpreter = sys.executable
if not current_python and os.path.isfile(_BUNDLED):
if os.path.realpath(_BUNDLED) != os.path.realpath(sys.executable):
interpreter = _BUNDLED
if interpreter == sys.executable and not _current_python_supported():
return 1
environment = dict(os.environ)
if os.path.isdir(_PYLIBS):
existing = environment.get("PYTHONPATH")
environment["PYTHONPATH"] = _PYLIBS + (os.pathsep + existing if existing else "")
# Running a skill must not change its installed content digest through .pyc.
environment["PYTHONDONTWRITEBYTECODE"] = "1"
arguments = ["-B", target, *arguments[1:]]
try:
return subprocess.run([interpreter, *arguments], env=environment).returncode
except OSError as error:
if interpreter == sys.executable:
sys.stderr.write("with-deps.py: could not start Python: " + str(error) + "\n")
return 126
# Fall back only when the process could not start. A target's nonzero
# exit or signal must never replay an edit that may have already run.
sys.stderr.write("with-deps.py: managed Python could not start; trying current Python.\n")
if not _current_python_supported():
return 1
try:
return subprocess.run([sys.executable, *arguments], env=environment).returncode
except OSError as fallback_error:
sys.stderr.write("with-deps.py: could not start Python: " + str(fallback_error) + "\n")
return 126
if __name__ == "__main__":
raise SystemExit(main())
+17 -4
View File
@@ -16,7 +16,7 @@ description: >-
report, standalone Python script, database pipeline, or Google Sheets API report, standalone Python script, database pipeline, or Google Sheets API
integration, even if tabular data is involved. Use when 用户提到 Excel、 integration, even if tabular data is involved. Use when 用户提到 Excel、
电子表格、xlsx、表格处理、公式计算、数据清洗、图表、CSV导入导出。 电子表格、xlsx、表格处理、公式计算、数据清洗、图表、CSV导入导出。
version: 1.0.4 version: 1.0.5
type: procedural type: procedural
risk_level: low risk_level: low
status: enabled status: enabled
@@ -28,7 +28,7 @@ tags:
- office - office
metadata: metadata:
author: anthropic author: anthropic
updated_at: '2026-10-14' updated_at: '2026-10-28'
i18n: i18n:
default_locale: en-US default_locale: en-US
source_locale: zh-CN source_locale: zh-CN
@@ -41,7 +41,7 @@ metadata:
description: >- description: >-
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. Use when 用户提到 Excel、 电子表格、xlsx、表格处理、公式计算、数据清洗、图表、CSV导入导出。 Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. Use when 用户提到 Excel、 电子表格、xlsx、表格处理、公式计算、数据清洗、图表、CSV导入导出。
body: ./SKILL.zh-CN.md body: ./SKILL.zh-CN.md
source_hash: sha256:17c76a78ed03d451 source_hash: sha256:6cd6c553d8340840
translated_by: human translated_by: human
en-US: en-US:
name: Spreadsheet Processing name: Spreadsheet Processing
@@ -49,7 +49,7 @@ metadata:
description: >- description: >-
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. Use when the user mentions Excel, spreadsheets, xlsx, table processing, formula computation, data cleaning, charts, or CSV import/export. Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. Use when the user mentions Excel, spreadsheets, xlsx, table processing, formula computation, data cleaning, charts, or CSV import/export.
body: ./SKILL.md body: ./SKILL.md
source_hash: sha256:e399420dae6ea7b4 source_hash: sha256:6cd6c553d8340840
translated_by: human translated_by: human
market: market:
icon: >- icon: >-
@@ -106,6 +106,17 @@ python "<skill-dir>/scripts/recalc.py" output.xlsx 30
**NEVER** run `python scripts/recalc.py` directly — that relative path does not exist in the user's working directory. **NEVER** run `python scripts/recalc.py` directly — that relative path does not exist in the user's working directory.
For low-level Office XML unpacking/packing, use this skill's own cross-platform launcher:
```bash
python "<skill-dir>/scripts/with-deps.py" office/unpack.py workbook.xlsx unpacked/
python "<skill-dir>/scripts/with-deps.py" office/pack.py unpacked/ output.xlsx
```
The launcher loads `defusedxml` and `lxml` from the client's prepared `runtime-deps/python-libs` and prefers its `runtime-deps/python-runtime` interpreter. Targets are relative to `scripts/` or absolute; workdir, arguments and failure exit codes are preserved. It installs nothing, requires no docx/pptx skill, and suppresses child bytecode caches. If the prepared interpreter cannot start, the current Python must be 3.10+; missing dependencies fail rather than pretending validation succeeded.
This does **not** add full XLSX XSD validation: `office/validate.py` currently rejects `.xlsx` as unsupported. Packing success alone is not complete validation. Reopen the output with the actual spreadsheet library, check required cells/formulas/styles, and run recalculation as appropriate. Report the unsupported validation boundary. Keep `recalc.py` on the Python where openpyxl is installed; the Office XML profile does not install openpyxl or pandas.
## Prerequisites ## Prerequisites
### Python 3 (required) ### Python 3 (required)
@@ -128,6 +139,8 @@ for everything else (LibreOffice / containers / WSL), load the `dev-environment-
### Python Package Dependencies ### Python Package Dependencies
The launcher consumes the client's preinstalled `defusedxml`/`lxml` for Office XML scripts without `pip install`. Restore the prepared runtime if those libraries are unavailable. These shared libraries do not provide the openpyxl/pandas dependencies below or full XLSX validation.
This Skill depends on the following Python packages (checked on demand): This Skill depends on the following Python packages (checked on demand):
- `openpyxl` — Excel file creation and editing (formulas, formatting) - `openpyxl` — Excel file creation and editing (formulas, formatting)
+14 -1
View File
@@ -43,6 +43,8 @@ python3 --version 2>/dev/null || python --version 2>/dev/null
### Python 包依赖 ### Python 包依赖
Office XML 脚本经启动器消费客户端运行时预装的 `defusedxml`/`lxml`,无需 `pip install`;缺失时修复客户端已准备的运行时。这些共享库不提供下方的 openpyxl/pandas,也不代表已实现 XLSX 完整校验。
本技能依赖以下 Python 包(按需检测): 本技能依赖以下 Python 包(按需检测):
- `openpyxl` — Excel 文件创建和编辑(公式、格式) - `openpyxl` — Excel 文件创建和编辑(公式、格式)
@@ -70,6 +72,17 @@ python "<skill-dir>/scripts/recalc.py" output.xlsx 30
**禁止**直接执行 `python scripts/recalc.py`——该相对路径在用户工作目录下不存在。 **禁止**直接执行 `python scripts/recalc.py`——该相对路径在用户工作目录下不存在。
如需低层 Office XML 解包/打包,使用本技能自带的跨平台启动器:
```bash
python "<skill-dir>/scripts/with-deps.py" office/unpack.py workbook.xlsx unpacked/
python "<skill-dir>/scripts/with-deps.py" office/pack.py unpacked/ output.xlsx
```
启动器从客户端已准备的 `runtime-deps/python-libs` 加载 `defusedxml` 与 `lxml`,优先使用 `runtime-deps/python-runtime` 解释器。目标路径相对 `scripts/`,也接受绝对路径;工作目录、参数和失败退出码保持不变。它不安装任何包,不依赖 docx/pptx 技能,并抑制子脚本字节码缓存。受控解释器不能启动时,当前 Python 必须为 3.10+;缺依赖时明确失败,不伪装成校验成功。
这**没有**增加 XLSX 完整 XSD 校验:`office/validate.py` 目前对 `.xlsx` 明确返回不支持。打包成功不等于完整校验,应使用实际表格库重新打开,核对所需单元格、公式与样式,并按需重算;交付时说明尚不支持完整校验。`recalc.py` 继续使用装有 openpyxl 的 Python,Office XML profile 不会安装 openpyxl 或 pandas。
## Output Rule ## Output Rule
When you create or modify a .xlsx file, you **MUST** tell the user the absolute path of the output file in your response. Example: "文件已保存到:`/path/to/output.xlsx`" When you create or modify a .xlsx file, you **MUST** tell the user the absolute path of the output file in your response. Example: "文件已保存到:`/path/to/output.xlsx`"
@@ -357,4 +370,4 @@ The script returns JSON with error details:
**For Excel files themselves**: **For Excel files themselves**:
- Add comments to cells with complex formulas or important assumptions - Add comments to cells with complex formulas or important assumptions
- Document data sources for hardcoded values - Document data sources for hardcoded values
- Include notes for key calculations and model sections - Include notes for key calculations and model sections
+2 -2
View File
@@ -29,13 +29,13 @@
}, },
"release": { "release": {
"state": "known", "state": "known",
"version": "1.0.4", "version": "1.0.5",
"versionScheme": "semver" "versionScheme": "semver"
}, },
"timestamps": { "timestamps": {
"catalogUpdatedAt": { "catalogUpdatedAt": {
"state": "known", "state": "known",
"value": "2026-10-14", "value": "2026-10-28",
"precision": "day" "precision": "day"
}, },
"releasePublishedAt": { "releasePublishedAt": {
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Run Office XML scripts with the client's prepared Python dependencies.
Each installed skill carries this launcher so it works without another Office
skill. The bootstrap uses only the standard library, including on Python 3.9;
the target requires Python 3.10+ and prefers the runtime's prepared interpreter.
No packages are installed and target failures are never reported as success.
python "<skill-dir>/scripts/with-deps.py" office/unpack.py input.pptx unpacked/
"""
import os
import subprocess
import sys
_HERE = os.path.dirname(os.path.abspath(__file__))
# scripts -> skill -> skills -> the effective DesireCore data root
_ROOT = os.path.abspath(os.path.join(_HERE, "..", "..", ".."))
_PYLIBS = os.path.join(_ROOT, "runtime-deps", "python-libs")
_BUNDLED = os.path.join(
_ROOT,
"runtime-deps",
"python-runtime",
"python.exe" if os.name == "nt" else os.path.join("bin", "python3"),
)
def _current_python_supported():
if sys.version_info[:2] >= (3, 10):
return True
sys.stderr.write(
"with-deps.py: Office XML scripts require Python 3.10+. "
"Prepare the managed Python runtime in DesireCore and retry.\n"
)
return False
def main():
arguments = list(sys.argv[1:])
current_python = bool(arguments and arguments[0] == "--current-python")
if current_python:
arguments.pop(0)
if not arguments:
sys.stderr.write("usage: with-deps.py [--current-python] <script.py> [args...]\n")
return 2
argument = arguments[0]
target = argument if os.path.isabs(argument) else os.path.join(_HERE, argument)
if not os.path.isfile(target):
sys.stderr.write("with-deps.py: target not found: " + target + "\n")
return 2
interpreter = sys.executable
if not current_python and os.path.isfile(_BUNDLED):
if os.path.realpath(_BUNDLED) != os.path.realpath(sys.executable):
interpreter = _BUNDLED
if interpreter == sys.executable and not _current_python_supported():
return 1
environment = dict(os.environ)
if os.path.isdir(_PYLIBS):
existing = environment.get("PYTHONPATH")
environment["PYTHONPATH"] = _PYLIBS + (os.pathsep + existing if existing else "")
# Running a skill must not change its installed content digest through .pyc.
environment["PYTHONDONTWRITEBYTECODE"] = "1"
arguments = ["-B", target, *arguments[1:]]
try:
return subprocess.run([interpreter, *arguments], env=environment).returncode
except OSError as error:
if interpreter == sys.executable:
sys.stderr.write("with-deps.py: could not start Python: " + str(error) + "\n")
return 126
# Fall back only when the process could not start. A target's nonzero
# exit or signal must never replay an edit that may have already run.
sys.stderr.write("with-deps.py: managed Python could not start; trying current Python.\n")
if not _current_python_supported():
return 1
try:
return subprocess.run([sys.executable, *arguments], env=environment).returncode
except OSError as fallback_error:
sys.stderr.write("with-deps.py: could not start Python: " + str(fallback_error) + "\n")
return 126
if __name__ == "__main__":
raise SystemExit(main())