artest-cro 0.2.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the 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 the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.4
2
+ Name: artest-cro
3
+ Version: 0.2.0
4
+ Summary: Artest: the autonomous CRO agent. Command line and web API.
5
+ License-Expression: Apache-2.0 AND MIT AND 0BSD
6
+ License-File: LICENSE
7
+ Requires-Dist: anyio>=4.9
8
+ Requires-Dist: artest-core==0.2.0
9
+ Requires-Dist: artest-engine==0.2.0
10
+ Requires-Dist: fastapi>=0.162
11
+ Requires-Dist: httpx>=0.28
12
+ Requires-Dist: mcp>=2.3,<3
13
+ Requires-Dist: python-dotenv>=1.1
14
+ Requires-Dist: typer>=0.20
15
+ Requires-Dist: uvicorn>=0.38
16
+ Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.45 ; extra == 'observability'
17
+ Requires-Dist: opentelemetry-sdk>=1.45 ; extra == 'observability'
18
+ Requires-Python: >=3.12
19
+ Project-URL: Repository, https://gitlab.com/Arta_Shoja/artest
20
+ Provides-Extra: observability
21
+ Description-Content-Type: text/markdown
22
+
23
+ # artest-cro
24
+
25
+ Artest: the autonomous CRO agent. Command line, web API and MCP server.
26
+
27
+ Three thin adapters over the same engine services: the `artest` command line (`artest.cli`), the
28
+ FastAPI web API and live event stream (`artest.server`), and the MCP server (`artest.mcp`), which reads kept
29
+ runs for any MCP client over stdio and starts audits only at the exact addresses named when it starts.
30
+
31
+ Import as `artest.cli`, `artest.server`, `artest.mcp`. See the [decision record](https://gitlab.com/Arta_Shoja/artest/-/blob/main/docs/adr/0001-repository-layout.md).
@@ -0,0 +1,9 @@
1
+ # artest-cro
2
+
3
+ Artest: the autonomous CRO agent. Command line, web API and MCP server.
4
+
5
+ Three thin adapters over the same engine services: the `artest` command line (`artest.cli`), the
6
+ FastAPI web API and live event stream (`artest.server`), and the MCP server (`artest.mcp`), which reads kept
7
+ runs for any MCP client over stdio and starts audits only at the exact addresses named when it starts.
8
+
9
+ Import as `artest.cli`, `artest.server`, `artest.mcp`. See the [decision record](https://gitlab.com/Arta_Shoja/artest/-/blob/main/docs/adr/0001-repository-layout.md).
@@ -0,0 +1,48 @@
1
+ [project]
2
+ name = "artest-cro"
3
+ version = "0.2.0"
4
+ description = "Artest: the autonomous CRO agent. Command line and web API."
5
+ readme = "README.md"
6
+ license = "Apache-2.0 AND MIT AND 0BSD"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.12"
9
+ dependencies = [
10
+ "anyio>=4.9",
11
+ "artest-core==0.2.0",
12
+ "artest-engine==0.2.0",
13
+ "fastapi>=0.162",
14
+ "httpx>=0.28",
15
+ "mcp>=2.3,<3",
16
+ "python-dotenv>=1.1",
17
+ "typer>=0.20",
18
+ "uvicorn>=0.38",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ observability = [
23
+ "opentelemetry-exporter-otlp-proto-http>=1.45",
24
+ "opentelemetry-sdk>=1.45",
25
+ ]
26
+
27
+ [project.scripts]
28
+ artest = "artest.cli.main:app"
29
+
30
+ [project.urls]
31
+ Repository = "https://gitlab.com/Arta_Shoja/artest"
32
+
33
+ [build-system]
34
+ requires = ["uv_build>=0.13,<0.14"]
35
+ build-backend = "uv_build"
36
+
37
+ [tool.uv.build-backend]
38
+ module-name = [
39
+ "artest.cli",
40
+ "artest.server",
41
+ "artest.mcp",
42
+ ]
43
+
44
+ [tool.uv.sources.artest-engine]
45
+ workspace = true
46
+
47
+ [tool.uv.sources.artest-core]
48
+ workspace = true
@@ -0,0 +1,43 @@
1
+ [project]
2
+ name = "artest-cro"
3
+ version = "0.2.0"
4
+ description = "Artest: the autonomous CRO agent. Command line and web API."
5
+ readme = "README.md"
6
+ # The wheel carries the web app, which bundles its dependencies: their licences are in its third-party-licenses.md.
7
+ license = "Apache-2.0 AND MIT AND 0BSD"
8
+ license-files = ["LICENSE"]
9
+ requires-python = ">=3.12"
10
+ dependencies = [
11
+ "anyio>=4.9",
12
+ "artest-core==0.2.0",
13
+ "artest-engine==0.2.0",
14
+ "fastapi>=0.162",
15
+ "httpx>=0.28",
16
+ "mcp>=2.3,<3",
17
+ "python-dotenv>=1.1",
18
+ "typer>=0.20",
19
+ "uvicorn>=0.38",
20
+ ]
21
+
22
+ [project.optional-dependencies]
23
+ observability = [
24
+ "opentelemetry-exporter-otlp-proto-http>=1.45",
25
+ "opentelemetry-sdk>=1.45",
26
+ ]
27
+
28
+ [project.scripts]
29
+ artest = "artest.cli.main:app"
30
+
31
+ [project.urls]
32
+ Repository = "https://gitlab.com/Arta_Shoja/artest"
33
+
34
+ [build-system]
35
+ requires = ["uv_build>=0.13,<0.14"]
36
+ build-backend = "uv_build"
37
+
38
+ [tool.uv.build-backend]
39
+ module-name = ["artest.cli", "artest.server", "artest.mcp"]
40
+
41
+ [tool.uv.sources]
42
+ artest-engine = { workspace = true }
43
+ artest-core = { workspace = true }
@@ -0,0 +1 @@
1
+ """Artest command line: run an audit, serve the app, export reports."""
@@ -0,0 +1,286 @@
1
+ """`artest doctor`: checks what the chosen setup needs, and says how to fix what it lacks.
2
+
3
+ It calls no model. It looks for a key but never tries it or shows it, and it asks Ollama only what it has:
4
+ listing a model doesn't load it, and doctor never pulls one. Ollama comes up only for a profile that lists
5
+ a local model (ADR-0023).
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ import tempfile
11
+ from dataclasses import dataclass
12
+ from enum import StrEnum
13
+ from pathlib import Path
14
+ from urllib.parse import urlsplit
15
+
16
+ import httpx
17
+
18
+ from artest.browser.launch import BrowserUnavailableError, chromium_version
19
+ from artest.cli.env import hidden_key, in_checkout, in_compose, key_source, no_key, without_a_key
20
+ from artest.engine.agents import AGENTS
21
+ from artest.engine.config import MissingKeyError, Settings, SettingsError, data_dir
22
+ from artest.llm import ANY_TERMS, CacheMode, Profile, longest_context, ollama_version, pulled_models, route
23
+
24
+ _TIMEOUT = 5
25
+ _GB = 2**30
26
+ _EVERYTHING_ELSE = 10 * _GB
27
+ """What runs beside the local models in a full demo (ADR-0009): browser, server, Docker VM, the system."""
28
+ _THIS_MACHINE = {"localhost", "127.0.0.1", "::1"}
29
+ _SHOP_EXPORT = Path("apps/shop/out/v1/index.html")
30
+ _SHOP_IN_COMPOSE = "http://localhost:3100/v1/"
31
+
32
+
33
+ class Status(StrEnum):
34
+ OK = "ok"
35
+ WARN = "warn"
36
+ """Worth knowing, but a run can go ahead."""
37
+ FAIL = "fail"
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Check:
42
+ name: str
43
+ status: Status
44
+ detail: str
45
+ fix: str | None = None
46
+
47
+
48
+ def unserved(profile: Profile) -> list[str]:
49
+ """The agents ``profile`` has no model for, which a run with it leaves out."""
50
+ return [
51
+ agent.name
52
+ for agent in AGENTS
53
+ if route(profile, agent.needs, purpose=agent.name, policy=ANY_TERMS).model is None
54
+ ]
55
+
56
+
57
+ async def examine(*, model: str | None = None, profile: str | None = None) -> list[Check]:
58
+ """Every check the setup calls for, with the model or routing profile the command line gives. Settings
59
+ that can't be read don't stop the checks that don't depend on them."""
60
+ checks: list[Check] = []
61
+ try:
62
+ settings = Settings.from_env(os.environ, model=model, profile=profile)
63
+ except SettingsError as error:
64
+ checks.append(Check("settings", Status.FAIL, str(error), _settings_fix()))
65
+ else:
66
+ checks += _models(settings)
67
+ checks += await _ollama(settings)
68
+ checks += [await _browser(), _data(data_dir(os.environ))]
69
+ if (shop := await _shop()) is not None:
70
+ checks.append(shop)
71
+ return checks
72
+
73
+
74
+ def _client(base_url: str) -> httpx.AsyncClient:
75
+ return httpx.AsyncClient(base_url=base_url, timeout=_TIMEOUT)
76
+
77
+
78
+ def _settings_fix() -> str:
79
+ if in_compose():
80
+ return (
81
+ "Correct it in .env (see .env.example) or in your shell, then start the container again: "
82
+ "docker compose up -d"
83
+ )
84
+ example = " (see .env.example)" if in_checkout() else ""
85
+ return f"Correct it on the command line, in .env{example} or in your shell"
86
+
87
+
88
+ def _models(settings: Settings) -> list[Check]:
89
+ profile = settings.profile
90
+ if profile is None:
91
+ return [Check("models", Status.OK, "none: a run explores, models the funnel and runs the rules")]
92
+ listed = ", ".join(profile.listed)
93
+ named = listed if profile.single is not None else f"{profile.name}: {listed}"
94
+ if settings.llm_mode is CacheMode.REPLAY:
95
+ return [Check("models", Status.OK, f"{named}, in replay mode: every answer comes from the cache")]
96
+ checks = [Check("models", Status.OK, named)]
97
+ if left_out := unserved(profile):
98
+ reason = f"{', '.join(left_out)} won't run: no model in {profile.name} can do their work"
99
+ checks.append(Check("agents", Status.WARN, reason, "List a model that can in the profile"))
100
+ try:
101
+ settings.check()
102
+ except MissingKeyError as error:
103
+ need, _, fix = no_key(error).partition(": ")
104
+ checks.append(Check("key", Status.FAIL, need, fix if hidden_key() else f"{fix}. {without_a_key()}"))
105
+ except SettingsError as error:
106
+ checks.append(Check("models", Status.FAIL, str(error), _settings_fix()))
107
+ else:
108
+ if "anthropic" in profile.providers:
109
+ found = (
110
+ f"ANTHROPIC_API_KEY is set, from {key_source()}. Only a live run can show Anthropic takes it"
111
+ )
112
+ checks.append(Check("key", Status.OK, found))
113
+ return checks
114
+
115
+
116
+ async def _ollama(settings: Settings) -> list[Check]:
117
+ profile = settings.profile
118
+ if profile is None or settings.llm_mode is CacheMode.REPLAY or "ollama" not in profile.providers:
119
+ return []
120
+ wanted = {
121
+ _tagged(spec.model): spec.context_window
122
+ for spec in map(profile.spec, profile.listed)
123
+ if spec.provider == "ollama"
124
+ }
125
+ where = _address(settings.ollama_url)
126
+ if where is None:
127
+ return [Check("ollama", Status.FAIL, "OLLAMA_HOST isn't a URL", _not_a_url_fix())]
128
+ try:
129
+ async with _client(settings.ollama_url) as client:
130
+ version = await ollama_version(client)
131
+ pulled = await pulled_models(client)
132
+ contexts = {name: await _longest(client, name) for name in wanted if name in pulled}
133
+ except (httpx.HTTPError, httpx.InvalidURL, ValueError, KeyError, TypeError):
134
+ return [Check("ollama", Status.FAIL, f"no Ollama answers at {where}", _ollama_fix())]
135
+ checks = [Check("ollama", Status.OK, f"Ollama {version} at {where}")]
136
+ if missing := [name for name in wanted if name not in pulled]:
137
+ pull = "; ".join(f"ollama pull {name}" for name in missing)
138
+ checks.append(Check("pulled", Status.FAIL, f"Ollama doesn't have {', '.join(missing)}", pull))
139
+ checks += [_context(name, wanted[name], longest) for name, longest in contexts.items()]
140
+ sizes = {name: pulled[name] for name in contexts}
141
+ if sizes:
142
+ checks.append(_memory(settings.ollama_url, sizes))
143
+ return checks
144
+
145
+
146
+ def _tagged(model: str) -> str:
147
+ """``model`` as Ollama lists it: with no tag, it means the one called latest."""
148
+ return model if ":" in model else f"{model}:latest"
149
+
150
+
151
+ def _address(url: str) -> str | None:
152
+ """Where ``url`` points, from its scheme, host and port alone, as a login or a token shouldn't reach a
153
+ screen or a log. None when it has no host, as in Ollama's own form of the setting, ``127.0.0.1:11434``."""
154
+ try:
155
+ parsed = httpx.URL(url)
156
+ except httpx.InvalidURL:
157
+ return None
158
+ if parsed.scheme not in {"http", "https"} or not parsed.host:
159
+ return None
160
+ return str(httpx.URL(scheme=parsed.scheme, host=parsed.host, port=parsed.port))
161
+
162
+
163
+ def _not_a_url_fix() -> str:
164
+ name = "ARTEST_DOCKER_OLLAMA_HOST" if in_compose() else "OLLAMA_HOST"
165
+ return f"Set {name} in .env or your shell to a URL, such as http://localhost:11434"
166
+
167
+
168
+ async def _longest(client: httpx.AsyncClient, model: str) -> int | None:
169
+ """The longest context ``model`` takes, or None if Ollama can't say: it answered about the rest."""
170
+ try:
171
+ return await longest_context(client, model)
172
+ except (httpx.HTTPError, ValueError):
173
+ return None
174
+
175
+
176
+ def _ollama_fix() -> str:
177
+ if in_compose():
178
+ return (
179
+ "Start Ollama on the machine that runs Docker. On Linux, also make it listen beyond localhost: "
180
+ "OLLAMA_HOST=0.0.0.0 ollama serve. ARTEST_DOCKER_OLLAMA_HOST in .env points the container "
181
+ "at another server"
182
+ )
183
+ return "Start Ollama (the app, or ollama serve), or set OLLAMA_HOST in .env or your shell to its URL"
184
+
185
+
186
+ def _context(model: str, asks: int, longest: int | None) -> Check:
187
+ if longest is None:
188
+ return Check(
189
+ "context",
190
+ Status.WARN,
191
+ f"Ollama doesn't say how long a context {model} takes; Artest asks for {asks} tokens",
192
+ )
193
+ if longest < asks:
194
+ return Check(
195
+ "context",
196
+ Status.FAIL,
197
+ f"{model} takes {longest} tokens and Artest asks for {asks}, so prompts would lose their start",
198
+ "Use a model with a longer context",
199
+ )
200
+ return Check("context", Status.OK, f"{model} takes {longest} tokens; Artest asks for {asks} on each call")
201
+
202
+
203
+ def _memory(url: str, sizes: dict[str, int]) -> Check:
204
+ needed = sum(sizes.values())
205
+ models = f"{', '.join(sizes)} ({_in_gb(needed)})"
206
+ if (urlsplit(url).hostname or "") not in _THIS_MACHINE:
207
+ return Check(
208
+ "memory",
209
+ Status.WARN,
210
+ f"Ollama runs outside what doctor can see, so check there's room for {models}",
211
+ )
212
+ total = _physical_memory()
213
+ spare = total - needed - _EVERYTHING_ELSE
214
+ used = f"{models} and about {_in_gb(_EVERYTHING_ELSE)} for the rest of a run"
215
+ if spare < 0:
216
+ return Check(
217
+ "memory",
218
+ Status.WARN,
219
+ f"{used} are more than this machine's {_in_gb(total)}, so it may swap",
220
+ "Close what else is running, or use a smaller model",
221
+ )
222
+ return Check("memory", Status.OK, f"{used} leave {_in_gb(spare)} of {_in_gb(total)}")
223
+
224
+
225
+ def _in_gb(size: int) -> str:
226
+ return f"{size / _GB:.1f} GB"
227
+
228
+
229
+ def _physical_memory() -> int:
230
+ return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
231
+
232
+
233
+ async def _browser() -> Check:
234
+ try:
235
+ version = await chromium_version()
236
+ except BrowserUnavailableError as error:
237
+ playwright = "uv run playwright" if in_checkout() else f"{sys.executable} -m playwright"
238
+ fix = (
239
+ "Build the image again: docker compose up -d --build"
240
+ if in_compose()
241
+ else f"{playwright} install chromium; on Linux, add --with-deps"
242
+ )
243
+ return Check("browser", Status.FAIL, str(error), fix)
244
+ return Check("browser", Status.OK, f"Chromium {version} starts")
245
+
246
+
247
+ def _data(folder: Path) -> Check:
248
+ try:
249
+ folder.mkdir(parents=True, exist_ok=True)
250
+ with tempfile.TemporaryFile(dir=folder):
251
+ pass
252
+ except OSError as error:
253
+ fix = (
254
+ "If the disk isn't full, the artest-data volume doesn't belong to the image's user: "
255
+ "docker compose down -v makes a new one, and deletes the runs in this one"
256
+ if in_compose()
257
+ else "Set ARTEST_DATA_DIR in .env to a folder you can write to, or change this one's permissions"
258
+ )
259
+ return Check("data", Status.FAIL, f"can't write runs to {folder}: {error.strerror}", fix)
260
+ return Check("data", Status.OK, f"runs go to {folder}")
261
+
262
+
263
+ async def _shop() -> Check | None:
264
+ """Whether the demo shop is there to audit. Auditing a shop of your own doesn't need it, so it only
265
+ warns."""
266
+ return await _shop_in_compose() if in_compose() else _shop_in_checkout()
267
+
268
+
269
+ async def _shop_in_compose() -> Check:
270
+ try:
271
+ async with _client(_SHOP_IN_COMPOSE) as client:
272
+ (await client.get(_SHOP_IN_COMPOSE)).raise_for_status()
273
+ except httpx.HTTPError:
274
+ answers = f"the demo shop doesn't answer at {_SHOP_IN_COMPOSE}"
275
+ restart = "docker compose restart shop. A one-off docker compose run can't see the shop: use exec"
276
+ return Check("shop", Status.WARN, answers, restart)
277
+ return Check("shop", Status.OK, f"the demo shop answers at {_SHOP_IN_COMPOSE}")
278
+
279
+
280
+ def _shop_in_checkout() -> Check | None:
281
+ """Outside a checkout, there is no demo shop to look for."""
282
+ if not _SHOP_EXPORT.parents[2].is_dir():
283
+ return None
284
+ if not _SHOP_EXPORT.exists():
285
+ return Check("shop", Status.WARN, "the demo shop isn't built", "pnpm --filter @artest/shop build")
286
+ return Check("shop", Status.OK, f"the demo shop is built, in {_SHOP_EXPORT.parents[1]}")