promptex-py 0.0.0__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,3 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ tmp/
@@ -0,0 +1,204 @@
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
44
+ purposes of this License, Derivative Works shall not include works
45
+ that remain separable from, or merely link (or bind by name) to the
46
+ interfaces of, the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including the
49
+ 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
52
+ owner or by an individual or Legal Entity authorized to submit on
53
+ behalf of the copyright owner. For the purposes of this definition,
54
+ "submitted" means any form of electronic, verbal, or written
55
+ communication sent to the Licensor or its representatives,
56
+ including but not limited to communication on electronic mailing
57
+ lists, source code control systems, and issue tracking systems that
58
+ are managed by, or on behalf of, the Licensor for the purpose of
59
+ discussing and improving the Work, but excluding communication that
60
+ is conspicuously marked or otherwise designated in writing by the
61
+ copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing
142
+ the origin of the Work and reproducing the content of the NOTICE
143
+ file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this
154
+ License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as a
162
+ result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor
166
+ has been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. While redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ APPENDIX: How to apply the Apache License to your work.
182
+
183
+ To apply the Apache License to your work, attach the following
184
+ boilerplate notice, with the fields enclosed by brackets "[]"
185
+ replaced with your own identifying information. (Don't include
186
+ the brackets!) The text should be enclosed in the appropriate
187
+ comment syntax for the file format. We also recommend that a
188
+ file or class name and description of purpose be included on the
189
+ same "printed page" as the copyright notice for easier
190
+ identification within third-party archives.
191
+
192
+ Copyright 2026 promptex-ai
193
+
194
+ Licensed under the Apache License, Version 2.0 (the "License");
195
+ you may not use this file except in compliance with the License.
196
+ You may obtain a copy of the License at
197
+
198
+ http://www.apache.org/licenses/LICENSE-2.0
199
+
200
+ Unless required by applicable law or agreed to in writing, software
201
+ distributed under the License is distributed on an "AS IS" BASIS,
202
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203
+ See the License for the specific language governing permissions and
204
+ limitations under the License.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 promptex-ai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.5
2
+ Name: promptex-py
3
+ Version: 0.0.0
4
+ Summary: promptex 的 Python SDK 最小原型(alpha):宣告 skill 並投影成 SKILL.md,並提供 plugin 與 adapter 契約的介面樁(只有型別與簽名,沒有實作)
5
+ Project-URL: Homepage, https://github.com/promptex-ai/promptex
6
+ Project-URL: Repository, https://github.com/promptex-ai/promptex
7
+ Project-URL: Issues, https://github.com/promptex-ai/promptex/issues
8
+ Author: promptex-ai
9
+ License: MIT OR Apache-2.0
10
+ License-File: LICENSE-APACHE
11
+ License-File: LICENSE-MIT
12
+ Keywords: agent,ai,claude,codegen,llm,prompt,prompt-engineering,skills
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: License :: OSI Approved :: MIT License
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 :: Software Development :: Build Tools
23
+ Classifier: Topic :: Software Development :: Code Generators
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+
28
+ # promptex-py(alpha 原型)
29
+
30
+ promptex 的 Python SDK **最小原型**。目前的能力只有一項:宣告 skill,建置成
31
+ Claude Code 的 `SKILL.md` 產物。
32
+
33
+ ## 這不是什麼
34
+
35
+ 本套件是早期 alpha,**不是**完整的 promptex。正式版的單一套件內含 SDK、核心的
36
+ 預編譯二進位綁定與完整命令列工具三者;本原型只有 SDK 的最窄一條路徑,命令列
37
+ 工具只有 `build` 一個動詞,沒有原生綁定、沒有多平台投影、沒有引用與關係圖、
38
+ 沒有安裝與所有權登記。plugin 與 adapter 的契約面(`Plugin`、`AdapterContext`、
39
+ `defineTarget` 等)是**介面樁**:型別與簽名逐字複製正式版,方法本體一律拋錯,
40
+ 存在的目的是讓第三方擴充能對本套件編譯並發布;要實際執行,工作區得覆寫成本地的
41
+ 正式版 SDK。
42
+
43
+ 介面與產物格式在正式版之前都會變,不保證任何相容性。正式版發布時本原型會被
44
+ 整份取代。
45
+
46
+ ## 安裝
47
+
48
+ ```bash
49
+ pip install --pre promptex-py
50
+ ```
51
+
52
+ 需要 Python 3.10 以上。`--pre` 是必要的:預發布版號不會被 pip 預設選中。
53
+
54
+ ## 用法
55
+
56
+ 把宣告寫在 `prompts/` 下:
57
+
58
+ ```python
59
+ # prompts/skill.py
60
+ from promptex import config, define_skill
61
+
62
+ commit_helper = define_skill(
63
+ "commit-helper",
64
+ "Commit 訊息協助",
65
+ config=config(when_to_use="當使用者要求撰寫 commit 訊息時使用"),
66
+ content=[
67
+ "依 Conventional Commits 撰寫:type(scope): subject。",
68
+ "subject 用繁體中文、50 字內,不以句號結尾;body 說明變更動機而非變更內容。",
69
+ ],
70
+ )
71
+ ```
72
+
73
+ 建置:
74
+
75
+ ```bash
76
+ promptex build
77
+ ```
78
+
79
+ 產出 `./.claude/skills/commit-helper/SKILL.md`:
80
+
81
+ ```text
82
+ ---
83
+ name: commit-helper
84
+ description: 當使用者要求撰寫 commit 訊息時使用
85
+ ---
86
+
87
+ 依 Conventional Commits 撰寫:type(scope): subject。
88
+
89
+ subject 用繁體中文、50 字內,不以句號結尾;body 說明變更動機而非變更內容。
90
+ ```
91
+
92
+ ### 命令列選項
93
+
94
+ ```text
95
+ promptex build [--src <目錄>] [--out <目錄>]
96
+
97
+ --src <目錄> 宣告檔所在目錄,預設 prompts
98
+ --out <目錄> 產物輸出目錄,預設當前目錄
99
+ ```
100
+
101
+ ### 程式化呼叫
102
+
103
+ ```python
104
+ from promptex import build, config, define_skill
105
+
106
+ define_skill("commit-helper", "Commit 訊息協助", config=config(when_to_use="..."), content="...")
107
+ written = build(".")
108
+ ```
109
+
110
+ ## 授權
111
+
112
+ MIT OR Apache-2.0,見 `LICENSE-MIT` 與 `LICENSE-APACHE`。
@@ -0,0 +1,85 @@
1
+ # promptex-py(alpha 原型)
2
+
3
+ promptex 的 Python SDK **最小原型**。目前的能力只有一項:宣告 skill,建置成
4
+ Claude Code 的 `SKILL.md` 產物。
5
+
6
+ ## 這不是什麼
7
+
8
+ 本套件是早期 alpha,**不是**完整的 promptex。正式版的單一套件內含 SDK、核心的
9
+ 預編譯二進位綁定與完整命令列工具三者;本原型只有 SDK 的最窄一條路徑,命令列
10
+ 工具只有 `build` 一個動詞,沒有原生綁定、沒有多平台投影、沒有引用與關係圖、
11
+ 沒有安裝與所有權登記。plugin 與 adapter 的契約面(`Plugin`、`AdapterContext`、
12
+ `defineTarget` 等)是**介面樁**:型別與簽名逐字複製正式版,方法本體一律拋錯,
13
+ 存在的目的是讓第三方擴充能對本套件編譯並發布;要實際執行,工作區得覆寫成本地的
14
+ 正式版 SDK。
15
+
16
+ 介面與產物格式在正式版之前都會變,不保證任何相容性。正式版發布時本原型會被
17
+ 整份取代。
18
+
19
+ ## 安裝
20
+
21
+ ```bash
22
+ pip install --pre promptex-py
23
+ ```
24
+
25
+ 需要 Python 3.10 以上。`--pre` 是必要的:預發布版號不會被 pip 預設選中。
26
+
27
+ ## 用法
28
+
29
+ 把宣告寫在 `prompts/` 下:
30
+
31
+ ```python
32
+ # prompts/skill.py
33
+ from promptex import config, define_skill
34
+
35
+ commit_helper = define_skill(
36
+ "commit-helper",
37
+ "Commit 訊息協助",
38
+ config=config(when_to_use="當使用者要求撰寫 commit 訊息時使用"),
39
+ content=[
40
+ "依 Conventional Commits 撰寫:type(scope): subject。",
41
+ "subject 用繁體中文、50 字內,不以句號結尾;body 說明變更動機而非變更內容。",
42
+ ],
43
+ )
44
+ ```
45
+
46
+ 建置:
47
+
48
+ ```bash
49
+ promptex build
50
+ ```
51
+
52
+ 產出 `./.claude/skills/commit-helper/SKILL.md`:
53
+
54
+ ```text
55
+ ---
56
+ name: commit-helper
57
+ description: 當使用者要求撰寫 commit 訊息時使用
58
+ ---
59
+
60
+ 依 Conventional Commits 撰寫:type(scope): subject。
61
+
62
+ subject 用繁體中文、50 字內,不以句號結尾;body 說明變更動機而非變更內容。
63
+ ```
64
+
65
+ ### 命令列選項
66
+
67
+ ```text
68
+ promptex build [--src <目錄>] [--out <目錄>]
69
+
70
+ --src <目錄> 宣告檔所在目錄,預設 prompts
71
+ --out <目錄> 產物輸出目錄,預設當前目錄
72
+ ```
73
+
74
+ ### 程式化呼叫
75
+
76
+ ```python
77
+ from promptex import build, config, define_skill
78
+
79
+ define_skill("commit-helper", "Commit 訊息協助", config=config(when_to_use="..."), content="...")
80
+ written = build(".")
81
+ ```
82
+
83
+ ## 授權
84
+
85
+ MIT OR Apache-2.0,見 `LICENSE-MIT` 與 `LICENSE-APACHE`。
@@ -0,0 +1,48 @@
1
+ [project]
2
+ name = "promptex-py"
3
+ # 與 npm/crates.io 側的介面樁同版號;0.0.0 在本生態是「介面樁版本,真實作
4
+ # 尚未發布」的語意,消費端的工作區以 [tool.uv.sources] 覆寫到本地正式版。
5
+ version = "0.0.0"
6
+ description = "promptex 的 Python SDK 最小原型(alpha):宣告 skill 並投影成 SKILL.md,並提供 plugin 與 adapter 契約的介面樁(只有型別與簽名,沒有實作)"
7
+ requires-python = ">=3.10"
8
+ license = { text = "MIT OR Apache-2.0" }
9
+ readme = "README.md"
10
+ authors = [{ name = "promptex-ai" }]
11
+ keywords = ["prompt", "prompt-engineering", "ai", "llm", "agent", "claude", "skills", "codegen"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Developers",
15
+ "License :: OSI Approved :: MIT License",
16
+ "License :: OSI Approved :: Apache Software License",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Software Development :: Build Tools",
23
+ "Topic :: Software Development :: Code Generators",
24
+ # 這一項要成立得靠 src/promptex/py.typed 隨 wheel 一起出貨(PEP 561):
25
+ # 型別檢查器對已安裝的套件一律先找標記檔,找不到就整個套件視為無標註。
26
+ "Typing :: Typed",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/promptex-ai/promptex"
31
+ Repository = "https://github.com/promptex-ai/promptex"
32
+ Issues = "https://github.com/promptex-ai/promptex/issues"
33
+
34
+ [project.scripts]
35
+ promptex = "promptex.cli:main"
36
+
37
+ [build-system]
38
+ requires = ["hatchling>=1.25"]
39
+ build-backend = "hatchling.build"
40
+
41
+ [tool.hatch.build.targets.wheel]
42
+ packages = ["src/promptex"]
43
+
44
+ [tool.hatch.build]
45
+ # 開發樹本身就是 python-source,直譯器跑過測試留下的 __pycache__ 會被收進
46
+ # wheel。那些 .pyc 綁死在建置機的 Python 版本上,對安裝端無用,卻讓 wheel
47
+ # 的內容清單隨「誰在哪台機器上建的」而變。
48
+ exclude = ["**/__pycache__/**"]
@@ -0,0 +1,168 @@
1
+ """promptex 的 Python SDK 最小原型(alpha)。
2
+
3
+ 目前的能力只有一條路徑:宣告 skill,投影成 Claude Code 的 SKILL.md。
4
+ 正式版的核心綁定、多平台投影、引用與關係圖都不在本原型範圍內。
5
+
6
+ 另有 plugin 與 adapter 契約的**介面樁**:``plugin``/``adapter``/``diag``/``ir``/
7
+ ``registry``/``content`` 的公開型別與函式簽名逐字複製正式版,方法本體只要碰到
8
+ 註冊表查詢、渲染或投影就拋 ``PromptexStubError``。它們讓第三方擴充能對本套件
9
+ 安裝並發布;要實際執行,工作區得以 ``[tool.uv.sources]`` 指向本地的正式版 SDK。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+
17
+ from .adapter import (
18
+ AdapterContext,
19
+ AdapterEmit,
20
+ AdapterExtension,
21
+ DegradeItem,
22
+ EmitFiles,
23
+ EmitReport,
24
+ define_target,
25
+ format_report,
26
+ report_payload,
27
+ )
28
+ from .content import MDNode
29
+ from .diag import Diagnostic, format_diagnostic, has_errors
30
+ from .ir import KINDS, Kind
31
+ from .plugin import LockEntry, Plugin, PluginEntry, PrepareContext, TransformContext, ValidateContext
32
+ from .registry import Content, ContentPiece, Ref
33
+
34
+ __all__ = [
35
+ "AdapterContext",
36
+ "AdapterEmit",
37
+ "AdapterExtension",
38
+ "CapabilityConfig",
39
+ "Content",
40
+ "ContentPiece",
41
+ "DegradeItem",
42
+ "Diagnostic",
43
+ "EmitFiles",
44
+ "EmitReport",
45
+ "KINDS",
46
+ "Kind",
47
+ "LockEntry",
48
+ "MDNode",
49
+ "Plugin",
50
+ "PluginEntry",
51
+ "PrepareContext",
52
+ "Ref",
53
+ "TransformContext",
54
+ "ValidateContext",
55
+ "build",
56
+ "config",
57
+ "declared_count",
58
+ "define_skill",
59
+ "define_target",
60
+ "format_diagnostic",
61
+ "format_report",
62
+ "has_errors",
63
+ "render_skill",
64
+ "report_payload",
65
+ "skill_path",
66
+ ]
67
+
68
+ __version__ = "0.0.0"
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class CapabilityConfig:
73
+ """skill 的觸發設定。"""
74
+
75
+ when_to_use: str = ""
76
+
77
+
78
+ def config(*, when_to_use: str = "") -> CapabilityConfig:
79
+ """建立觸發設定。與正式版的宣告形態一致,以具名參數承載。"""
80
+ return CapabilityConfig(when_to_use=when_to_use)
81
+
82
+
83
+ @dataclass
84
+ class _Skill:
85
+ """登記處內的正規化形態。"""
86
+
87
+ id: str
88
+ name: str
89
+ when_to_use: str
90
+ content: list[str] = field(default_factory=list)
91
+
92
+
93
+ # 模組層級的登記處:宣告散落在多個檔案時,逐一回傳並手動彙整會讓每個檔案
94
+ # 都得認識彙整點。正式版的收集語意相同。
95
+ _registry: list[_Skill] = []
96
+
97
+
98
+ def _is_valid_id(value: str) -> bool:
99
+ """id 是否可安全作為單層目錄名。
100
+
101
+ 產物路徑由 id 直接組成,不擋下來的話 ``../`` 這類值會把檔案寫到輸出
102
+ 目錄之外。
103
+ """
104
+ return bool(value) and "/" not in value and "\\" not in value and value not in {".", ".."}
105
+
106
+
107
+ def define_skill(
108
+ id: str,
109
+ name: str,
110
+ *,
111
+ config: CapabilityConfig | None = None,
112
+ content: str | list[str] | None = None,
113
+ ) -> Ref:
114
+ """宣告一份 skill。
115
+
116
+ 宣告本身不寫檔;產物在 :func:`build` 被呼叫時一次產出。
117
+ """
118
+ if not _is_valid_id(id):
119
+ raise ValueError(f"skill id 不可為空、且不可含 `/`、`\\` 或 `..`:{id!r}")
120
+ pieces = [] if content is None else ([content] if isinstance(content, str) else list(content))
121
+ _registry.append(
122
+ _Skill(
123
+ id=id,
124
+ name=name,
125
+ when_to_use=(config or CapabilityConfig()).when_to_use,
126
+ content=pieces,
127
+ )
128
+ )
129
+ return Ref(kind="skill", id=id)
130
+
131
+
132
+ def declared_count() -> int:
133
+ """目前已登記的宣告數。供呼叫端在建置前自我核對用。"""
134
+ return len(_registry)
135
+
136
+
137
+ def render_skill(skill: _Skill) -> str:
138
+ """把一份 skill 投影成 SKILL.md 的完整內容。
139
+
140
+ frontmatter 的 ``name`` 取 id 而非顯示名稱:平台側以 ``name`` 作為喚起時
141
+ 的識別。
142
+ """
143
+ header = f"---\nname: {skill.id}\ndescription: {skill.when_to_use}\n---\n"
144
+ if not skill.content:
145
+ return header
146
+ return header + "\n" + "\n\n".join(skill.content) + "\n"
147
+
148
+
149
+ def skill_path(out_dir: str | Path, id: str) -> Path:
150
+ """一份 skill 在輸出目錄下的產物路徑。"""
151
+ return Path(out_dir) / ".claude" / "skills" / id / "SKILL.md"
152
+
153
+
154
+ def build(out_dir: str | Path) -> list[Path]:
155
+ """把目前登記的全部宣告投影到輸出目錄,回傳產物路徑。
156
+
157
+ 呼叫後登記處清空:同一行程內連續建置兩個輸出目錄時,第二次不該重複
158
+ 寫出第一次的內容。
159
+ """
160
+ skills = list(_registry)
161
+ _registry.clear()
162
+ written: list[Path] = []
163
+ for skill in skills:
164
+ path = skill_path(out_dir, skill.id)
165
+ path.parent.mkdir(parents=True, exist_ok=True)
166
+ path.write_text(render_skill(skill), encoding="utf-8")
167
+ written.append(path)
168
+ return written
@@ -0,0 +1,5 @@
1
+ """讓 ``python -m promptex`` 與 ``promptex`` 執行檔走同一條路徑。"""
2
+
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,27 @@
1
+ """介面樁的統一落點:訊息帶套件名與版號,讓「裝到的是樁」在第一個錯誤就看得
2
+ 出來,而不是在某個 ``None`` 或空清單上安靜地繼續。
3
+
4
+ 不從套件根匯出:``PromptexStubError`` 不是正式版的公開面,匯出它會讓樁的公開
5
+ 名字多出一個正式版沒有的。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import NoReturn
11
+
12
+ _PACKAGE = "promptex-py 0.0.0"
13
+
14
+
15
+ class PromptexStubError(NotImplementedError):
16
+ """呼叫到介面樁時拋出;訊息指名該去哪裡接上真實作。"""
17
+
18
+ def __init__(self, what: str) -> None:
19
+ super().__init__(
20
+ f"promptex 介面樁({_PACKAGE}):`{what}` 沒有實作。"
21
+ "本版只提供型別與函式簽名讓擴充能編譯;要實際執行,"
22
+ "請把工作區的 [tool.uv.sources] 指向本地 promptex 框架,或等正式版發布。"
23
+ )
24
+
25
+
26
+ def stub(what: str) -> NoReturn:
27
+ raise PromptexStubError(what)
@@ -0,0 +1,156 @@
1
+ """第三方 adapter 的公開介面(介面樁):型別與方法簽名逐字複製正式版
2
+ ``promptex/adapter.py``。
3
+
4
+ 照抄與樁的分界:``define_target`` 只是組一個 dict,照抄;``AdapterContext`` 的
5
+ ``degrade``/``unsupported``/``report``/``has_notes`` 只碰自身欄位,照抄;
6
+ ``entries``/``render``/``overrides``/``reserved``/``unsupported_override`` 要查
7
+ 註冊表或委派核心,本體為樁;``format_report`` 委派核心的報告渲染,本體為樁。
8
+ ``report_payload`` 是純序列化,照抄。
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass, field
14
+ from typing import Any, Callable, Mapping, Optional, Sequence, Union
15
+
16
+ from ._stub import stub
17
+ from .plugin import PluginEntry
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class DegradeItem:
22
+ """降級或不支援的一筆記錄,與核心 ``adapter::DegradeEntry`` 同型(``node_id``
23
+ 序列化為 ``nodeId``)。欄位名用 ``from_`` 而非 ``from``:後者是 Python
24
+ 關鍵字;序列化時還原為 ``from``。
25
+ """
26
+
27
+ kind: str
28
+ node_id: str
29
+ feature: str
30
+ note: str
31
+ from_: Optional[str] = None
32
+ to: Optional[str] = None
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class EmitReport:
37
+ """一次第三方投影的安裝報告,與內建平台的 ``Report`` 同一形態。"""
38
+
39
+ platform: str
40
+ emitted: Sequence[str]
41
+ degraded: Sequence[DegradeItem]
42
+ unsupported: Sequence[DegradeItem]
43
+
44
+
45
+ #: 第三方投影的產物表:鍵為相對安裝根的路徑,值依實際內容型態為文字或 ``bytes``。
46
+ EmitFiles = dict[str, Union[str, bytes]]
47
+
48
+ #: 第三方適配的投影函式:宣告「我是一個新平台」。
49
+ AdapterEmit = Callable[["AdapterContext"], EmitFiles]
50
+
51
+ #: 平台適配的擴充函式:宣告「我為既有平台補一種產物形態」。
52
+ AdapterExtension = Callable[["AdapterContext", EmitFiles], None]
53
+
54
+
55
+ @dataclass
56
+ class AdapterContext:
57
+ """第三方 adapter 的公開介面:官方與第三方適配使用同一組九個方法。"""
58
+
59
+ platform: str
60
+ select: Optional[dict[str, Any]] = None
61
+ _degraded: list[DegradeItem] = field(default_factory=list, init=False)
62
+ _unsupported: list[DegradeItem] = field(default_factory=list, init=False)
63
+
64
+ def entries(self, kind: Optional[str] = None) -> list[PluginEntry]:
65
+ """本平台要產出的節點(省略 kind 即全部)。"""
66
+ del kind
67
+ stub("AdapterContext.entries")
68
+
69
+ def render(self, entry: PluginEntry, self_path: str, layout: Mapping[str, str]) -> str:
70
+ """依落點表渲染節點內容:第三個參數是落點對照表,不是回呼函式。"""
71
+ del entry, self_path, layout
72
+ stub("AdapterContext.render")
73
+
74
+ def overrides(self, entry: PluginEntry) -> Optional[dict[str, Any]]:
75
+ """本節點為本平台宣告的平台原生鍵覆寫;未宣告或空物件時回傳 ``None``。"""
76
+ del entry
77
+ stub("AdapterContext.overrides")
78
+
79
+ def reserved(self, entry: PluginEntry) -> Optional[dict[str, str]]:
80
+ """本節點宣告的框架保留鍵(``promptex:`` 命名空間);未宣告時回傳 ``None``。"""
81
+ del entry
82
+ stub("AdapterContext.reserved")
83
+
84
+ def unsupported_override(self, entry: PluginEntry, form: str) -> None:
85
+ """本節點在本平台的產物沒有承載鍵的位置時,把該筆記進不支援清單。"""
86
+ del entry, form
87
+ stub("AdapterContext.unsupported_override")
88
+
89
+ def degrade(self, item: DegradeItem) -> None:
90
+ """記錄能力降級,進安裝報告。"""
91
+ self._degraded.append(item)
92
+
93
+ def unsupported(self, item: DegradeItem) -> None:
94
+ """記錄平台不支援而未產出的節點,進安裝報告。"""
95
+ self._unsupported.append(item)
96
+
97
+ def report(self, platform: str, emitted: Sequence[str]) -> EmitReport:
98
+ """把本次累積的降級與不支援併成安裝報告。"""
99
+ return EmitReport(
100
+ platform=platform,
101
+ emitted=list(emitted),
102
+ degraded=list(self._degraded),
103
+ unsupported=list(self._unsupported),
104
+ )
105
+
106
+ def has_notes(self) -> bool:
107
+ """是否累積了任何降級或不支援記錄。"""
108
+ return bool(self._degraded or self._unsupported)
109
+
110
+
111
+ def define_target(
112
+ platform: str,
113
+ emit: AdapterEmit,
114
+ config_schema: Optional[Any] = None,
115
+ config_schema_locales: Optional[dict[str, Any]] = None,
116
+ ) -> dict[str, Any]:
117
+ """第三方套件用本函式建構 target:與內建 ``claude()``/``codex()`` 回傳同一種
118
+ 形狀,多帶一個 ``emit`` 實作。
119
+ """
120
+ target: dict[str, Any] = {"platform": platform, "emit": emit}
121
+ if config_schema is not None:
122
+ target["config_schema"] = config_schema
123
+ if config_schema_locales:
124
+ target["config_schema_locales"] = config_schema_locales
125
+ return target
126
+
127
+
128
+ def _item_payload(item: DegradeItem) -> dict[str, Any]:
129
+ """一筆記錄的序列化形態,欄位名對齊核心 ``adapter::DegradeEntry``。"""
130
+ payload: dict[str, Any] = {
131
+ "kind": item.kind,
132
+ "nodeId": item.node_id,
133
+ "feature": item.feature,
134
+ "note": item.note,
135
+ }
136
+ if item.from_ is not None:
137
+ payload["from"] = item.from_
138
+ if item.to is not None:
139
+ payload["to"] = item.to
140
+ return payload
141
+
142
+
143
+ def report_payload(report: EmitReport) -> dict[str, Any]:
144
+ """``EmitReport`` 轉成核心 ``adapter::Report`` 收的線上形態。"""
145
+ return {
146
+ "platform": report.platform,
147
+ "emitted": list(report.emitted),
148
+ "degraded": [_item_payload(d) for d in report.degraded],
149
+ "unsupported": [_item_payload(u) for u in report.unsupported],
150
+ }
151
+
152
+
153
+ def format_report(report: EmitReport) -> str:
154
+ """格式化為人讀文字:正式版委派核心 ``adapter::Report::format``。"""
155
+ del report
156
+ stub("format_report")
@@ -0,0 +1,70 @@
1
+ """promptex 命令列工具(alpha 原型)。
2
+
3
+ 只有一個動詞:``build``。載入來源目錄下的宣告檔,把登記處內的 skill 投影成
4
+ SKILL.md。正式版的其餘動詞(evaluate、declare、config、diagnostics)不在本
5
+ 原型範圍內。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import importlib.util
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ from . import build, declared_count
16
+
17
+
18
+ def _load_source(path: Path) -> None:
19
+ """以檔案路徑載入一份宣告檔。
20
+
21
+ 走 importlib 的 spec 載入而非 ``import``:宣告檔住使用者的專案目錄,
22
+ 不在套件搜尋路徑上,也不該為了載入它去改動 ``sys.path``。
23
+ """
24
+ module_name = f"_promptex_source_{path.stem}"
25
+ spec = importlib.util.spec_from_file_location(module_name, path)
26
+ if spec is None or spec.loader is None:
27
+ raise RuntimeError(f"無法載入宣告檔:{path}")
28
+ module = importlib.util.module_from_spec(spec)
29
+ sys.modules[module_name] = module
30
+ spec.loader.exec_module(module)
31
+
32
+
33
+ def _collect_sources(src_dir: Path) -> list[Path]:
34
+ """列出來源目錄下的宣告檔,依路徑排序讓載入順序不隨檔案系統而變。"""
35
+ return sorted(p for p in src_dir.rglob("*.py") if p.name != "__init__.py")
36
+
37
+
38
+ def main(argv: list[str] | None = None) -> int:
39
+ parser = argparse.ArgumentParser(prog="promptex", description="promptex(alpha 原型)")
40
+ sub = parser.add_subparsers(dest="verb", required=True)
41
+ build_parser = sub.add_parser("build", help="把宣告投影成產物")
42
+ build_parser.add_argument("--src", default="prompts", help="宣告檔所在目錄,預設 prompts")
43
+ build_parser.add_argument("--out", default=".", help="產物輸出目錄,預設當前目錄")
44
+
45
+ args = parser.parse_args(sys.argv[1:] if argv is None else argv)
46
+
47
+ src_dir = Path(args.src).resolve()
48
+ if not src_dir.is_dir():
49
+ print(f"找不到來源目錄:{src_dir}", file=sys.stderr)
50
+ return 1
51
+
52
+ sources = _collect_sources(src_dir)
53
+ if not sources:
54
+ print(f"來源目錄沒有宣告檔(*.py):{src_dir}", file=sys.stderr)
55
+ return 1
56
+
57
+ for source in sources:
58
+ _load_source(source)
59
+
60
+ if declared_count() == 0:
61
+ print(f"載入了 {len(sources)} 份宣告檔,但沒有任何 skill 被宣告。", file=sys.stderr)
62
+ return 1
63
+
64
+ for path in build(Path(args.out).resolve()):
65
+ print(path)
66
+ return 0
67
+
68
+
69
+ if __name__ == "__main__":
70
+ raise SystemExit(main())
@@ -0,0 +1,38 @@
1
+ """內容片段的型別(介面樁):只承載正式版 ``promptex/content.py`` 對外匯出的
2
+ ``Piece`` 與 ``MDNode``,逐字複製。建構函式本體(``prose``/``section`` 等)
3
+ 不在本樁範圍。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+
11
+ #: 內容片段:以資料結構表達,不含任何平台的渲染結果。Python 側維持一般 dict
12
+ #: (``{'t': ..., ...}``)表達。
13
+ Piece = dict[str, Any]
14
+
15
+
16
+ def _piece_reject_message(piece: Piece) -> str:
17
+ return (
18
+ f"內容片段({piece.get('t')})不可插入字串或 f-string:"
19
+ "片段是結構化資料,轉換當下只會得到它的 repr,投影階段無從還原。\n"
20
+ ' 內容以清單元素形態承載:content=["前文", bold("重點"), "後文"]'
21
+ )
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class MDNode:
26
+ """建構函式的回傳值。包一層是為了與純字串區分。
27
+
28
+ 覆寫 ``__str__``/``__format__`` 封住字串轉換:片段必須以物件形態保留到
29
+ 投影才能渲染出結構,提前轉換會讓內容靜默退化成一段沒有意義的文字。
30
+ """
31
+
32
+ piece: Piece
33
+
34
+ def __str__(self) -> str: # noqa: D105
35
+ raise TypeError(_piece_reject_message(self.piece))
36
+
37
+ def __format__(self, format_spec: str) -> str: # noqa: D105
38
+ raise TypeError(_piece_reject_message(self.piece))
@@ -0,0 +1,39 @@
1
+ """診斷的型別與人讀格式(介面樁):逐字複製正式版 ``promptex/diag.py`` 的
2
+ ``Diagnostic`` 與兩個純函式。診斷本身不含引擎邏輯,因此照抄而非樁;位置捕捉
3
+ (``capture_at``)與相似度計算屬求值期內部工具,不在公開匯出面,不帶。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+ from typing import Optional
10
+
11
+ #: 嚴重度:'error'(阻斷級中止建置)或 'warning'(非阻斷級列入報告後放行)。
12
+
13
+
14
+ @dataclass
15
+ class Diagnostic:
16
+ """一筆診斷。代碼、訊息、位置三項必含;``at`` 是清單以便同時指出兩處位置。"""
17
+
18
+ code: str
19
+ message: str
20
+ at: list[str]
21
+ hint: Optional[str] = None
22
+ severity: Optional[str] = None
23
+
24
+
25
+ def has_errors(diags: list[Diagnostic]) -> bool:
26
+ """本批診斷是否含阻斷級項目。"""
27
+ return any((d.severity or "error") == "error" for d in diags)
28
+
29
+
30
+ def format_diagnostic(d: Diagnostic) -> list[str]:
31
+ """一筆診斷的人讀形態,逐行回傳:嚴重度標記(阻斷級 ``✗``、非阻斷級 ``※``)、
32
+ 位置逐一列出、有提示才列提示。
33
+ """
34
+ marker = "✗" if (d.severity or "error") == "error" else "※"
35
+ lines = [f"{marker} {d.code} {d.message}"]
36
+ lines.extend(f" at {at}" for at in d.at)
37
+ if d.hint:
38
+ lines.append(f" {d.hint}")
39
+ return lines
@@ -0,0 +1,68 @@
1
+ """中介表示的型別文件(介面樁):逐字複製正式版 ``promptex/ir.py`` 的公開型別。
2
+ 純型別,執行期只有 ``KINDS`` 這個集合。
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any, List, Literal, TypedDict
8
+
9
+ #: 資源類型:集合封閉,不可由擴充新增。
10
+ Kind = Literal[
11
+ "skill",
12
+ "rule",
13
+ "agent",
14
+ "hook",
15
+ "mcp",
16
+ "instruction",
17
+ "permission",
18
+ "resource",
19
+ "asset",
20
+ "dir",
21
+ ]
22
+
23
+ #: 與 Kind 同義的執行期可迭代集合,供成員檢查使用。
24
+ KINDS: frozenset[str] = frozenset(
25
+ {
26
+ "skill",
27
+ "rule",
28
+ "agent",
29
+ "hook",
30
+ "mcp",
31
+ "instruction",
32
+ "permission",
33
+ "resource",
34
+ "asset",
35
+ "dir",
36
+ }
37
+ )
38
+
39
+
40
+ class RefTarget(TypedDict):
41
+ """引用目標:類型加識別字的複合鍵。"""
42
+
43
+ kind: Kind
44
+ id: str
45
+
46
+
47
+ class Node(TypedDict, total=False):
48
+ """欄位順序即契約:宣告順序要與 Rust/TypeScript 側一致。"""
49
+
50
+ id: str
51
+ name: str
52
+ kind: Kind
53
+ config: dict[str, Any]
54
+ meta: dict[str, Any]
55
+ content: list[dict[str, Any]]
56
+
57
+
58
+ class Provenance(TypedDict):
59
+ sourceCommit: str
60
+ confHash: str
61
+ engineVersion: str
62
+
63
+
64
+ class Ir(TypedDict):
65
+ version: str
66
+ provenance: Provenance
67
+ nodes: List[Node]
68
+ resources: List[Node]
@@ -0,0 +1,132 @@
1
+ """擴充機制(plugin)的型別契約(介面樁):逐字複製正式版 ``promptex/plugin.py``。
2
+
3
+ 三個脈絡類別的方法只是委派建構時注入的 callable,本身沒有引擎邏輯,因此照抄
4
+ 而非樁;引擎住框架端注入的函式裡,而樁裡沒有人會建構這些脈絡。``Plugin`` 是
5
+ dataclass,生命週期是欄位持有的 callable,同樣照抄。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from typing import Any, Awaitable, Callable, Optional, Sequence
12
+
13
+ from .diag import Diagnostic
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class PluginEntry:
18
+ """plugin 生命週期看到的節點視圖;Python 側為唯讀快照。"""
19
+
20
+ id: str
21
+ kind: str
22
+ name: str
23
+ #: 宣告在源碼中的位置,供診斷指出節點定義於何處。
24
+ at: str
25
+ description: Optional[str] = None
26
+ config: Optional[dict[str, Any]] = None
27
+ meta: Optional[dict[str, Any]] = None
28
+ content: Any = None
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class LockEntry:
33
+ """外部依賴的一筆鎖定記錄。"""
34
+
35
+ id: str
36
+ source: str
37
+ version: str
38
+
39
+
40
+ class PrepareContext:
41
+ """準備階段看到的框架協助:快取落點與鎖定檔由框架統一提供。"""
42
+
43
+ def __init__(
44
+ self, cache_dir: str, project_root: str, write_lock_fn: Callable[[list[LockEntry]], None]
45
+ ) -> None:
46
+ self.cache_dir = cache_dir
47
+ self.project_root = project_root
48
+ self._write_lock_fn = write_lock_fn
49
+
50
+ def write_lock(self, entries: list[LockEntry]) -> None:
51
+ """寫入本 plugin 的鎖定區段。"""
52
+ self._write_lock_fn(entries)
53
+
54
+
55
+ class ValidateContext:
56
+ """解析遍看到的框架協助:唯讀查詢當下註冊表狀態、讀取本 plugin 的自訂
57
+ 參數、取得本輪求值的專案根。
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ entries_fn: Callable[..., list[PluginEntry]],
63
+ plugin_name: str,
64
+ project_root_fn: Callable[[], str],
65
+ ) -> None:
66
+ self._entries_fn = entries_fn
67
+ self._plugin_name = plugin_name
68
+ self._project_root_fn = project_root_fn
69
+
70
+ @property
71
+ def project_root(self) -> str:
72
+ """本輪求值的專案根,與 ``PrepareContext.project_root`` 同一個值。"""
73
+ return self._project_root_fn()
74
+
75
+ @property
76
+ def entries(self) -> list[PluginEntry]:
77
+ """當下註冊表的全部節點,依 id 排序;每次存取都重新查詢。"""
78
+ return self._entries_fn()
79
+
80
+ def entries_of(self, kind: str) -> list[PluginEntry]:
81
+ """限定某個 kind 的節點清單。"""
82
+ return self._entries_fn(kind)
83
+
84
+ def params(self, entry: PluginEntry) -> Any:
85
+ """讀本 plugin 的自訂參數(``meta.plugins[plugin_name]``);未宣告回傳 ``None``。"""
86
+ plugins = (entry.meta or {}).get("plugins") or {}
87
+ return plugins.get(self._plugin_name)
88
+
89
+
90
+ class TransformContext(ValidateContext):
91
+ """改寫遍看到的框架協助:在 ``ValidateContext`` 的唯讀能力之上,加上對
92
+ 節點的疊加型與覆寫型改寫。
93
+ """
94
+
95
+ def __init__(
96
+ self,
97
+ entries_fn: Callable[..., list[PluginEntry]],
98
+ plugin_name: str,
99
+ append_content_fn: Callable[[PluginEntry, Any], None],
100
+ patch_config_fn: Callable[[PluginEntry, dict[str, Any]], None],
101
+ project_root_fn: Callable[[], str],
102
+ ) -> None:
103
+ super().__init__(entries_fn, plugin_name, project_root_fn)
104
+ self._append_content_fn = append_content_fn
105
+ self._patch_config_fn = patch_config_fn
106
+
107
+ def append_content(self, entry: PluginEntry, content: Any) -> None:
108
+ """對節點的 content 追加一段內容(疊加型改寫)。"""
109
+ self._append_content_fn(entry, content)
110
+
111
+ def patch_config(self, entry: PluginEntry, patch: dict[str, Any]) -> None:
112
+ """合併進節點的 config(覆寫型改寫);衝突偵測到鍵的層級。"""
113
+ self._patch_config_fn(entry, patch)
114
+
115
+
116
+ @dataclass
117
+ class Plugin:
118
+ """一個擴充:dataclass 讓作者以關鍵字引數宣告用得到的生命週期,其餘留
119
+ ``None``;未宣告的生命週期完全略過。
120
+ """
121
+
122
+ name: str
123
+ version: Optional[str] = None
124
+ # 這個擴充作用在哪幾種節點類型;None 即不限。
125
+ kinds: Optional[Sequence[str]] = None
126
+ # 本擴充接受哪些建構參數,標準 JSON Schema;純資料,穿得過中介表示的邊界。
127
+ config_schema: Optional[Any] = None
128
+ # 各語系的覆蓋層:語系標籤 → 「JSON Pointer → 替換值」的對照。
129
+ config_schema_locales: Optional[dict[str, Any]] = None
130
+ prepare: Optional[Callable[[PrepareContext], Awaitable[None]]] = None
131
+ validate: Optional[Callable[[ValidateContext], list[Diagnostic]]] = None
132
+ transform: Optional[Callable[[TransformContext], None]] = None
File without changes
@@ -0,0 +1,42 @@
1
+ """註冊表相關的公開型別(介面樁):只承載正式版 ``promptex/registry.py`` 對外
2
+ 匯出的 ``ContentPiece``/``Content``/``Ref``,逐字複製。註冊表本體(``register``
3
+ /``engine``/求值)不在本樁範圍。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+ from typing import Union
10
+
11
+ from .content import MDNode
12
+
13
+ #: 內容欄位可接受的形態:純文字、建構函式結果、引用,或它們的清單。
14
+ ContentPiece = Union[str, MDNode, "Ref"]
15
+ Content = Union[ContentPiece, list[ContentPiece]]
16
+
17
+
18
+ def _ref_reject_message(id_: str, kind: str) -> str:
19
+ return (
20
+ f'Ref "{id_}"({kind})不可插入字串或 f-string:'
21
+ "轉換當下會固定為文字,之後無法解析為產物連結。\n"
22
+ f' 引用以清單元素形態承載:content=["前文", use_resource("{id_}"), "後文"]'
23
+ )
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Ref:
28
+ """宣告函式的回傳值:帶來源資源的類型資訊。同時是引用函式的回傳值,可直接
29
+ 放進另一個節點的 content。
30
+
31
+ 覆寫 ``__str__``/``__format__`` 封住字串轉換:Ref 必須以物件形態保留到
32
+ 投影才能解析為連結,提前轉換會讓引用靜默退化成文字。
33
+ """
34
+
35
+ id: str
36
+ kind: str
37
+
38
+ def __str__(self) -> str: # noqa: D105
39
+ raise TypeError(_ref_reject_message(self.id, self.kind))
40
+
41
+ def __format__(self, format_spec: str) -> str: # noqa: D105
42
+ raise TypeError(_ref_reject_message(self.id, self.kind))
@@ -0,0 +1,78 @@
1
+ """SDK 的單元測試。以 stdlib 的 unittest 承載,不引入測試框架依賴。
2
+
3
+ 執行:``PYTHONPATH=src python3 -m unittest discover -s tests``
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import tempfile
9
+ import unittest
10
+ from pathlib import Path
11
+
12
+ import promptex
13
+ from promptex import build, config, declared_count, define_skill, render_skill, skill_path
14
+
15
+ HEADER = "---\nname: commit-helper\ndescription: 當使用者要求撰寫 commit 訊息時使用\n---\n"
16
+ PARAGRAPHS = [
17
+ "依 Conventional Commits 撰寫:type(scope): subject。",
18
+ "subject 用繁體中文、50 字內,不以句號結尾。",
19
+ ]
20
+
21
+
22
+ class RenderTests(unittest.TestCase):
23
+ def setUp(self) -> None:
24
+ promptex._registry.clear()
25
+
26
+ def test_renders_frontmatter_and_paragraphs(self) -> None:
27
+ define_skill(
28
+ "commit-helper",
29
+ "Commit 訊息協助",
30
+ config=config(when_to_use="當使用者要求撰寫 commit 訊息時使用"),
31
+ content=PARAGRAPHS,
32
+ )
33
+ expected = HEADER + "\n" + "\n\n".join(PARAGRAPHS) + "\n"
34
+ self.assertEqual(render_skill(promptex._registry[0]), expected)
35
+
36
+ def test_renders_frontmatter_only_when_content_is_empty(self) -> None:
37
+ define_skill(
38
+ "commit-helper",
39
+ "Commit 訊息協助",
40
+ config=config(when_to_use="當使用者要求撰寫 commit 訊息時使用"),
41
+ )
42
+ self.assertEqual(render_skill(promptex._registry[0]), HEADER)
43
+
44
+ def test_single_string_content_becomes_one_paragraph(self) -> None:
45
+ define_skill("x", "X", config=config(when_to_use="t"), content="只有一段")
46
+ self.assertEqual(promptex._registry[0].content, ["只有一段"])
47
+
48
+ def test_rejects_ids_that_escape_the_output_directory(self) -> None:
49
+ with self.assertRaisesRegex(ValueError, "skill id 不可為空"):
50
+ define_skill("../escape", "X", config=config(when_to_use="t"), content="c")
51
+
52
+
53
+ class BuildTests(unittest.TestCase):
54
+ def setUp(self) -> None:
55
+ promptex._registry.clear()
56
+
57
+ def test_writes_to_claude_skills_layout_and_drains_registry(self) -> None:
58
+ define_skill(
59
+ "commit-helper",
60
+ "Commit 訊息協助",
61
+ config=config(when_to_use="當使用者要求撰寫 commit 訊息時使用"),
62
+ content=PARAGRAPHS,
63
+ )
64
+ self.assertEqual(declared_count(), 1)
65
+
66
+ with tempfile.TemporaryDirectory() as tmp:
67
+ written = build(tmp)
68
+ self.assertEqual(written, [skill_path(tmp, "commit-helper")])
69
+ self.assertEqual(
70
+ Path(written[0]).read_text(encoding="utf-8"),
71
+ HEADER + "\n" + "\n\n".join(PARAGRAPHS) + "\n",
72
+ )
73
+ self.assertEqual(declared_count(), 0)
74
+ self.assertEqual(build(tmp), [])
75
+
76
+
77
+ if __name__ == "__main__":
78
+ unittest.main()