dmint-cli 0.1.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,176 @@
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
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: dmint-cli
3
+ Version: 0.1.0
4
+ Summary: CLI tooling for Dmint policy creation, compilation, and management
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: dmint<0.2.0,>=0.1.0
10
+ Requires-Dist: dmint-skills<0.2.0,>=0.1.0
11
+ Dynamic: license-file
12
+
13
+ # dmint-cli
14
+
15
+ > **Developer tooling for creating, compiling, and validating Dmint security policies.**
16
+
17
+ `dmint-cli` provides command-line utilities for discovering tools via AST analysis, gathering security requirements, and compiling natural language security rules into schema-compliant Dmint policy files (`policy.json`).
18
+
19
+ ```text
20
+ access.md (Human Security Intent)
21
+ ↓
22
+ dmint compile-policy / create-policy
23
+ ↓
24
+ LLM Compiler & Dmint Skill
25
+ ↓
26
+ Dmint Core Validation (Policy.from_mapping)
27
+ ↓
28
+ policy.json (Authoritative Policy)
29
+ ```
30
+
31
+ > **Note:** The CLI helps developers *author* and *validate* policies during development. `dmint` core remains the sole trusted runtime authorization engine.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ pip install dmint-cli
37
+ ```
38
+
39
+ ## CLI Commands
40
+
41
+ ### 1. Interactive Policy Wizard (`dmint create-policy`)
42
+
43
+ Inspect Python source code for tool declarations using AST analysis (zero execution), prompt the developer for security rules, and generate `access.md` + verified `policy.json`.
44
+
45
+ ```bash
46
+ dmint create-policy --tools my_tools.py -f access.md -o policy.json
47
+ ```
48
+
49
+ ### 2. Policy Compiler (`dmint compile-policy`)
50
+
51
+ Compile natural language security requirements into a strictly validated `policy.json` file using an OpenAI-compatible API or local fallback parser.
52
+
53
+ ```bash
54
+ dmint compile-policy -f access.md -o policy.json
55
+ ```
56
+
57
+ ## Environment Configuration
58
+
59
+ Set API credentials via environment variables for LLM policy compilation:
60
+
61
+ ```bash
62
+ export OPENAI_API_KEY="sk-..."
63
+ # Optional custom provider / base URL
64
+ export DMINT_BASE_URL="https://api.openai.com/v1"
65
+ export DMINT_MODEL="gpt-4o-mini"
66
+ ```
67
+
68
+ ## Testing
69
+
70
+ Run the CLI test suite:
71
+
72
+ ```bash
73
+ pytest -v
74
+ ```
75
+
76
+ ## License
77
+
78
+ Licensed under the [Apache License, Version 2.0](LICENSE).
79
+ See the [`LICENSE`](LICENSE) file for the complete license text.
@@ -0,0 +1,67 @@
1
+ # dmint-cli
2
+
3
+ > **Developer tooling for creating, compiling, and validating Dmint security policies.**
4
+
5
+ `dmint-cli` provides command-line utilities for discovering tools via AST analysis, gathering security requirements, and compiling natural language security rules into schema-compliant Dmint policy files (`policy.json`).
6
+
7
+ ```text
8
+ access.md (Human Security Intent)
9
+ ↓
10
+ dmint compile-policy / create-policy
11
+ ↓
12
+ LLM Compiler & Dmint Skill
13
+ ↓
14
+ Dmint Core Validation (Policy.from_mapping)
15
+ ↓
16
+ policy.json (Authoritative Policy)
17
+ ```
18
+
19
+ > **Note:** The CLI helps developers *author* and *validate* policies during development. `dmint` core remains the sole trusted runtime authorization engine.
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ pip install dmint-cli
25
+ ```
26
+
27
+ ## CLI Commands
28
+
29
+ ### 1. Interactive Policy Wizard (`dmint create-policy`)
30
+
31
+ Inspect Python source code for tool declarations using AST analysis (zero execution), prompt the developer for security rules, and generate `access.md` + verified `policy.json`.
32
+
33
+ ```bash
34
+ dmint create-policy --tools my_tools.py -f access.md -o policy.json
35
+ ```
36
+
37
+ ### 2. Policy Compiler (`dmint compile-policy`)
38
+
39
+ Compile natural language security requirements into a strictly validated `policy.json` file using an OpenAI-compatible API or local fallback parser.
40
+
41
+ ```bash
42
+ dmint compile-policy -f access.md -o policy.json
43
+ ```
44
+
45
+ ## Environment Configuration
46
+
47
+ Set API credentials via environment variables for LLM policy compilation:
48
+
49
+ ```bash
50
+ export OPENAI_API_KEY="sk-..."
51
+ # Optional custom provider / base URL
52
+ export DMINT_BASE_URL="https://api.openai.com/v1"
53
+ export DMINT_MODEL="gpt-4o-mini"
54
+ ```
55
+
56
+ ## Testing
57
+
58
+ Run the CLI test suite:
59
+
60
+ ```bash
61
+ pytest -v
62
+ ```
63
+
64
+ ## License
65
+
66
+ Licensed under the [Apache License, Version 2.0](LICENSE).
67
+ See the [`LICENSE`](LICENSE) file for the complete license text.
@@ -0,0 +1,21 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "dmint-cli"
7
+ version = "0.1.0"
8
+ description = "CLI tooling for Dmint policy creation, compilation, and management"
9
+ license = "Apache-2.0"
10
+ requires-python = ">=3.10"
11
+ readme = "README.md"
12
+ dependencies = [
13
+ "dmint>=0.1.0,<0.2.0",
14
+ "dmint-skills>=0.1.0,<0.2.0",
15
+ ]
16
+
17
+ [project.scripts]
18
+ dmint = "dmint_cli.__main__:main"
19
+
20
+ [tool.setuptools.packages.find]
21
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,14 @@
1
+ """Dmint CLI package."""
2
+
3
+ from .api import OpenAICompatClient, mask_secret
4
+ from .compile_policy import compile_policy_file, main_compile
5
+ from .create_policy import main_create, run_create_policy_wizard
6
+
7
+ __all__ = [
8
+ "OpenAICompatClient",
9
+ "compile_policy_file",
10
+ "main_compile",
11
+ "main_create",
12
+ "mask_secret",
13
+ "run_create_policy_wizard",
14
+ ]
@@ -0,0 +1,66 @@
1
+ """Entry point for dmint CLI command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from dmint_cli.compile_policy import main_compile
9
+ from dmint_cli.create_policy import main_create
10
+
11
+
12
+ def main(args: list[str] | None = None) -> int:
13
+ if args is None:
14
+ args = sys.argv[1:]
15
+
16
+ # Normalize subcommands like "create policy" -> "create-policy" and "compile policy" -> "compile-policy"
17
+ normalized_args: list[str] = []
18
+ i = 0
19
+ while i < len(args):
20
+ arg = args[i]
21
+ if arg == "create" and i + 1 < len(args) and args[i + 1] == "policy":
22
+ normalized_args.append("create-policy")
23
+ i += 2
24
+ continue
25
+ if arg == "compile" and i + 1 < len(args) and args[i + 1] == "policy":
26
+ normalized_args.append("compile-policy")
27
+ i += 2
28
+ continue
29
+ normalized_args.append(arg)
30
+ i += 1
31
+
32
+ parser = argparse.ArgumentParser(
33
+ prog="dmint",
34
+ description="Dmint deterministic security enforcement & policy authoring CLI.",
35
+ )
36
+ subparsers = parser.add_subparsers(dest="command", help="Command to run")
37
+
38
+ subparsers.add_parser(
39
+ "compile-policy",
40
+ help="Compile natural language policy requirements into a validated policy.json file",
41
+ add_help=False,
42
+ )
43
+ subparsers.add_parser(
44
+ "create-policy",
45
+ help="Interactive wizard to discover tools, ask security questions, and create policy files",
46
+ add_help=False,
47
+ )
48
+
49
+ if not normalized_args or normalized_args[0] in ("-h", "--help"):
50
+ parser.print_help()
51
+ return 0
52
+
53
+ cmd = normalized_args[0]
54
+ cmd_args = normalized_args[1:]
55
+
56
+ if cmd == "compile-policy":
57
+ return main_compile(cmd_args)
58
+ elif cmd == "create-policy":
59
+ return main_create(cmd_args)
60
+ else:
61
+ parser.print_help()
62
+ return 2
63
+
64
+
65
+ if __name__ == "__main__":
66
+ sys.exit(main())
@@ -0,0 +1,172 @@
1
+ """Minimal OpenAI-compatible HTTP API client using Python standard library only.
2
+
3
+ Supports OpenAI, Groq, DeepSeek, Together, Ollama, LM Studio, and Google Gemini
4
+ via OpenAI-compatible /v1/chat/completions endpoints.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import re
12
+ import urllib.error
13
+ import urllib.request
14
+ from typing import Any, Mapping
15
+
16
+ DEFAULT_BASE_URL = "https://api.openai.com/v1"
17
+ DEFAULT_MODEL = "gpt-4o-mini"
18
+ GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai"
19
+
20
+
21
+ def mask_secret(secret: str | None) -> str:
22
+ """Return a safely redacted representation of a secret string."""
23
+ if not secret:
24
+ return "<none>"
25
+ if len(secret) <= 8:
26
+ return "***"
27
+ return f"{secret[:3]}...{secret[-4:]}"
28
+
29
+
30
+ def resolve_base_url(base_url: str | None = None, provider: str | None = None) -> str:
31
+ """Resolve the target base URL for OpenAI-compatible completions API."""
32
+ if provider:
33
+ prov = provider.lower().strip()
34
+ if prov in {"gemini", "google"}:
35
+ return GEMINI_BASE_URL
36
+ if prov == "groq":
37
+ return "https://api.groq.com/openai/v1"
38
+ if prov == "openrouter":
39
+ return "https://openrouter.ai/api/v1"
40
+ if prov == "ollama":
41
+ return "http://localhost:11434/v1"
42
+
43
+ if base_url:
44
+ url = base_url.strip().rstrip("/")
45
+ if url.endswith("/chat/completions"):
46
+ return url[:-len("/chat/completions")]
47
+ return url
48
+
49
+ return DEFAULT_BASE_URL
50
+
51
+
52
+ def resolve_api_key(api_key: str | None = None, provider: str | None = None) -> str | None:
53
+ """Resolve API key from parameter or standard environment variables."""
54
+ if api_key and api_key.strip():
55
+ return api_key.strip()
56
+
57
+ prov = (provider or "").lower().strip()
58
+ if prov in {"gemini", "google"}:
59
+ env_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("OPENAI_API_KEY")
60
+ if env_key:
61
+ return env_key.strip()
62
+ elif prov == "groq":
63
+ env_key = os.environ.get("GROQ_API_KEY") or os.environ.get("OPENAI_API_KEY")
64
+ if env_key:
65
+ return env_key.strip()
66
+
67
+ # Fallback to OPENAI_API_KEY
68
+ env_openai = os.environ.get("OPENAI_API_KEY")
69
+ if env_openai:
70
+ return env_openai.strip()
71
+
72
+ return None
73
+
74
+
75
+ class OpenAICompatClient:
76
+ """Standard-library HTTP client targeting OpenAI-compatible /chat/completions endpoints."""
77
+
78
+ def __init__(
79
+ self,
80
+ *,
81
+ base_url: str | None = None,
82
+ api_key: str | None = None,
83
+ model: str | None = None,
84
+ provider: str | None = None,
85
+ timeout: float = 60.0,
86
+ ) -> None:
87
+ self.base_url = resolve_base_url(base_url, provider)
88
+ self.api_key = resolve_api_key(api_key, provider)
89
+ self.model = model or DEFAULT_MODEL
90
+ self.timeout = timeout
91
+
92
+ def chat_completion(
93
+ self,
94
+ messages: list[Mapping[str, Any]],
95
+ *,
96
+ temperature: float = 0.0,
97
+ response_format: Mapping[str, Any] | None = None,
98
+ ) -> str:
99
+ """Send a chat completion request and return the assistant response content string."""
100
+ endpoint = f"{self.base_url}/chat/completions"
101
+ payload: dict[str, Any] = {
102
+ "model": self.model,
103
+ "messages": messages,
104
+ "temperature": temperature,
105
+ }
106
+ if response_format:
107
+ payload["response_format"] = response_format
108
+
109
+ data = json.dumps(payload).encode("utf-8")
110
+ headers = {
111
+ "Content-Type": "application/json",
112
+ "User-Agent": "dmint-policy-author/0.1.0",
113
+ }
114
+ if self.api_key:
115
+ headers["Authorization"] = f"Bearer {self.api_key}"
116
+
117
+ req = urllib.request.Request(
118
+ endpoint,
119
+ data=data,
120
+ headers=headers,
121
+ method="POST",
122
+ )
123
+
124
+ try:
125
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
126
+ resp_bytes = resp.read()
127
+ try:
128
+ resp_data = json.loads(resp_bytes.decode("utf-8"))
129
+ except Exception as exc:
130
+ raise RuntimeError("API response is not valid JSON") from exc
131
+ except urllib.error.HTTPError as exc:
132
+ try:
133
+ error_body = exc.read().decode("utf-8", errors="ignore")
134
+ error_json = json.loads(error_body)
135
+ msg = error_json.get("error", {}).get("message", error_body)
136
+ except Exception:
137
+ msg = f"HTTP Error {exc.code}"
138
+ # Never leak key in exception
139
+ masked_key = mask_secret(self.api_key)
140
+ raise RuntimeError(f"OpenAI-compatible API HTTP {exc.code}: {msg} (key: {masked_key})") from exc
141
+ except urllib.error.URLError as exc:
142
+ raise RuntimeError(f"API connection failed ({self.base_url}): {exc.reason}") from exc
143
+ except Exception as exc:
144
+ raise RuntimeError(f"API request failed: {exc}") from exc
145
+
146
+ choices = resp_data.get("choices")
147
+ if not choices or not isinstance(choices, list):
148
+ raise RuntimeError("API response missing 'choices' array")
149
+
150
+ message = choices[0].get("message", {})
151
+ content = message.get("content")
152
+ if content is None:
153
+ content = ""
154
+
155
+ return extract_json_text(content)
156
+
157
+
158
+ def extract_json_text(text: str) -> str:
159
+ """Extract clean JSON text, removing markdown code fences if present."""
160
+ text = text.strip()
161
+ if text.startswith("```"):
162
+ # Match ```json ... ``` or ``` ... ```
163
+ match = re.search(r"```(?:json)?\s*(.*?)\s*```", text, re.DOTALL | re.IGNORECASE)
164
+ if match:
165
+ return match.group(1).strip()
166
+ lines = text.splitlines()
167
+ if lines[0].startswith("```"):
168
+ lines = lines[1:]
169
+ if lines and lines[-1].startswith("```"):
170
+ lines = lines[:-1]
171
+ return "\n".join(lines).strip()
172
+ return text