feat(plugins): add managed runtime SDK and release 2.4.5

This commit is contained in:
chenmingxuan committed 2026-10-30 14:39:21 +08:00
1 parent 506e3bf1c5
commit 2a3bbaa3fb
45 files changed
+3348 -98

No files matched your search

+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+5
View File
@@ -0,0 +1,5 @@
# 模板来源
本目录为 ARTEMIS 主程序仓库提供的文件证据开发模板,适用本目录 LICENSE 的 Apache-2.0,来源以随模板交付的主程序源码提交为准。没有包含厂商协议、内部资料或用户测试数据。
复制模板后,新增代码、资料和第三方依赖需要分别记录实际来源与分发许可,并为本次候选包保存真实验证结果。模板许可不重新许可新增内容。
+2 -1
View File
@@ -7,7 +7,8 @@
"artemis_version": ">=2.0.0,<3.0.0",
"platforms": ["win32", "linux", "darwin"],
"architectures": ["amd64", "arm64"],
"server": {"command": "${config.python}", "args": ["${plugin_dir}/server.py"]},
"license": "Apache-2.0",
"server": {"command": "${config.python}", "args": ["-B", "${plugin_dir}/server.py"]},
"config": {"python": {"label": "含 MCP 依赖的 Python", "default": "python"}},
"skill": "SKILL.md",
"targets": ["mixed", "computer"],
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,19 @@
# 受管工具与文件快照模板
本模板使用 ARTEMIS 2.4.5 新增的 `artemis.plugins.sdk`,最低宿主版本为 2.4.5。复制模板后使用该版本或更新版本的 ARTEMIS Python;正式的 2.4.4 包不提供这些接口。模板随源码和 Skill 分发,尚未发布到市场。纯文件写入可用相邻 evidence-demo,本模板用于需要外部工具或已批准文件输入的插件。
复制整个目录,使用 ARTEMIS 自己的 Python:
```sh
<ARTEMIS_PYTHON> -B test_contract.py
```
测试只在临时目录创建样例和休眠进程,验证 SDK 的文件替换、超时、取消、后代回收、输出上限,以及真实 stdio MCP 调用、错误输入拒绝和宿主附件回读。结果分为 SDK 自测与本模板离线契约,不证明改写后的插件、设备或业务通过。
扩展时保持固定 argv 和工作目录。先用 `snapshot_file(path, approved_sha256)` 得到不可变 bytes,再将 `snapshot.data` 或 `snapshot.chunks()` 交给实际消费者;不要重新打开原路径。默认内存输入上限 64 MiB,按明确需求选择上限;超大固件需要另外实现有等价保护的流式存储,并单独验证。
`await run_process(argv, cwd=..., timeout=..., input_data=...)` 不执行 shell、不重试,返回原始退出码与 stdout/stderr。标准输入最多 64 MiB,stdout/stderr 共用默认 4 MiB 上限。它在正常退出、超时、取消、输出超限时回收后代;Windows 先将等待启动的引导进程加入 Job Object,再运行工具。POSIX 使用独立会话;这些是生命周期管理,不是恶意程序沙箱,不能托管主动逃离进程组的程序。
宿主负责整个 MCP 调用的期限;插件负责内部操作和子进程。内部超时先发生时,插件必须在返回前完成回收。取消会在回收后传播,不能吞掉 `CancelledError` 后声称完成。`ManagedProcessError.error_code` 稳定且不回显命令,`may_have_started` 决定能否声明尚未执行;`process_cleanup_unconfirmed` 必须按未知处理。命令输出可能包含敏感数据,按业务白名单转换后再返回。
本工具只处理已有任务文件,不提供观察或任意命令能力。保留模板 LICENSE、SOURCE.md,并补充新增代码、协议、资料与依赖的来源和业务回归。在副本中执行 `check_plugin.py --prepare-market` 生成全部未验证的市场记录;本模板自身的离线通过不能填作真实业务验收。
@@ -0,0 +1,8 @@
---
name: managed-tool-demo
description: 对任务目录中已明确批准的文件制作不可变快照,并通过固定工具校验、保存回执。
---
调用 plugin_load 返回映射后的 verify_note。name 只允许任务目录内的普通文件名,sha256 必须是用户明确批准的内容摘要;不要临时计算另一份内容的摘要来绕过批准。
固定工具只读取快照并计算摘要,不提供任意命令、不访问设备或网络。校验与回执保存成功不等于业务测试通过。超时、取消或结果不明时先观察实际状态,不自动重试写操作。没有视觉能力,不能独立承担纯电脑任务。
@@ -0,0 +1,5 @@
# 模板来源
本目录为 ARTEMIS 主程序仓库提供的插件开发模板,适用本目录 LICENSE 的 Apache-2.0。来源为主程序仓库中随该模板交付的对应源码提交;模板使用主程序的 `artemis.plugins.sdk`,不另行分发设备协议、厂商资料或用户用例。
复制后应记录自己的代码、所适配上游、第三方依赖、协议资料和用例的实际来源与许可证;新增内容的分发范围需要分别确认。模板的许可不会重新许可这些新增材料。运行记录须使用自己的实际候选版本和验证结果,不能沿用模板演示结论。
@@ -0,0 +1,23 @@
{
"schema_version": 2,
"id": "managed-tool-demo",
"name": "受管工具与文件快照示例",
"version": "1.0.0",
"description": "开发模板:读取已批准的任务文件快照,调用固定校验程序并保存真实回执。",
"artemis_version": ">=2.4.5,<3.0.0",
"platforms": ["win32", "linux", "darwin"],
"architectures": ["amd64", "arm64"],
"license": "Apache-2.0",
"server": {"command": "${config.python}", "args": ["-B", "${plugin_dir}/server.py"]},
"config": {"python": {"label": "当前 ARTEMIS 环境的 Python", "default": "python"}},
"skill": "SKILL.md",
"targets": ["android", "mixed", "computer"],
"resources": [],
"capabilities": {
"kind": "file", "recording": "none", "required_tools": ["verify_note"],
"tools": {"verify_note": {
"effect": "read", "observation": false, "idempotent": false,
"cancellation": "confirmed", "evidence": ["text", "file"]
}}
}
}
@@ -0,0 +1,128 @@
"""A fixed checksum tool using the installed ARTEMIS authoring SDK."""
import hashlib
import json
import os
from pathlib import Path
import sys
from typing import Annotated
import uuid
from mcp.server.fastmcp import FastMCP
from mcp.types import CallToolResult, TextContent, ToolAnnotations
from pydantic import Field
from artemis.plugins.sdk import ManagedProcessError, run_process, snapshot_file
mcp = FastMCP("managed-tool-demo")
CHECKSUM = "import hashlib,sys; print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())"
def failure(code: str, *, execution: str = "not_started") -> CallToolResult:
return CallToolResult(
isError=True,
content=[TextContent(type="text", text=code)],
structuredContent={
"artemis": {
"version": 1,
"execution": execution,
"side_effect": "none",
"error_code": code,
"retryable": False,
}
},
)
@mcp.tool(
annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=False)
)
async def verify_note(
name: Annotated[str, Field(min_length=1, max_length=180)],
sha256: Annotated[str, Field(pattern=r"^[a-fA-F0-9]{64}$")],
) -> CallToolResult:
"""Verify a task-owned file of at most 64 MiB against its explicitly approved SHA256."""
location = os.environ.get("ARTEMIS_ARTIFACTS_DIR")
if (
not location
or name in {".", ".."}
or Path(name).name != name
or any(c in name for c in '/\\:*?"<>|')
or name.rstrip(" .") != name
or any(ord(c) < 32 for c in name)
):
return failure("invalid_task_filename")
root = Path(location)
try:
if root.is_symlink() or root.is_junction() or root.resolve() != root.absolute():
return failure("invalid_task_directory")
snapshot = snapshot_file(root / name, sha256)
except (OSError, ValueError):
return failure("input_not_bound_to_approved_digest")
try:
# Never reopen the original pathname after verification. The fixed tool
# receives the same immutable bytes even if the source file changes.
result = await run_process(
[sys.executable, "-I", "-B", "-c", CHECKSUM],
cwd=root,
timeout=5,
input_data=snapshot.data,
)
except ManagedProcessError as exc:
return failure(
exc.error_code,
execution="unknown"
if exc.error_code == "process_cleanup_unconfirmed"
else "partial"
if exc.may_have_started
else "not_started",
)
if (
result.returncode != 0
or result.stdout.strip().decode("ascii", errors="replace") != snapshot.sha256
):
return failure("checksum_tool_result_invalid", execution="partial")
content = json.dumps(
{
"source_name": name,
"snapshot_sha256": snapshot.sha256,
"snapshot_bytes": snapshot.size,
"tool_returncode": result.returncode,
"test_verdict": "not_evaluated",
},
ensure_ascii=False,
).encode("utf-8")
receipt_name = f"verified-{uuid.uuid4().hex}.json"
try:
with (root / receipt_name).open("xb") as handle:
handle.write(content)
except OSError:
return failure("receipt_write_failed", execution="partial")
return CallToolResult(
content=[TextContent(type="text", text="已核对批准的文件快照,回执已保存。")],
structuredContent={
"snapshot_sha256": snapshot.sha256,
"artemis": {
"version": 1,
"execution": "completed",
"side_effect": "none",
"retryable": False,
"source": {
"kind": "file",
"target_id": "task-artifacts",
"label": "已批准文件快照",
},
"attachments": [
{
"name": receipt_name,
"media_type": "application/json",
"sha256": hashlib.sha256(content).hexdigest(),
}
],
},
},
)
if __name__ == "__main__":
mcp.run(transport="stdio")
@@ -0,0 +1,69 @@
"""Run with the current ARTEMIS Python; no pytest/device/service/config needed."""
import asyncio
import hashlib
import json
from pathlib import Path
import sys
import tempfile
from artemis.plugins.evidence import persist_attachments, validate_tools
from artemis.plugins.models import PluginManifest, PluginProfile
from artemis.plugins.sdk_checks import run_checks
from artemis.plugins.session import PluginSession, resolve_server
async def run_contract():
directory = Path(__file__).resolve().parent
manifest = PluginManifest.model_validate_json((directory / "plugin.json").read_text("utf-8"))
with tempfile.TemporaryDirectory(prefix="artemis-template-contract-") as temporary:
trace = Path(temporary).resolve()
artifacts = trace / "artifacts" / "plugins" / manifest.id
artifacts.mkdir(parents=True)
content = "synthetic local sample\n中文\x00".encode()
(artifacts / "样例.txt").write_bytes(content)
server = resolve_server(
manifest, PluginProfile(values={"python": sys.executable}), directory
)
server.env["ARTEMIS_ARTIFACTS_DIR"] = str(artifacts)
server.env["PYTHONDONTWRITEBYTECODE"] = "1"
session = await PluginSession(server, directory).start()
try:
validate_tools(manifest, session.tools)
success = await session.call(
"verify_note", {"name": "样例.txt", "sha256": hashlib.sha256(content).hexdigest()}
)
if success.isError:
raise AssertionError("MCP 校验入口失败")
receipt = success.structuredContent["artemis"]
attachments = persist_attachments(trace, manifest.id, receipt["attachments"])
if len(attachments) != 1:
raise AssertionError("宿主未回读到校验回执")
for name, digest in (("样例.txt", "0" * 64), ("../outside.txt", "0" * 64)):
denied = await session.call("verify_note", {"name": name, "sha256": digest})
if (
not denied.isError
or denied.structuredContent["artemis"]["execution"] != "not_started"
):
raise AssertionError("无效输入没有在工具启动前拒绝")
finally:
await session.aclose()
return {
"status": "passed",
"scope": "template_offline_contract",
"mcp_calls": 3,
"host_attachments_verified": 1,
"real_device_actions": False,
}
async def main():
print(
json.dumps(
{"sdk": await run_checks(), "template": await run_contract()}, ensure_ascii=False
)
)
if __name__ == "__main__":
asyncio.run(main())