jev-cli 0.7.0__tar.gz → 0.8.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.
- {jev_cli-0.7.0 → jev_cli-0.8.0}/PKG-INFO +41 -3
- {jev_cli-0.7.0 → jev_cli-0.8.0}/README.md +40 -2
- {jev_cli-0.7.0 → jev_cli-0.8.0}/pyproject.toml +1 -1
- {jev_cli-0.7.0 → jev_cli-0.8.0}/src/jev_cli/__init__.py +181 -18
- {jev_cli-0.7.0 → jev_cli-0.8.0}/src/jev_cli/mcp_server.py +8 -5
- {jev_cli-0.7.0 → jev_cli-0.8.0}/tests/test_jev.py +318 -4
- {jev_cli-0.7.0 → jev_cli-0.8.0}/tests/test_mcp_server.py +65 -1
- {jev_cli-0.7.0 → jev_cli-0.8.0}/LICENSE +0 -0
- {jev_cli-0.7.0 → jev_cli-0.8.0}/scripts/embed_skills.py +0 -0
- {jev_cli-0.7.0 → jev_cli-0.8.0}/skills/jev-cli/SKILL.md +0 -0
- {jev_cli-0.7.0 → jev_cli-0.8.0}/skills/jev-cli/references/cli.md +0 -0
- {jev_cli-0.7.0 → jev_cli-0.8.0}/src/jev_cli/bundled_skills/jev-cli/SKILL.md +0 -0
- {jev_cli-0.7.0 → jev_cli-0.8.0}/src/jev_cli/bundled_skills/jev-cli/references/cli.md +0 -0
- {jev_cli-0.7.0 → jev_cli-0.8.0}/src/jev_cli/py.typed +0 -0
- {jev_cli-0.7.0 → jev_cli-0.8.0}/tests/test_skill.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: jev-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.8.0
|
|
4
4
|
Summary: Small CLI and stdio MCP server for TypeSafe Jev
|
|
5
5
|
Keywords: typesafe,jev,cli,mcp,ai
|
|
6
6
|
License-Expression: MIT
|
|
@@ -73,7 +73,7 @@ jev --version
|
|
|
73
73
|
Expected output:
|
|
74
74
|
|
|
75
75
|
```text
|
|
76
|
-
jev 0.
|
|
76
|
+
jev 0.8.0
|
|
77
77
|
```
|
|
78
78
|
|
|
79
79
|
## Authentication
|
|
@@ -99,7 +99,7 @@ Jev is also available through Vercel AI Gateway and OpenRouter. Select a provide
|
|
|
99
99
|
|---|---|---|---|
|
|
100
100
|
| TypeSafe official | `official` | `TYPESAFE_API_KEY` | `jev-latest` |
|
|
101
101
|
| Vercel AI Gateway | `vercel` | `AI_GATEWAY_API_KEY` | `typesafe-ai/jev` |
|
|
102
|
-
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | `typesafe/jev-1.
|
|
102
|
+
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | `typesafe/jev-1.14` |
|
|
103
103
|
| Jev-compatible proxy | `custom` | `JEV_API_KEY` | `JEV_MODEL` or `jev-latest` |
|
|
104
104
|
| Cloudflare Workers AI (Clef) | `cloudflare` | `CLOUDFLARE_API_TOKEN` | `clef-flash` |
|
|
105
105
|
|
|
@@ -287,6 +287,44 @@ printf '%s' '{"message":"Please respond today"}' | \
|
|
|
287
287
|
--value
|
|
288
288
|
```
|
|
289
289
|
|
|
290
|
+
### Images
|
|
291
|
+
|
|
292
|
+
`noul`, `choice`, and `score` accept `--image PATH` (`-i`), repeatable, for PNG or JPEG files. With `--image`, the state is optional and stdin is not read unless `--state` is given.
|
|
293
|
+
|
|
294
|
+
```bash
|
|
295
|
+
jev noul \
|
|
296
|
+
--question 'Is `image` a receipt?' \
|
|
297
|
+
--image receipt.png \
|
|
298
|
+
--value
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
Each file is base64-encoded into the request's `assets` map and referenced from the state as `image`, `image_2`, `image_3`, and so on, in the order given. Text state is kept under `text`. The request also carries the `TypeSafe-Danger-Zone-Images: true` header.
|
|
302
|
+
|
|
303
|
+
The following are rejected before any network access:
|
|
304
|
+
|
|
305
|
+
- A JSON state that already contains one of the generated keys (`image`, `image_2`, ...). The CLI never replaces your keys; rename them in the state.
|
|
306
|
+
- A file larger than 16 MiB. At most 16 MiB plus one byte of any path is read.
|
|
307
|
+
- A request whose serialized size, base64 image data included, exceeds 32 MiB. Base64 adds about one third, so several large images can exceed this even when each file is under 16 MiB. The same file given more than once is sent once.
|
|
308
|
+
- Anything other than a still PNG or JPEG, including animated PNG.
|
|
309
|
+
- A side outside 280-1568 px, or a pixel count outside 78,400-2,458,624. Images are never resized.
|
|
310
|
+
- A header-only or obviously truncated file: a PNG must have a leading `IHDR`, non-empty `IDAT`, and a closing `IEND` chunk; a JPEG must have a frame header, a scan with data, and an end-of-image marker.
|
|
311
|
+
|
|
312
|
+
This validation is structural only. The CLI does not decode images: it does not verify PNG checksums, decompress pixel data, or decode JPEG scans, so a corrupt file with intact structure is still sent and the API decides whether it is usable.
|
|
313
|
+
|
|
314
|
+
Provider support for `--image`:
|
|
315
|
+
|
|
316
|
+
| Provider | `--image` |
|
|
317
|
+
|---|---|
|
|
318
|
+
| `official` | Supported. |
|
|
319
|
+
| `custom` | Sent as above; the proxy must implement the native `assets` contract. |
|
|
320
|
+
| `vercel` | Sent as above; not verified by this project. |
|
|
321
|
+
| `openrouter` | Rejected. OpenRouter does not accept this encoding. Use `--provider official`, or build a request that uses OpenRouter Decisions' own `image_url` state parts and send it with `jev run --provider openrouter`. |
|
|
322
|
+
| `cloudflare` | Rejected. Use `jev run` with Clef's `images` field. |
|
|
323
|
+
|
|
324
|
+
`run` sends your request JSON as written and performs none of the image checks above.
|
|
325
|
+
|
|
326
|
+
For requests containing `assets`, HTTP errors report the status but omit the response body, because it may quote private image data or state.
|
|
327
|
+
|
|
290
328
|
## Batch questions
|
|
291
329
|
|
|
292
330
|
Jev evaluates questions independently against the same state. Use `run` to send a complete System One request and avoid one API call per question.
|
|
@@ -54,7 +54,7 @@ jev --version
|
|
|
54
54
|
Expected output:
|
|
55
55
|
|
|
56
56
|
```text
|
|
57
|
-
jev 0.
|
|
57
|
+
jev 0.8.0
|
|
58
58
|
```
|
|
59
59
|
|
|
60
60
|
## Authentication
|
|
@@ -80,7 +80,7 @@ Jev is also available through Vercel AI Gateway and OpenRouter. Select a provide
|
|
|
80
80
|
|---|---|---|---|
|
|
81
81
|
| TypeSafe official | `official` | `TYPESAFE_API_KEY` | `jev-latest` |
|
|
82
82
|
| Vercel AI Gateway | `vercel` | `AI_GATEWAY_API_KEY` | `typesafe-ai/jev` |
|
|
83
|
-
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | `typesafe/jev-1.
|
|
83
|
+
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | `typesafe/jev-1.14` |
|
|
84
84
|
| Jev-compatible proxy | `custom` | `JEV_API_KEY` | `JEV_MODEL` or `jev-latest` |
|
|
85
85
|
| Cloudflare Workers AI (Clef) | `cloudflare` | `CLOUDFLARE_API_TOKEN` | `clef-flash` |
|
|
86
86
|
|
|
@@ -268,6 +268,44 @@ printf '%s' '{"message":"Please respond today"}' | \
|
|
|
268
268
|
--value
|
|
269
269
|
```
|
|
270
270
|
|
|
271
|
+
### Images
|
|
272
|
+
|
|
273
|
+
`noul`, `choice`, and `score` accept `--image PATH` (`-i`), repeatable, for PNG or JPEG files. With `--image`, the state is optional and stdin is not read unless `--state` is given.
|
|
274
|
+
|
|
275
|
+
```bash
|
|
276
|
+
jev noul \
|
|
277
|
+
--question 'Is `image` a receipt?' \
|
|
278
|
+
--image receipt.png \
|
|
279
|
+
--value
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
Each file is base64-encoded into the request's `assets` map and referenced from the state as `image`, `image_2`, `image_3`, and so on, in the order given. Text state is kept under `text`. The request also carries the `TypeSafe-Danger-Zone-Images: true` header.
|
|
283
|
+
|
|
284
|
+
The following are rejected before any network access:
|
|
285
|
+
|
|
286
|
+
- A JSON state that already contains one of the generated keys (`image`, `image_2`, ...). The CLI never replaces your keys; rename them in the state.
|
|
287
|
+
- A file larger than 16 MiB. At most 16 MiB plus one byte of any path is read.
|
|
288
|
+
- A request whose serialized size, base64 image data included, exceeds 32 MiB. Base64 adds about one third, so several large images can exceed this even when each file is under 16 MiB. The same file given more than once is sent once.
|
|
289
|
+
- Anything other than a still PNG or JPEG, including animated PNG.
|
|
290
|
+
- A side outside 280-1568 px, or a pixel count outside 78,400-2,458,624. Images are never resized.
|
|
291
|
+
- A header-only or obviously truncated file: a PNG must have a leading `IHDR`, non-empty `IDAT`, and a closing `IEND` chunk; a JPEG must have a frame header, a scan with data, and an end-of-image marker.
|
|
292
|
+
|
|
293
|
+
This validation is structural only. The CLI does not decode images: it does not verify PNG checksums, decompress pixel data, or decode JPEG scans, so a corrupt file with intact structure is still sent and the API decides whether it is usable.
|
|
294
|
+
|
|
295
|
+
Provider support for `--image`:
|
|
296
|
+
|
|
297
|
+
| Provider | `--image` |
|
|
298
|
+
|---|---|
|
|
299
|
+
| `official` | Supported. |
|
|
300
|
+
| `custom` | Sent as above; the proxy must implement the native `assets` contract. |
|
|
301
|
+
| `vercel` | Sent as above; not verified by this project. |
|
|
302
|
+
| `openrouter` | Rejected. OpenRouter does not accept this encoding. Use `--provider official`, or build a request that uses OpenRouter Decisions' own `image_url` state parts and send it with `jev run --provider openrouter`. |
|
|
303
|
+
| `cloudflare` | Rejected. Use `jev run` with Clef's `images` field. |
|
|
304
|
+
|
|
305
|
+
`run` sends your request JSON as written and performs none of the image checks above.
|
|
306
|
+
|
|
307
|
+
For requests containing `assets`, HTTP errors report the status but omit the response body, because it may quote private image data or state.
|
|
308
|
+
|
|
271
309
|
## Batch questions
|
|
272
310
|
|
|
273
311
|
Jev evaluates questions independently against the same state. Use `run` to send a complete System One request and avoid one API call per question.
|
|
@@ -4,7 +4,9 @@
|
|
|
4
4
|
from __future__ import annotations
|
|
5
5
|
|
|
6
6
|
import argparse
|
|
7
|
+
import base64
|
|
7
8
|
import getpass
|
|
9
|
+
import hashlib
|
|
8
10
|
import json
|
|
9
11
|
import os
|
|
10
12
|
import re
|
|
@@ -30,7 +32,7 @@ PROVIDERS = {
|
|
|
30
32
|
"openrouter": {
|
|
31
33
|
"endpoint": "https://openrouter.ai/api/alpha/decisions",
|
|
32
34
|
"key_env": "OPENROUTER_API_KEY",
|
|
33
|
-
"model": "typesafe/jev-1.
|
|
35
|
+
"model": "typesafe/jev-1.14",
|
|
34
36
|
},
|
|
35
37
|
"custom": {
|
|
36
38
|
"endpoint": None,
|
|
@@ -209,6 +211,144 @@ def state_value(value: str | None, force_json: bool) -> Any:
|
|
|
209
211
|
return text
|
|
210
212
|
|
|
211
213
|
|
|
214
|
+
IMAGE_HEADER = "TypeSafe-Danger-Zone-Images"
|
|
215
|
+
IMAGE_MAX_BYTES = 16 * 1024 * 1024
|
|
216
|
+
IMAGE_SIDE = (280, 1568)
|
|
217
|
+
IMAGE_PIXELS = (78_400, 2_458_624)
|
|
218
|
+
# Native System One limit for the whole serialized request, base64 image data included.
|
|
219
|
+
REQUEST_MAX_BYTES = 32 * 1024 * 1024
|
|
220
|
+
ERROR_BODY_MAX_BYTES = 64 * 1024
|
|
221
|
+
ERROR_DETAIL_MAX_CHARS = 2000
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def image_dimensions(data: bytes) -> tuple[str, int, int]:
|
|
225
|
+
"""Return (format, width, height) for a structurally complete still PNG or JPEG.
|
|
226
|
+
|
|
227
|
+
This is a container check, not a decoder: it walks PNG chunks / JPEG segments so that
|
|
228
|
+
header-only and obviously truncated files are rejected. It does not verify PNG CRCs,
|
|
229
|
+
decompress pixel data, or decode JPEG scans, so a corrupt image can still pass.
|
|
230
|
+
"""
|
|
231
|
+
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
|
232
|
+
position = 8
|
|
233
|
+
size: tuple[int, int] | None = None
|
|
234
|
+
has_pixels = False
|
|
235
|
+
while position + 12 <= len(data):
|
|
236
|
+
length = int.from_bytes(data[position : position + 4], "big")
|
|
237
|
+
kind = data[position + 4 : position + 8]
|
|
238
|
+
end = position + 12 + length # length, type, data and CRC
|
|
239
|
+
if end > len(data):
|
|
240
|
+
break
|
|
241
|
+
if size is None:
|
|
242
|
+
if kind != b"IHDR" or length != 13:
|
|
243
|
+
raise CliError("PNG does not start with an IHDR chunk")
|
|
244
|
+
size = (int.from_bytes(data[16:20], "big"), int.from_bytes(data[20:24], "big"))
|
|
245
|
+
elif kind == b"acTL":
|
|
246
|
+
raise CliError("animated PNG images are not supported")
|
|
247
|
+
elif kind == b"IDAT":
|
|
248
|
+
has_pixels = has_pixels or length > 0
|
|
249
|
+
elif kind == b"IEND":
|
|
250
|
+
if not has_pixels:
|
|
251
|
+
raise CliError("PNG has no image data")
|
|
252
|
+
return "png", size[0], size[1]
|
|
253
|
+
position = end
|
|
254
|
+
raise CliError("PNG is truncated or incomplete")
|
|
255
|
+
if data.startswith(b"\xff\xd8"):
|
|
256
|
+
position = 2
|
|
257
|
+
size = None
|
|
258
|
+
while position + 4 <= len(data):
|
|
259
|
+
if data[position] != 0xFF:
|
|
260
|
+
break
|
|
261
|
+
marker = data[position + 1]
|
|
262
|
+
if marker == 0xFF: # fill byte before a marker
|
|
263
|
+
position += 1
|
|
264
|
+
continue
|
|
265
|
+
if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD7:
|
|
266
|
+
position += 2
|
|
267
|
+
continue
|
|
268
|
+
if marker == 0xD9: # end of image before any scan
|
|
269
|
+
break
|
|
270
|
+
length = int.from_bytes(data[position + 2 : position + 4], "big")
|
|
271
|
+
end = position + 2 + length
|
|
272
|
+
if length < 2 or end > len(data):
|
|
273
|
+
break
|
|
274
|
+
if marker == 0xDA:
|
|
275
|
+
# A scan must follow a frame header, hold entropy data, and be closed by EOI.
|
|
276
|
+
if size is None or data.find(b"\xff\xd9", end + 1) < 0:
|
|
277
|
+
break
|
|
278
|
+
return "jpg", size[0], size[1]
|
|
279
|
+
# SOF markers carry the frame size; C4, C8 and CC share the range but are not frames.
|
|
280
|
+
if size is None and 0xC0 <= marker <= 0xCF and marker not in (0xC4, 0xC8, 0xCC):
|
|
281
|
+
if length < 8:
|
|
282
|
+
break
|
|
283
|
+
height = int.from_bytes(data[position + 5 : position + 7], "big")
|
|
284
|
+
width = int.from_bytes(data[position + 7 : position + 9], "big")
|
|
285
|
+
size = (width, height)
|
|
286
|
+
position = end
|
|
287
|
+
raise CliError("JPEG is truncated or incomplete")
|
|
288
|
+
raise CliError("images must be PNG or JPEG")
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def image_asset(path: str) -> dict[str, Any]:
|
|
292
|
+
"""Read and validate one image; images outside TypeSafe's limits are rejected, never resized."""
|
|
293
|
+
try:
|
|
294
|
+
# Bounded read: never load more than one byte past the limit, whatever the path points at.
|
|
295
|
+
with open(path, "rb") as file:
|
|
296
|
+
data = file.read(IMAGE_MAX_BYTES + 1)
|
|
297
|
+
except OSError as exc:
|
|
298
|
+
raise CliError(f"cannot read image: {exc}") from exc
|
|
299
|
+
if len(data) > IMAGE_MAX_BYTES:
|
|
300
|
+
raise CliError(f"{path}: image is larger than 16 MiB")
|
|
301
|
+
try:
|
|
302
|
+
kind, width, height = image_dimensions(data)
|
|
303
|
+
except CliError as exc:
|
|
304
|
+
raise CliError(f"{path}: {exc}") from exc
|
|
305
|
+
low, high = IMAGE_SIDE
|
|
306
|
+
if not (low <= width <= high and low <= height <= high):
|
|
307
|
+
raise CliError(f"{path}: {width}x{height} is outside {low}-{high} px per side")
|
|
308
|
+
if not IMAGE_PIXELS[0] <= width * height <= IMAGE_PIXELS[1]:
|
|
309
|
+
raise CliError(f"{path}: {width * height} pixels is outside {IMAGE_PIXELS[0]}-{IMAGE_PIXELS[1]}")
|
|
310
|
+
return {"type": "image", "format": kind, "data_base64": base64.b64encode(data).decode()}
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def attach_images(payload: dict[str, Any], paths: list[str]) -> dict[str, Any]:
|
|
314
|
+
"""Put each image in the assets map and reference it from the state as image, image_2, ...
|
|
315
|
+
|
|
316
|
+
Fails before any network access when a generated state key would replace a caller-supplied
|
|
317
|
+
one, or when the serialized request would exceed the native request size limit.
|
|
318
|
+
"""
|
|
319
|
+
state = payload["state"]
|
|
320
|
+
names = ["image" if index == 1 else f"image_{index}" for index in range(1, len(paths) + 1)]
|
|
321
|
+
if isinstance(state, dict) and (taken := [name for name in names if name in state]):
|
|
322
|
+
raise CliError(f"state already has the key(s) {', '.join(taken)} that --image generates; rename them in the state")
|
|
323
|
+
too_large = "request with images is larger than 32 MiB once base64-encoded; send fewer or smaller images"
|
|
324
|
+
assets: dict[str, Any] = {}
|
|
325
|
+
references: dict[str, str] = {}
|
|
326
|
+
encoded = 0
|
|
327
|
+
for name, path in zip(names, paths):
|
|
328
|
+
asset = image_asset(path)
|
|
329
|
+
reference = f"image-{hashlib.sha256(asset['data_base64'].encode()).hexdigest()[:12]}"
|
|
330
|
+
if reference not in assets:
|
|
331
|
+
# Stop reading further files as soon as the image data alone is over the limit.
|
|
332
|
+
encoded += len(asset["data_base64"])
|
|
333
|
+
if encoded > REQUEST_MAX_BYTES:
|
|
334
|
+
raise CliError(too_large)
|
|
335
|
+
assets[reference] = asset
|
|
336
|
+
elif assets[reference] != asset:
|
|
337
|
+
raise CliError(f"{path}: image reference collides with another image")
|
|
338
|
+
references[name] = reference
|
|
339
|
+
if isinstance(state, dict):
|
|
340
|
+
state = {**state, **references}
|
|
341
|
+
elif state is None:
|
|
342
|
+
state = references
|
|
343
|
+
else:
|
|
344
|
+
state = {"text": state, **references}
|
|
345
|
+
# Exact wire size without serializing the image data a second time.
|
|
346
|
+
skeleton = {**payload, "state": state, "assets": {key: {**value, "data_base64": ""} for key, value in assets.items()}}
|
|
347
|
+
if len(json.dumps(skeleton, ensure_ascii=False).encode()) + encoded > REQUEST_MAX_BYTES:
|
|
348
|
+
raise CliError(too_large)
|
|
349
|
+
return {**payload, "state": state, "assets": assets}
|
|
350
|
+
|
|
351
|
+
|
|
212
352
|
def split_pair(value: str) -> tuple[str, str]:
|
|
213
353
|
key, separator, description = value.partition("=")
|
|
214
354
|
if not separator or not key or not description:
|
|
@@ -244,8 +384,12 @@ def provider_request(payload: dict[str, Any], provider: str) -> tuple[dict[str,
|
|
|
244
384
|
return payload, headers
|
|
245
385
|
|
|
246
386
|
|
|
247
|
-
def cloudflare_result(envelope: dict[str, Any]) -> dict[str, Any]:
|
|
248
|
-
"""Unwrap a Workers AI REST envelope, failing closed on anything but a successful decision result.
|
|
387
|
+
def cloudflare_result(envelope: dict[str, Any], questions: Any = None) -> dict[str, Any]:
|
|
388
|
+
"""Unwrap a Workers AI REST envelope, failing closed on anything but a successful decision result.
|
|
389
|
+
|
|
390
|
+
When the submitted `questions` is a mapping, every submitted question ID must have an answer;
|
|
391
|
+
extra answers are tolerated.
|
|
392
|
+
"""
|
|
249
393
|
if envelope.get("success") is not True:
|
|
250
394
|
# Envelope errors are not reflected: they may echo request content.
|
|
251
395
|
raise CliError("Cloudflare Workers AI reported a failed request", 1)
|
|
@@ -254,15 +398,18 @@ def cloudflare_result(envelope: dict[str, Any]) -> dict[str, Any]:
|
|
|
254
398
|
raise CliError("Cloudflare Workers AI returned a malformed result", 1)
|
|
255
399
|
if not all(isinstance(answer, dict) for answer in answers.values()):
|
|
256
400
|
raise CliError("Cloudflare Workers AI returned a malformed answer", 1)
|
|
401
|
+
if isinstance(questions, dict) and any(name not in answers for name in questions):
|
|
402
|
+
# Neither the response nor the missing IDs are reflected; the message stays bounded.
|
|
403
|
+
raise CliError("Cloudflare Workers AI omitted a requested answer", 1)
|
|
257
404
|
return {
|
|
258
405
|
**result,
|
|
259
406
|
"answers": {name: {k: v for k, v in answer.items() if k != "type"} for name, answer in answers.items()},
|
|
260
407
|
}
|
|
261
408
|
|
|
262
409
|
|
|
263
|
-
def normalize_response(result: dict[str, Any], provider: str) -> dict[str, Any]:
|
|
410
|
+
def normalize_response(result: dict[str, Any], provider: str, questions: Any = None) -> dict[str, Any]:
|
|
264
411
|
if provider == "cloudflare":
|
|
265
|
-
return cloudflare_result(result)
|
|
412
|
+
return cloudflare_result(result, questions)
|
|
266
413
|
if provider != "vercel":
|
|
267
414
|
return result
|
|
268
415
|
result = dict(result)
|
|
@@ -318,6 +465,7 @@ def provider_model(provider: str) -> str:
|
|
|
318
465
|
|
|
319
466
|
|
|
320
467
|
def call(payload: dict[str, Any], endpoint: str, provider: str = "official") -> dict[str, Any]:
|
|
468
|
+
questions = payload.get("questions")
|
|
321
469
|
payload, provider_headers = provider_request(payload, provider)
|
|
322
470
|
request = urllib.request.Request(
|
|
323
471
|
endpoint,
|
|
@@ -325,8 +473,9 @@ def call(payload: dict[str, Any], endpoint: str, provider: str = "official") ->
|
|
|
325
473
|
headers={
|
|
326
474
|
"Authorization": f"Bearer {api_key(provider)}",
|
|
327
475
|
"Content-Type": "application/json",
|
|
328
|
-
"User-Agent": "jev-cli/0.
|
|
476
|
+
"User-Agent": "jev-cli/0.8.0",
|
|
329
477
|
**provider_headers,
|
|
478
|
+
**({IMAGE_HEADER: "true"} if payload.get("assets") else {}),
|
|
330
479
|
},
|
|
331
480
|
method="POST",
|
|
332
481
|
)
|
|
@@ -334,20 +483,21 @@ def call(payload: dict[str, Any], endpoint: str, provider: str = "official") ->
|
|
|
334
483
|
with urllib.request.urlopen(request, timeout=60) as response:
|
|
335
484
|
result = json.load(response)
|
|
336
485
|
except urllib.error.HTTPError as exc:
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
detail =
|
|
340
|
-
|
|
341
|
-
|
|
486
|
+
if payload.get("assets"):
|
|
487
|
+
# An upstream error can quote any portion of an image or its private context.
|
|
488
|
+
detail = "response body omitted for asset requests"
|
|
489
|
+
else:
|
|
490
|
+
body = exc.read(ERROR_BODY_MAX_BYTES).decode(errors="replace")
|
|
491
|
+
detail = json.dumps(body[:ERROR_DETAIL_MAX_CHARS], ensure_ascii=False)
|
|
342
492
|
code = 3 if exc.code in (401, 403) else 4 if exc.code in (429, 500, 502, 503, 504) else 1
|
|
343
|
-
raise CliError(f"API HTTP {exc.code}: {
|
|
493
|
+
raise CliError(f"API HTTP {exc.code}: {detail}", code) from exc
|
|
344
494
|
except json.JSONDecodeError as exc:
|
|
345
495
|
raise CliError(f"API returned invalid JSON: {exc}", 4) from exc
|
|
346
496
|
except (urllib.error.URLError, TimeoutError) as exc:
|
|
347
497
|
raise CliError(f"API connection failed: {exc}", 4) from exc
|
|
348
498
|
if not isinstance(result, dict):
|
|
349
499
|
raise CliError("API returned a non-object response", 1)
|
|
350
|
-
return normalize_response(result, provider)
|
|
500
|
+
return normalize_response(result, provider, questions)
|
|
351
501
|
|
|
352
502
|
|
|
353
503
|
def common_parser() -> argparse.ArgumentParser:
|
|
@@ -372,7 +522,7 @@ def parser() -> argparse.ArgumentParser:
|
|
|
372
522
|
prog="jev",
|
|
373
523
|
description="Evaluate text or JSON with TypeSafe Jev. Uses its own local credential store.",
|
|
374
524
|
)
|
|
375
|
-
root.add_argument("--version", action="version", version="jev 0.
|
|
525
|
+
root.add_argument("--version", action="version", version="jev 0.8.0")
|
|
376
526
|
sub = root.add_subparsers(dest="command", required=True)
|
|
377
527
|
common = common_parser()
|
|
378
528
|
|
|
@@ -392,16 +542,19 @@ def parser() -> argparse.ArgumentParser:
|
|
|
392
542
|
|
|
393
543
|
noul = sub.add_parser("noul", parents=[common], help="answer one yes/no question with a probability")
|
|
394
544
|
noul.add_argument("-q", "--question", required=True, help="question to answer")
|
|
395
|
-
noul.add_argument("-s", "--state", help="text, @file, or - for stdin (default: stdin)")
|
|
545
|
+
noul.add_argument("-s", "--state", help="text, @file, or - for stdin (default: stdin, or none with --image)")
|
|
546
|
+
noul.add_argument("-i", "--image", action="append", default=[], metavar="PATH", help="PNG or JPEG to evaluate (repeatable)")
|
|
396
547
|
|
|
397
548
|
choice = sub.add_parser("choice", parents=[common], help="choose one option")
|
|
398
549
|
choice.add_argument("-q", "--question", required=True, help="question to answer")
|
|
399
|
-
choice.add_argument("-s", "--state", help="text, @file, or - for stdin (default: stdin)")
|
|
550
|
+
choice.add_argument("-s", "--state", help="text, @file, or - for stdin (default: stdin, or none with --image)")
|
|
551
|
+
choice.add_argument("-i", "--image", action="append", default=[], metavar="PATH", help="PNG or JPEG to evaluate (repeatable)")
|
|
400
552
|
choice.add_argument("-o", "--option", action="append", type=split_pair, required=True, metavar="KEY=DESCRIPTION")
|
|
401
553
|
|
|
402
554
|
score = sub.add_parser("score", parents=[common], help="score against ordered levels")
|
|
403
555
|
score.add_argument("-q", "--question", required=True, help="question to answer")
|
|
404
|
-
score.add_argument("-s", "--state", help="text, @file, or - for stdin (default: stdin)")
|
|
556
|
+
score.add_argument("-s", "--state", help="text, @file, or - for stdin (default: stdin, or none with --image)")
|
|
557
|
+
score.add_argument("-i", "--image", action="append", default=[], metavar="PATH", help="PNG or JPEG to evaluate (repeatable)")
|
|
405
558
|
score.add_argument("-l", "--level", action="append", required=True, metavar="DESCRIPTION")
|
|
406
559
|
|
|
407
560
|
run = sub.add_parser("run", parents=[common], help="send a complete request JSON for batched questions")
|
|
@@ -424,13 +577,23 @@ def request_for(args: argparse.Namespace) -> tuple[dict[str, Any], str | None]:
|
|
|
424
577
|
return payload, None
|
|
425
578
|
|
|
426
579
|
criteria = dict(args.option) if args.command == "choice" else args.level if args.command == "score" else None
|
|
580
|
+
if args.image and args.provider == "cloudflare":
|
|
581
|
+
raise CliError("--image is not supported with the cloudflare provider; use run with Clef's images field")
|
|
582
|
+
if args.image and args.provider == "openrouter":
|
|
583
|
+
raise CliError(
|
|
584
|
+
"--image is not supported with the openrouter provider: it does not accept this CLI's image asset "
|
|
585
|
+
"encoding; use --provider official, or send OpenRouter's own image_url state parts with jev run"
|
|
586
|
+
)
|
|
587
|
+
state = None if args.image and args.state is None else state_value(args.state, args.json_state)
|
|
427
588
|
payload = question_request(
|
|
428
589
|
args.command,
|
|
429
|
-
|
|
590
|
+
state,
|
|
430
591
|
args.question,
|
|
431
592
|
criteria,
|
|
432
593
|
args.model or provider_model(args.provider),
|
|
433
594
|
)
|
|
595
|
+
if args.image:
|
|
596
|
+
payload = attach_images(payload, args.image)
|
|
434
597
|
return payload, args.command
|
|
435
598
|
|
|
436
599
|
|
|
@@ -87,8 +87,8 @@ class QuestionSpec(TypedDict):
|
|
|
87
87
|
"Required by `choice` and `score`, omitted by `noul`. For `choice`, at "
|
|
88
88
|
"least two option keys mapped to what each key means; the selected key is "
|
|
89
89
|
"returned verbatim. For `score`, at least two level descriptions ordered "
|
|
90
|
-
"from lowest to highest; the
|
|
91
|
-
"
|
|
90
|
+
"from lowest to highest, numbered from zero; the score is on that zero-based "
|
|
91
|
+
"scale and may be fractional, for example a Clef probability-weighted score."
|
|
92
92
|
)
|
|
93
93
|
),
|
|
94
94
|
]
|
|
@@ -134,7 +134,7 @@ logger = logging.getLogger(__name__)
|
|
|
134
134
|
mcp = MCPServer(
|
|
135
135
|
name="jev",
|
|
136
136
|
title="TypeSafe Jev",
|
|
137
|
-
version="0.
|
|
137
|
+
version="0.8.0",
|
|
138
138
|
instructions=(
|
|
139
139
|
"Ask TypeSafe Jev typed questions about text or JSON state. Use noul for a yes/no "
|
|
140
140
|
"probability, choice for one key from explicit options, score for an ordered level, "
|
|
@@ -227,8 +227,9 @@ def score(
|
|
|
227
227
|
list[str],
|
|
228
228
|
Field(
|
|
229
229
|
description=(
|
|
230
|
-
"At least two level descriptions ordered from lowest to highest
|
|
231
|
-
"
|
|
230
|
+
"At least two level descriptions ordered from lowest to highest, numbered from "
|
|
231
|
+
"zero. The score is on that zero-based scale and may be fractional, for example "
|
|
232
|
+
"a Clef probability-weighted score."
|
|
232
233
|
)
|
|
233
234
|
),
|
|
234
235
|
],
|
|
@@ -238,6 +239,8 @@ def score(
|
|
|
238
239
|
) -> dict[str, Any]:
|
|
239
240
|
"""Score the state against at least two ordered levels, numbered from zero in the supplied order.
|
|
240
241
|
|
|
242
|
+
The score may be fractional, for example a Clef probability-weighted score between levels.
|
|
243
|
+
|
|
241
244
|
The state is sent verbatim; `-` and `@path` are literal strings here, not stdin or a file.
|
|
242
245
|
"""
|
|
243
246
|
# A single level is not a scale, so the minimum useful cardinality is two.
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import io
|
|
2
2
|
import json
|
|
3
3
|
import os
|
|
4
|
+
import tempfile
|
|
4
5
|
import unittest
|
|
5
6
|
import urllib.error
|
|
7
|
+
import zlib
|
|
6
8
|
from email.message import Message
|
|
7
9
|
from pathlib import Path
|
|
8
|
-
from unittest.mock import MagicMock, patch
|
|
10
|
+
from unittest.mock import MagicMock, mock_open, patch
|
|
9
11
|
|
|
10
12
|
try:
|
|
11
13
|
import termios
|
|
@@ -104,6 +106,218 @@ class JevTest(unittest.TestCase):
|
|
|
104
106
|
self.assertEqual(kind, "choice")
|
|
105
107
|
self.assertEqual(payload["questions"]["answer"]["criteria"], {"tech": "Bug", "sales": "Purchase"})
|
|
106
108
|
|
|
109
|
+
@staticmethod
|
|
110
|
+
def image_bytes(width, height, kind="png", animated=False, shade=0):
|
|
111
|
+
"""Build a small, complete, decodable flat grayscale image (a synthetic fixture, no codec)."""
|
|
112
|
+
if kind == "png":
|
|
113
|
+
|
|
114
|
+
def chunk(name, body):
|
|
115
|
+
return len(body).to_bytes(4, "big") + name + body + zlib.crc32(name + body).to_bytes(4, "big")
|
|
116
|
+
|
|
117
|
+
# 8-bit grayscale, no interlace; every scanline is a filter byte plus `width` samples.
|
|
118
|
+
header = width.to_bytes(4, "big") + height.to_bytes(4, "big") + bytes([8, 0, 0, 0, 0])
|
|
119
|
+
pixels = zlib.compress((b"\x00" + bytes([shade]) * width) * height)
|
|
120
|
+
control = chunk(b"acTL", (1).to_bytes(4, "big") + bytes(4)) if animated else b""
|
|
121
|
+
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + control + chunk(b"IDAT", pixels) + chunk(b"IEND", b"")
|
|
122
|
+
|
|
123
|
+
def segment(marker, body):
|
|
124
|
+
return bytes([0xFF, marker]) + (len(body) + 2).to_bytes(2, "big") + body
|
|
125
|
+
|
|
126
|
+
# Baseline grayscale JPEG: one-code DC and AC Huffman tables, so each 8x8 block is the
|
|
127
|
+
# two bits "00" (zero DC difference, then end of block). The scan is padded with 1 bits.
|
|
128
|
+
bits = 2 * -(-width // 8) * -(-height // 8)
|
|
129
|
+
scan = bytes(bits // 8) + (bytes([0xFF >> (bits % 8)]) if bits % 8 else b"")
|
|
130
|
+
return (
|
|
131
|
+
b"\xff\xd8"
|
|
132
|
+
+ segment(0xE0, b"JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00")
|
|
133
|
+
+ segment(0xDB, b"\x00" + bytes([1 + shade]) * 64)
|
|
134
|
+
+ segment(0xC0, bytes([8]) + height.to_bytes(2, "big") + width.to_bytes(2, "big") + bytes([1, 1, 0x11, 0]))
|
|
135
|
+
+ segment(0xC4, b"\x00" + bytes([1]) + bytes(15) + b"\x00")
|
|
136
|
+
+ segment(0xC4, b"\x10" + bytes([1]) + bytes(15) + b"\x00")
|
|
137
|
+
+ segment(0xDA, bytes([1, 1, 0x00, 0, 63, 0]))
|
|
138
|
+
+ scan
|
|
139
|
+
+ b"\xff\xd9"
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
def write_image(self, directory, name, width, height, kind="png", animated=False, shade=0):
|
|
143
|
+
path = Path(directory) / name
|
|
144
|
+
path.write_bytes(self.image_bytes(width, height, kind, animated, shade))
|
|
145
|
+
return str(path)
|
|
146
|
+
|
|
147
|
+
def test_state_key_collision_is_rejected_before_reading_or_sending(self):
|
|
148
|
+
# The image path does not exist: the collision must be reported before any file is read.
|
|
149
|
+
for state, images, taken in (
|
|
150
|
+
('{"image": "mine"}', ["missing.png"], "image"),
|
|
151
|
+
('{"image_2": "mine", "note": 1}', ["missing.png", "missing-2.png"], "image_2"),
|
|
152
|
+
):
|
|
153
|
+
argv = ["jev", "noul", "-q", "Receipt?", "--json-state", "-s", state]
|
|
154
|
+
for image in images:
|
|
155
|
+
argv += ["-i", image]
|
|
156
|
+
with self.subTest(taken), patch("sys.argv", argv), patch("urllib.request.urlopen") as opened, patch(
|
|
157
|
+
"sys.stderr", new_callable=io.StringIO
|
|
158
|
+
) as stderr:
|
|
159
|
+
self.assertEqual(jev.main(), 2)
|
|
160
|
+
opened.assert_not_called()
|
|
161
|
+
self.assertIn(f"already has the key(s) {taken}", json.loads(stderr.getvalue())["error"])
|
|
162
|
+
|
|
163
|
+
def test_json_state_without_generated_keys_is_preserved(self):
|
|
164
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
165
|
+
png = self.write_image(directory, "a.png", 640, 480)
|
|
166
|
+
args = jev.parser().parse_args(
|
|
167
|
+
["noul", "-q", "Receipt?", "--json-state", "-s", '{"note": "n", "image_2": "kept"}', "-i", png]
|
|
168
|
+
)
|
|
169
|
+
payload, _ = jev.request_for(args)
|
|
170
|
+
self.assertEqual(payload["state"]["note"], "n")
|
|
171
|
+
self.assertEqual(payload["state"]["image_2"], "kept")
|
|
172
|
+
self.assertIn(payload["state"]["image"], payload["assets"])
|
|
173
|
+
|
|
174
|
+
def test_image_read_is_bounded(self):
|
|
175
|
+
data = self.image_bytes(640, 480)
|
|
176
|
+
with patch("builtins.open", mock_open(read_data=data)) as opened:
|
|
177
|
+
jev.image_asset("a.png")
|
|
178
|
+
opened.return_value.read.assert_called_once_with(jev.IMAGE_MAX_BYTES + 1)
|
|
179
|
+
self.assertEqual(jev.IMAGE_MAX_BYTES, 16 * 1024 * 1024)
|
|
180
|
+
with tempfile.TemporaryDirectory() as directory, patch.object(jev, "IMAGE_MAX_BYTES", len(data) - 1):
|
|
181
|
+
with self.assertRaisesRegex(jev.CliError, "larger than 16 MiB"):
|
|
182
|
+
jev.image_asset(self.write_image(directory, "a.png", 640, 480))
|
|
183
|
+
|
|
184
|
+
def test_total_request_size_is_bounded_for_repeated_images(self):
|
|
185
|
+
self.assertEqual(jev.REQUEST_MAX_BYTES, 32 * 1024 * 1024)
|
|
186
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
187
|
+
first = self.write_image(directory, "a.png", 640, 480)
|
|
188
|
+
second = self.write_image(directory, "b.png", 640, 480, shade=200)
|
|
189
|
+
encoded = sum(len(jev.image_asset(path)["data_base64"]) for path in (first, second))
|
|
190
|
+
payload = jev.question_request("noul", None, "Receipt?", None, "m")
|
|
191
|
+
for limit in (encoded - 1, encoded + 10):
|
|
192
|
+
with self.subTest(limit=limit), patch.object(jev, "REQUEST_MAX_BYTES", limit):
|
|
193
|
+
with self.assertRaisesRegex(jev.CliError, "larger than 32 MiB"):
|
|
194
|
+
jev.attach_images(payload, [first, second])
|
|
195
|
+
with patch.object(jev, "REQUEST_MAX_BYTES", encoded + 10_000):
|
|
196
|
+
request = jev.attach_images(payload, [first, second])
|
|
197
|
+
self.assertLessEqual(len(json.dumps(request, ensure_ascii=False).encode()), encoded + 10_000)
|
|
198
|
+
# The same image repeated is sent once, so it counts once against the limit.
|
|
199
|
+
with patch.object(jev, "REQUEST_MAX_BYTES", encoded // 2 + 10_000):
|
|
200
|
+
repeated = jev.attach_images(payload, [first, first, first])
|
|
201
|
+
self.assertEqual(len(repeated["assets"]), 1)
|
|
202
|
+
self.assertEqual(set(repeated["state"]), {"image", "image_2", "image_3"})
|
|
203
|
+
self.assertEqual(len(set(repeated["state"].values())), 1)
|
|
204
|
+
|
|
205
|
+
def test_truncated_or_header_only_images_are_rejected(self):
|
|
206
|
+
png = self.image_bytes(640, 480)
|
|
207
|
+
jpg = self.image_bytes(800, 600, kind="jpg")
|
|
208
|
+
frame = jpg.index(b"\xff\xc0")
|
|
209
|
+
scan = jpg.index(b"\xff\xda")
|
|
210
|
+
cases = {
|
|
211
|
+
"png signature only": png[:8],
|
|
212
|
+
"png header only": png[:33],
|
|
213
|
+
"png cut inside pixel data": png[:60],
|
|
214
|
+
"png without end chunk": png[:-12],
|
|
215
|
+
"png without pixel data": png[:33] + png[-12:],
|
|
216
|
+
"jpeg marker only": jpg[:2],
|
|
217
|
+
"jpeg header only": jpg[: frame + 19],
|
|
218
|
+
"jpeg without scan": jpg[:scan] + b"\xff\xd9",
|
|
219
|
+
"jpeg scan header only": jpg[: scan + 10] + b"\xff\xd9",
|
|
220
|
+
"jpeg without end marker": jpg[:-2],
|
|
221
|
+
}
|
|
222
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
223
|
+
for name, data in cases.items():
|
|
224
|
+
path = Path(directory) / "image.bin"
|
|
225
|
+
path.write_bytes(data)
|
|
226
|
+
with self.subTest(name), self.assertRaisesRegex(jev.CliError, "truncated or incomplete|no image data|PNG or JPEG"):
|
|
227
|
+
jev.image_asset(str(path))
|
|
228
|
+
self.assertEqual(jev.image_dimensions(png), ("png", 640, 480))
|
|
229
|
+
self.assertEqual(jev.image_dimensions(jpg), ("jpg", 800, 600))
|
|
230
|
+
|
|
231
|
+
def test_http_error_does_not_reflect_image_data(self):
|
|
232
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
233
|
+
asset = jev.image_asset(self.write_image(directory, "a.png", 640, 480))
|
|
234
|
+
encoded = asset["data_base64"]
|
|
235
|
+
payload = {"state": {"image": "image-x"}, "model": "m", "questions": {}, "assets": {"image-x": asset}}
|
|
236
|
+
bodies = {
|
|
237
|
+
"whole": json.dumps({"error": "bad request", "request": payload}).encode(),
|
|
238
|
+
"partial": json.dumps({"error": "bad image: " + "QUJD" * 100}).encode(),
|
|
239
|
+
"plain": ("<html>" + encoded + "</html>").encode(),
|
|
240
|
+
"huge": json.dumps({"error": "x " * 200_000}).encode(),
|
|
241
|
+
}
|
|
242
|
+
for name, body in bodies.items():
|
|
243
|
+
error = urllib.error.HTTPError("https://example.test", 400, "Bad Request", Message(), io.BytesIO(body))
|
|
244
|
+
with self.subTest(name), patch.object(jev, "api_key", return_value="test-key"), patch(
|
|
245
|
+
"urllib.request.urlopen", side_effect=error
|
|
246
|
+
):
|
|
247
|
+
with self.assertRaisesRegex(jev.CliError, "API HTTP 400") as raised:
|
|
248
|
+
jev.call(payload, "https://example.test")
|
|
249
|
+
message = str(raised.exception)
|
|
250
|
+
self.assertEqual(raised.exception.exit_code, 1)
|
|
251
|
+
self.assertNotIn(encoded, message)
|
|
252
|
+
self.assertNotIn("QUJD" * 50, message)
|
|
253
|
+
self.assertEqual(message, "API HTTP 400: response body omitted for asset requests")
|
|
254
|
+
|
|
255
|
+
def test_image_request_builds_assets_and_state_references(self):
|
|
256
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
257
|
+
png = self.write_image(directory, "a.png", 640, 480)
|
|
258
|
+
jpg = self.write_image(directory, "b.jpg", 800, 600, kind="jpg")
|
|
259
|
+
args = jev.parser().parse_args(["noul", "-q", "Is `image` a receipt?", "-i", png, "-i", jpg])
|
|
260
|
+
payload, kind = jev.request_for(args)
|
|
261
|
+
self.assertEqual(kind, "noul")
|
|
262
|
+
state = payload["state"]
|
|
263
|
+
self.assertEqual(set(state), {"image", "image_2"})
|
|
264
|
+
self.assertEqual(payload["assets"][state["image"]]["format"], "png")
|
|
265
|
+
self.assertEqual(payload["assets"][state["image_2"]]["format"], "jpg")
|
|
266
|
+
self.assertEqual(payload["assets"][state["image"]]["type"], "image")
|
|
267
|
+
|
|
268
|
+
def test_image_with_text_state_keeps_text(self):
|
|
269
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
270
|
+
png = self.write_image(directory, "a.png", 640, 480)
|
|
271
|
+
args = jev.parser().parse_args(["score", "-q", "Quality?", "-s", "note", "-i", png, "-l", "bad", "-l", "good"])
|
|
272
|
+
payload, _ = jev.request_for(args)
|
|
273
|
+
self.assertEqual(payload["state"]["text"], "note")
|
|
274
|
+
self.assertIn("image", payload["state"])
|
|
275
|
+
|
|
276
|
+
def test_image_limits_are_enforced(self):
|
|
277
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
278
|
+
cases = {
|
|
279
|
+
"small": self.write_image(directory, "s.png", 100, 400),
|
|
280
|
+
"large": self.write_image(directory, "l.jpg", 2000, 400, kind="jpg"),
|
|
281
|
+
"animated": self.write_image(directory, "a.png", 640, 480, animated=True),
|
|
282
|
+
}
|
|
283
|
+
gif = Path(directory) / "x.gif"
|
|
284
|
+
gif.write_bytes(b"GIF89a")
|
|
285
|
+
cases["format"] = str(gif)
|
|
286
|
+
reasons = {"small": "px per side", "large": "px per side", "animated": "animated", "format": "PNG or JPEG"}
|
|
287
|
+
for name, path in cases.items():
|
|
288
|
+
with self.subTest(name), self.assertRaisesRegex(jev.CliError, reasons[name]):
|
|
289
|
+
jev.image_asset(path)
|
|
290
|
+
|
|
291
|
+
def test_image_side_below_280_is_rejected(self):
|
|
292
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
293
|
+
with self.assertRaises(jev.CliError):
|
|
294
|
+
jev.image_asset(self.write_image(directory, "s.png", 279, 400))
|
|
295
|
+
jev.image_asset(self.write_image(directory, "ok.png", 280, 400))
|
|
296
|
+
|
|
297
|
+
def test_image_with_openrouter_is_rejected(self):
|
|
298
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
299
|
+
png = self.write_image(directory, "a.png", 640, 480)
|
|
300
|
+
args = jev.parser().parse_args(["noul", "-q", "Receipt?", "-i", png, "--provider", "openrouter"])
|
|
301
|
+
with self.assertRaisesRegex(jev.CliError, "openrouter") as raised:
|
|
302
|
+
jev.request_for(args)
|
|
303
|
+
message = str(raised.exception)
|
|
304
|
+
self.assertIn("--provider official", message)
|
|
305
|
+
self.assertIn("jev run", message)
|
|
306
|
+
self.assertNotIn("use typesafe", message)
|
|
307
|
+
|
|
308
|
+
def test_image_requests_send_the_images_header(self):
|
|
309
|
+
def respond(*_args, **_kwargs):
|
|
310
|
+
response = MagicMock()
|
|
311
|
+
response.__enter__.return_value = io.BytesIO(b'{"answers": {}}')
|
|
312
|
+
return response
|
|
313
|
+
|
|
314
|
+
with patch.dict(os.environ, {"TYPESAFE_API_KEY": "k"}), patch("urllib.request.urlopen", side_effect=respond) as opened:
|
|
315
|
+
jev.call({"state": {}, "model": "m", "questions": {}, "assets": {"x": {}}}, "https://example.test")
|
|
316
|
+
jev.call({"state": "", "model": "m", "questions": {}}, "https://example.test")
|
|
317
|
+
with_images, without = (call.args[0] for call in opened.call_args_list)
|
|
318
|
+
self.assertEqual(with_images.get_header("Typesafe-danger-zone-images"), "true")
|
|
319
|
+
self.assertIsNone(without.get_header("Typesafe-danger-zone-images"))
|
|
320
|
+
|
|
107
321
|
def test_short_options_for_question_and_state(self):
|
|
108
322
|
args = jev.parser().parse_args(["noul", "-q", "Urgent?", "-s", "today", "--value"])
|
|
109
323
|
payload, kind = jev.request_for(args)
|
|
@@ -182,7 +396,7 @@ class JevTest(unittest.TestCase):
|
|
|
182
396
|
cases = {
|
|
183
397
|
"official": "jev-latest",
|
|
184
398
|
"vercel": "typesafe-ai/jev",
|
|
185
|
-
"openrouter": "typesafe/jev-1.
|
|
399
|
+
"openrouter": "typesafe/jev-1.14",
|
|
186
400
|
"custom": "jev-latest",
|
|
187
401
|
"cloudflare": "clef-flash",
|
|
188
402
|
}
|
|
@@ -310,7 +524,18 @@ class JevTest(unittest.TestCase):
|
|
|
310
524
|
"official": {"answers": {}},
|
|
311
525
|
"openrouter": {"answers": {}},
|
|
312
526
|
"custom": {"answers": {}},
|
|
313
|
-
"cloudflare": {
|
|
527
|
+
"cloudflare": {
|
|
528
|
+
"success": True,
|
|
529
|
+
"result": {
|
|
530
|
+
"model": "clef-flash",
|
|
531
|
+
"answers": {
|
|
532
|
+
"urgent": {"type": "noul", "noul": 0.0},
|
|
533
|
+
"route": {"type": "choice", "choice": "a"},
|
|
534
|
+
"quality": {"type": "score", "score": 0.35},
|
|
535
|
+
},
|
|
536
|
+
},
|
|
537
|
+
"errors": [],
|
|
538
|
+
},
|
|
314
539
|
"vercel": {
|
|
315
540
|
"answers": {
|
|
316
541
|
"urgent": {"type": "boolean", "probability": 0.9},
|
|
@@ -347,7 +572,13 @@ class JevTest(unittest.TestCase):
|
|
|
347
572
|
self.assertEqual(result["answers"]["quality"]["score"], 1.0)
|
|
348
573
|
elif provider == "cloudflare":
|
|
349
574
|
self.assertEqual(body, payload)
|
|
350
|
-
self.assertEqual(
|
|
575
|
+
self.assertEqual(
|
|
576
|
+
result,
|
|
577
|
+
{
|
|
578
|
+
"model": "clef-flash",
|
|
579
|
+
"answers": {"urgent": {"noul": 0.0}, "route": {"choice": "a"}, "quality": {"score": 0.35}},
|
|
580
|
+
},
|
|
581
|
+
)
|
|
351
582
|
else:
|
|
352
583
|
self.assertEqual(body, payload)
|
|
353
584
|
|
|
@@ -603,6 +834,89 @@ class CloudflareProviderTest(unittest.TestCase):
|
|
|
603
834
|
self.assertNotIn("secret-input", stderr)
|
|
604
835
|
self.assertNotIn("cf-token", stderr)
|
|
605
836
|
|
|
837
|
+
def test_missing_requested_answers_never_emit_decisions(self):
|
|
838
|
+
batch = {
|
|
839
|
+
"state": "today",
|
|
840
|
+
"questions": {
|
|
841
|
+
"urgent": {"type": "noul", "instructions": "Urgent?"},
|
|
842
|
+
"anger": {"type": "score", "instructions": "Anger?", "criteria": ["Calm", "Angry"]},
|
|
843
|
+
},
|
|
844
|
+
}
|
|
845
|
+
cases = (
|
|
846
|
+
(["noul", "-q", "Urgent?", "-s", "today"], {}, None),
|
|
847
|
+
(["noul", "-q", "Urgent?", "-s", "today", "--value"], {}, None),
|
|
848
|
+
(["noul", "-q", "Urgent?", "-s", "today"], {"other": {"type": "noul", "noul": 0.7}}, None),
|
|
849
|
+
# A partially answered batch is still incomplete.
|
|
850
|
+
(["run", "-"], {"urgent": {"type": "noul", "noul": 0.7}}, batch),
|
|
851
|
+
(["auth", "test"], {}, None),
|
|
852
|
+
)
|
|
853
|
+
for argv, answers, request in cases:
|
|
854
|
+
with self.subTest(argv=argv, answers=answers):
|
|
855
|
+
code, stdout, stderr, captured = self.run_main(
|
|
856
|
+
[*argv, "--provider", "cloudflare"],
|
|
857
|
+
cloudflare_envelope(answers),
|
|
858
|
+
stdin=io.StringIO(json.dumps(request)) if request else None,
|
|
859
|
+
)
|
|
860
|
+
self.assertEqual(len(captured), 1)
|
|
861
|
+
self.assertEqual(code, 1)
|
|
862
|
+
self.assertEqual(stdout, "")
|
|
863
|
+
error = json.loads(stderr)
|
|
864
|
+
self.assertFalse(error["ok"])
|
|
865
|
+
self.assertEqual(error["error"], "Cloudflare Workers AI omitted a requested answer")
|
|
866
|
+
self.assertNotIn("0.7", stderr)
|
|
867
|
+
self.assertNotIn("cf-token", stderr)
|
|
868
|
+
|
|
869
|
+
def test_complete_answers_preserve_zero_and_fractional_values(self):
|
|
870
|
+
request = {
|
|
871
|
+
"state": "today",
|
|
872
|
+
"questions": {
|
|
873
|
+
"urgent": {"type": "noul", "instructions": "Urgent?"},
|
|
874
|
+
"anger": {"type": "score", "instructions": "Anger?", "criteria": ["Calm", "Concerned", "Angry"]},
|
|
875
|
+
"level": {"type": "score", "instructions": "Level?", "criteria": ["Low", "High"]},
|
|
876
|
+
},
|
|
877
|
+
}
|
|
878
|
+
answers = {
|
|
879
|
+
"urgent": {"type": "noul", "noul": 0.0},
|
|
880
|
+
"anger": {"type": "score", "score": 1.4, "probabilities": {"0": 0.1, "1": 0.4, "2": 0.5}},
|
|
881
|
+
"level": {"type": "score", "score": 0},
|
|
882
|
+
# Extra answers and fields are tolerated; exact key equality is not required.
|
|
883
|
+
"extra": {"type": "noul", "noul": 0.5, "unknown": True},
|
|
884
|
+
}
|
|
885
|
+
code, stdout, _, _ = self.run_main(
|
|
886
|
+
["run", "-", "--provider", "cloudflare"], cloudflare_envelope(answers), stdin=io.StringIO(json.dumps(request))
|
|
887
|
+
)
|
|
888
|
+
self.assertEqual(code, 0)
|
|
889
|
+
self.assertEqual(
|
|
890
|
+
json.loads(stdout)["answers"],
|
|
891
|
+
{
|
|
892
|
+
"urgent": {"noul": 0.0},
|
|
893
|
+
"anger": {"score": 1.4, "probabilities": {"0": 0.1, "1": 0.4, "2": 0.5}},
|
|
894
|
+
"level": {"score": 0},
|
|
895
|
+
"extra": {"noul": 0.5, "unknown": True},
|
|
896
|
+
},
|
|
897
|
+
)
|
|
898
|
+
for value, expected in ((0.0, "0.0\n"), (0.25, "0.25\n")):
|
|
899
|
+
with self.subTest(value=value):
|
|
900
|
+
code, stdout, _, _ = self.run_main(
|
|
901
|
+
["score", "--provider", "cloudflare", "-q", "Q?", "-s", "today", "-l", "Low", "-l", "High", "--value"],
|
|
902
|
+
cloudflare_envelope({"answer": {"type": "score", "score": value}}),
|
|
903
|
+
)
|
|
904
|
+
self.assertEqual((code, stdout), (0, expected))
|
|
905
|
+
|
|
906
|
+
def test_only_mapping_shaped_questions_are_checked(self):
|
|
907
|
+
envelope = cloudflare_envelope({"answer": {"type": "noul", "noul": 0.5}})
|
|
908
|
+
for questions in (None, ["missing"], "missing"):
|
|
909
|
+
with self.subTest(questions=questions):
|
|
910
|
+
self.assertEqual(jev.cloudflare_result(envelope, questions)["answers"], {"answer": {"noul": 0.5}})
|
|
911
|
+
with self.assertRaises(jev.CliError) as raised:
|
|
912
|
+
jev.cloudflare_result(envelope, {"missing": {}})
|
|
913
|
+
self.assertEqual(raised.exception.exit_code, 1)
|
|
914
|
+
|
|
915
|
+
def test_other_providers_do_not_require_complete_answers(self):
|
|
916
|
+
payload = {"model": "m", "state": "s", "questions": {"answer": {"type": "noul", "instructions": "Q?"}}}
|
|
917
|
+
self.assertEqual(jev.normalize_response({"answers": {}}, "official", payload["questions"]), {"answers": {}})
|
|
918
|
+
self.assertEqual(jev.normalize_response({"answers": {}}, "vercel", payload["questions"]), {"answers": {}})
|
|
919
|
+
|
|
606
920
|
def test_http_failures_keep_existing_exit_codes(self):
|
|
607
921
|
for status, expected in ((401, 3), (403, 3), (429, 4), (500, 4), (400, 1)):
|
|
608
922
|
error = urllib.error.HTTPError(
|
|
@@ -109,6 +109,21 @@ class McpStdioTransportTest(unittest.IsolatedAsyncioTestCase):
|
|
|
109
109
|
self.assertIn("choice", criteria)
|
|
110
110
|
self.assertIn("score", criteria)
|
|
111
111
|
|
|
112
|
+
async def test_score_descriptions_explain_zero_based_fractional_scores(self):
|
|
113
|
+
schemas = await self.published_schemas()
|
|
114
|
+
run = schemas["run"]
|
|
115
|
+
request = resolve(run, run["properties"]["request"])
|
|
116
|
+
question = resolve(run, request["properties"]["questions"]["additionalProperties"])
|
|
117
|
+
descriptions = {
|
|
118
|
+
"score levels": schemas["score"]["properties"]["levels"]["description"],
|
|
119
|
+
"run criteria": question["properties"]["criteria"]["description"],
|
|
120
|
+
}
|
|
121
|
+
for name, description in descriptions.items():
|
|
122
|
+
with self.subTest(description=name):
|
|
123
|
+
self.assertIn("zero", description)
|
|
124
|
+
self.assertIn("fractional", description)
|
|
125
|
+
self.assertIn("Clef probability-weighted", description)
|
|
126
|
+
|
|
112
127
|
async def test_the_readme_run_example_matches_the_published_request_schema(self):
|
|
113
128
|
schema = (await self.published_schemas())["run"]
|
|
114
129
|
example = readme_run_example()
|
|
@@ -334,7 +349,7 @@ class McpToolBehaviorTest(unittest.IsolatedAsyncioTestCase):
|
|
|
334
349
|
for provider, model in (
|
|
335
350
|
("official", "jev-latest"),
|
|
336
351
|
("vercel", "typesafe-ai/jev"),
|
|
337
|
-
("openrouter", "typesafe/jev-1.
|
|
352
|
+
("openrouter", "typesafe/jev-1.14"),
|
|
338
353
|
):
|
|
339
354
|
with self.subTest(provider=provider):
|
|
340
355
|
_, call = await self.invoke(
|
|
@@ -597,6 +612,55 @@ class McpToolBehaviorTest(unittest.IsolatedAsyncioTestCase):
|
|
|
597
612
|
self.assertNotIn("0.9", result.content[0].text)
|
|
598
613
|
self.assertNotIn("cf-token", result.content[0].text)
|
|
599
614
|
|
|
615
|
+
async def cloudflare_tool(self, name, arguments, answers):
|
|
616
|
+
account = "0123456789abcdef0123456789abcdef"
|
|
617
|
+
body = {"success": True, "result": {"model": "clef-flash", "answers": answers}, "errors": [], "messages": []}
|
|
618
|
+
environment = {"CLOUDFLARE_ACCOUNT_ID": account, "CLOUDFLARE_API_TOKEN": "cf-token"}
|
|
619
|
+
with patch.dict(os.environ, environment), patch(
|
|
620
|
+
"urllib.request.urlopen", return_value=HttpResponse(json.dumps(body).encode())
|
|
621
|
+
):
|
|
622
|
+
return await self.call_tool(name, {**arguments, "provider": "cloudflare"})
|
|
623
|
+
|
|
624
|
+
async def test_cloudflare_missing_requested_answers_are_tool_errors(self):
|
|
625
|
+
batch = {
|
|
626
|
+
"state": "s",
|
|
627
|
+
"questions": {
|
|
628
|
+
"urgent": {"type": "noul", "instructions": "Urgent?"},
|
|
629
|
+
"anger": {"type": "score", "instructions": "Anger?", "criteria": ["Calm", "Angry"]},
|
|
630
|
+
},
|
|
631
|
+
}
|
|
632
|
+
cases = (
|
|
633
|
+
("noul", {"state": "s", "question": "q"}, {}),
|
|
634
|
+
("score", {"state": "s", "question": "q", "levels": ["a", "b"]}, {"other": {"type": "score", "score": 0.7}}),
|
|
635
|
+
("run", {"request": batch}, {"urgent": {"type": "noul", "noul": 0.7}}),
|
|
636
|
+
)
|
|
637
|
+
for name, arguments, answers in cases:
|
|
638
|
+
with self.subTest(tool=name):
|
|
639
|
+
result = await self.cloudflare_tool(name, arguments, answers)
|
|
640
|
+
self.assertTrue(result.is_error)
|
|
641
|
+
self.assertIsNone(result.structured_content)
|
|
642
|
+
self.assertIn("omitted a requested answer", result.content[0].text)
|
|
643
|
+
self.assertNotIn("0.7", result.content[0].text)
|
|
644
|
+
self.assertNotIn("cf-token", result.content[0].text)
|
|
645
|
+
|
|
646
|
+
async def test_cloudflare_complete_answers_keep_zero_and_fractional_scores(self):
|
|
647
|
+
batch = {
|
|
648
|
+
"state": "s",
|
|
649
|
+
"questions": {
|
|
650
|
+
"urgent": {"type": "noul", "instructions": "Urgent?"},
|
|
651
|
+
"anger": {"type": "score", "instructions": "Anger?", "criteria": ["Calm", "Angry"]},
|
|
652
|
+
},
|
|
653
|
+
}
|
|
654
|
+
answers = {"urgent": {"type": "noul", "noul": 0.0}, "anger": {"type": "score", "score": 0.35}}
|
|
655
|
+
result = await self.cloudflare_tool("run", {"request": batch}, answers)
|
|
656
|
+
self.assertFalse(result.is_error)
|
|
657
|
+
self.assertEqual(result.structured_content["answers"], {"urgent": {"noul": 0.0}, "anger": {"score": 0.35}})
|
|
658
|
+
result = await self.cloudflare_tool(
|
|
659
|
+
"score", {"state": "s", "question": "q", "levels": ["a", "b"]}, {"answer": {"type": "score", "score": 0}}
|
|
660
|
+
)
|
|
661
|
+
self.assertFalse(result.is_error)
|
|
662
|
+
self.assertEqual(result.structured_content["answers"], {"answer": {"score": 0}})
|
|
663
|
+
|
|
600
664
|
|
|
601
665
|
if __name__ == "__main__":
|
|
602
666
|
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|