askjev 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- askjev-0.1.0/LICENSE +21 -0
- askjev-0.1.0/PKG-INFO +103 -0
- askjev-0.1.0/README.md +93 -0
- askjev-0.1.0/pyproject.toml +45 -0
- askjev-0.1.0/pyproject.toml.orig +39 -0
- askjev-0.1.0/src/askjev/__init__.py +5 -0
- askjev-0.1.0/src/askjev/cli.py +384 -0
- askjev-0.1.0/src/askjev/config.py +101 -0
- askjev-0.1.0/src/askjev/errors.py +70 -0
- askjev-0.1.0/src/askjev/gate.py +36 -0
- askjev-0.1.0/src/askjev/render.py +70 -0
askjev-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 askjev contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
askjev-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: askjev
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Agent-facing CLI for TypeSafe Jev: ask typed questions, get calibrated decisions as JSON with gateable exit codes.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Dist: typesafe-sdk>=0.7.5
|
|
8
|
+
Requires-Python: >=3.12
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# askjev
|
|
12
|
+
|
|
13
|
+
An agent-facing CLI for [TypeSafe Jev](https://docs.typesafe.ai), the System
|
|
14
|
+
One decision model. Send a state and typed questions; get calibrated answers
|
|
15
|
+
(`noul`, `choice`, `score`, `box`) as JSON, with exit codes that carry a
|
|
16
|
+
three-band confidence gate so shell scripts and agent skills can act, escalate,
|
|
17
|
+
or refuse without parsing anything.
|
|
18
|
+
|
|
19
|
+
Built on the official [`typesafe-sdk`](https://docs.typesafe.ai/sdk.md). No
|
|
20
|
+
community dependencies.
|
|
21
|
+
|
|
22
|
+
> Unofficial tooling around an official SDK: this project is not affiliated
|
|
23
|
+
> with or endorsed by TypeSafe AI.
|
|
24
|
+
|
|
25
|
+
## Why
|
|
26
|
+
|
|
27
|
+
Existing `jev` CLIs are either unmaintained, single-maintainer, or missing
|
|
28
|
+
primitives. `askjev` combines the best audited ideas — an allowlisted `.env`
|
|
29
|
+
credential loader that cannot be redirected by a planted file, a documented
|
|
30
|
+
agent calling contract (`AGENTS.md` in this repo), three-band confidence exit
|
|
31
|
+
codes, and image pre-flight — on the vendor's own SDK.
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
uv tool install askjev # from a published wheel, once published
|
|
37
|
+
# or from a checkout:
|
|
38
|
+
uv tool install --from . askjev
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Quick start
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
export TYPESAFE_API_KEY=... # or put it in a git-ignored .env
|
|
45
|
+
askjev noul -q "Is this urgent?" -s "Restore service today." --value
|
|
46
|
+
# 0.98
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Full command reference, output schema, exit codes, and scripting patterns:
|
|
50
|
+
[AGENTS.md](AGENTS.md) (the calling contract agents read) and `askjev --help`.
|
|
51
|
+
|
|
52
|
+
## Decision gate
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
askjev noul --gate --value -q "Safe to run unattended?" -s "$CMD"
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Exit `0` act, `10` unsure (escalate), `11` confident no. Thresholds default to
|
|
59
|
+
`0.5:0.9`; override with `--gate 0.3:0.95`.
|
|
60
|
+
|
|
61
|
+
## Credentials
|
|
62
|
+
|
|
63
|
+
The key is read from `TYPESAFE_API_KEY` or the allowlisted key in a `.env`
|
|
64
|
+
file. Only the key may come from a file; endpoint and model overrides are
|
|
65
|
+
env-var only. There is no `--api-key` flag. The key is never printed.
|
|
66
|
+
|
|
67
|
+
## Development
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
uv sync
|
|
71
|
+
uv run pytest # unit tests; no network needed; coverage floor is 100%
|
|
72
|
+
uv run ruff check .
|
|
73
|
+
uv run mypy .
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Live calls need `TYPESAFE_API_KEY`; tests are offline by design. The coverage
|
|
77
|
+
gate is pinned at 100% (the workspace-wide floor — see
|
|
78
|
+
`agents-home/scripts/check_coverage_gate.py`): every line must run under test,
|
|
79
|
+
and tests pinning behavior are verified by mutation (deliberately breaking the
|
|
80
|
+
behavior must fail the suite).
|
|
81
|
+
|
|
82
|
+
## Releasing
|
|
83
|
+
|
|
84
|
+
Releases are tag-driven: push a tag `v1.2.3` and GitHub Actions runs the gates,
|
|
85
|
+
builds the sdist/wheel with `uv build`, and publishes to PyPI via
|
|
86
|
+
[trusted publishing](https://docs.pypi.org/trusted-publishers/) (OIDC — no API
|
|
87
|
+
token is stored in the repository).
|
|
88
|
+
|
|
89
|
+
One-time setup (repository owner, on PyPI):
|
|
90
|
+
|
|
91
|
+
1. On `pypi.org` → *Manage project* (after the first manual upload) or
|
|
92
|
+
*Publishing* → **Add a new pending publisher** with:
|
|
93
|
+
- Owner `magitech-ai`, repository `askjev`, workflow `release.yml`,
|
|
94
|
+
environment `release`.
|
|
95
|
+
2. On GitHub, create the `release` environment for this repository.
|
|
96
|
+
3. Push the tag; the `publish` job attests provenance automatically.
|
|
97
|
+
|
|
98
|
+
Until the pending publisher is configured, `uv tool install --from . askjev`
|
|
99
|
+
installs from a checkout.
|
|
100
|
+
|
|
101
|
+
## License
|
|
102
|
+
|
|
103
|
+
[MIT](LICENSE)
|
askjev-0.1.0/README.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# askjev
|
|
2
|
+
|
|
3
|
+
An agent-facing CLI for [TypeSafe Jev](https://docs.typesafe.ai), the System
|
|
4
|
+
One decision model. Send a state and typed questions; get calibrated answers
|
|
5
|
+
(`noul`, `choice`, `score`, `box`) as JSON, with exit codes that carry a
|
|
6
|
+
three-band confidence gate so shell scripts and agent skills can act, escalate,
|
|
7
|
+
or refuse without parsing anything.
|
|
8
|
+
|
|
9
|
+
Built on the official [`typesafe-sdk`](https://docs.typesafe.ai/sdk.md). No
|
|
10
|
+
community dependencies.
|
|
11
|
+
|
|
12
|
+
> Unofficial tooling around an official SDK: this project is not affiliated
|
|
13
|
+
> with or endorsed by TypeSafe AI.
|
|
14
|
+
|
|
15
|
+
## Why
|
|
16
|
+
|
|
17
|
+
Existing `jev` CLIs are either unmaintained, single-maintainer, or missing
|
|
18
|
+
primitives. `askjev` combines the best audited ideas — an allowlisted `.env`
|
|
19
|
+
credential loader that cannot be redirected by a planted file, a documented
|
|
20
|
+
agent calling contract (`AGENTS.md` in this repo), three-band confidence exit
|
|
21
|
+
codes, and image pre-flight — on the vendor's own SDK.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
uv tool install askjev # from a published wheel, once published
|
|
27
|
+
# or from a checkout:
|
|
28
|
+
uv tool install --from . askjev
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Quick start
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
export TYPESAFE_API_KEY=... # or put it in a git-ignored .env
|
|
35
|
+
askjev noul -q "Is this urgent?" -s "Restore service today." --value
|
|
36
|
+
# 0.98
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Full command reference, output schema, exit codes, and scripting patterns:
|
|
40
|
+
[AGENTS.md](AGENTS.md) (the calling contract agents read) and `askjev --help`.
|
|
41
|
+
|
|
42
|
+
## Decision gate
|
|
43
|
+
|
|
44
|
+
```sh
|
|
45
|
+
askjev noul --gate --value -q "Safe to run unattended?" -s "$CMD"
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Exit `0` act, `10` unsure (escalate), `11` confident no. Thresholds default to
|
|
49
|
+
`0.5:0.9`; override with `--gate 0.3:0.95`.
|
|
50
|
+
|
|
51
|
+
## Credentials
|
|
52
|
+
|
|
53
|
+
The key is read from `TYPESAFE_API_KEY` or the allowlisted key in a `.env`
|
|
54
|
+
file. Only the key may come from a file; endpoint and model overrides are
|
|
55
|
+
env-var only. There is no `--api-key` flag. The key is never printed.
|
|
56
|
+
|
|
57
|
+
## Development
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
uv sync
|
|
61
|
+
uv run pytest # unit tests; no network needed; coverage floor is 100%
|
|
62
|
+
uv run ruff check .
|
|
63
|
+
uv run mypy .
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Live calls need `TYPESAFE_API_KEY`; tests are offline by design. The coverage
|
|
67
|
+
gate is pinned at 100% (the workspace-wide floor — see
|
|
68
|
+
`agents-home/scripts/check_coverage_gate.py`): every line must run under test,
|
|
69
|
+
and tests pinning behavior are verified by mutation (deliberately breaking the
|
|
70
|
+
behavior must fail the suite).
|
|
71
|
+
|
|
72
|
+
## Releasing
|
|
73
|
+
|
|
74
|
+
Releases are tag-driven: push a tag `v1.2.3` and GitHub Actions runs the gates,
|
|
75
|
+
builds the sdist/wheel with `uv build`, and publishes to PyPI via
|
|
76
|
+
[trusted publishing](https://docs.pypi.org/trusted-publishers/) (OIDC — no API
|
|
77
|
+
token is stored in the repository).
|
|
78
|
+
|
|
79
|
+
One-time setup (repository owner, on PyPI):
|
|
80
|
+
|
|
81
|
+
1. On `pypi.org` → *Manage project* (after the first manual upload) or
|
|
82
|
+
*Publishing* → **Add a new pending publisher** with:
|
|
83
|
+
- Owner `magitech-ai`, repository `askjev`, workflow `release.yml`,
|
|
84
|
+
environment `release`.
|
|
85
|
+
2. On GitHub, create the `release` environment for this repository.
|
|
86
|
+
3. Push the tag; the `publish` job attests provenance automatically.
|
|
87
|
+
|
|
88
|
+
Until the pending publisher is configured, `uv tool install --from . askjev`
|
|
89
|
+
installs from a checkout.
|
|
90
|
+
|
|
91
|
+
## License
|
|
92
|
+
|
|
93
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "askjev"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Agent-facing CLI for TypeSafe Jev: ask typed questions, get calibrated decisions as JSON with gateable exit codes."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
dependencies = ["typesafe-sdk>=0.7.5"]
|
|
10
|
+
|
|
11
|
+
[project.scripts]
|
|
12
|
+
askjev = "askjev.cli:main"
|
|
13
|
+
|
|
14
|
+
[build-system]
|
|
15
|
+
requires = ["uv_build>=0.8.8,<0.13.0"]
|
|
16
|
+
build-backend = "uv_build"
|
|
17
|
+
|
|
18
|
+
[dependency-groups]
|
|
19
|
+
dev = [
|
|
20
|
+
"pytest>=9.0.1",
|
|
21
|
+
"pytest-cov>=6.0.0",
|
|
22
|
+
"ruff>=0.12.0",
|
|
23
|
+
"mypy>=1.16.0",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[tool.pytest.ini_options]
|
|
27
|
+
addopts = "--cov=askjev --cov-report=term-missing --cov-fail-under=100"
|
|
28
|
+
|
|
29
|
+
[tool.ruff]
|
|
30
|
+
line-length = 88
|
|
31
|
+
target-version = "py312"
|
|
32
|
+
|
|
33
|
+
[tool.ruff.lint]
|
|
34
|
+
select = [
|
|
35
|
+
"E",
|
|
36
|
+
"F",
|
|
37
|
+
"I",
|
|
38
|
+
"UP",
|
|
39
|
+
"B",
|
|
40
|
+
"SIM",
|
|
41
|
+
"SLF",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
[tool.mypy]
|
|
45
|
+
strict = true
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "askjev"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Agent-facing CLI for TypeSafe Jev: ask typed questions, get calibrated decisions as JSON with gateable exit codes."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
dependencies = [
|
|
10
|
+
"typesafe-sdk>=0.7.5",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
[project.scripts]
|
|
14
|
+
askjev = "askjev.cli:main"
|
|
15
|
+
|
|
16
|
+
[build-system]
|
|
17
|
+
requires = ["uv_build>=0.8.8,<0.13.0"]
|
|
18
|
+
build-backend = "uv_build"
|
|
19
|
+
|
|
20
|
+
[dependency-groups]
|
|
21
|
+
dev = [
|
|
22
|
+
"pytest>=9.0.1",
|
|
23
|
+
"pytest-cov>=6.0.0",
|
|
24
|
+
"ruff>=0.12.0",
|
|
25
|
+
"mypy>=1.16.0",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[tool.pytest.ini_options]
|
|
29
|
+
addopts = "--cov=askjev --cov-report=term-missing --cov-fail-under=100"
|
|
30
|
+
|
|
31
|
+
[tool.ruff]
|
|
32
|
+
line-length = 88
|
|
33
|
+
target-version = "py312"
|
|
34
|
+
|
|
35
|
+
[tool.ruff.lint]
|
|
36
|
+
select = ["E", "F", "I", "UP", "B", "SIM", "SLF"]
|
|
37
|
+
|
|
38
|
+
[tool.mypy]
|
|
39
|
+
strict = true
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
"""The askjev command-line interface.
|
|
2
|
+
|
|
3
|
+
Commands: ``noul``, ``choice``, ``score``, ``box``, ``run`` (alias ``ask``),
|
|
4
|
+
``models``. One JSON object on stdout; errors as JSON on stderr; exit codes
|
|
5
|
+
carry the decision gate (see ``askjev.errors``).
|
|
6
|
+
|
|
7
|
+
The client is injected (``client_factory``) so tests run without network.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import json
|
|
14
|
+
import sys
|
|
15
|
+
from collections.abc import Callable, Sequence
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, TextIO, cast
|
|
18
|
+
|
|
19
|
+
from typesafe_sdk import (
|
|
20
|
+
Box,
|
|
21
|
+
Choice,
|
|
22
|
+
Image,
|
|
23
|
+
Noul,
|
|
24
|
+
Score,
|
|
25
|
+
TypeSafeClient,
|
|
26
|
+
TypeSafeError,
|
|
27
|
+
)
|
|
28
|
+
from typesafe_sdk._core.response_types import SystemOneResponse
|
|
29
|
+
|
|
30
|
+
from askjev import config
|
|
31
|
+
from askjev.errors import (
|
|
32
|
+
EXIT_OK,
|
|
33
|
+
EXIT_USAGE,
|
|
34
|
+
emit_error,
|
|
35
|
+
exit_code_for,
|
|
36
|
+
)
|
|
37
|
+
from askjev.gate import gate_exit, parse_gate
|
|
38
|
+
from askjev.render import (
|
|
39
|
+
answer_payload,
|
|
40
|
+
primary_probability,
|
|
41
|
+
primary_value,
|
|
42
|
+
render_json,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
ClientFactory = Callable[..., Any]
|
|
46
|
+
|
|
47
|
+
PRIMITIVES = ("noul", "choice", "score", "box")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
51
|
+
parser = argparse.ArgumentParser(
|
|
52
|
+
prog="askjev",
|
|
53
|
+
description=(
|
|
54
|
+
"Ask TypeSafe Jev typed questions and get calibrated decisions as JSON. "
|
|
55
|
+
"Jev does not generate text: it answers noul (yes/no probability), "
|
|
56
|
+
"choice, score, and box questions about a state."
|
|
57
|
+
),
|
|
58
|
+
)
|
|
59
|
+
parser.add_argument("--version", action="version", version="askjev 0.1.0")
|
|
60
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
61
|
+
common.add_argument(
|
|
62
|
+
"--model", default=None, help="Model ID or alias (default: jev-latest)."
|
|
63
|
+
)
|
|
64
|
+
common.add_argument(
|
|
65
|
+
"--env-file",
|
|
66
|
+
default=None,
|
|
67
|
+
help="Path to a .env file; only TYPESAFE_API_KEY is read from it.",
|
|
68
|
+
)
|
|
69
|
+
common.add_argument(
|
|
70
|
+
"--pretty", action="store_true", help="Pretty-print JSON output."
|
|
71
|
+
)
|
|
72
|
+
common.add_argument(
|
|
73
|
+
"--value",
|
|
74
|
+
action="store_true",
|
|
75
|
+
help="Print only the primary value (probability, label, score, or box).",
|
|
76
|
+
)
|
|
77
|
+
common.add_argument(
|
|
78
|
+
"--gate",
|
|
79
|
+
nargs="?",
|
|
80
|
+
const="",
|
|
81
|
+
default=None,
|
|
82
|
+
metavar="LOW:HIGH",
|
|
83
|
+
help=(
|
|
84
|
+
"Three-band exit codes on the primary probability: 0 act, 10 unsure, "
|
|
85
|
+
"11 confident-no. Bare for 0.5:0.9 defaults."
|
|
86
|
+
),
|
|
87
|
+
)
|
|
88
|
+
state = argparse.ArgumentParser(add_help=False)
|
|
89
|
+
state.add_argument(
|
|
90
|
+
"-s",
|
|
91
|
+
"--state",
|
|
92
|
+
default=None,
|
|
93
|
+
help="State text; '-' reads stdin, '@path' reads a file.",
|
|
94
|
+
)
|
|
95
|
+
state.add_argument(
|
|
96
|
+
"--json-state",
|
|
97
|
+
action="store_true",
|
|
98
|
+
help="Parse the state as JSON (named fields are referable in questions).",
|
|
99
|
+
)
|
|
100
|
+
state.add_argument(
|
|
101
|
+
"-i",
|
|
102
|
+
"--image",
|
|
103
|
+
action="append",
|
|
104
|
+
default=[],
|
|
105
|
+
metavar="PATH",
|
|
106
|
+
help="Attach a PNG/JPEG image; repeatable. Referenced as image, image_2, ...",
|
|
107
|
+
)
|
|
108
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
109
|
+
|
|
110
|
+
for name in PRIMITIVES:
|
|
111
|
+
sub = subparsers.add_parser(
|
|
112
|
+
name,
|
|
113
|
+
parents=[common, state],
|
|
114
|
+
help=f"Ask one {name} question.",
|
|
115
|
+
)
|
|
116
|
+
sub.add_argument(
|
|
117
|
+
"-q", "--question", required=True, help="Question instructions."
|
|
118
|
+
)
|
|
119
|
+
if name == "choice":
|
|
120
|
+
sub.add_argument(
|
|
121
|
+
"-o",
|
|
122
|
+
"--option",
|
|
123
|
+
action="append",
|
|
124
|
+
required=True,
|
|
125
|
+
default=[],
|
|
126
|
+
metavar="KEY=DESCRIPTION",
|
|
127
|
+
help="One option; repeatable, at least two required.",
|
|
128
|
+
)
|
|
129
|
+
if name == "score":
|
|
130
|
+
sub.add_argument(
|
|
131
|
+
"-l",
|
|
132
|
+
"--level",
|
|
133
|
+
action="append",
|
|
134
|
+
required=True,
|
|
135
|
+
default=[],
|
|
136
|
+
metavar="LEVEL",
|
|
137
|
+
help="One ordered level, lowest first; repeatable, min two.",
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
runner = subparsers.add_parser(
|
|
141
|
+
"run",
|
|
142
|
+
parents=[common],
|
|
143
|
+
aliases=["ask"],
|
|
144
|
+
help="Send a complete System One request (JSON file or stdin).",
|
|
145
|
+
description="Send a complete System One request document as-is.",
|
|
146
|
+
)
|
|
147
|
+
runner.add_argument(
|
|
148
|
+
"request", nargs="?", default=None, help="Request JSON path, or '-' for stdin."
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
subparsers.add_parser(
|
|
152
|
+
"models",
|
|
153
|
+
parents=[common],
|
|
154
|
+
help="List the models available to the account.",
|
|
155
|
+
)
|
|
156
|
+
return parser
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def read_state(args: argparse.Namespace, stdin: TextIO) -> str | dict[str, Any] | None:
|
|
160
|
+
"""Resolve the state from arguments, stdin (only via '-'), or a file reference."""
|
|
161
|
+
raw: str | None = args.state
|
|
162
|
+
if raw is None:
|
|
163
|
+
return None
|
|
164
|
+
if raw == "-":
|
|
165
|
+
raw = stdin.read()
|
|
166
|
+
if not raw.strip():
|
|
167
|
+
raise TypeSafeError("state '-' read no input from stdin.")
|
|
168
|
+
elif raw.startswith("@"):
|
|
169
|
+
raw = Path(raw[1:]).read_text(encoding="utf-8")
|
|
170
|
+
if args.json_state:
|
|
171
|
+
try:
|
|
172
|
+
return cast(dict[str, Any], json.loads(raw))
|
|
173
|
+
except json.JSONDecodeError as error:
|
|
174
|
+
raise TypeSafeError(f"--json-state: invalid JSON: {error}") from error
|
|
175
|
+
return raw
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def parse_options(values: list[str]) -> dict[str, str]:
|
|
179
|
+
"""Parse repeated ``KEY=DESCRIPTION`` option flags into a criteria mapping."""
|
|
180
|
+
if len(values) < 2:
|
|
181
|
+
raise TypeSafeError(
|
|
182
|
+
"choice requires at least two --option KEY=DESCRIPTION values."
|
|
183
|
+
)
|
|
184
|
+
criteria: dict[str, str] = {}
|
|
185
|
+
for option in values:
|
|
186
|
+
key, sep, description = option.partition("=")
|
|
187
|
+
if not sep or not key.strip():
|
|
188
|
+
raise TypeSafeError(f"option {option!r} must be KEY=DESCRIPTION.")
|
|
189
|
+
criteria[key.strip()] = description.strip()
|
|
190
|
+
return criteria
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def question_for(command: str, args: argparse.Namespace) -> Any:
|
|
194
|
+
"""Build the single-question mapping for a primitive command."""
|
|
195
|
+
if command == "noul":
|
|
196
|
+
return {"answer": Noul(instructions=args.question)}
|
|
197
|
+
if command == "choice":
|
|
198
|
+
return {
|
|
199
|
+
"answer": Choice(
|
|
200
|
+
instructions=args.question, criteria=parse_options(args.option)
|
|
201
|
+
)
|
|
202
|
+
}
|
|
203
|
+
if command == "score":
|
|
204
|
+
if len(args.level) < 2:
|
|
205
|
+
raise TypeSafeError(
|
|
206
|
+
"score requires at least two --level values, lowest first."
|
|
207
|
+
)
|
|
208
|
+
return {"answer": Score(instructions=args.question, criteria=list(args.level))}
|
|
209
|
+
if command == "box":
|
|
210
|
+
if not args.image:
|
|
211
|
+
raise TypeSafeError("box requires at least one --image PATH.")
|
|
212
|
+
return {"answer": Box(instructions=args.question)}
|
|
213
|
+
raise ValueError(f"unknown command: {command!r}")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def assets_and_state(
|
|
217
|
+
args: argparse.Namespace,
|
|
218
|
+
state: str | dict[str, Any] | None,
|
|
219
|
+
) -> tuple[str | dict[str, Any] | None, dict[str, Image]]:
|
|
220
|
+
"""Attach images and fold their references into a JSON state.
|
|
221
|
+
|
|
222
|
+
The first image is referenced as ``image``, the second as ``image_2``, and
|
|
223
|
+
so on; text state is kept under ``text``.
|
|
224
|
+
"""
|
|
225
|
+
if not args.image:
|
|
226
|
+
return state, {}
|
|
227
|
+
assets: dict[str, Image] = {}
|
|
228
|
+
references: dict[str, str] = {}
|
|
229
|
+
for index, path in enumerate(args.image):
|
|
230
|
+
image = Image(Path(path))
|
|
231
|
+
name = "image" if index == 0 else f"image_{index + 1}"
|
|
232
|
+
assets[str(image)] = image
|
|
233
|
+
references[name] = str(image)
|
|
234
|
+
if isinstance(state, dict):
|
|
235
|
+
for name in references:
|
|
236
|
+
if name in state:
|
|
237
|
+
raise TypeSafeError(
|
|
238
|
+
f"state already contains key {name!r}; "
|
|
239
|
+
"rename it or drop the colliding --image."
|
|
240
|
+
)
|
|
241
|
+
state.update(references)
|
|
242
|
+
return state, assets
|
|
243
|
+
payload: dict[str, Any] = dict(references)
|
|
244
|
+
if state is not None:
|
|
245
|
+
payload["text"] = state
|
|
246
|
+
return payload, assets
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def primitive_exit(
|
|
250
|
+
command: str,
|
|
251
|
+
gate_spec: str | None,
|
|
252
|
+
answer: Any,
|
|
253
|
+
) -> int:
|
|
254
|
+
"""Exit code for a primitive: the three-band gate when enabled, else 0."""
|
|
255
|
+
if gate_spec is None:
|
|
256
|
+
return EXIT_OK
|
|
257
|
+
low, high = parse_gate(gate_spec)
|
|
258
|
+
return gate_exit(primary_probability(command, answer), low, high)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def run_request(
|
|
262
|
+
client: Any,
|
|
263
|
+
args: argparse.Namespace,
|
|
264
|
+
stdin: TextIO,
|
|
265
|
+
) -> tuple[dict[str, Any], str | None, int]:
|
|
266
|
+
"""Execute the parsed command; return (payload, primary value, exit code)."""
|
|
267
|
+
command = args.command
|
|
268
|
+
if command == "models":
|
|
269
|
+
response = client.models.list()
|
|
270
|
+
payload = {
|
|
271
|
+
"ok": True,
|
|
272
|
+
"models": [entry.model_dump(mode="json") for entry in response.models],
|
|
273
|
+
}
|
|
274
|
+
return payload, None, EXIT_OK
|
|
275
|
+
|
|
276
|
+
if command in ("run", "ask"):
|
|
277
|
+
raw = args.request
|
|
278
|
+
if raw is None:
|
|
279
|
+
raise TypeSafeError("run requires a request document (path or '-').")
|
|
280
|
+
if raw == "-":
|
|
281
|
+
raw = stdin.read()
|
|
282
|
+
elif raw.startswith("@"):
|
|
283
|
+
raw = Path(raw[1:]).read_text(encoding="utf-8")
|
|
284
|
+
else:
|
|
285
|
+
raw = Path(raw).read_text(encoding="utf-8")
|
|
286
|
+
if not raw.strip():
|
|
287
|
+
raise TypeSafeError("run requires a request document (path or stdin).")
|
|
288
|
+
try:
|
|
289
|
+
request = json.loads(raw)
|
|
290
|
+
except json.JSONDecodeError as error:
|
|
291
|
+
raise TypeSafeError(f"run: invalid request JSON: {error}") from error
|
|
292
|
+
if (
|
|
293
|
+
not isinstance(request, dict)
|
|
294
|
+
or "state" not in request
|
|
295
|
+
or "questions" not in request
|
|
296
|
+
):
|
|
297
|
+
raise TypeSafeError(
|
|
298
|
+
"run: request must be an object with 'state' and 'questions'."
|
|
299
|
+
)
|
|
300
|
+
response = client.system_one(
|
|
301
|
+
request["state"],
|
|
302
|
+
request["questions"],
|
|
303
|
+
model=request.get("model", args.model),
|
|
304
|
+
)
|
|
305
|
+
return _response_payload(response), None, EXIT_OK
|
|
306
|
+
|
|
307
|
+
state = read_state(args, stdin)
|
|
308
|
+
state, assets = assets_and_state(args, state)
|
|
309
|
+
questions = question_for(command, args)
|
|
310
|
+
if command == "box":
|
|
311
|
+
response = client.system_one(
|
|
312
|
+
Image(Path(args.image[0])),
|
|
313
|
+
questions,
|
|
314
|
+
model=args.model,
|
|
315
|
+
)
|
|
316
|
+
else:
|
|
317
|
+
response = client.system_one(
|
|
318
|
+
state if state is not None else "",
|
|
319
|
+
questions,
|
|
320
|
+
model=args.model,
|
|
321
|
+
assets=assets or None,
|
|
322
|
+
)
|
|
323
|
+
answer = response.answers["answer"]
|
|
324
|
+
payload = _response_payload(response)
|
|
325
|
+
return (
|
|
326
|
+
payload,
|
|
327
|
+
primary_value(command, answer),
|
|
328
|
+
primitive_exit(command, args.gate, answer),
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _response_payload(response: SystemOneResponse) -> dict[str, Any]:
|
|
333
|
+
return {
|
|
334
|
+
"ok": True,
|
|
335
|
+
"model": response.model,
|
|
336
|
+
"answers": [
|
|
337
|
+
answer_payload(name, answer) for name, answer in response.answers.items()
|
|
338
|
+
],
|
|
339
|
+
"usage": {
|
|
340
|
+
"input_tokens": response.usage.input_tokens,
|
|
341
|
+
"output_tokens": response.usage.output_tokens,
|
|
342
|
+
},
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def main(
|
|
347
|
+
argv: Sequence[str] | None = None,
|
|
348
|
+
client_factory: ClientFactory = TypeSafeClient,
|
|
349
|
+
stdin: TextIO | None = None,
|
|
350
|
+
) -> int:
|
|
351
|
+
"""Entry point; returns the process exit code."""
|
|
352
|
+
parser = build_parser()
|
|
353
|
+
args = parser.parse_args(argv)
|
|
354
|
+
stdin = stdin if stdin is not None else sys.stdin
|
|
355
|
+
|
|
356
|
+
api_key, _env_file = config.resolve_api_key(args.env_file)
|
|
357
|
+
if api_key is None:
|
|
358
|
+
return emit_error(
|
|
359
|
+
"TYPESAFE_API_KEY is not set; export it or put it in a .env file "
|
|
360
|
+
"(only the key variable is read from .env).",
|
|
361
|
+
EXIT_USAGE,
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
try:
|
|
365
|
+
client = client_factory(api_key=api_key)
|
|
366
|
+
try:
|
|
367
|
+
payload, value, exit_code = run_request(client, args, stdin)
|
|
368
|
+
finally:
|
|
369
|
+
close = getattr(client, "close", None)
|
|
370
|
+
if callable(close):
|
|
371
|
+
close()
|
|
372
|
+
except TypeSafeError as error:
|
|
373
|
+
# A bare TypeSafeError is local input validation; API errors map by class.
|
|
374
|
+
code = EXIT_USAGE if type(error) is TypeSafeError else exit_code_for(error)
|
|
375
|
+
return emit_error(str(error), code)
|
|
376
|
+
except (OSError, ValueError) as error:
|
|
377
|
+
return emit_error(str(error), EXIT_USAGE)
|
|
378
|
+
|
|
379
|
+
if args.value and value is not None:
|
|
380
|
+
print(value)
|
|
381
|
+
return exit_code
|
|
382
|
+
|
|
383
|
+
print(render_json(payload, args.pretty))
|
|
384
|
+
return exit_code
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Credential resolution with an allowlisted ``.env`` loader.
|
|
2
|
+
|
|
3
|
+
Rules (D-033):
|
|
4
|
+
|
|
5
|
+
- The API key comes from the process environment or from an allowlisted key in
|
|
6
|
+
a ``.env`` file — never from a command-line argument, never from a credential
|
|
7
|
+
file written by this tool, and it is never printed or logged.
|
|
8
|
+
- Only ``TYPESAFE_API_KEY`` may load from a ``.env`` file. Every other variable
|
|
9
|
+
— in particular ``TYPESAFE_BASE_URL`` and ``TYPESAFE_DEFAULT_MODEL`` — is read
|
|
10
|
+
from the process environment only, so a planted ``.env`` can never redirect
|
|
11
|
+
requests to a different endpoint.
|
|
12
|
+
- The file is looked up at ``$ASKJEV_ENV_FILE`` if set, else ``.env`` in the
|
|
13
|
+
working directory, else the nearest ``.env`` in parent directories.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
from askjev.errors import json_line
|
|
23
|
+
|
|
24
|
+
API_KEY_VAR = "TYPESAFE_API_KEY"
|
|
25
|
+
ENV_FILE_VAR = "ASKJEV_ENV_FILE"
|
|
26
|
+
DEFAULT_ENV_FILE = ".env"
|
|
27
|
+
|
|
28
|
+
#: The only variables a .env file may supply.
|
|
29
|
+
ALLOWED_ENV_FILE_KEYS = frozenset({API_KEY_VAR})
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def parse_env_file(path: Path) -> tuple[dict[str, str], list[str]]:
|
|
33
|
+
"""Parse a ``.env`` file into allowlisted values and rejected key names.
|
|
34
|
+
|
|
35
|
+
Returns ``(values, rejected)`` where ``values`` holds only allowlisted keys
|
|
36
|
+
and ``rejected`` lists every non-allowlisted key that appeared in the file.
|
|
37
|
+
"""
|
|
38
|
+
values: dict[str, str] = {}
|
|
39
|
+
rejected: list[str] = []
|
|
40
|
+
try:
|
|
41
|
+
text = path.read_text(encoding="utf-8")
|
|
42
|
+
except OSError:
|
|
43
|
+
return values, rejected
|
|
44
|
+
for raw_line in text.splitlines():
|
|
45
|
+
line = raw_line.strip()
|
|
46
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
47
|
+
continue
|
|
48
|
+
key, _, value = line.partition("=")
|
|
49
|
+
key = key.strip()
|
|
50
|
+
value = value.strip().strip("'\"")
|
|
51
|
+
if key in ALLOWED_ENV_FILE_KEYS:
|
|
52
|
+
if value:
|
|
53
|
+
values[key] = value
|
|
54
|
+
else:
|
|
55
|
+
rejected.append(key)
|
|
56
|
+
return values, rejected
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def find_env_file(explicit: str | None = None) -> Path | None:
|
|
60
|
+
"""Locate the env file: explicit path, ``$ASKJEV_ENV_FILE``, or cwd walk-up."""
|
|
61
|
+
if explicit:
|
|
62
|
+
candidate = Path(explicit)
|
|
63
|
+
return candidate if candidate.is_file() else None
|
|
64
|
+
from_env = os.environ.get(ENV_FILE_VAR)
|
|
65
|
+
if from_env:
|
|
66
|
+
candidate = Path(from_env)
|
|
67
|
+
return candidate if candidate.is_file() else None
|
|
68
|
+
for directory in [Path.cwd(), *Path.cwd().parents]:
|
|
69
|
+
candidate = directory / DEFAULT_ENV_FILE
|
|
70
|
+
if candidate.is_file():
|
|
71
|
+
return candidate
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def resolve_api_key(env_file_arg: str | None = None) -> tuple[str | None, Path | None]:
|
|
76
|
+
"""Return ``(api_key, loaded_env_file)``.
|
|
77
|
+
|
|
78
|
+
The process environment wins over the file. A non-allowlisted key found in
|
|
79
|
+
the file is reported on stderr as a JSON warning and ignored.
|
|
80
|
+
"""
|
|
81
|
+
from_environment = os.environ.get(API_KEY_VAR, "").strip()
|
|
82
|
+
if from_environment:
|
|
83
|
+
return from_environment, None
|
|
84
|
+
located = find_env_file(env_file_arg)
|
|
85
|
+
if located is None:
|
|
86
|
+
return None, None
|
|
87
|
+
values, rejected = parse_env_file(located)
|
|
88
|
+
if rejected:
|
|
89
|
+
print(
|
|
90
|
+
json_line(
|
|
91
|
+
{
|
|
92
|
+
"ok": False,
|
|
93
|
+
"warning": (
|
|
94
|
+
f"{located}: ignored non-allowlisted keys {sorted(rejected)}; "
|
|
95
|
+
"only TYPESAFE_API_KEY may load from a .env file"
|
|
96
|
+
),
|
|
97
|
+
}
|
|
98
|
+
),
|
|
99
|
+
file=sys.stderr,
|
|
100
|
+
)
|
|
101
|
+
return values.get(API_KEY_VAR), located
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Exit-code taxonomy and SDK error mapping.
|
|
2
|
+
|
|
3
|
+
Three-band decision gate (applies to the primary probability of a single
|
|
4
|
+
primitive command when ``--gate`` is passed):
|
|
5
|
+
|
|
6
|
+
- ``0`` — act: probability met or exceeded the high threshold.
|
|
7
|
+
- ``10`` — unsure: probability above the low threshold but below the high one.
|
|
8
|
+
- ``11`` — confident-no: probability at or below the low threshold.
|
|
9
|
+
|
|
10
|
+
Error classes occupy ``1``–``4``; ``2`` means "the request was wrong" whether
|
|
11
|
+
the CLI or the API rejected it.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import sys
|
|
18
|
+
|
|
19
|
+
from typesafe_sdk import (
|
|
20
|
+
TypeSafeAPIConnectionError,
|
|
21
|
+
TypeSafeAPITimeoutError,
|
|
22
|
+
TypeSafeAuthenticationError,
|
|
23
|
+
TypeSafeBadRequestError,
|
|
24
|
+
TypeSafeInternalServerError,
|
|
25
|
+
TypeSafeNotFoundError,
|
|
26
|
+
TypeSafePermissionDeniedError,
|
|
27
|
+
TypeSafeRateLimitError,
|
|
28
|
+
TypeSafeUnprocessableEntityError,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
EXIT_OK = 0
|
|
32
|
+
EXIT_ERROR = 1
|
|
33
|
+
EXIT_USAGE = 2
|
|
34
|
+
EXIT_AUTH = 3
|
|
35
|
+
EXIT_TRANSIENT = 4
|
|
36
|
+
EXIT_GATE_UNSURE = 10
|
|
37
|
+
EXIT_GATE_NO = 11
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def exit_code_for(error: Exception) -> int:
|
|
41
|
+
"""Map an SDK error to the CLI's exit-code taxonomy."""
|
|
42
|
+
if isinstance(error, (TypeSafeAuthenticationError, TypeSafePermissionDeniedError)):
|
|
43
|
+
return EXIT_AUTH
|
|
44
|
+
if isinstance(error, TypeSafeNotFoundError):
|
|
45
|
+
# A missing model or endpoint is a caller mistake, not an outage.
|
|
46
|
+
return EXIT_USAGE
|
|
47
|
+
if isinstance(
|
|
48
|
+
error,
|
|
49
|
+
(
|
|
50
|
+
TypeSafeRateLimitError,
|
|
51
|
+
TypeSafeAPIConnectionError,
|
|
52
|
+
TypeSafeAPITimeoutError,
|
|
53
|
+
TypeSafeInternalServerError,
|
|
54
|
+
),
|
|
55
|
+
):
|
|
56
|
+
return EXIT_TRANSIENT
|
|
57
|
+
if isinstance(error, (TypeSafeBadRequestError, TypeSafeUnprocessableEntityError)):
|
|
58
|
+
return EXIT_USAGE
|
|
59
|
+
return EXIT_ERROR
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def json_line(payload: dict[str, object]) -> str:
|
|
63
|
+
"""Serialize a payload as one compact JSON line."""
|
|
64
|
+
return json.dumps(payload, separators=(",", ":"))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def emit_error(message: str, code: int) -> int:
|
|
68
|
+
"""Print one JSON error object on stderr and return the exit code."""
|
|
69
|
+
print(json_line({"ok": False, "error": message}), file=sys.stderr)
|
|
70
|
+
return code
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Three-band decision gate on a primary probability."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from askjev.errors import EXIT_GATE_NO, EXIT_GATE_UNSURE, EXIT_OK
|
|
6
|
+
|
|
7
|
+
DEFAULT_GATE_LOW = 0.5
|
|
8
|
+
DEFAULT_GATE_HIGH = 0.9
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def parse_gate(spec: str | None) -> tuple[float, float]:
|
|
12
|
+
"""Parse ``--gate``: bare for defaults, or ``LOW:HIGH``.
|
|
13
|
+
|
|
14
|
+
Raises ``ValueError`` on malformed specs so the caller can exit ``2``.
|
|
15
|
+
"""
|
|
16
|
+
if spec is None or spec == "":
|
|
17
|
+
return DEFAULT_GATE_LOW, DEFAULT_GATE_HIGH
|
|
18
|
+
low_text, sep, high_text = spec.partition(":")
|
|
19
|
+
if not sep:
|
|
20
|
+
high_text = low_text
|
|
21
|
+
low = float(low_text)
|
|
22
|
+
high = float(high_text)
|
|
23
|
+
if not 0.0 <= low < high <= 1.0:
|
|
24
|
+
raise ValueError(
|
|
25
|
+
f"gate thresholds must satisfy 0 <= low < high <= 1, got {spec!r}"
|
|
26
|
+
)
|
|
27
|
+
return low, high
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def gate_exit(probability: float, low: float, high: float) -> int:
|
|
31
|
+
"""Map a probability to the three-band exit code."""
|
|
32
|
+
if probability >= high:
|
|
33
|
+
return EXIT_OK
|
|
34
|
+
if probability > low:
|
|
35
|
+
return EXIT_GATE_UNSURE
|
|
36
|
+
return EXIT_GATE_NO
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Output shaping: JSON payloads and bare ``--value`` extraction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from askjev.errors import json_line
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def render_json(payload: dict[str, Any], pretty: bool) -> str:
|
|
13
|
+
"""Serialize a success payload, compact by default."""
|
|
14
|
+
if pretty:
|
|
15
|
+
return json.dumps(payload, indent=2, sort_keys=False)
|
|
16
|
+
return json_line(payload)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def answer_payload(name: str, answer: Any) -> dict[str, Any]:
|
|
20
|
+
"""Serialize one answer object, keeping the question's name."""
|
|
21
|
+
data: dict[str, Any] = answer.model_dump(mode="json")
|
|
22
|
+
data["question"] = name
|
|
23
|
+
return data
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def primary_value(command: str, answer: Any) -> str:
|
|
27
|
+
"""Extract the bare primary value for ``--value`` mode.
|
|
28
|
+
|
|
29
|
+
- ``noul`` -> the probability.
|
|
30
|
+
- ``choice`` -> the selected label.
|
|
31
|
+
- ``score`` -> the expected score.
|
|
32
|
+
- ``box`` -> ``left,top,right,bottom`` fractions.
|
|
33
|
+
"""
|
|
34
|
+
if command == "noul":
|
|
35
|
+
return str(answer.noul)
|
|
36
|
+
if command == "choice":
|
|
37
|
+
return str(answer.choice)
|
|
38
|
+
if command == "score":
|
|
39
|
+
return str(answer.score)
|
|
40
|
+
if command == "box":
|
|
41
|
+
box = answer.box
|
|
42
|
+
return f"{box.left},{box.top},{box.right},{box.bottom}"
|
|
43
|
+
raise ValueError(f"unknown command for --value: {command!r}")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def primary_probability(command: str, answer: Any) -> float:
|
|
47
|
+
"""Extract the probability the gate applies to.
|
|
48
|
+
|
|
49
|
+
- ``noul`` -> p(yes).
|
|
50
|
+
- ``choice`` -> the selected option's probability.
|
|
51
|
+
- ``score`` -> the highest level probability.
|
|
52
|
+
- ``box`` -> the answer's confidence (0.0 when unreported).
|
|
53
|
+
"""
|
|
54
|
+
if command == "noul":
|
|
55
|
+
return float(answer.noul)
|
|
56
|
+
if command == "choice":
|
|
57
|
+
return float(answer.probabilities.get(answer.choice, 0.0))
|
|
58
|
+
if command == "score":
|
|
59
|
+
return max((float(p) for p in answer.probabilities.values()), default=0.0)
|
|
60
|
+
if command == "box":
|
|
61
|
+
return float(answer.confidence or 0.0)
|
|
62
|
+
raise ValueError(f"unknown command for gating: {command!r}")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def print_stdout(text: str) -> None:
|
|
66
|
+
print(text)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def print_stderr(text: str) -> None:
|
|
70
|
+
print(text, file=sys.stderr)
|