artiwright 0.13.17__tar.gz

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.
@@ -0,0 +1,40 @@
1
+ node_modules/
2
+ dist/
3
+ coverage/
4
+ .turbo/
5
+ *.tsbuildinfo
6
+ .DS_Store
7
+ # .NET
8
+ bin/
9
+ obj/
10
+ *.user
11
+ .vs/
12
+ # generated code
13
+ packages/model/src/gen/
14
+ # local outputs
15
+ out/
16
+ *.local.*
17
+
18
+ # built engine runtime (pnpm engine:wasm)
19
+ packages/engine/wasm/
20
+
21
+ # python
22
+ python/.venv/
23
+ python/src/artiwright/_vendor/*.tgz
24
+ python/dist/
25
+ __pycache__/
26
+ .pytest_cache/
27
+
28
+ # evals
29
+ evals/results/
30
+
31
+ # Claude Code session files and agent worktrees
32
+ .claude/
33
+
34
+ # files a test run can leave in a package folder
35
+ packages/*/x.pptx
36
+ packages/*/*.manifest.ndjson
37
+ packages/*/.artiwright/
38
+ # Copied by pnpm python:vendor for the wheel
39
+ python/LICENSE
40
+ python/NOTICE
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 The Artiwright Authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1,18 @@
1
+ Artiwright
2
+ Copyright 2026-present Venugopal Balaji
3
+
4
+ This product includes software developed by third parties. The npm package lists the software
5
+ it bundles, with their licenses, in THIRD_PARTY_NOTICES.md (written by
6
+ packages/artiwright/scripts/pack.mjs).
7
+
8
+ packages/tokens/src/palette.ts contains the Tailwind CSS color palette values,
9
+ Copyright (c) Tailwind Labs, Inc., used under the MIT License.
10
+
11
+ packages/render/src/geometry/gen/presets.ts contains preset shape geometry derived from
12
+ ECMA-376 Part 1, Office Open XML File Formats (presetShapeDefinitions.xml), © Ecma International,
13
+ used in accordance with the Ecma copyright notice reproduced in that file and in
14
+ scripts/ecma-copyright.txt.
15
+
16
+ packages/fonts/fonts contains Carlito, Liberation and Figtree fonts, licensed under the SIL Open
17
+ Font License 1.1, and Caladea (Copyright (c) 2012 Huerta Tipografia), licensed under the Apache
18
+ License 2.0; their copyright notices and licenses are in packages/fonts/licenses.
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.5
2
+ Name: artiwright
3
+ Version: 0.13.17
4
+ Summary: Native, editable PowerPoint and Excel files for AI agents: Google ADK and LangGraph helpers over the Artiwright MCP server
5
+ Project-URL: Homepage, https://artiwright.com
6
+ Project-URL: Documentation, https://artiwright.com/docs/integrations/google-adk/
7
+ Project-URL: Source, https://github.com/bvenu17/artiwright
8
+ Project-URL: Issues, https://github.com/bvenu17/artiwright/issues
9
+ Project-URL: Changelog, https://github.com/bvenu17/artiwright/blob/main/CHANGELOG.md
10
+ Author: Venugopal Balaji
11
+ License-Expression: Apache-2.0 AND OFL-1.1
12
+ License-File: LICENSE
13
+ License-File: NOTICE
14
+ Keywords: agents,excel,google-adk,langgraph,mcp,powerpoint,pptx,xlsx
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Office/Business :: Office Suites
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Requires-Dist: mcp>=1.9
27
+ Requires-Dist: nodejs-wheel-binaries>=22
28
+ Provides-Extra: adk
29
+ Requires-Dist: google-adk>=2.11; extra == 'adk'
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
32
+ Requires-Dist: pytest>=8; extra == 'dev'
33
+ Requires-Dist: ruff>=0.6; extra == 'dev'
34
+ Provides-Extra: langgraph
35
+ Requires-Dist: langchain-mcp-adapters>=0.3.2; extra == 'langgraph'
36
+ Requires-Dist: langgraph>=0.3; extra == 'langgraph'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # artiwright for Python
40
+
41
+ Google ADK and LangGraph helpers for [Artiwright](https://artiwright.com): give your agents the
42
+ tools to create, edit and check native, editable PowerPoint and Excel files, with live charts,
43
+ tables and formulas.
44
+
45
+ ```bash
46
+ pip install "artiwright[adk]" # Google ADK
47
+ pip install "artiwright[langgraph]" # LangGraph and LangChain
48
+ ```
49
+
50
+ Requires Python 3.10 or newer. The package brings the Artiwright JavaScript package and Node.js
51
+ with it, so `pip install` is all a Python sandbox needs; `artiwright-setup` prepares the
52
+ JavaScript side ahead of the first run.
53
+
54
+ ```python
55
+ from artiwright.adk import artiwright_agent
56
+
57
+ # An ADK agent with Artiwright's tools and its build, look, check, fix loop.
58
+ docs = artiwright_agent(root="/srv/artiwright-sessions", model=MODEL, theme="ledger")
59
+ ```
60
+
61
+ ```python
62
+ from artiwright.langgraph import INSTRUCTION, agent_tools, compact_messages, get_tools
63
+
64
+ tools = agent_tools(await get_tools(root="/srv/artiwright-sessions", session=thread_id))
65
+ ```
66
+
67
+ - Docs: [Google ADK](https://artiwright.com/docs/integrations/google-adk/) ·
68
+ [LangGraph](https://artiwright.com/docs/integrations/langgraph/) ·
69
+ [In your agent pipeline](https://artiwright.com/docs/guides/agent-pipelines/)
70
+ - Source and issues: [github.com/bvenu17/artiwright](https://github.com/bvenu17/artiwright)
71
+ - License: Apache-2.0
@@ -0,0 +1,33 @@
1
+ # artiwright for Python
2
+
3
+ Google ADK and LangGraph helpers for [Artiwright](https://artiwright.com): give your agents the
4
+ tools to create, edit and check native, editable PowerPoint and Excel files, with live charts,
5
+ tables and formulas.
6
+
7
+ ```bash
8
+ pip install "artiwright[adk]" # Google ADK
9
+ pip install "artiwright[langgraph]" # LangGraph and LangChain
10
+ ```
11
+
12
+ Requires Python 3.10 or newer. The package brings the Artiwright JavaScript package and Node.js
13
+ with it, so `pip install` is all a Python sandbox needs; `artiwright-setup` prepares the
14
+ JavaScript side ahead of the first run.
15
+
16
+ ```python
17
+ from artiwright.adk import artiwright_agent
18
+
19
+ # An ADK agent with Artiwright's tools and its build, look, check, fix loop.
20
+ docs = artiwright_agent(root="/srv/artiwright-sessions", model=MODEL, theme="ledger")
21
+ ```
22
+
23
+ ```python
24
+ from artiwright.langgraph import INSTRUCTION, agent_tools, compact_messages, get_tools
25
+
26
+ tools = agent_tools(await get_tools(root="/srv/artiwright-sessions", session=thread_id))
27
+ ```
28
+
29
+ - Docs: [Google ADK](https://artiwright.com/docs/integrations/google-adk/) ·
30
+ [LangGraph](https://artiwright.com/docs/integrations/langgraph/) ·
31
+ [In your agent pipeline](https://artiwright.com/docs/guides/agent-pipelines/)
32
+ - Source and issues: [github.com/bvenu17/artiwright](https://github.com/bvenu17/artiwright)
33
+ - License: Apache-2.0
@@ -0,0 +1,71 @@
1
+ [project]
2
+ name = "artiwright"
3
+ version = "0.13.17"
4
+ description = "Native, editable PowerPoint and Excel files for AI agents: Google ADK and LangGraph helpers over the Artiwright MCP server"
5
+ readme = "README.md"
6
+ # Apache-2.0 for Artiwright; the bundled fonts (inside the vendored tarball) are OFL-1.1.
7
+ license = "Apache-2.0 AND OFL-1.1"
8
+ # Copied from the repository root by `pnpm python:vendor`.
9
+ license-files = ["LICENSE", "NOTICE"]
10
+ requires-python = ">=3.10"
11
+ authors = [{ name = "Venugopal Balaji" }]
12
+ keywords = ["pptx", "xlsx", "powerpoint", "excel", "agents", "mcp", "google-adk", "langgraph"]
13
+ dependencies = [
14
+ "mcp>=1.9",
15
+ # Node.js as a wheel, so Python-only sandboxes need nothing else installed.
16
+ "nodejs-wheel-binaries>=22",
17
+ ]
18
+ classifiers = [
19
+ "Development Status :: 4 - Beta",
20
+ "Intended Audience :: Developers",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Topic :: Office/Business :: Office Suites",
27
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
28
+ "Typing :: Typed",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://artiwright.com"
33
+ Documentation = "https://artiwright.com/docs/integrations/google-adk/"
34
+ Source = "https://github.com/bvenu17/artiwright"
35
+ Issues = "https://github.com/bvenu17/artiwright/issues"
36
+ Changelog = "https://github.com/bvenu17/artiwright/blob/main/CHANGELOG.md"
37
+
38
+ [project.optional-dependencies]
39
+ adk = ["google-adk>=2.11"]
40
+ langgraph = ["langchain-mcp-adapters>=0.3.2", "langgraph>=0.3"]
41
+ dev = ["pytest>=8", "pytest-asyncio>=0.23", "ruff>=0.6"]
42
+
43
+ [project.scripts]
44
+ artiwright-setup = "artiwright.runtime:main"
45
+
46
+ [build-system]
47
+ requires = ["hatchling>=1.27"]
48
+ build-backend = "hatchling.build"
49
+
50
+ [tool.hatch.build.targets.wheel]
51
+ packages = ["src/artiwright"]
52
+ artifacts = ["src/artiwright/_vendor/*.tgz"]
53
+
54
+ [tool.hatch.build.targets.sdist]
55
+ artifacts = ["src/artiwright/_vendor/*.tgz"]
56
+ exclude = ["/tests", "/uv.lock", "/.gitignore", "/.venv", "/.pytest_cache", "/dist"]
57
+
58
+ [tool.ruff]
59
+ line-length = 140
60
+ target-version = "py310"
61
+
62
+ [tool.ruff.lint]
63
+ select = ["E", "F", "I", "UP", "B"]
64
+
65
+ [tool.ruff.lint.per-file-ignores]
66
+ # Test fixtures hold JavaScript and JSON on one line.
67
+ "tests/*" = ["E501"]
68
+
69
+ [tool.pytest.ini_options]
70
+ asyncio_mode = "auto"
71
+ testpaths = ["tests"]
@@ -0,0 +1,12 @@
1
+ """Artiwright for Python: native, editable PowerPoint and Excel files for AI agents.
2
+
3
+ - `artiwright.adk`: Google ADK toolset, agent and callbacks.
4
+ - `artiwright.langgraph`: LangGraph / LangChain tools.
5
+ - `artiwright.server`: the MCP server command, for any other MCP client.
6
+ """
7
+
8
+ from .runtime import RuntimeNotReady, cli_path, ensure_installed, node_path
9
+ from .server import ServerCommand, server_command, session_id
10
+
11
+ __version__ = "0.13.17"
12
+ __all__ = ["RuntimeNotReady", "ServerCommand", "cli_path", "ensure_installed", "node_path", "server_command", "session_id"]
File without changes
@@ -0,0 +1,444 @@
1
+ """Google ADK helpers: the Artiwright tools as an McpToolset, per-chat sessions, and finished
2
+ files saved to the ADK artifact service.
3
+
4
+ from artiwright.adk import artiwright_agent
5
+
6
+ root_agent = LlmAgent(name="router", model=MODEL,
7
+ sub_agents=[rag_agent, artiwright_agent(root="/srv/artiwright", model=MODEL)])
8
+
9
+ Every Artiwright call is tied to the ADK session that made it (user id + session id), so a later
10
+ turn ("make slide 3 a line chart") continues the same deck. A successful artiwright_finalize saves
11
+ the .pptx as a session artifact; your app shows it like any other ADK artifact.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import re
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from .server import server_command, session_id
23
+
24
+ __all__ = [
25
+ "INSTRUCTION",
26
+ "skill_text",
27
+ "toolset",
28
+ "use_session",
29
+ "before_tool",
30
+ "save_outputs",
31
+ "attach_images",
32
+ "compact_history",
33
+ "prepare_request",
34
+ "artiwright_agent",
35
+ "AGENT_TOOLS",
36
+ ]
37
+
38
+ PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
39
+ XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
40
+
41
+ INSTRUCTION = """You make native, editable PowerPoint decks with the artiwright tools.
42
+
43
+ Work in a loop and keep going until the deck is right:
44
+ 1. Plan: the audience, the story, one message per slide. Get facts from the other agents or tools
45
+ before you build; never invent numbers.
46
+ 2. Build with artiwright_run, each slide from a layout recipe (TitleSlide, SectionDivider,
47
+ TitleBullets, TwoColumns, KpiCards, BigNumber, ChartTakeaway, TwoCharts, ComparisonTable,
48
+ Timeline, ProcessSteps, …): `compose(deck.slides.add(), h(KpiCards, { title, kpis }))`. A recipe slide is a
49
+ few lines and comes out lint clean; place shapes by hand only for a slide no recipe fits. Use
50
+ native charts and tables for data, never pictures of them.
51
+ 3. Look: artiwright_render shows the slides; artiwright_lint lists overflow, overlap, small text
52
+ and contrast problems with the anchor (sh_…) to fix.
53
+ 4. Fix by anchor (deck.resolve("sh_…").update({…}) or .replaceText(…)), then render and lint again.
54
+ 5. Review as the audience will: the headlines alone, the wording on each slide, and slides that
55
+ look alike but say different kinds of things. Clean lint does not mean the deck reads well.
56
+ 6. Publish with artiwright_finalize, stating requirements (slideCount, nativeCharts, …). The file
57
+ is then saved for the user; tell them what is in it.
58
+ To change a deck or workbook the user attached (.pptx, .xlsx), or to follow their company
59
+ template, start with artiwright_open (path: the attachment's file name; template: true for a
60
+ deck template). An opened workbook is `workbook` in artiwright_run.
61
+ artiwright_help with "skill presentations" returns the full working guide (recipes, writing,
62
+ design, review); read it before your first deck. Use artiwright_help too when unsure of a call or
63
+ option. Keep slides short: a headline that states the finding (a plain name for setup slides),
64
+ at most five bullets, one visual per slide."""
65
+
66
+
67
+ def skill_text(skill: str = "presentations") -> str:
68
+ """A skill's full text (SKILL.md: "presentations" or "spreadsheets") from the installed package,
69
+ or the short INSTRUCTION."""
70
+ from .runtime import RuntimeNotReady, cli_path
71
+
72
+ try:
73
+ path = Path(cli_path()).parent.parent / "skills" / f"artiwright-{skill}" / "SKILL.md"
74
+ text = path.read_text(encoding="utf-8")
75
+ except (OSError, RuntimeNotReady):
76
+ return INSTRUCTION
77
+ # Drop the front matter; the agent only needs the body.
78
+ return text.split("---", 2)[2].strip() if text.startswith("---") else text
79
+
80
+
81
+ def toolset(
82
+ root: str | os.PathLike[str],
83
+ *,
84
+ sandbox: bool = True,
85
+ timeout: float = 120.0,
86
+ tool_filter: list[str] | None = None,
87
+ theme: str | os.PathLike[str] | dict[str, Any] | None = None,
88
+ ) -> Any:
89
+ """The Artiwright MCP tools for an ADK agent, over stdio. Sessions are kept under `root`;
90
+ `theme` is the theme new documents start in (see server_command)."""
91
+ from google.adk.tools.mcp_tool import McpToolset
92
+ from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams
93
+ from mcp import StdioServerParameters
94
+
95
+ cmd = server_command(root, sandbox=sandbox, theme=theme)
96
+ params = StdioServerParameters(command=cmd.command, args=cmd.args, env=cmd.env)
97
+ return McpToolset(
98
+ connection_params=StdioConnectionParams(server_params=params, timeout=timeout),
99
+ **({"tool_filter": tool_filter} if tool_filter else {}),
100
+ )
101
+
102
+
103
+ def _session_for(tool_context: Any) -> str:
104
+ user = getattr(tool_context, "user_id", None) or "user"
105
+ session = getattr(getattr(tool_context, "session", None), "id", None) or "default"
106
+ return session_id(f"{user}-{session}")
107
+
108
+
109
+ def use_session(tool: Any, args: dict[str, Any], tool_context: Any) -> dict[str, Any] | None:
110
+ """before_tool_callback: ties every Artiwright call to the ADK user and session."""
111
+ if getattr(tool, "name", "").startswith("artiwright_") and tool.name != "artiwright_help":
112
+ args["session"] = _session_for(tool_context)
113
+ return None
114
+
115
+
116
+ async def before_tool(tool: Any, args: dict[str, Any], tool_context: Any) -> dict[str, Any] | None:
117
+ """before_tool_callback for artiwright_agent: ties calls to the ADK session (use_session) and lets
118
+ artiwright_open and artiwright_import name a file the user attached. A `path` that is not absolute is looked up as
119
+ an ADK artifact and sent to the server as its content, so the model never handles the bytes.
120
+ (Let user uploads become artifacts with ADK's SaveFilesAsArtifactsPlugin.)"""
121
+ use_session(tool, args, tool_context)
122
+ name = getattr(tool, "name", "")
123
+ if name not in ("artiwright_open", "artiwright_import") or "content" in args:
124
+ return None
125
+ path = args.get("path")
126
+ if not isinstance(path, str) or os.path.isabs(path) or not hasattr(tool_context, "load_artifact"):
127
+ return None
128
+ import base64
129
+
130
+ artifact = await tool_context.load_artifact(filename=path)
131
+ data = getattr(getattr(artifact, "inline_data", None), "data", None) if artifact is not None else None
132
+ if not data:
133
+ return {"ok": False, "error": f"No attached file named '{path}'. Ask the user to attach the file, or give its absolute path."}
134
+ args.pop("path", None)
135
+ if name == "artiwright_import":
136
+ # A CSV or table file goes as its text, named after the attachment.
137
+ args["content"] = data.decode("utf-8-sig")
138
+ args.setdefault("sheet", os.path.splitext(os.path.basename(path))[0][:31])
139
+ else:
140
+ args["content"] = base64.b64encode(data).decode("ascii")
141
+ return None
142
+
143
+
144
+ def _payload(tool_response: Any) -> dict[str, Any] | None:
145
+ """The JSON an Artiwright tool returned, from ADK's view of an MCP result."""
146
+ content = tool_response.get("content") if isinstance(tool_response, dict) else getattr(tool_response, "content", None)
147
+ if not content:
148
+ return None
149
+ first = content[0]
150
+ text = first.get("text") if isinstance(first, dict) else getattr(first, "text", None)
151
+ try:
152
+ return json.loads(text) if text else None
153
+ except (TypeError, ValueError):
154
+ return None
155
+
156
+
157
+ # Rendered slides waiting to be shown to the model on its next turn, per ADK session.
158
+ _PENDING_IMAGES: dict[str, list[bytes]] = {}
159
+
160
+
161
+ def _take_images(tool_context: Any, tool_response: Any) -> dict[str, Any] | None:
162
+ """Moves render images out of the tool result.
163
+
164
+ ADK passes MCP results to the model as JSON, so an image would arrive as base64 text: about
165
+ 100k tokens for a contact sheet, resent with every later call. attach_images() gives the model
166
+ the pictures as real images instead, once, at about 1-2k tokens each.
167
+ """
168
+ import base64
169
+
170
+ content = tool_response.get("content") if isinstance(tool_response, dict) else getattr(tool_response, "content", None)
171
+ if not content:
172
+ return None
173
+ blocks = [c if isinstance(c, dict) else c.model_dump() for c in content]
174
+ images = [b for b in blocks if b.get("type") == "image" and b.get("data")]
175
+ if not images:
176
+ return None
177
+ _PENDING_IMAGES.setdefault(_session_for(tool_context), []).extend(base64.b64decode(b["data"]) for b in images)
178
+ kept = [b for b in blocks if b.get("type") != "image"]
179
+ note = f"{len(images)} image(s) rendered; they are attached to your next turn. Look at them before you continue."
180
+ response = dict(tool_response) if isinstance(tool_response, dict) else {}
181
+ response["content"] = [*kept, {"type": "text", "text": note}]
182
+ return response
183
+
184
+
185
+ def attach_images(callback_context: Any, llm_request: Any) -> None:
186
+ """before_model_callback: shows the model the slides artiwright_render drew, as images."""
187
+ images = _PENDING_IMAGES.pop(_session_for(callback_context), None)
188
+ if not images:
189
+ return None
190
+ from google.genai import types
191
+
192
+ last = llm_request.contents[-1] if llm_request.contents else None
193
+ renders = (
194
+ [p.function_response for p in (last.parts or []) if p.function_response and p.function_response.name == "artiwright_render"]
195
+ if last
196
+ else []
197
+ )
198
+ model = str(getattr(llm_request, "model", "") or "")
199
+ if renders and not re.match(r"(.*/)?gemini-[12][.-]", model):
200
+ # Newer model generations take images inside the function response (the API rejects a
201
+ # turn that mixes a function response with loose image parts). Set on this request only, not the stored
202
+ # event, so the bytes are sent once rather than with every later call.
203
+ response = renders[-1]
204
+ response.parts = [*(response.parts or []), *(types.FunctionResponsePart.from_bytes(data=b, mime_type="image/png") for b in images)]
205
+ return None
206
+ parts = [types.Part(text="Rendered slides:"), *(types.Part.from_bytes(data=b, mime_type="image/png") for b in images)]
207
+ if last is not None and last.role == "user" and any(p.function_response for p in (last.parts or [])):
208
+ last.parts = [*(last.parts or []), *parts]
209
+ else:
210
+ llm_request.contents.append(types.Content(role="user", parts=parts))
211
+ return None
212
+
213
+
214
+ KEEP_RECENT = 3
215
+ # Older calls are shortened in batches of this many exchanges, so the start of the request stays the
216
+ # same from one call to the next and the provider's prompt cache keeps working between batches.
217
+ COMPACT_EVERY = 4
218
+ _ARG_LIMIT = 300
219
+ _RESULT_LIMIT = 600
220
+
221
+
222
+ def compact_history(callback_context: Any, llm_request: Any, keep: int = KEEP_RECENT) -> None:
223
+ """before_model_callback: sends older tool calls and results in short form.
224
+
225
+ Every model call resends the conversation, so a deck's code and tool output from twenty calls
226
+ ago is paid for twenty times. The document on disk holds the real state (inspect reads it), so
227
+ older calls are shortened: long arguments (the code that was run) and long results are cut, with
228
+ a note saying so. The last `keep` tool exchanges (up to `keep + COMPACT_EVERY - 1` between
229
+ batches) stay whole, and so does the latest long code among the shortened calls. Only this
230
+ request changes; the session's events stay complete.
231
+ """
232
+ contents = llm_request.contents or []
233
+ exchanges = [i for i, c in enumerate(contents) if c.role == "user" and any(p.function_response for p in (c.parts or []))]
234
+ shortened = (len(exchanges) - keep) // COMPACT_EVERY * COMPACT_EVERY
235
+ if shortened <= 0:
236
+ return None
237
+ # The first exchange kept whole starts at the model turn that made its calls.
238
+ cutoff = exchanges[shortened]
239
+ while cutoff > 0 and contents[cutoff - 1].role == "model":
240
+ cutoff -= 1
241
+ # When every call of its own in the history is a note, some models (Gemini 4 Argon) send a note
242
+ # as their next code, so the latest code among the shortened calls is kept as an example.
243
+ latest = max(
244
+ (i for i, c in enumerate(contents[:cutoff]) if any(p.function_call and _long_args(p.function_call.args) for p in (c.parts or []))),
245
+ default=-1,
246
+ )
247
+ for i, content in enumerate(contents[:cutoff]):
248
+ parts = content.parts or []
249
+ if not any(p.function_call or p.function_response for p in parts):
250
+ continue
251
+ contents[i] = content.model_copy(update={"parts": [_compact_part(p, keep_args=i == latest) for p in parts]})
252
+ return None
253
+
254
+
255
+ def _long_args(args: Any) -> bool:
256
+ return isinstance(args, dict) and any(isinstance(v, str) and len(v) > _ARG_LIMIT for v in args.values())
257
+
258
+
259
+ def _compact_part(part: Any, keep_args: bool = False) -> Any:
260
+ if part.function_call and part.function_call.args and not keep_args:
261
+ args = {k: _ran(v) for k, v in part.function_call.args.items()}
262
+ if args != part.function_call.args:
263
+ return part.model_copy(update={"function_call": part.function_call.model_copy(update={"args": args})})
264
+ # Help answers stay whole: they are reference the agent would otherwise look up again.
265
+ if part.function_response and part.function_response.response is not None and not (part.function_response.name or "").endswith("_help"):
266
+ body = part.function_response.response
267
+ text = json.dumps(body, default=str)
268
+ if len(text) > _RESULT_LIMIT:
269
+ short: dict[str, Any] = {"summary": _cut(text, _RESULT_LIMIT, OLDER_RESULT)}
270
+ if isinstance(body, dict) and body.get("isError"):
271
+ short["isError"] = True
272
+ return part.model_copy(update={"function_response": part.function_response.model_copy(update={"response": short})})
273
+ return part
274
+
275
+
276
+ OLDER_RESULT = (
277
+ "older result shortened, so the numbers in it are no longer shown. Read them again "
278
+ "(artiwright_inspect, or return them from code) before you use one"
279
+ )
280
+
281
+
282
+ def _ran(value: Any) -> Any:
283
+ """An older call's long argument (its code), as a note that can't pass for code.
284
+
285
+ Cutting the code to its first lines invited some models to copy the cut version into a new
286
+ call. A note in brackets says what ran without a fragment to copy.
287
+ """
288
+ if not isinstance(value, str) or len(value) <= _ARG_LIMIT:
289
+ return value
290
+ first = next((line.strip() for line in value.splitlines() if line.strip()), "")[:80]
291
+ return (
292
+ f"[already run: {len(value):,} characters beginning {json.dumps(first)}. A note, not code: "
293
+ "send new code in full, and use artiwright_inspect to see what it built.]"
294
+ )
295
+
296
+
297
+ def _cut(value: Any, limit: int, note: str) -> Any:
298
+ if isinstance(value, str) and len(value) > limit:
299
+ return f"{value[:limit]}… [{len(value) - limit} more characters cut: {note}]"
300
+ return value
301
+
302
+
303
+ def prepare_request(callback_context: Any, llm_request: Any) -> None:
304
+ """before_model_callback for artiwright_agent: shorter history, then render images attached."""
305
+ compact_history(callback_context, llm_request)
306
+ return attach_images(callback_context, llm_request)
307
+
308
+
309
+ async def save_outputs(tool: Any, args: dict[str, Any], tool_context: Any, tool_response: Any) -> dict[str, Any] | None:
310
+ """after_tool_callback: turns render images into real images for the model (see attach_images),
311
+ and saves each finalized deck as an ADK artifact, telling the model its name."""
312
+ name = getattr(tool, "name", "")
313
+ if name == "artiwright_render":
314
+ return _take_images(tool_context, tool_response)
315
+ if name != "artiwright_finalize":
316
+ return None
317
+ result = _payload(tool_response)
318
+ if not result or not result.get("ok") or not result.get("path"):
319
+ return None
320
+ from google.genai import types
321
+
322
+ path = Path(result["path"])
323
+ data = path.read_bytes()
324
+ version = await tool_context.save_artifact(
325
+ filename=path.name,
326
+ artifact=types.Part.from_bytes(data=data, mime_type=XLSX if path.suffix.lower() == ".xlsx" else PPTX),
327
+ custom_metadata={"sha256": result.get("sha256"), "source": "artiwright"},
328
+ )
329
+ response = dict(tool_response) if isinstance(tool_response, dict) else {"content": tool_response.content}
330
+ note = {"type": "text", "text": f"Saved for the user as artifact '{path.name}' (version {version})."}
331
+ response["content"] = [*response.get("content", []), note]
332
+ return response
333
+
334
+
335
+ def _fixed(text: str) -> Any:
336
+ """An instruction provider that returns `text` as is (no {state} templating)."""
337
+
338
+ def provide(_context: Any) -> str:
339
+ return text
340
+
341
+ return provide
342
+
343
+
344
+ AGENT_TOOLS = [
345
+ "artiwright_run",
346
+ "artiwright_open",
347
+ "artiwright_import",
348
+ "artiwright_render",
349
+ "artiwright_inspect",
350
+ "artiwright_lint",
351
+ "artiwright_finalize",
352
+ "artiwright_help",
353
+ "artiwright_undo",
354
+ "artiwright_redo",
355
+ "artiwright_status",
356
+ ]
357
+ """The tools artiwright_agent gives its model: every Artiwright tool but artiwright_apply."""
358
+
359
+
360
+ def one_choice(model: Any) -> Any:
361
+ """A LiteLlm model whose replies ADK reads whole.
362
+
363
+ Newer OpenAI models (gpt-6.1-sol, say) can answer with a note and the tool calls as separate
364
+ choices. ADK reads only the first choice, so the agent sees a note without the calls and stops.
365
+ This joins the choices into one. Other models pass through unchanged. artiwright_agent applies it.
366
+ """
367
+ try:
368
+ from google.adk.models.lite_llm import LiteLlm, LiteLLMClient
369
+ except ImportError:
370
+ return model
371
+ if not isinstance(model, LiteLlm) or type(model.llm_client) is not LiteLLMClient:
372
+ return model
373
+
374
+ class OneChoiceClient(LiteLLMClient):
375
+ async def acompletion(self, model: Any, messages: Any, tools: Any, **kwargs: Any) -> Any:
376
+ return _join_choices(await super().acompletion(model, messages, tools, **kwargs))
377
+
378
+ model.llm_client = OneChoiceClient()
379
+ return model
380
+
381
+
382
+ def _join_choices(response: Any) -> Any:
383
+ choices = getattr(response, "choices", None)
384
+ if not isinstance(choices, list) or len(choices) < 2 or not all(hasattr(c, "message") for c in choices):
385
+ return response
386
+ first = choices[0]
387
+ texts = [c.message.content for c in choices if isinstance(c.message.content, str) and c.message.content.strip()]
388
+ calls = [call for c in choices for call in (c.message.tool_calls or [])]
389
+ first.message.content = "\n\n".join(texts) or None
390
+ first.message.tool_calls = calls or None
391
+ if calls:
392
+ first.finish_reason = "tool_calls"
393
+ response.choices = [first]
394
+ return response
395
+
396
+
397
+ DESCRIPTIONS = {
398
+ "presentations": "Builds PowerPoint decks: plans, builds, checks and publishes native, editable files.",
399
+ "spreadsheets": "Builds Excel workbooks: plans, builds, checks and publishes native, editable files.",
400
+ }
401
+ """What a router reads to decide when to hand a request over, by skill."""
402
+
403
+
404
+ def artiwright_agent(
405
+ *,
406
+ root: str | os.PathLike[str],
407
+ model: Any,
408
+ name: str = "artiwright_agent",
409
+ description: str | None = None,
410
+ instruction: str = "",
411
+ tools: list[Any] | None = None,
412
+ sandbox: bool = True,
413
+ full_skill: bool = True,
414
+ skill: str = "presentations",
415
+ theme: str | os.PathLike[str] | dict[str, Any] | None = None,
416
+ ) -> Any:
417
+ """An LlmAgent that makes decks (or, with skill="spreadsheets", workbooks): Artiwright tools,
418
+ the working loop, sessions and artifacts.
419
+
420
+ Pass your own tools (a RAG agent wrapped in AgentTool, say) in `tools`, and extra guidance
421
+ (house style, audience, where the facts are) in `instruction`; it is added to the working guide.
422
+ Leave out rules that shorten the build, look, check, fix loop ("one step", "don't render"): they
423
+ make documents plainer, and the model and its thinking level are what set the speed.
424
+
425
+ `full_skill` uses the whole presentations skill as the instruction (recommended); False uses the
426
+ short INSTRUCTION. `theme` is the company theme every
427
+ new deck and workbook starts in: a preset name, a template path, or {"brand": "#0B5FFF"}; files
428
+ the user attaches keep their own look.
429
+ """
430
+ from google.adk.agents import LlmAgent
431
+
432
+ return LlmAgent(
433
+ name=name,
434
+ model=one_choice(model),
435
+ description=description or DESCRIPTIONS.get(skill, DESCRIPTIONS["presentations"]),
436
+ # A function, so ADK doesn't read code like `({ Workbook })` in the skill as a state placeholder.
437
+ instruction=_fixed(f"{skill_text(skill) if full_skill else INSTRUCTION}\n\n{instruction}".strip()),
438
+ # artiwright_apply is for clients that can't run code; this agent runs code, so leaving the
439
+ # tool out keeps its schema out of every request.
440
+ tools=[toolset(root, sandbox=sandbox, tool_filter=AGENT_TOOLS, theme=theme), *(tools or [])],
441
+ before_tool_callback=before_tool,
442
+ after_tool_callback=save_outputs,
443
+ before_model_callback=prepare_request,
444
+ )
@@ -0,0 +1,106 @@
1
+ """LangGraph / LangChain helpers: the Artiwright tools through langchain-mcp-adapters.
2
+
3
+ from artiwright.langgraph import agent_tools, compact_messages, get_tools, skill_text
4
+ tools = agent_tools(await get_tools(root="/srv/artiwright", session=thread_id))
5
+ agent = create_react_agent(model, tools, prompt=skill_text("presentations"), pre_model_hook=compact_messages)
6
+
7
+ `skill_text("spreadsheets")` or `skill_text("presentations")` is the full guide the skill gives
8
+ Claude; `INSTRUCTION` is the short form.
9
+
10
+ One session per thread: pass the LangGraph thread id as `session`, and every call continues the
11
+ same deck.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ from typing import Any
18
+
19
+ from .adk import (
20
+ _RESULT_LIMIT,
21
+ AGENT_TOOLS,
22
+ COMPACT_EVERY,
23
+ INSTRUCTION,
24
+ KEEP_RECENT,
25
+ OLDER_RESULT,
26
+ _cut,
27
+ _long_args,
28
+ _ran,
29
+ skill_text,
30
+ )
31
+ from .server import server_command
32
+
33
+ __all__ = ["INSTRUCTION", "agent_tools", "compact_messages", "connection", "get_tools", "skill_text"]
34
+
35
+
36
+ def connection(
37
+ root: str | os.PathLike[str],
38
+ session: str | None = None,
39
+ sandbox: bool = True,
40
+ theme: str | os.PathLike[str] | dict[str, Any] | None = None,
41
+ ) -> dict[str, Any]:
42
+ """A langchain-mcp-adapters stdio connection for the Artiwright server; `theme` as in server_command."""
43
+ cmd = server_command(root, session=session, sandbox=sandbox, theme=theme)
44
+ return {"transport": "stdio", "command": cmd.command, "args": cmd.args, "env": cmd.env}
45
+
46
+
47
+ async def get_tools(
48
+ root: str | os.PathLike[str],
49
+ session: str | None = None,
50
+ sandbox: bool = True,
51
+ theme: str | os.PathLike[str] | dict[str, Any] | None = None,
52
+ ) -> list[Any]:
53
+ """The Artiwright tools as LangChain tools, with `session` as the default session and `theme`
54
+ as the theme new documents start in (a preset name, a template path, or {"brand": "#0B5FFF"})."""
55
+ from langchain_mcp_adapters.client import MultiServerMCPClient
56
+
57
+ client = MultiServerMCPClient({"artiwright": connection(root, session=session, sandbox=sandbox, theme=theme)})
58
+ return await client.get_tools()
59
+
60
+
61
+ def agent_tools(tools: list[Any]) -> list[Any]:
62
+ """The tools an agent that runs code needs: all but artiwright_apply (for clients that can't),
63
+ so its schema isn't sent with every request."""
64
+ return [t for t in tools if getattr(t, "name", "") in AGENT_TOOLS]
65
+
66
+
67
+ def compact_messages(state: dict[str, Any], keep: int = KEEP_RECENT) -> dict[str, Any]:
68
+ """pre_model_hook for create_react_agent: sends older tool calls and results in short form.
69
+
70
+ Every model call resends the conversation, so code and tool output from twenty calls ago is
71
+ paid for twenty times. The document on disk holds the real state (inspect reads it), so older
72
+ exchanges are shortened, in batches as in compact_history: long code is cut, long results and
73
+ old render images are replaced by a short summary. Help answers, the last `keep` exchanges and
74
+ the latest code among the shortened ones stay whole. The graph state keeps every message; only
75
+ what the model is sent changes.
76
+ """
77
+ messages = list(state.get("messages", []))
78
+ calls = [i for i, m in enumerate(messages) if getattr(m, "type", "") == "ai" and getattr(m, "tool_calls", None)]
79
+ shortened = (len(calls) - keep) // COMPACT_EVERY * COMPACT_EVERY
80
+ if shortened <= 0:
81
+ return {"llm_input_messages": messages}
82
+ cutoff = calls[shortened]
83
+ # Kept as an example, so the model doesn't copy the note in place of code (see compact_history).
84
+ latest = max((i for i in calls[:shortened] if any(_long_args(c["args"]) for c in messages[i].tool_calls)), default=-1)
85
+ out = []
86
+ for i, m in enumerate(messages):
87
+ kind = getattr(m, "type", "")
88
+ if i >= cutoff or i == latest or kind not in ("ai", "tool"):
89
+ out.append(m)
90
+ elif kind == "ai" and m.tool_calls:
91
+ short = [{**c, "args": {k: _ran(v) for k, v in c["args"].items()}} for c in m.tool_calls]
92
+ out.append(m.model_copy(update={"tool_calls": short}))
93
+ elif kind == "tool" and not (getattr(m, "name", "") or "").endswith("_help"):
94
+ blocks = m.content if isinstance(m.content, list) else [m.content]
95
+ text = "".join(
96
+ b if isinstance(b, str) else str(b.get("text", "")) for b in blocks if isinstance(b, str) or b.get("type") == "text"
97
+ )
98
+ images = sum(1 for b in blocks if isinstance(b, dict) and b.get("type") == "image")
99
+ note = f" [{images} older image(s) left out]" if images else ""
100
+ if len(text) > _RESULT_LIMIT or images:
101
+ out.append(m.model_copy(update={"content": _cut(text, _RESULT_LIMIT, OLDER_RESULT) + note}))
102
+ else:
103
+ out.append(m)
104
+ else:
105
+ out.append(m)
106
+ return {"llm_input_messages": out}
File without changes
@@ -0,0 +1,145 @@
1
+ """Finds Node.js and the Artiwright JavaScript package, installing the latter on first use.
2
+
3
+ Order of preference:
4
+
5
+ 1. ``ARTIWRIGHT_CLI``: path to an existing ``artiwright`` ``cli.js`` (a checkout or an install).
6
+ 2. The package bundled in this wheel (``_vendor/artiwright-*.tgz``), installed with npm into
7
+ ``$ARTIWRIGHT_HOME`` (default ``~/.cache/artiwright``) the first time it is needed.
8
+
9
+ Node comes from ``ARTIWRIGHT_NODE``, else the ``nodejs-wheel-binaries`` dependency, else ``node``
10
+ on the PATH. Node 22 or later is required.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ __all__ = ["cli_path", "node_path", "ensure_installed", "main", "RuntimeNotReady"]
25
+
26
+ _VENDOR = Path(__file__).parent / "_vendor"
27
+
28
+
29
+ class RuntimeNotReady(RuntimeError):
30
+ """Node or the Artiwright JavaScript package is missing, with a fix in the message."""
31
+
32
+
33
+ def node_path() -> str:
34
+ """The Node.js executable to run the server with."""
35
+ explicit = os.environ.get("ARTIWRIGHT_NODE")
36
+ candidates = [explicit] if explicit else []
37
+ try:
38
+ import nodejs_wheel # type: ignore[import-untyped]
39
+
40
+ bundled = Path(nodejs_wheel.__file__).parent / "bin" / ("node.exe" if sys.platform == "win32" else "node")
41
+ candidates.append(str(bundled))
42
+ except ImportError:
43
+ pass
44
+ candidates.append(shutil.which("node") or "")
45
+ for candidate in candidates:
46
+ if candidate and Path(candidate).exists() and _node_major(candidate) >= 22:
47
+ return candidate
48
+ raise RuntimeNotReady(
49
+ "Artiwright needs Node.js 22 or later. Install the `nodejs-wheel-binaries` package "
50
+ "(a dependency of artiwright) or set ARTIWRIGHT_NODE to a node executable."
51
+ )
52
+
53
+
54
+ def _node_major(node: str) -> int:
55
+ try:
56
+ out = subprocess.run([node, "--version"], capture_output=True, text=True, timeout=30).stdout
57
+ except (OSError, subprocess.SubprocessError):
58
+ return 0
59
+ match = re.match(r"v(\d+)", out.strip())
60
+ return int(match.group(1)) if match else 0
61
+
62
+
63
+ def _bundled_tarball() -> Path | None:
64
+ tarballs = sorted(_VENDOR.glob("artiwright-*.tgz"))
65
+ return tarballs[-1] if tarballs else None
66
+
67
+
68
+ def _home() -> Path:
69
+ return Path(os.environ.get("ARTIWRIGHT_HOME", Path.home() / ".cache" / "artiwright"))
70
+
71
+
72
+ def _npm_cli(node: str) -> list[str]:
73
+ """npm as `node npm-cli.js`, so it runs with the same Node (the wheel's npm script uses PATH)."""
74
+ root = Path(node).resolve().parent.parent
75
+ for candidate in (root / "lib" / "node_modules" / "npm" / "bin" / "npm-cli.js", root / "node_modules" / "npm" / "bin" / "npm-cli.js"):
76
+ if candidate.exists():
77
+ return [node, str(candidate)]
78
+ npm = shutil.which("npm")
79
+ if npm:
80
+ return [npm]
81
+ raise RuntimeNotReady("npm was not found next to Node; set ARTIWRIGHT_CLI to an installed artiwright cli.js.")
82
+
83
+
84
+ def ensure_installed(quiet: bool = True) -> Path:
85
+ """Installs the bundled JavaScript package (once per version) and returns its cli.js."""
86
+ tarball = _bundled_tarball()
87
+ if tarball is None:
88
+ raise RuntimeNotReady(
89
+ "This artiwright wheel has no bundled JavaScript package. Build one with "
90
+ "`pnpm pack:local && pnpm python:vendor`, or set ARTIWRIGHT_CLI."
91
+ )
92
+ # Keyed by content, so a rebuilt tarball with the same version number installs afresh.
93
+ digest = hashlib.sha256(tarball.read_bytes()).hexdigest()[:12]
94
+ version = tarball.stem.removeprefix("artiwright-")
95
+ prefix = _home() / "js" / f"{version}-{digest}"
96
+ cli = prefix / "node_modules" / "artiwright" / "dist" / "cli.js"
97
+ if cli.exists():
98
+ return cli
99
+ prefix.mkdir(parents=True, exist_ok=True)
100
+ (prefix / "package.json").write_text(json.dumps({"name": "artiwright-runtime", "private": True}))
101
+ node = node_path()
102
+ env = {**os.environ, "PATH": f"{Path(node).parent}{os.pathsep}{os.environ.get('PATH', '')}"}
103
+ result = subprocess.run(
104
+ # The tarball's npm-shrinkwrap.json pins every dependency; none needs an install script.
105
+ [
106
+ *_npm_cli(node),
107
+ "install",
108
+ str(tarball),
109
+ "--no-audit",
110
+ "--no-fund",
111
+ "--omit=dev",
112
+ "--ignore-scripts",
113
+ *(["--silent"] if quiet else []),
114
+ ],
115
+ cwd=prefix,
116
+ env=env,
117
+ capture_output=quiet,
118
+ text=True,
119
+ )
120
+ if result.returncode != 0 or not cli.exists():
121
+ detail = (result.stderr or "").strip()[-2000:] if quiet else ""
122
+ raise RuntimeNotReady(f"Installing the Artiwright JavaScript package failed (npm exit {result.returncode}). {detail}")
123
+ return cli
124
+
125
+
126
+ def cli_path() -> str:
127
+ """Path to the artiwright CLI (cli.js), installing the bundled package if needed."""
128
+ explicit = os.environ.get("ARTIWRIGHT_CLI")
129
+ if explicit:
130
+ if not Path(explicit).exists():
131
+ raise RuntimeNotReady(f"ARTIWRIGHT_CLI points at {explicit}, which does not exist.")
132
+ return explicit
133
+ return str(ensure_installed())
134
+
135
+
136
+ def main() -> None:
137
+ """`artiwright-setup`: install ahead of time (useful when building a sandbox image)."""
138
+ node = node_path()
139
+ cli = cli_path() if os.environ.get("ARTIWRIGHT_CLI") else str(ensure_installed(quiet=False))
140
+ version = subprocess.run([node, cli, "version"], capture_output=True, text=True, check=True).stdout.strip()
141
+ print(f"Artiwright ready: {version}\nnode: {node}\ncli: {cli}")
142
+
143
+
144
+ if __name__ == "__main__":
145
+ main()
@@ -0,0 +1,76 @@
1
+ """How to start the Artiwright MCP server, for any MCP client library."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from .runtime import cli_path, node_path
13
+
14
+ __all__ = ["ServerCommand", "server_command", "session_id"]
15
+
16
+ _UNSAFE = re.compile(r"[^A-Za-z0-9_.-]+")
17
+
18
+
19
+ def session_id(value: str) -> str:
20
+ """An Artiwright session id from any chat or thread id: safe characters only, at most 128."""
21
+ cleaned = _UNSAFE.sub("-", str(value)).strip("-.") or "default"
22
+ if not cleaned[0].isalnum():
23
+ cleaned = f"s{cleaned}"
24
+ return cleaned[:128]
25
+
26
+
27
+ @dataclass
28
+ class ServerCommand:
29
+ """A command line that starts the server on stdio."""
30
+
31
+ command: str
32
+ args: list[str]
33
+ env: dict[str, str] = field(default_factory=dict)
34
+
35
+
36
+ def server_command(
37
+ root: str | os.PathLike[str],
38
+ session: str | None = None,
39
+ sandbox: bool = True,
40
+ theme: str | os.PathLike[str] | dict[str, Any] | None = None,
41
+ ) -> ServerCommand:
42
+ """The stdio server command: sessions under `root`; `session` sets the default session id.
43
+
44
+ `theme` is the theme new documents start in: a preset name ("ledger"), a company template path
45
+ (.potx, .pptx, .xltx, .xlsx), or a dict of defineTheme options such as {"brand": "#0B5FFF"}.
46
+
47
+ The environment passed to the server is minimal (PATH and Artiwright settings), so the agent
48
+ process's keys and tokens are not handed to it.
49
+ """
50
+ root_path = Path(root).expanduser().resolve()
51
+ root_path.mkdir(parents=True, exist_ok=True)
52
+ args = [cli_path(), "mcp", "--root", str(root_path)]
53
+ if session:
54
+ args += ["--session", session_id(session)]
55
+ if theme is not None:
56
+ args += ["--theme", _theme_arg(theme)]
57
+ env = {"PATH": os.environ.get("PATH", "")}
58
+ for key in ("ARTIWRIGHT_ENGINE_WORKERS", "ARTIWRIGHT_HOME"):
59
+ if key in os.environ:
60
+ env[key] = os.environ[key]
61
+ if not sandbox:
62
+ env["ARTIWRIGHT_SANDBOX"] = "off"
63
+ return ServerCommand(node_path(), args, env)
64
+
65
+
66
+ def _theme_arg(theme: str | os.PathLike[str] | dict[str, Any]) -> str:
67
+ """--theme for the server: JSON for a dict, an absolute path for a template file, else the name."""
68
+ if isinstance(theme, dict):
69
+ return json.dumps(theme)
70
+ text = os.fspath(theme)
71
+ if text.lower().endswith((".potx", ".pptx", ".xltx", ".xlsx")):
72
+ path = Path(text).expanduser().resolve()
73
+ if not path.exists():
74
+ raise FileNotFoundError(f"Theme template {path} does not exist.")
75
+ return str(path)
76
+ return text