jev-cli 0.6.3__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.6.3 → jev_cli-0.8.0}/PKG-INFO +61 -3
- {jev_cli-0.6.3 → jev_cli-0.8.0}/README.md +60 -2
- {jev_cli-0.6.3 → jev_cli-0.8.0}/pyproject.toml +1 -1
- {jev_cli-0.6.3 → jev_cli-0.8.0}/skills/jev-cli/SKILL.md +2 -2
- {jev_cli-0.6.3/src/jev_cli/bundled_skills → jev_cli-0.8.0/skills}/jev-cli/references/cli.md +13 -1
- {jev_cli-0.6.3 → jev_cli-0.8.0}/src/jev_cli/__init__.py +230 -19
- {jev_cli-0.6.3 → jev_cli-0.8.0}/src/jev_cli/bundled_skills/jev-cli/SKILL.md +2 -2
- {jev_cli-0.6.3/skills → jev_cli-0.8.0/src/jev_cli/bundled_skills}/jev-cli/references/cli.md +13 -1
- {jev_cli-0.6.3 → jev_cli-0.8.0}/src/jev_cli/mcp_server.py +10 -7
- jev_cli-0.8.0/tests/test_jev.py +1007 -0
- {jev_cli-0.6.3 → jev_cli-0.8.0}/tests/test_mcp_server.py +167 -1
- jev_cli-0.6.3/tests/test_jev.py +0 -397
- {jev_cli-0.6.3 → jev_cli-0.8.0}/LICENSE +0 -0
- {jev_cli-0.6.3 → jev_cli-0.8.0}/scripts/embed_skills.py +0 -0
- {jev_cli-0.6.3 → jev_cli-0.8.0}/src/jev_cli/py.typed +0 -0
- {jev_cli-0.6.3 → 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
|
|
@@ -19,6 +19,8 @@ Description-Content-Type: text/markdown
|
|
|
19
19
|
|
|
20
20
|
# jev-cli
|
|
21
21
|
|
|
22
|
+
[](https://www.producthunt.com/products/jev-cli)
|
|
23
|
+
|
|
22
24
|
A small CLI and stdio MCP server for [TypeSafe Jev](https://docs.typesafe.ai/introduction). Send text or JSON state, ask typed questions, and receive machine-readable `noul`, `choice`, or `score` answers.
|
|
23
25
|
|
|
24
26
|
The `jev` command is useful when application code needs a fast classification or judgment instead of generated prose. The `jev-mcp` command exposes the same judgments to MCP hosts over stdio.
|
|
@@ -71,7 +73,7 @@ jev --version
|
|
|
71
73
|
Expected output:
|
|
72
74
|
|
|
73
75
|
```text
|
|
74
|
-
jev 0.
|
|
76
|
+
jev 0.8.0
|
|
75
77
|
```
|
|
76
78
|
|
|
77
79
|
## Authentication
|
|
@@ -97,8 +99,9 @@ Jev is also available through Vercel AI Gateway and OpenRouter. Select a provide
|
|
|
97
99
|
|---|---|---|---|
|
|
98
100
|
| TypeSafe official | `official` | `TYPESAFE_API_KEY` | `jev-latest` |
|
|
99
101
|
| Vercel AI Gateway | `vercel` | `AI_GATEWAY_API_KEY` | `typesafe-ai/jev` |
|
|
100
|
-
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | `typesafe/jev-1.
|
|
102
|
+
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | `typesafe/jev-1.14` |
|
|
101
103
|
| Jev-compatible proxy | `custom` | `JEV_API_KEY` | `JEV_MODEL` or `jev-latest` |
|
|
104
|
+
| Cloudflare Workers AI (Clef) | `cloudflare` | `CLOUDFLARE_API_TOKEN` | `clef-flash` |
|
|
102
105
|
|
|
103
106
|
Store and test a provider-specific key without exposing it in shell history:
|
|
104
107
|
|
|
@@ -135,6 +138,23 @@ jev noul -q 'Is this urgent?' -s 'Restore service today.' --value
|
|
|
135
138
|
|
|
136
139
|
`--endpoint` can replace `JEV_ENDPOINT` for one command. The CLI sends `JEV_API_KEY` to that endpoint as a bearer token, so use only a trusted HTTPS endpoint.
|
|
137
140
|
|
|
141
|
+
### Cloudflare Workers AI (Clef)
|
|
142
|
+
|
|
143
|
+
The `cloudflare` provider runs Cloudflare's Clef decision models through the Workers AI REST API. `clef-flash` is the default; select `clef` with `--model clef`. No other model is accepted for this provider.
|
|
144
|
+
|
|
145
|
+
Create a Cloudflare API token with the **Workers AI** permission (Read and Edit), and set the 32-character account ID. The account ID is not secret and is read from the environment; the token can come from `CLOUDFLARE_API_TOKEN` or the credential store.
|
|
146
|
+
|
|
147
|
+
```bash
|
|
148
|
+
export CLOUDFLARE_ACCOUNT_ID='your-32-character-account-id'
|
|
149
|
+
jev auth set --provider cloudflare # or: export CLOUDFLARE_API_TOKEN='your-api-token'
|
|
150
|
+
jev auth test --provider cloudflare
|
|
151
|
+
|
|
152
|
+
jev noul --provider cloudflare -q 'Is this urgent?' -s 'Restore service today.' --value
|
|
153
|
+
jev noul --provider cloudflare --model clef -q 'Is this urgent?' -s 'Restore service today.' --value
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
The request goes to `https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/@cf/cloudflare/<model>`, where `<model>` is the request's model. A missing or malformed account ID, or an unsupported model, fails before any network access. The CLI unwraps the Workers AI response envelope and prints the same answer keys as the other providers (`noul`, `choice`, `score`, plus `probabilities`, `confidence`, and `legend` when Clef returns them). A response with `success` other than `true`, or without a result object with answers, is an error and prints no decisions. `run` forwards additional request members such as Clef's `images` unchanged.
|
|
157
|
+
|
|
138
158
|
For non-interactive automation, piping the key to `jev auth set` remains supported.
|
|
139
159
|
|
|
140
160
|
`auth status` reports only whether a key is available. `auth test` sends a minimal request to Jev and verifies that the key is accepted. Neither command prints the key.
|
|
@@ -267,6 +287,44 @@ printf '%s' '{"message":"Please respond today"}' | \
|
|
|
267
287
|
--value
|
|
268
288
|
```
|
|
269
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
|
+
|
|
270
328
|
## Batch questions
|
|
271
329
|
|
|
272
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.
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# jev-cli
|
|
2
2
|
|
|
3
|
+
[](https://www.producthunt.com/products/jev-cli)
|
|
4
|
+
|
|
3
5
|
A small CLI and stdio MCP server for [TypeSafe Jev](https://docs.typesafe.ai/introduction). Send text or JSON state, ask typed questions, and receive machine-readable `noul`, `choice`, or `score` answers.
|
|
4
6
|
|
|
5
7
|
The `jev` command is useful when application code needs a fast classification or judgment instead of generated prose. The `jev-mcp` command exposes the same judgments to MCP hosts over stdio.
|
|
@@ -52,7 +54,7 @@ jev --version
|
|
|
52
54
|
Expected output:
|
|
53
55
|
|
|
54
56
|
```text
|
|
55
|
-
jev 0.
|
|
57
|
+
jev 0.8.0
|
|
56
58
|
```
|
|
57
59
|
|
|
58
60
|
## Authentication
|
|
@@ -78,8 +80,9 @@ Jev is also available through Vercel AI Gateway and OpenRouter. Select a provide
|
|
|
78
80
|
|---|---|---|---|
|
|
79
81
|
| TypeSafe official | `official` | `TYPESAFE_API_KEY` | `jev-latest` |
|
|
80
82
|
| Vercel AI Gateway | `vercel` | `AI_GATEWAY_API_KEY` | `typesafe-ai/jev` |
|
|
81
|
-
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | `typesafe/jev-1.
|
|
83
|
+
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | `typesafe/jev-1.14` |
|
|
82
84
|
| Jev-compatible proxy | `custom` | `JEV_API_KEY` | `JEV_MODEL` or `jev-latest` |
|
|
85
|
+
| Cloudflare Workers AI (Clef) | `cloudflare` | `CLOUDFLARE_API_TOKEN` | `clef-flash` |
|
|
83
86
|
|
|
84
87
|
Store and test a provider-specific key without exposing it in shell history:
|
|
85
88
|
|
|
@@ -116,6 +119,23 @@ jev noul -q 'Is this urgent?' -s 'Restore service today.' --value
|
|
|
116
119
|
|
|
117
120
|
`--endpoint` can replace `JEV_ENDPOINT` for one command. The CLI sends `JEV_API_KEY` to that endpoint as a bearer token, so use only a trusted HTTPS endpoint.
|
|
118
121
|
|
|
122
|
+
### Cloudflare Workers AI (Clef)
|
|
123
|
+
|
|
124
|
+
The `cloudflare` provider runs Cloudflare's Clef decision models through the Workers AI REST API. `clef-flash` is the default; select `clef` with `--model clef`. No other model is accepted for this provider.
|
|
125
|
+
|
|
126
|
+
Create a Cloudflare API token with the **Workers AI** permission (Read and Edit), and set the 32-character account ID. The account ID is not secret and is read from the environment; the token can come from `CLOUDFLARE_API_TOKEN` or the credential store.
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
export CLOUDFLARE_ACCOUNT_ID='your-32-character-account-id'
|
|
130
|
+
jev auth set --provider cloudflare # or: export CLOUDFLARE_API_TOKEN='your-api-token'
|
|
131
|
+
jev auth test --provider cloudflare
|
|
132
|
+
|
|
133
|
+
jev noul --provider cloudflare -q 'Is this urgent?' -s 'Restore service today.' --value
|
|
134
|
+
jev noul --provider cloudflare --model clef -q 'Is this urgent?' -s 'Restore service today.' --value
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
The request goes to `https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run/@cf/cloudflare/<model>`, where `<model>` is the request's model. A missing or malformed account ID, or an unsupported model, fails before any network access. The CLI unwraps the Workers AI response envelope and prints the same answer keys as the other providers (`noul`, `choice`, `score`, plus `probabilities`, `confidence`, and `legend` when Clef returns them). A response with `success` other than `true`, or without a result object with answers, is an error and prints no decisions. `run` forwards additional request members such as Clef's `images` unchanged.
|
|
138
|
+
|
|
119
139
|
For non-interactive automation, piping the key to `jev auth set` remains supported.
|
|
120
140
|
|
|
121
141
|
`auth status` reports only whether a key is available. `auth test` sends a minimal request to Jev and verifies that the key is accepted. Neither command prints the key.
|
|
@@ -248,6 +268,44 @@ printf '%s' '{"message":"Please respond today"}' | \
|
|
|
248
268
|
--value
|
|
249
269
|
```
|
|
250
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
|
+
|
|
251
309
|
## Batch questions
|
|
252
310
|
|
|
253
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.
|
|
@@ -42,8 +42,8 @@ Read [references/cli.md](references/cli.md) for copy-paste command forms, inputs
|
|
|
42
42
|
- Give `score` levels in ascending order; the returned number may be fractional.
|
|
43
43
|
- Use `--json-state` only when the state must retain JSON structure.
|
|
44
44
|
- Use `@file` or stdin for long input instead of embedding it in shell arguments. These forms are CLI-only: the MCP tools send `state` verbatim, so read the file in the host and pass its content.
|
|
45
|
-
- The official TypeSafe API is the default. Use `--provider vercel`, `--provider openrouter`, or `--provider
|
|
46
|
-
- Use the provider-specific environment variable only for process-level overrides: `TYPESAFE_API_KEY`, `AI_GATEWAY_API_KEY`, `OPENROUTER_API_KEY`, or `
|
|
45
|
+
- The official TypeSafe API is the default. Use `--provider vercel`, `--provider openrouter`, `--provider custom`, or `--provider cloudflare` only when the caller selects another provider.
|
|
46
|
+
- Use the provider-specific environment variable only for process-level overrides: `TYPESAFE_API_KEY`, `AI_GATEWAY_API_KEY`, `OPENROUTER_API_KEY`, `JEV_API_KEY`, or `CLOUDFLARE_API_TOKEN`. A custom provider also requires `JEV_ENDPOINT`; `JEV_MODEL` is optional. The cloudflare provider also requires `CLOUDFLARE_ACCOUNT_ID` (32 hexadecimal characters) and accepts only `clef-flash` (default) or `clef`. The normal credential store remains under the user's config directory.
|
|
47
47
|
- Treat model output as a structured judgment, not verified fact. Keep consequential actions behind the caller's own validation and authorization rules.
|
|
48
48
|
|
|
49
49
|
## Common pitfalls
|
|
@@ -28,7 +28,7 @@ printf '%s' "$TYPESAFE_API_KEY" | jev auth set
|
|
|
28
28
|
|
|
29
29
|
Resolution order:
|
|
30
30
|
|
|
31
|
-
1. The selected provider's environment variable: `TYPESAFE_API_KEY`, `AI_GATEWAY_API_KEY`, `OPENROUTER_API_KEY`, or `
|
|
31
|
+
1. The selected provider's environment variable: `TYPESAFE_API_KEY`, `AI_GATEWAY_API_KEY`, `OPENROUTER_API_KEY`, `JEV_API_KEY`, or `CLOUDFLARE_API_TOKEN`
|
|
32
32
|
2. `$XDG_CONFIG_HOME/jev-cli/credentials.json`
|
|
33
33
|
3. `~/.config/jev-cli/credentials.json`
|
|
34
34
|
|
|
@@ -57,6 +57,18 @@ jev noul -q 'Is this urgent?' -s 'Restore service today.' --value
|
|
|
57
57
|
|
|
58
58
|
Set `JEV_MODEL` or pass `--model` when the proxy requires a different model name. Use only a trusted HTTPS endpoint because the custom bearer key is sent to it.
|
|
59
59
|
|
|
60
|
+
For Cloudflare Workers AI Clef models (API token with the Workers AI Read and Edit permission):
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
export CLOUDFLARE_ACCOUNT_ID='your-32-character-account-id'
|
|
64
|
+
jev auth set --provider cloudflare
|
|
65
|
+
jev auth test --provider cloudflare
|
|
66
|
+
jev noul --provider cloudflare -q 'Is this urgent?' -s 'Restore service today.' --value
|
|
67
|
+
jev noul --provider cloudflare --model clef -q 'Is this urgent?' -s 'Restore service today.' --value
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`clef-flash` is the default and `clef` the only alternative; the request model selects the Workers AI URL. A missing or malformed account ID or an unsupported model fails before network access. The Workers AI envelope is unwrapped into the usual `noul`, `choice`, and `score` answers; a failed or malformed envelope is an error with no decisions.
|
|
71
|
+
|
|
60
72
|
## Typed questions
|
|
61
73
|
|
|
62
74
|
Use `-q` for `--question` and `-s` for `--state` when a shorter command is useful. `--value` has no short form.
|
|
@@ -4,9 +4,12 @@
|
|
|
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
|
|
12
|
+
import re
|
|
10
13
|
import shutil
|
|
11
14
|
import sys
|
|
12
15
|
import tempfile
|
|
@@ -29,14 +32,22 @@ PROVIDERS = {
|
|
|
29
32
|
"openrouter": {
|
|
30
33
|
"endpoint": "https://openrouter.ai/api/alpha/decisions",
|
|
31
34
|
"key_env": "OPENROUTER_API_KEY",
|
|
32
|
-
"model": "typesafe/jev-1.
|
|
35
|
+
"model": "typesafe/jev-1.14",
|
|
33
36
|
},
|
|
34
37
|
"custom": {
|
|
35
38
|
"endpoint": None,
|
|
36
39
|
"key_env": "JEV_API_KEY",
|
|
37
40
|
"model": "jev-latest",
|
|
38
41
|
},
|
|
42
|
+
# The Workers AI URL depends on the account and model, so it is built by provider_endpoint.
|
|
43
|
+
"cloudflare": {
|
|
44
|
+
"endpoint": None,
|
|
45
|
+
"key_env": "CLOUDFLARE_API_TOKEN",
|
|
46
|
+
"model": "clef-flash",
|
|
47
|
+
},
|
|
39
48
|
}
|
|
49
|
+
CLOUDFLARE_ENDPOINT = "https://api.cloudflare.com/client/v4/accounts/{account}/ai/run/@cf/cloudflare/{model}"
|
|
50
|
+
CLOUDFLARE_MODELS = ("clef", "clef-flash")
|
|
40
51
|
API_URL = PROVIDERS["official"]["endpoint"]
|
|
41
52
|
CREDENTIALS_FILE = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "jev-cli" / "credentials.json"
|
|
42
53
|
BUNDLED_SKILLS = Path(__file__).with_name("bundled_skills")
|
|
@@ -200,6 +211,144 @@ def state_value(value: str | None, force_json: bool) -> Any:
|
|
|
200
211
|
return text
|
|
201
212
|
|
|
202
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
|
+
|
|
203
352
|
def split_pair(value: str) -> tuple[str, str]:
|
|
204
353
|
key, separator, description = value.partition("=")
|
|
205
354
|
if not separator or not key or not description:
|
|
@@ -235,7 +384,32 @@ def provider_request(payload: dict[str, Any], provider: str) -> tuple[dict[str,
|
|
|
235
384
|
return payload, headers
|
|
236
385
|
|
|
237
386
|
|
|
238
|
-
def
|
|
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
|
+
"""
|
|
393
|
+
if envelope.get("success") is not True:
|
|
394
|
+
# Envelope errors are not reflected: they may echo request content.
|
|
395
|
+
raise CliError("Cloudflare Workers AI reported a failed request", 1)
|
|
396
|
+
result = envelope.get("result")
|
|
397
|
+
if not isinstance(result, dict) or not isinstance(answers := result.get("answers"), dict):
|
|
398
|
+
raise CliError("Cloudflare Workers AI returned a malformed result", 1)
|
|
399
|
+
if not all(isinstance(answer, dict) for answer in answers.values()):
|
|
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)
|
|
404
|
+
return {
|
|
405
|
+
**result,
|
|
406
|
+
"answers": {name: {k: v for k, v in answer.items() if k != "type"} for name, answer in answers.items()},
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def normalize_response(result: dict[str, Any], provider: str, questions: Any = None) -> dict[str, Any]:
|
|
411
|
+
if provider == "cloudflare":
|
|
412
|
+
return cloudflare_result(result, questions)
|
|
239
413
|
if provider != "vercel":
|
|
240
414
|
return result
|
|
241
415
|
result = dict(result)
|
|
@@ -250,7 +424,26 @@ def normalize_response(result: dict[str, Any], provider: str) -> dict[str, Any]:
|
|
|
250
424
|
return result
|
|
251
425
|
|
|
252
426
|
|
|
253
|
-
|
|
427
|
+
_DEFAULT_MODEL: Any = object()
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def provider_endpoint(provider: str, override: str | None = None, model: Any = _DEFAULT_MODEL) -> str:
|
|
431
|
+
"""Resolve the request URL; `model` is the effective payload model and matters only for cloudflare.
|
|
432
|
+
|
|
433
|
+
Only an omitted `model` falls back to the provider default; an explicit value, even a falsy one,
|
|
434
|
+
must be a supported Cloudflare model so the URL model always equals the body model.
|
|
435
|
+
"""
|
|
436
|
+
if provider == "cloudflare":
|
|
437
|
+
if model is _DEFAULT_MODEL:
|
|
438
|
+
model = PROVIDERS[provider]["model"]
|
|
439
|
+
if not isinstance(model, str) or model not in CLOUDFLARE_MODELS:
|
|
440
|
+
raise CliError(f"cloudflare provider supports only models: {', '.join(CLOUDFLARE_MODELS)}", 2)
|
|
441
|
+
if override:
|
|
442
|
+
return override
|
|
443
|
+
account = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "")
|
|
444
|
+
if not re.fullmatch(r"[0-9a-fA-F]{32}", account):
|
|
445
|
+
raise CliError("cloudflare provider requires CLOUDFLARE_ACCOUNT_ID (32 hexadecimal characters)", 2)
|
|
446
|
+
return CLOUDFLARE_ENDPOINT.format(account=account, model=model)
|
|
254
447
|
if override:
|
|
255
448
|
return override
|
|
256
449
|
if provider == "custom":
|
|
@@ -272,6 +465,7 @@ def provider_model(provider: str) -> str:
|
|
|
272
465
|
|
|
273
466
|
|
|
274
467
|
def call(payload: dict[str, Any], endpoint: str, provider: str = "official") -> dict[str, Any]:
|
|
468
|
+
questions = payload.get("questions")
|
|
275
469
|
payload, provider_headers = provider_request(payload, provider)
|
|
276
470
|
request = urllib.request.Request(
|
|
277
471
|
endpoint,
|
|
@@ -279,8 +473,9 @@ def call(payload: dict[str, Any], endpoint: str, provider: str = "official") ->
|
|
|
279
473
|
headers={
|
|
280
474
|
"Authorization": f"Bearer {api_key(provider)}",
|
|
281
475
|
"Content-Type": "application/json",
|
|
282
|
-
"User-Agent": "jev-cli/0.
|
|
476
|
+
"User-Agent": "jev-cli/0.8.0",
|
|
283
477
|
**provider_headers,
|
|
478
|
+
**({IMAGE_HEADER: "true"} if payload.get("assets") else {}),
|
|
284
479
|
},
|
|
285
480
|
method="POST",
|
|
286
481
|
)
|
|
@@ -288,20 +483,21 @@ def call(payload: dict[str, Any], endpoint: str, provider: str = "official") ->
|
|
|
288
483
|
with urllib.request.urlopen(request, timeout=60) as response:
|
|
289
484
|
result = json.load(response)
|
|
290
485
|
except urllib.error.HTTPError as exc:
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
detail =
|
|
294
|
-
|
|
295
|
-
|
|
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)
|
|
296
492
|
code = 3 if exc.code in (401, 403) else 4 if exc.code in (429, 500, 502, 503, 504) else 1
|
|
297
|
-
raise CliError(f"API HTTP {exc.code}: {
|
|
493
|
+
raise CliError(f"API HTTP {exc.code}: {detail}", code) from exc
|
|
298
494
|
except json.JSONDecodeError as exc:
|
|
299
495
|
raise CliError(f"API returned invalid JSON: {exc}", 4) from exc
|
|
300
496
|
except (urllib.error.URLError, TimeoutError) as exc:
|
|
301
497
|
raise CliError(f"API connection failed: {exc}", 4) from exc
|
|
302
498
|
if not isinstance(result, dict):
|
|
303
499
|
raise CliError("API returned a non-object response", 1)
|
|
304
|
-
return normalize_response(result, provider)
|
|
500
|
+
return normalize_response(result, provider, questions)
|
|
305
501
|
|
|
306
502
|
|
|
307
503
|
def common_parser() -> argparse.ArgumentParser:
|
|
@@ -326,7 +522,7 @@ def parser() -> argparse.ArgumentParser:
|
|
|
326
522
|
prog="jev",
|
|
327
523
|
description="Evaluate text or JSON with TypeSafe Jev. Uses its own local credential store.",
|
|
328
524
|
)
|
|
329
|
-
root.add_argument("--version", action="version", version="jev 0.
|
|
525
|
+
root.add_argument("--version", action="version", version="jev 0.8.0")
|
|
330
526
|
sub = root.add_subparsers(dest="command", required=True)
|
|
331
527
|
common = common_parser()
|
|
332
528
|
|
|
@@ -346,16 +542,19 @@ def parser() -> argparse.ArgumentParser:
|
|
|
346
542
|
|
|
347
543
|
noul = sub.add_parser("noul", parents=[common], help="answer one yes/no question with a probability")
|
|
348
544
|
noul.add_argument("-q", "--question", required=True, help="question to answer")
|
|
349
|
-
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)")
|
|
350
547
|
|
|
351
548
|
choice = sub.add_parser("choice", parents=[common], help="choose one option")
|
|
352
549
|
choice.add_argument("-q", "--question", required=True, help="question to answer")
|
|
353
|
-
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)")
|
|
354
552
|
choice.add_argument("-o", "--option", action="append", type=split_pair, required=True, metavar="KEY=DESCRIPTION")
|
|
355
553
|
|
|
356
554
|
score = sub.add_parser("score", parents=[common], help="score against ordered levels")
|
|
357
555
|
score.add_argument("-q", "--question", required=True, help="question to answer")
|
|
358
|
-
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)")
|
|
359
558
|
score.add_argument("-l", "--level", action="append", required=True, metavar="DESCRIPTION")
|
|
360
559
|
|
|
361
560
|
run = sub.add_parser("run", parents=[common], help="send a complete request JSON for batched questions")
|
|
@@ -378,13 +577,23 @@ def request_for(args: argparse.Namespace) -> tuple[dict[str, Any], str | None]:
|
|
|
378
577
|
return payload, None
|
|
379
578
|
|
|
380
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)
|
|
381
588
|
payload = question_request(
|
|
382
589
|
args.command,
|
|
383
|
-
|
|
590
|
+
state,
|
|
384
591
|
args.question,
|
|
385
592
|
criteria,
|
|
386
593
|
args.model or provider_model(args.provider),
|
|
387
594
|
)
|
|
595
|
+
if args.image:
|
|
596
|
+
payload = attach_images(payload, args.image)
|
|
388
597
|
return payload, args.command
|
|
389
598
|
|
|
390
599
|
|
|
@@ -403,10 +612,11 @@ def main() -> int:
|
|
|
403
612
|
set_api_key(args.provider)
|
|
404
613
|
print(json.dumps({"ok": True, "stored": True, "store": str(CREDENTIALS_FILE)}))
|
|
405
614
|
elif args.auth_command == "test":
|
|
615
|
+
model = provider_model(args.provider)
|
|
406
616
|
result = call(
|
|
407
617
|
{
|
|
408
618
|
"state": "authentication test",
|
|
409
|
-
"model":
|
|
619
|
+
"model": model,
|
|
410
620
|
"questions": {
|
|
411
621
|
"answer": {
|
|
412
622
|
"type": "noul",
|
|
@@ -414,7 +624,7 @@ def main() -> int:
|
|
|
414
624
|
}
|
|
415
625
|
},
|
|
416
626
|
},
|
|
417
|
-
provider_endpoint(args.provider),
|
|
627
|
+
provider_endpoint(args.provider, None, model),
|
|
418
628
|
args.provider,
|
|
419
629
|
)
|
|
420
630
|
print(json.dumps({"ok": True, "valid": True, "model": result.get("model")}))
|
|
@@ -428,7 +638,8 @@ def main() -> int:
|
|
|
428
638
|
if args.provider not in PROVIDERS:
|
|
429
639
|
raise CliError(f"invalid JEV_PROVIDER: {args.provider}")
|
|
430
640
|
payload, kind = request_for(args)
|
|
431
|
-
|
|
641
|
+
endpoint = provider_endpoint(args.provider, args.endpoint, payload["model"])
|
|
642
|
+
result = call(payload, endpoint, args.provider)
|
|
432
643
|
if args.value:
|
|
433
644
|
print(primary_value(result, kind))
|
|
434
645
|
else:
|
|
@@ -42,8 +42,8 @@ Read [references/cli.md](references/cli.md) for copy-paste command forms, inputs
|
|
|
42
42
|
- Give `score` levels in ascending order; the returned number may be fractional.
|
|
43
43
|
- Use `--json-state` only when the state must retain JSON structure.
|
|
44
44
|
- Use `@file` or stdin for long input instead of embedding it in shell arguments. These forms are CLI-only: the MCP tools send `state` verbatim, so read the file in the host and pass its content.
|
|
45
|
-
- The official TypeSafe API is the default. Use `--provider vercel`, `--provider openrouter`, or `--provider
|
|
46
|
-
- Use the provider-specific environment variable only for process-level overrides: `TYPESAFE_API_KEY`, `AI_GATEWAY_API_KEY`, `OPENROUTER_API_KEY`, or `
|
|
45
|
+
- The official TypeSafe API is the default. Use `--provider vercel`, `--provider openrouter`, `--provider custom`, or `--provider cloudflare` only when the caller selects another provider.
|
|
46
|
+
- Use the provider-specific environment variable only for process-level overrides: `TYPESAFE_API_KEY`, `AI_GATEWAY_API_KEY`, `OPENROUTER_API_KEY`, `JEV_API_KEY`, or `CLOUDFLARE_API_TOKEN`. A custom provider also requires `JEV_ENDPOINT`; `JEV_MODEL` is optional. The cloudflare provider also requires `CLOUDFLARE_ACCOUNT_ID` (32 hexadecimal characters) and accepts only `clef-flash` (default) or `clef`. The normal credential store remains under the user's config directory.
|
|
47
47
|
- Treat model output as a structured judgment, not verified fact. Keep consequential actions behind the caller's own validation and authorization rules.
|
|
48
48
|
|
|
49
49
|
## Common pitfalls
|