jev-cli 0.6.2__tar.gz → 0.7.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.2 → jev_cli-0.7.0}/PKG-INFO +22 -2
- {jev_cli-0.6.2 → jev_cli-0.7.0}/README.md +21 -1
- {jev_cli-0.6.2 → jev_cli-0.7.0}/pyproject.toml +1 -1
- {jev_cli-0.6.2 → jev_cli-0.7.0}/skills/jev-cli/SKILL.md +2 -2
- {jev_cli-0.6.2/src/jev_cli/bundled_skills → jev_cli-0.7.0/skills}/jev-cli/references/cli.md +13 -1
- {jev_cli-0.6.2 → jev_cli-0.7.0}/src/jev_cli/__init__.py +56 -6
- {jev_cli-0.6.2 → jev_cli-0.7.0}/src/jev_cli/bundled_skills/jev-cli/SKILL.md +2 -2
- {jev_cli-0.6.2/skills → jev_cli-0.7.0/src/jev_cli/bundled_skills}/jev-cli/references/cli.md +13 -1
- {jev_cli-0.6.2 → jev_cli-0.7.0}/src/jev_cli/mcp_server.py +3 -3
- {jev_cli-0.6.2 → jev_cli-0.7.0}/tests/test_jev.py +304 -0
- {jev_cli-0.6.2 → jev_cli-0.7.0}/tests/test_mcp_server.py +102 -0
- {jev_cli-0.6.2 → jev_cli-0.7.0}/LICENSE +0 -0
- {jev_cli-0.6.2 → jev_cli-0.7.0}/scripts/embed_skills.py +0 -0
- {jev_cli-0.6.2 → jev_cli-0.7.0}/src/jev_cli/py.typed +0 -0
- {jev_cli-0.6.2 → jev_cli-0.7.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.7.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.7.0
|
|
75
77
|
```
|
|
76
78
|
|
|
77
79
|
## Authentication
|
|
@@ -99,6 +101,7 @@ Jev is also available through Vercel AI Gateway and OpenRouter. Select a provide
|
|
|
99
101
|
| Vercel AI Gateway | `vercel` | `AI_GATEWAY_API_KEY` | `typesafe-ai/jev` |
|
|
100
102
|
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | `typesafe/jev-1.13` |
|
|
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.
|
|
@@ -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.7.0
|
|
56
58
|
```
|
|
57
59
|
|
|
58
60
|
## Authentication
|
|
@@ -80,6 +82,7 @@ Jev is also available through Vercel AI Gateway and OpenRouter. Select a provide
|
|
|
80
82
|
| Vercel AI Gateway | `vercel` | `AI_GATEWAY_API_KEY` | `typesafe-ai/jev` |
|
|
81
83
|
| OpenRouter | `openrouter` | `OPENROUTER_API_KEY` | `typesafe/jev-1.13` |
|
|
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.
|
|
@@ -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.
|
|
@@ -7,6 +7,7 @@ import argparse
|
|
|
7
7
|
import getpass
|
|
8
8
|
import json
|
|
9
9
|
import os
|
|
10
|
+
import re
|
|
10
11
|
import shutil
|
|
11
12
|
import sys
|
|
12
13
|
import tempfile
|
|
@@ -36,7 +37,15 @@ PROVIDERS = {
|
|
|
36
37
|
"key_env": "JEV_API_KEY",
|
|
37
38
|
"model": "jev-latest",
|
|
38
39
|
},
|
|
40
|
+
# The Workers AI URL depends on the account and model, so it is built by provider_endpoint.
|
|
41
|
+
"cloudflare": {
|
|
42
|
+
"endpoint": None,
|
|
43
|
+
"key_env": "CLOUDFLARE_API_TOKEN",
|
|
44
|
+
"model": "clef-flash",
|
|
45
|
+
},
|
|
39
46
|
}
|
|
47
|
+
CLOUDFLARE_ENDPOINT = "https://api.cloudflare.com/client/v4/accounts/{account}/ai/run/@cf/cloudflare/{model}"
|
|
48
|
+
CLOUDFLARE_MODELS = ("clef", "clef-flash")
|
|
40
49
|
API_URL = PROVIDERS["official"]["endpoint"]
|
|
41
50
|
CREDENTIALS_FILE = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "jev-cli" / "credentials.json"
|
|
42
51
|
BUNDLED_SKILLS = Path(__file__).with_name("bundled_skills")
|
|
@@ -235,7 +244,25 @@ def provider_request(payload: dict[str, Any], provider: str) -> tuple[dict[str,
|
|
|
235
244
|
return payload, headers
|
|
236
245
|
|
|
237
246
|
|
|
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."""
|
|
249
|
+
if envelope.get("success") is not True:
|
|
250
|
+
# Envelope errors are not reflected: they may echo request content.
|
|
251
|
+
raise CliError("Cloudflare Workers AI reported a failed request", 1)
|
|
252
|
+
result = envelope.get("result")
|
|
253
|
+
if not isinstance(result, dict) or not isinstance(answers := result.get("answers"), dict):
|
|
254
|
+
raise CliError("Cloudflare Workers AI returned a malformed result", 1)
|
|
255
|
+
if not all(isinstance(answer, dict) for answer in answers.values()):
|
|
256
|
+
raise CliError("Cloudflare Workers AI returned a malformed answer", 1)
|
|
257
|
+
return {
|
|
258
|
+
**result,
|
|
259
|
+
"answers": {name: {k: v for k, v in answer.items() if k != "type"} for name, answer in answers.items()},
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
|
|
238
263
|
def normalize_response(result: dict[str, Any], provider: str) -> dict[str, Any]:
|
|
264
|
+
if provider == "cloudflare":
|
|
265
|
+
return cloudflare_result(result)
|
|
239
266
|
if provider != "vercel":
|
|
240
267
|
return result
|
|
241
268
|
result = dict(result)
|
|
@@ -250,7 +277,26 @@ def normalize_response(result: dict[str, Any], provider: str) -> dict[str, Any]:
|
|
|
250
277
|
return result
|
|
251
278
|
|
|
252
279
|
|
|
253
|
-
|
|
280
|
+
_DEFAULT_MODEL: Any = object()
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def provider_endpoint(provider: str, override: str | None = None, model: Any = _DEFAULT_MODEL) -> str:
|
|
284
|
+
"""Resolve the request URL; `model` is the effective payload model and matters only for cloudflare.
|
|
285
|
+
|
|
286
|
+
Only an omitted `model` falls back to the provider default; an explicit value, even a falsy one,
|
|
287
|
+
must be a supported Cloudflare model so the URL model always equals the body model.
|
|
288
|
+
"""
|
|
289
|
+
if provider == "cloudflare":
|
|
290
|
+
if model is _DEFAULT_MODEL:
|
|
291
|
+
model = PROVIDERS[provider]["model"]
|
|
292
|
+
if not isinstance(model, str) or model not in CLOUDFLARE_MODELS:
|
|
293
|
+
raise CliError(f"cloudflare provider supports only models: {', '.join(CLOUDFLARE_MODELS)}", 2)
|
|
294
|
+
if override:
|
|
295
|
+
return override
|
|
296
|
+
account = os.environ.get("CLOUDFLARE_ACCOUNT_ID", "")
|
|
297
|
+
if not re.fullmatch(r"[0-9a-fA-F]{32}", account):
|
|
298
|
+
raise CliError("cloudflare provider requires CLOUDFLARE_ACCOUNT_ID (32 hexadecimal characters)", 2)
|
|
299
|
+
return CLOUDFLARE_ENDPOINT.format(account=account, model=model)
|
|
254
300
|
if override:
|
|
255
301
|
return override
|
|
256
302
|
if provider == "custom":
|
|
@@ -279,7 +325,7 @@ def call(payload: dict[str, Any], endpoint: str, provider: str = "official") ->
|
|
|
279
325
|
headers={
|
|
280
326
|
"Authorization": f"Bearer {api_key(provider)}",
|
|
281
327
|
"Content-Type": "application/json",
|
|
282
|
-
"User-Agent": "jev-cli/0.
|
|
328
|
+
"User-Agent": "jev-cli/0.7.0",
|
|
283
329
|
**provider_headers,
|
|
284
330
|
},
|
|
285
331
|
method="POST",
|
|
@@ -295,6 +341,8 @@ def call(payload: dict[str, Any], endpoint: str, provider: str = "official") ->
|
|
|
295
341
|
detail = body
|
|
296
342
|
code = 3 if exc.code in (401, 403) else 4 if exc.code in (429, 500, 502, 503, 504) else 1
|
|
297
343
|
raise CliError(f"API HTTP {exc.code}: {json.dumps(detail, ensure_ascii=False)}", code) from exc
|
|
344
|
+
except json.JSONDecodeError as exc:
|
|
345
|
+
raise CliError(f"API returned invalid JSON: {exc}", 4) from exc
|
|
298
346
|
except (urllib.error.URLError, TimeoutError) as exc:
|
|
299
347
|
raise CliError(f"API connection failed: {exc}", 4) from exc
|
|
300
348
|
if not isinstance(result, dict):
|
|
@@ -324,7 +372,7 @@ def parser() -> argparse.ArgumentParser:
|
|
|
324
372
|
prog="jev",
|
|
325
373
|
description="Evaluate text or JSON with TypeSafe Jev. Uses its own local credential store.",
|
|
326
374
|
)
|
|
327
|
-
root.add_argument("--version", action="version", version="jev 0.
|
|
375
|
+
root.add_argument("--version", action="version", version="jev 0.7.0")
|
|
328
376
|
sub = root.add_subparsers(dest="command", required=True)
|
|
329
377
|
common = common_parser()
|
|
330
378
|
|
|
@@ -401,10 +449,11 @@ def main() -> int:
|
|
|
401
449
|
set_api_key(args.provider)
|
|
402
450
|
print(json.dumps({"ok": True, "stored": True, "store": str(CREDENTIALS_FILE)}))
|
|
403
451
|
elif args.auth_command == "test":
|
|
452
|
+
model = provider_model(args.provider)
|
|
404
453
|
result = call(
|
|
405
454
|
{
|
|
406
455
|
"state": "authentication test",
|
|
407
|
-
"model":
|
|
456
|
+
"model": model,
|
|
408
457
|
"questions": {
|
|
409
458
|
"answer": {
|
|
410
459
|
"type": "noul",
|
|
@@ -412,7 +461,7 @@ def main() -> int:
|
|
|
412
461
|
}
|
|
413
462
|
},
|
|
414
463
|
},
|
|
415
|
-
provider_endpoint(args.provider),
|
|
464
|
+
provider_endpoint(args.provider, None, model),
|
|
416
465
|
args.provider,
|
|
417
466
|
)
|
|
418
467
|
print(json.dumps({"ok": True, "valid": True, "model": result.get("model")}))
|
|
@@ -426,7 +475,8 @@ def main() -> int:
|
|
|
426
475
|
if args.provider not in PROVIDERS:
|
|
427
476
|
raise CliError(f"invalid JEV_PROVIDER: {args.provider}")
|
|
428
477
|
payload, kind = request_for(args)
|
|
429
|
-
|
|
478
|
+
endpoint = provider_endpoint(args.provider, args.endpoint, payload["model"])
|
|
479
|
+
result = call(payload, endpoint, args.provider)
|
|
430
480
|
if args.value:
|
|
431
481
|
print(primary_value(result, kind))
|
|
432
482
|
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
|
|
@@ -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.
|
|
@@ -27,7 +27,7 @@ from . import (
|
|
|
27
27
|
question_request,
|
|
28
28
|
)
|
|
29
29
|
|
|
30
|
-
Provider = Literal["official", "vercel", "openrouter", "custom"]
|
|
30
|
+
Provider = Literal["official", "vercel", "openrouter", "custom", "cloudflare"]
|
|
31
31
|
|
|
32
32
|
State = Annotated[
|
|
33
33
|
Any,
|
|
@@ -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.7.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, "
|
|
@@ -154,7 +154,7 @@ def selected_provider(provider: str | None) -> str:
|
|
|
154
154
|
def evaluate(payload: dict[str, Any], provider: str, endpoint: str | None) -> dict[str, Any]:
|
|
155
155
|
"""Send a prepared request through the shared client and bound every failure to a tool error."""
|
|
156
156
|
try:
|
|
157
|
-
return call(payload, provider_endpoint(provider, endpoint), provider)
|
|
157
|
+
return call(payload, provider_endpoint(provider, endpoint, payload["model"]), provider)
|
|
158
158
|
except CliError as exc:
|
|
159
159
|
raise ToolError(str(exc)) from exc
|
|
160
160
|
except (KeyError, TypeError) as exc:
|
|
@@ -184,6 +184,7 @@ class JevTest(unittest.TestCase):
|
|
|
184
184
|
"vercel": "typesafe-ai/jev",
|
|
185
185
|
"openrouter": "typesafe/jev-1.13",
|
|
186
186
|
"custom": "jev-latest",
|
|
187
|
+
"cloudflare": "clef-flash",
|
|
187
188
|
}
|
|
188
189
|
for provider, model in cases.items():
|
|
189
190
|
args = jev.parser().parse_args(
|
|
@@ -309,6 +310,7 @@ class JevTest(unittest.TestCase):
|
|
|
309
310
|
"official": {"answers": {}},
|
|
310
311
|
"openrouter": {"answers": {}},
|
|
311
312
|
"custom": {"answers": {}},
|
|
313
|
+
"cloudflare": {"success": True, "result": {"model": "clef-flash", "answers": {}}, "errors": []},
|
|
312
314
|
"vercel": {
|
|
313
315
|
"answers": {
|
|
314
316
|
"urgent": {"type": "boolean", "probability": 0.9},
|
|
@@ -319,6 +321,8 @@ class JevTest(unittest.TestCase):
|
|
|
319
321
|
}
|
|
320
322
|
for provider, config in jev.PROVIDERS.items():
|
|
321
323
|
captured = []
|
|
324
|
+
# Providers without a fixed endpoint (custom, cloudflare) are given one explicitly;
|
|
325
|
+
# call() is the transport and does not resolve or validate endpoints itself.
|
|
322
326
|
endpoint = config["endpoint"] or "https://proxy.example.test/v1/systemone"
|
|
323
327
|
|
|
324
328
|
def open_url(request, timeout):
|
|
@@ -341,6 +345,9 @@ class JevTest(unittest.TestCase):
|
|
|
341
345
|
self.assertEqual(result["answers"]["urgent"], {"noul": 0.9})
|
|
342
346
|
self.assertEqual(result["answers"]["route"]["choice"], "a")
|
|
343
347
|
self.assertEqual(result["answers"]["quality"]["score"], 1.0)
|
|
348
|
+
elif provider == "cloudflare":
|
|
349
|
+
self.assertEqual(body, payload)
|
|
350
|
+
self.assertEqual(result, {"model": "clef-flash", "answers": {}})
|
|
344
351
|
else:
|
|
345
352
|
self.assertEqual(body, payload)
|
|
346
353
|
|
|
@@ -369,6 +376,14 @@ class JevTest(unittest.TestCase):
|
|
|
369
376
|
jev.call({"state": "test", "questions": {}}, "https://example.test")
|
|
370
377
|
self.assertEqual(raised.exception.exit_code, 4)
|
|
371
378
|
|
|
379
|
+
def test_call_maps_non_json_success_response_to_exit_code_4(self):
|
|
380
|
+
with patch.object(jev, "api_key", return_value="test-key"), patch(
|
|
381
|
+
"urllib.request.urlopen", return_value=io.BytesIO(b"<html>gateway timeout</html>")
|
|
382
|
+
):
|
|
383
|
+
with self.assertRaisesRegex(jev.CliError, "API returned invalid JSON") as raised:
|
|
384
|
+
jev.call({"state": "test", "questions": {}}, "https://example.test")
|
|
385
|
+
self.assertEqual(raised.exception.exit_code, 4)
|
|
386
|
+
|
|
372
387
|
def test_main_prints_only_primary_value(self):
|
|
373
388
|
argv = ["jev", "noul", "--question", "Urgent?", "--state", "today", "--value"]
|
|
374
389
|
with patch("sys.argv", argv), patch.object(
|
|
@@ -385,5 +400,294 @@ class JevTest(unittest.TestCase):
|
|
|
385
400
|
self.assertEqual(json.loads(stderr.getvalue())["ok"], False)
|
|
386
401
|
|
|
387
402
|
|
|
403
|
+
CLOUDFLARE_ACCOUNT = "0123456789abcdef0123456789ABCDEF"
|
|
404
|
+
CLOUDFLARE_ENVIRONMENT = {"CLOUDFLARE_ACCOUNT_ID": CLOUDFLARE_ACCOUNT, "CLOUDFLARE_API_TOKEN": "cf-token"}
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def cloudflare_url(model: str) -> str:
|
|
408
|
+
return f"https://api.cloudflare.com/client/v4/accounts/{CLOUDFLARE_ACCOUNT}/ai/run/@cf/cloudflare/{model}"
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def cloudflare_envelope(answers: dict) -> dict:
|
|
412
|
+
"""A successful Workers AI REST envelope as documented by the Clef output schema."""
|
|
413
|
+
return {
|
|
414
|
+
"success": True,
|
|
415
|
+
"result": {"model": "clef-flash", "answers": answers, "usage": {"input_tokens": 12, "output_tokens": 3}},
|
|
416
|
+
"errors": [],
|
|
417
|
+
"messages": [],
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
TYPED_CLOUDFLARE_ANSWERS = {
|
|
422
|
+
"urgent": {"type": "noul", "noul": 0.82},
|
|
423
|
+
"route": {"type": "choice", "choice": "tech", "probabilities": {"tech": 0.7, "sales": 0.3}, "confidence": 0.55},
|
|
424
|
+
"anger": {
|
|
425
|
+
"type": "score",
|
|
426
|
+
"score": 1.4,
|
|
427
|
+
"legend": {"0": "Calm", "1": "Concerned", "2": "Angry"},
|
|
428
|
+
"probabilities": {"0": 0.1, "1": 0.4, "2": 0.5},
|
|
429
|
+
"confidence": 0.3,
|
|
430
|
+
},
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
class HttpResponse(io.BytesIO):
|
|
435
|
+
def __enter__(self):
|
|
436
|
+
return self
|
|
437
|
+
|
|
438
|
+
def __exit__(self, *args):
|
|
439
|
+
self.close()
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
class CloudflareProviderTest(unittest.TestCase):
|
|
443
|
+
def run_main(self, argv, body=None, environment=CLOUDFLARE_ENVIRONMENT, stdin=None):
|
|
444
|
+
"""Run the CLI against a fake Workers AI endpoint and return (exit, stdout, stderr, requests)."""
|
|
445
|
+
captured = []
|
|
446
|
+
|
|
447
|
+
def open_url(request, timeout):
|
|
448
|
+
captured.append(request)
|
|
449
|
+
return HttpResponse(json.dumps(body).encode())
|
|
450
|
+
|
|
451
|
+
stdout, stderr = io.StringIO(), io.StringIO()
|
|
452
|
+
with patch.dict(os.environ, environment, clear=True), patch("sys.argv", ["jev", *argv]), patch(
|
|
453
|
+
"urllib.request.urlopen", side_effect=open_url
|
|
454
|
+
), patch("sys.stdout", stdout), patch("sys.stderr", stderr), patch(
|
|
455
|
+
"sys.stdin", stdin or io.StringIO("")
|
|
456
|
+
):
|
|
457
|
+
code = jev.main()
|
|
458
|
+
return code, stdout.getvalue(), stderr.getvalue(), captured
|
|
459
|
+
|
|
460
|
+
def test_endpoint_follows_the_selected_model(self):
|
|
461
|
+
with patch.dict(os.environ, {"CLOUDFLARE_ACCOUNT_ID": CLOUDFLARE_ACCOUNT}, clear=True):
|
|
462
|
+
self.assertEqual(jev.provider_endpoint("cloudflare"), cloudflare_url("clef-flash"))
|
|
463
|
+
self.assertEqual(jev.provider_endpoint("cloudflare", None, "clef-flash"), cloudflare_url("clef-flash"))
|
|
464
|
+
self.assertEqual(jev.provider_endpoint("cloudflare", None, "clef"), cloudflare_url("clef"))
|
|
465
|
+
|
|
466
|
+
def test_other_providers_ignore_the_model_argument(self):
|
|
467
|
+
with patch.dict(os.environ, {}, clear=True):
|
|
468
|
+
self.assertEqual(jev.provider_endpoint("official", None, "anything"), jev.API_URL)
|
|
469
|
+
self.assertEqual(
|
|
470
|
+
jev.provider_endpoint("openrouter", None, "clef"), jev.PROVIDERS["openrouter"]["endpoint"]
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
def test_cli_posts_each_model_to_its_url_with_bearer_token(self):
|
|
474
|
+
for model, extra in (("clef-flash", []), ("clef", ["--model", "clef"])):
|
|
475
|
+
with self.subTest(model=model):
|
|
476
|
+
code, stdout, _, captured = self.run_main(
|
|
477
|
+
["noul", "--provider", "cloudflare", "-q", "Urgent?", "-s", "today", *extra],
|
|
478
|
+
cloudflare_envelope({"answer": {"type": "noul", "noul": 0.9}}),
|
|
479
|
+
)
|
|
480
|
+
self.assertEqual(code, 0)
|
|
481
|
+
request = captured[0]
|
|
482
|
+
self.assertEqual(request.full_url, cloudflare_url(model))
|
|
483
|
+
self.assertEqual(request.get_method(), "POST")
|
|
484
|
+
self.assertEqual(request.headers["Authorization"], "Bearer cf-token")
|
|
485
|
+
self.assertEqual(json.loads(request.data)["model"], model)
|
|
486
|
+
self.assertEqual(
|
|
487
|
+
json.loads(stdout),
|
|
488
|
+
{
|
|
489
|
+
"model": "clef-flash",
|
|
490
|
+
"answers": {"answer": {"noul": 0.9}},
|
|
491
|
+
"usage": {"input_tokens": 12, "output_tokens": 3},
|
|
492
|
+
},
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
def test_invalid_configuration_fails_before_network_access(self):
|
|
496
|
+
cases = (
|
|
497
|
+
({"CLOUDFLARE_API_TOKEN": "cf-token"}, [], "CLOUDFLARE_ACCOUNT_ID"),
|
|
498
|
+
({**CLOUDFLARE_ENVIRONMENT, "CLOUDFLARE_ACCOUNT_ID": "abc123"}, [], "CLOUDFLARE_ACCOUNT_ID"),
|
|
499
|
+
({**CLOUDFLARE_ENVIRONMENT, "CLOUDFLARE_ACCOUNT_ID": "g" * 32}, [], "CLOUDFLARE_ACCOUNT_ID"),
|
|
500
|
+
({**CLOUDFLARE_ENVIRONMENT, "CLOUDFLARE_ACCOUNT_ID": CLOUDFLARE_ACCOUNT + "/x"}, [], "CLOUDFLARE_ACCOUNT_ID"),
|
|
501
|
+
(CLOUDFLARE_ENVIRONMENT, ["--model", "jev-latest"], "clef"),
|
|
502
|
+
(CLOUDFLARE_ENVIRONMENT, ["--model", "clef/../other"], "clef"),
|
|
503
|
+
# An endpoint override replaces only the account-derived URL, never model validation.
|
|
504
|
+
(CLOUDFLARE_ENVIRONMENT, ["--model", "other", "--endpoint", "https://proxy.test/clef"], "clef"),
|
|
505
|
+
)
|
|
506
|
+
for environment, extra, message in cases:
|
|
507
|
+
with self.subTest(environment=environment, extra=extra):
|
|
508
|
+
code, stdout, stderr, captured = self.run_main(
|
|
509
|
+
["noul", "--provider", "cloudflare", "-q", "Urgent?", "-s", "today", *extra],
|
|
510
|
+
environment=environment,
|
|
511
|
+
)
|
|
512
|
+
self.assertEqual(code, 2)
|
|
513
|
+
self.assertEqual(stdout, "")
|
|
514
|
+
self.assertEqual(captured, [])
|
|
515
|
+
error = json.loads(stderr)
|
|
516
|
+
self.assertFalse(error["ok"])
|
|
517
|
+
self.assertIn(message, error["error"])
|
|
518
|
+
self.assertNotIn("cf-token", stderr)
|
|
519
|
+
|
|
520
|
+
def test_run_with_an_explicit_falsy_model_fails_before_network_access(self):
|
|
521
|
+
for model in (None, "", False, 0):
|
|
522
|
+
with self.subTest(model=model):
|
|
523
|
+
request = json.dumps({"state": "today", "questions": {}, "model": model})
|
|
524
|
+
code, stdout, stderr, captured = self.run_main(
|
|
525
|
+
["run", "-", "--provider", "cloudflare"], stdin=io.StringIO(request)
|
|
526
|
+
)
|
|
527
|
+
self.assertEqual(code, 2)
|
|
528
|
+
self.assertEqual(stdout, "")
|
|
529
|
+
self.assertEqual(captured, [])
|
|
530
|
+
error = json.loads(stderr)
|
|
531
|
+
self.assertFalse(error["ok"])
|
|
532
|
+
self.assertIn("clef, clef-flash", error["error"])
|
|
533
|
+
|
|
534
|
+
def test_endpoint_override_bypasses_only_the_account_requirement(self):
|
|
535
|
+
code, _, _, captured = self.run_main(
|
|
536
|
+
["noul", "--provider", "cloudflare", "--model", "clef", "-q", "Urgent?", "-s", "today",
|
|
537
|
+
"--endpoint", "https://proxy.test/clef"],
|
|
538
|
+
cloudflare_envelope({"answer": {"type": "noul", "noul": 0.4}}),
|
|
539
|
+
environment={"CLOUDFLARE_API_TOKEN": "cf-token"},
|
|
540
|
+
)
|
|
541
|
+
self.assertEqual(code, 0)
|
|
542
|
+
self.assertEqual(captured[0].full_url, "https://proxy.test/clef")
|
|
543
|
+
|
|
544
|
+
def test_typed_answers_are_normalized_without_synthesized_values(self):
|
|
545
|
+
result = jev.normalize_response(cloudflare_envelope(TYPED_CLOUDFLARE_ANSWERS), "cloudflare")
|
|
546
|
+
self.assertEqual(
|
|
547
|
+
result,
|
|
548
|
+
{
|
|
549
|
+
"model": "clef-flash",
|
|
550
|
+
"answers": {
|
|
551
|
+
"urgent": {"noul": 0.82},
|
|
552
|
+
"route": {"choice": "tech", "probabilities": {"tech": 0.7, "sales": 0.3}, "confidence": 0.55},
|
|
553
|
+
"anger": {
|
|
554
|
+
"score": 1.4,
|
|
555
|
+
"legend": {"0": "Calm", "1": "Concerned", "2": "Angry"},
|
|
556
|
+
"probabilities": {"0": 0.1, "1": 0.4, "2": 0.5},
|
|
557
|
+
"confidence": 0.3,
|
|
558
|
+
},
|
|
559
|
+
},
|
|
560
|
+
"usage": {"input_tokens": 12, "output_tokens": 3},
|
|
561
|
+
},
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
def test_value_output_exposes_each_typed_decision(self):
|
|
565
|
+
cases = (
|
|
566
|
+
(["noul"], {"type": "noul", "noul": 0.82}, "0.82\n"),
|
|
567
|
+
(["choice", "-o", "tech=Bug", "-o", "sales=Purchase"], TYPED_CLOUDFLARE_ANSWERS["route"], "tech\n"),
|
|
568
|
+
(["score", "-l", "Calm", "-l", "Concerned", "-l", "Angry"], TYPED_CLOUDFLARE_ANSWERS["anger"], "1.4\n"),
|
|
569
|
+
)
|
|
570
|
+
for command, answer, expected in cases:
|
|
571
|
+
with self.subTest(command=command[0]):
|
|
572
|
+
code, stdout, _, captured = self.run_main(
|
|
573
|
+
[*command, "--provider", "cloudflare", "-q", "Q?", "-s", "today", "--value"],
|
|
574
|
+
cloudflare_envelope({"answer": answer}),
|
|
575
|
+
)
|
|
576
|
+
self.assertEqual(code, 0)
|
|
577
|
+
self.assertEqual(stdout, expected)
|
|
578
|
+
self.assertEqual(json.loads(captured[0].data)["questions"]["answer"]["type"], command[0])
|
|
579
|
+
|
|
580
|
+
def test_failed_or_malformed_envelopes_never_emit_decisions(self):
|
|
581
|
+
decisions = {"answer": {"type": "noul", "noul": 0.9}}
|
|
582
|
+
bodies = (
|
|
583
|
+
{"success": False, "result": {"answers": decisions}, "errors": [{"message": "secret-input"}]},
|
|
584
|
+
{"result": {"answers": decisions}},
|
|
585
|
+
{"success": "true", "result": {"answers": decisions}},
|
|
586
|
+
{"success": True, "result": None},
|
|
587
|
+
{"success": True, "result": [decisions]},
|
|
588
|
+
{"success": True, "result": {"model": "clef-flash"}},
|
|
589
|
+
{"success": True, "result": {"answers": [0.9]}},
|
|
590
|
+
{"success": True, "result": {"answers": {"answer": 0.9}}},
|
|
591
|
+
# A bare System One response is not a Workers AI envelope.
|
|
592
|
+
{"model": "clef-flash", "answers": decisions},
|
|
593
|
+
)
|
|
594
|
+
for body in bodies:
|
|
595
|
+
for value in ([], ["--value"]):
|
|
596
|
+
with self.subTest(body=body, value=value):
|
|
597
|
+
code, stdout, stderr, _ = self.run_main(
|
|
598
|
+
["noul", "--provider", "cloudflare", "-q", "Urgent?", "-s", "today", *value], body
|
|
599
|
+
)
|
|
600
|
+
self.assertEqual(code, 1)
|
|
601
|
+
self.assertEqual(stdout, "")
|
|
602
|
+
self.assertFalse(json.loads(stderr)["ok"])
|
|
603
|
+
self.assertNotIn("secret-input", stderr)
|
|
604
|
+
self.assertNotIn("cf-token", stderr)
|
|
605
|
+
|
|
606
|
+
def test_http_failures_keep_existing_exit_codes(self):
|
|
607
|
+
for status, expected in ((401, 3), (403, 3), (429, 4), (500, 4), (400, 1)):
|
|
608
|
+
error = urllib.error.HTTPError(
|
|
609
|
+
"https://api.cloudflare.com", status, "error", Message(), io.BytesIO(b'{"success":false}')
|
|
610
|
+
)
|
|
611
|
+
with self.subTest(status=status), patch.dict(os.environ, CLOUDFLARE_ENVIRONMENT, clear=True), patch(
|
|
612
|
+
"urllib.request.urlopen", side_effect=error
|
|
613
|
+
):
|
|
614
|
+
with self.assertRaises(jev.CliError) as raised:
|
|
615
|
+
jev.call({"model": "clef", "state": "s", "questions": {}}, cloudflare_url("clef"), "cloudflare")
|
|
616
|
+
self.assertEqual(raised.exception.exit_code, expected)
|
|
617
|
+
|
|
618
|
+
def test_run_forwards_images_and_unknown_fields_to_the_effective_model_url(self):
|
|
619
|
+
request = {
|
|
620
|
+
"state": {"message": "today"},
|
|
621
|
+
"questions": {
|
|
622
|
+
"urgent": {"type": "noul", "instructions": "Urgent?"},
|
|
623
|
+
"route": {"type": "choice", "instructions": "Route?", "criteria": {"tech": "Bug", "sales": "Buy"}},
|
|
624
|
+
},
|
|
625
|
+
"images": ["data:image/png;base64,iVBORw0KGgo=", {"content_type": "image/webp", "base64": "UklGRg=="}],
|
|
626
|
+
"unknown_request_field": {"nested": [1, 2]},
|
|
627
|
+
}
|
|
628
|
+
cases = (
|
|
629
|
+
(request, [], "clef-flash"),
|
|
630
|
+
(request, ["--model", "clef"], "clef"),
|
|
631
|
+
# The request model keeps precedence over --model, and selects the URL.
|
|
632
|
+
({**request, "model": "clef"}, ["--model", "clef-flash"], "clef"),
|
|
633
|
+
)
|
|
634
|
+
for sent, extra, model in cases:
|
|
635
|
+
with self.subTest(model=model, extra=extra):
|
|
636
|
+
code, stdout, _, captured = self.run_main(
|
|
637
|
+
["run", "-", "--provider", "cloudflare", *extra],
|
|
638
|
+
cloudflare_envelope(TYPED_CLOUDFLARE_ANSWERS),
|
|
639
|
+
stdin=io.StringIO(json.dumps(sent)),
|
|
640
|
+
)
|
|
641
|
+
self.assertEqual(code, 0)
|
|
642
|
+
self.assertEqual(captured[0].full_url, cloudflare_url(model))
|
|
643
|
+
self.assertEqual(json.loads(captured[0].data), {**sent, "model": model})
|
|
644
|
+
self.assertEqual(json.loads(stdout)["answers"]["urgent"], {"noul": 0.82})
|
|
645
|
+
|
|
646
|
+
def test_run_with_unsupported_request_model_fails_before_network(self):
|
|
647
|
+
code, stdout, _, captured = self.run_main(
|
|
648
|
+
["run", "-", "--provider", "cloudflare"],
|
|
649
|
+
stdin=io.StringIO(json.dumps({"state": "s", "questions": {}, "model": "jev-latest"})),
|
|
650
|
+
)
|
|
651
|
+
self.assertEqual((code, stdout, captured), (2, "", []))
|
|
652
|
+
|
|
653
|
+
def test_auth_test_uses_the_default_model_url(self):
|
|
654
|
+
code, stdout, _, captured = self.run_main(
|
|
655
|
+
["auth", "test", "--provider", "cloudflare"], cloudflare_envelope({"answer": {"type": "noul", "noul": 1.0}})
|
|
656
|
+
)
|
|
657
|
+
self.assertEqual(code, 0)
|
|
658
|
+
self.assertEqual(captured[0].full_url, cloudflare_url("clef-flash"))
|
|
659
|
+
self.assertEqual(json.loads(captured[0].data)["model"], "clef-flash")
|
|
660
|
+
self.assertEqual(json.loads(stdout), {"ok": True, "valid": True, "model": "clef-flash"})
|
|
661
|
+
|
|
662
|
+
def test_credentials_are_isolated_from_other_providers(self):
|
|
663
|
+
import tempfile
|
|
664
|
+
|
|
665
|
+
with tempfile.TemporaryDirectory() as directory, patch.object(
|
|
666
|
+
jev, "CREDENTIALS_FILE", Path(directory) / "jev-cli" / "credentials.json"
|
|
667
|
+
), patch.dict(os.environ, {}, clear=True):
|
|
668
|
+
for provider in ("official", "openrouter"):
|
|
669
|
+
with patch("sys.stdin", io.StringIO(f"{provider}-key\n")):
|
|
670
|
+
jev.set_api_key(provider)
|
|
671
|
+
with self.assertRaisesRegex(jev.CliError, "cloudflare API key"):
|
|
672
|
+
jev.api_key("cloudflare")
|
|
673
|
+
with patch("sys.stdin", io.StringIO("stored-cf-token\n")):
|
|
674
|
+
jev.set_api_key("cloudflare")
|
|
675
|
+
self.assertEqual(jev.api_key("cloudflare"), "stored-cf-token")
|
|
676
|
+
self.assertEqual(jev.api_key("official"), "official-key")
|
|
677
|
+
self.assertEqual(jev.api_key("openrouter"), "openrouter-key")
|
|
678
|
+
with patch.dict(os.environ, {"CLOUDFLARE_API_TOKEN": "environment-cf-token"}):
|
|
679
|
+
self.assertEqual(jev.api_key("cloudflare"), "environment-cf-token")
|
|
680
|
+
self.assertEqual(jev.api_key("official"), "official-key")
|
|
681
|
+
with patch.dict(os.environ, {"TYPESAFE_API_KEY": "typesafe-key"}):
|
|
682
|
+
self.assertEqual(jev.api_key("cloudflare"), "stored-cf-token")
|
|
683
|
+
self.assertNotIn("api_key", json.loads(jev.CREDENTIALS_FILE.read_text()))
|
|
684
|
+
|
|
685
|
+
def test_default_provider_is_unchanged(self):
|
|
686
|
+
with patch.dict(os.environ, {}, clear=True):
|
|
687
|
+
args = jev.parser().parse_args(["noul", "-q", "Urgent?", "-s", "today"])
|
|
688
|
+
self.assertEqual(args.provider, "official")
|
|
689
|
+
self.assertEqual(jev.request_for(args)[0]["model"], "jev-latest")
|
|
690
|
+
|
|
691
|
+
|
|
388
692
|
if __name__ == "__main__":
|
|
389
693
|
unittest.main()
|
|
@@ -496,5 +496,107 @@ class McpToolBehaviorTest(unittest.IsolatedAsyncioTestCase):
|
|
|
496
496
|
self.assertEqual(captured[0].headers["Ai-model-id"], "typesafe-ai/jev")
|
|
497
497
|
|
|
498
498
|
|
|
499
|
+
async def test_cloudflare_endpoint_matches_the_effective_model(self):
|
|
500
|
+
account = "0123456789abcdef0123456789abcdef"
|
|
501
|
+
base = f"https://api.cloudflare.com/client/v4/accounts/{account}/ai/run/@cf/cloudflare/"
|
|
502
|
+
cases = (
|
|
503
|
+
("noul", {"state": "today", "question": "Urgent?"}, "clef-flash"),
|
|
504
|
+
("noul", {"state": "today", "question": "Urgent?", "model": "clef"}, "clef"),
|
|
505
|
+
("score", {"state": "x", "question": "q", "levels": ["low", "high"], "model": "clef-flash"}, "clef-flash"),
|
|
506
|
+
("run", {"request": {"state": "today", "questions": {}}}, "clef-flash"),
|
|
507
|
+
("run", {"request": {"state": "today", "questions": {}, "model": "clef"}}, "clef"),
|
|
508
|
+
("run", {"request": {"state": "today", "questions": {}, "model": "clef"}, "model": "clef-flash"}, "clef-flash"),
|
|
509
|
+
)
|
|
510
|
+
for name, arguments, model in cases:
|
|
511
|
+
with self.subTest(tool=name, arguments=arguments), patch.dict(os.environ, {"CLOUDFLARE_ACCOUNT_ID": account}):
|
|
512
|
+
result, call = await self.invoke(name, {**arguments, "provider": "cloudflare"})
|
|
513
|
+
self.assertFalse(result.is_error)
|
|
514
|
+
payload, endpoint, provider = call.call_args.args
|
|
515
|
+
self.assertEqual(provider, "cloudflare")
|
|
516
|
+
self.assertEqual(payload["model"], model)
|
|
517
|
+
self.assertEqual(endpoint, base + model)
|
|
518
|
+
|
|
519
|
+
async def test_cloudflare_configuration_errors_fail_before_any_provider_access(self):
|
|
520
|
+
account = "0123456789abcdef0123456789abcdef"
|
|
521
|
+
cases = (
|
|
522
|
+
({}, {"state": "today", "question": "Urgent?"}, "CLOUDFLARE_ACCOUNT_ID"),
|
|
523
|
+
({"CLOUDFLARE_ACCOUNT_ID": "not-an-account"}, {"state": "today", "question": "Urgent?"}, "CLOUDFLARE_ACCOUNT_ID"),
|
|
524
|
+
({"CLOUDFLARE_ACCOUNT_ID": account}, {"state": "today", "question": "Urgent?", "model": "jev-latest"}, "clef"),
|
|
525
|
+
(
|
|
526
|
+
{},
|
|
527
|
+
{"state": "today", "question": "Urgent?", "model": "other", "endpoint": "https://proxy.test/clef"},
|
|
528
|
+
"clef",
|
|
529
|
+
),
|
|
530
|
+
)
|
|
531
|
+
for environment, arguments, message in cases:
|
|
532
|
+
with self.subTest(environment=environment, arguments=arguments):
|
|
533
|
+
with patch.dict(os.environ, environment), patch.object(mcp_server, "call") as call, patch(
|
|
534
|
+
"urllib.request.urlopen", side_effect=AssertionError("network access")
|
|
535
|
+
):
|
|
536
|
+
result = await self.call_tool("noul", {**arguments, "provider": "cloudflare"})
|
|
537
|
+
self.assertTrue(result.is_error)
|
|
538
|
+
self.assertIsNone(result.structured_content)
|
|
539
|
+
self.assertIn(message, result.content[0].text)
|
|
540
|
+
call.assert_not_called()
|
|
541
|
+
|
|
542
|
+
async def test_cloudflare_run_with_an_empty_request_model_fails_before_any_provider_access(self):
|
|
543
|
+
account = "0123456789abcdef0123456789abcdef"
|
|
544
|
+
with patch.dict(os.environ, {"CLOUDFLARE_ACCOUNT_ID": account}), patch.object(mcp_server, "call") as call, patch(
|
|
545
|
+
"urllib.request.urlopen", side_effect=AssertionError("network access")
|
|
546
|
+
):
|
|
547
|
+
result = await self.call_tool(
|
|
548
|
+
"run", {"request": {"state": "today", "questions": {}, "model": ""}, "provider": "cloudflare"}
|
|
549
|
+
)
|
|
550
|
+
self.assertTrue(result.is_error)
|
|
551
|
+
self.assertIsNone(result.structured_content)
|
|
552
|
+
self.assertIn("clef, clef-flash", result.content[0].text)
|
|
553
|
+
call.assert_not_called()
|
|
554
|
+
|
|
555
|
+
async def test_cloudflare_envelope_normalization_reaches_the_tool_result(self):
|
|
556
|
+
account = "0123456789abcdef0123456789abcdef"
|
|
557
|
+
body = {
|
|
558
|
+
"success": True,
|
|
559
|
+
"result": {
|
|
560
|
+
"model": "clef",
|
|
561
|
+
"answers": {"answer": {"type": "choice", "choice": "a", "probabilities": {"a": 0.6, "b": 0.4}, "confidence": 0.2}},
|
|
562
|
+
"usage": {"input_tokens": 5, "output_tokens": 1},
|
|
563
|
+
},
|
|
564
|
+
"errors": [],
|
|
565
|
+
"messages": [],
|
|
566
|
+
}
|
|
567
|
+
captured = []
|
|
568
|
+
|
|
569
|
+
def open_url(request, timeout):
|
|
570
|
+
captured.append(request)
|
|
571
|
+
return HttpResponse(json.dumps(body).encode())
|
|
572
|
+
|
|
573
|
+
environment = {"CLOUDFLARE_ACCOUNT_ID": account, "CLOUDFLARE_API_TOKEN": "cf-token"}
|
|
574
|
+
with patch.dict(os.environ, environment), patch("urllib.request.urlopen", side_effect=open_url):
|
|
575
|
+
result = await self.call_tool(
|
|
576
|
+
"choice",
|
|
577
|
+
{"state": "s", "question": "q", "options": {"a": "A", "b": "B"}, "provider": "cloudflare", "model": "clef"},
|
|
578
|
+
)
|
|
579
|
+
self.assertFalse(result.is_error)
|
|
580
|
+
self.assertEqual(result.structured_content, {**body["result"], "answers": {"answer": {"choice": "a", "probabilities": {"a": 0.6, "b": 0.4}, "confidence": 0.2}}})
|
|
581
|
+
self.assertEqual(
|
|
582
|
+
captured[0].full_url, f"https://api.cloudflare.com/client/v4/accounts/{account}/ai/run/@cf/cloudflare/clef"
|
|
583
|
+
)
|
|
584
|
+
self.assertEqual(captured[0].headers["Authorization"], "Bearer cf-token")
|
|
585
|
+
self.assertEqual(json.loads(captured[0].data)["model"], "clef")
|
|
586
|
+
|
|
587
|
+
async def test_cloudflare_failed_envelope_is_a_tool_error(self):
|
|
588
|
+
account = "0123456789abcdef0123456789abcdef"
|
|
589
|
+
body = {"success": False, "result": {"answers": {"answer": {"type": "noul", "noul": 0.9}}}, "errors": [{"message": "x"}]}
|
|
590
|
+
environment = {"CLOUDFLARE_ACCOUNT_ID": account, "CLOUDFLARE_API_TOKEN": "cf-token"}
|
|
591
|
+
with patch.dict(os.environ, environment), patch(
|
|
592
|
+
"urllib.request.urlopen", return_value=HttpResponse(json.dumps(body).encode())
|
|
593
|
+
):
|
|
594
|
+
result = await self.call_tool("noul", {"state": "s", "question": "q", "provider": "cloudflare"})
|
|
595
|
+
self.assertTrue(result.is_error)
|
|
596
|
+
self.assertIsNone(result.structured_content)
|
|
597
|
+
self.assertNotIn("0.9", result.content[0].text)
|
|
598
|
+
self.assertNotIn("cf-token", result.content[0].text)
|
|
599
|
+
|
|
600
|
+
|
|
499
601
|
if __name__ == "__main__":
|
|
500
602
|
unittest.main()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|