btai 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.
- btai-0.1.0/.gitignore +22 -0
- btai-0.1.0/PKG-INFO +5 -0
- btai-0.1.0/pyproject.toml +16 -0
- btai-0.1.0/src/btai_cli/__init__.py +1 -0
- btai-0.1.0/src/btai_cli/cache.py +123 -0
- btai-0.1.0/src/btai_cli/catalog.py +43 -0
- btai-0.1.0/src/btai_cli/cli.py +156 -0
- btai-0.1.0/src/btai_cli/feedback_cmd.py +121 -0
- btai-0.1.0/src/btai_cli/feedback_v2.py +101 -0
- btai-0.1.0/tests/test_cli_cache.py +33 -0
- btai-0.1.0/tests/test_feedback_cmd.py +111 -0
- btai-0.1.0/tests/test_feedback_contract.py +43 -0
btai-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
.env
|
|
2
|
+
.env.*
|
|
3
|
+
!.env.example
|
|
4
|
+
.DS_Store
|
|
5
|
+
spikes/**/out/
|
|
6
|
+
spikes/**/.cache/
|
|
7
|
+
.venv/
|
|
8
|
+
venv/
|
|
9
|
+
env/
|
|
10
|
+
__pycache__/
|
|
11
|
+
.pytest_cache/
|
|
12
|
+
.ruff_cache/
|
|
13
|
+
node_modules/
|
|
14
|
+
dist/
|
|
15
|
+
.wrangler/
|
|
16
|
+
*.sqlite
|
|
17
|
+
*.sqlite-wal
|
|
18
|
+
*.sqlite-shm
|
|
19
|
+
*.db
|
|
20
|
+
.idea/
|
|
21
|
+
.vscode/
|
|
22
|
+
*.pyc
|
btai-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "btai"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "btai.work public workflow launcher (catalog cache + zip fetch)"
|
|
5
|
+
requires-python = ">=3.12"
|
|
6
|
+
dependencies = []
|
|
7
|
+
|
|
8
|
+
[project.scripts]
|
|
9
|
+
btai = "btai_cli.cli:main"
|
|
10
|
+
|
|
11
|
+
[build-system]
|
|
12
|
+
requires = ["hatchling"]
|
|
13
|
+
build-backend = "hatchling.build"
|
|
14
|
+
|
|
15
|
+
[tool.hatch.build.targets.wheel]
|
|
16
|
+
packages = ["src/btai_cli"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Global btai.work CLI: cached catalog, zip download with sha256 verify."""
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""On-disk catalog and workflow zip cache."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from datetime import UTC, datetime, timedelta
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
CATALOG_URL = "https://api.btai.work/v1/workflows"
|
|
14
|
+
CATALOG_TTL = timedelta(hours=24)
|
|
15
|
+
DEFAULT_CACHE_ROOT = Path(os.environ.get("BTAI_CACHE_ROOT", Path.home() / ".cache" / "btai" / "launcher"))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class CatalogCache:
|
|
20
|
+
root: Path
|
|
21
|
+
|
|
22
|
+
@classmethod
|
|
23
|
+
def default(cls) -> CatalogCache:
|
|
24
|
+
return cls(DEFAULT_CACHE_ROOT)
|
|
25
|
+
|
|
26
|
+
def catalog_path(self) -> Path:
|
|
27
|
+
return self.root / "catalog.json"
|
|
28
|
+
|
|
29
|
+
def etag_path(self) -> Path:
|
|
30
|
+
return self.root / "etag.txt"
|
|
31
|
+
|
|
32
|
+
def fetched_at_path(self) -> Path:
|
|
33
|
+
return self.root / "fetched-at.txt"
|
|
34
|
+
|
|
35
|
+
def workflow_dir(self, workflow_id: str) -> Path:
|
|
36
|
+
return self.root / "workflows" / workflow_id
|
|
37
|
+
|
|
38
|
+
def workflow_meta_path(self, workflow_id: str) -> Path:
|
|
39
|
+
return self.workflow_dir(workflow_id) / "meta.json"
|
|
40
|
+
|
|
41
|
+
def workflow_zip_path(self, workflow_id: str) -> Path:
|
|
42
|
+
return self.workflow_dir(workflow_id) / "workflow.zip"
|
|
43
|
+
|
|
44
|
+
def ensure_dirs(self) -> None:
|
|
45
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
|
|
47
|
+
def read_fetched_at(self) -> datetime | None:
|
|
48
|
+
path = self.fetched_at_path()
|
|
49
|
+
if not path.is_file():
|
|
50
|
+
return None
|
|
51
|
+
try:
|
|
52
|
+
return datetime.fromisoformat(path.read_text(encoding="utf-8").strip())
|
|
53
|
+
except ValueError:
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
def catalog_fresh(self, now: datetime | None = None) -> bool:
|
|
57
|
+
ts = self.read_fetched_at()
|
|
58
|
+
if ts is None:
|
|
59
|
+
return False
|
|
60
|
+
now = now or datetime.now(UTC)
|
|
61
|
+
if ts.tzinfo is None:
|
|
62
|
+
ts = ts.replace(tzinfo=UTC)
|
|
63
|
+
return now - ts < CATALOG_TTL
|
|
64
|
+
|
|
65
|
+
def load_catalog(self) -> dict[str, Any] | None:
|
|
66
|
+
path = self.catalog_path()
|
|
67
|
+
if not path.is_file():
|
|
68
|
+
return None
|
|
69
|
+
try:
|
|
70
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
71
|
+
except (OSError, json.JSONDecodeError):
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
def save_catalog(self, body: dict[str, Any], *, etag: str | None = None) -> None:
|
|
75
|
+
self.ensure_dirs()
|
|
76
|
+
self.catalog_path().write_text(
|
|
77
|
+
json.dumps(body, ensure_ascii=False, indent=2) + "\n",
|
|
78
|
+
encoding="utf-8",
|
|
79
|
+
)
|
|
80
|
+
self.fetched_at_path().write_text(datetime.now(UTC).isoformat(), encoding="utf-8")
|
|
81
|
+
if etag:
|
|
82
|
+
self.etag_path().write_text(etag.strip(), encoding="utf-8")
|
|
83
|
+
|
|
84
|
+
def list_workflows(self) -> list[dict[str, Any]]:
|
|
85
|
+
cat = self.load_catalog()
|
|
86
|
+
if not cat:
|
|
87
|
+
return []
|
|
88
|
+
rows = cat.get("workflows")
|
|
89
|
+
return [r for r in rows if isinstance(r, dict)] if isinstance(rows, list) else []
|
|
90
|
+
|
|
91
|
+
def find_workflow(self, workflow_id: str) -> dict[str, Any] | None:
|
|
92
|
+
for row in self.list_workflows():
|
|
93
|
+
if row.get("id") == workflow_id:
|
|
94
|
+
return row
|
|
95
|
+
return None
|
|
96
|
+
|
|
97
|
+
def save_workflow_zip(
|
|
98
|
+
self,
|
|
99
|
+
workflow_id: str,
|
|
100
|
+
zip_bytes: bytes,
|
|
101
|
+
*,
|
|
102
|
+
generation: int,
|
|
103
|
+
sha256: str,
|
|
104
|
+
) -> None:
|
|
105
|
+
d = self.workflow_dir(workflow_id)
|
|
106
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
107
|
+
self.workflow_zip_path(workflow_id).write_bytes(zip_bytes)
|
|
108
|
+
meta = {
|
|
109
|
+
"workflow_id": workflow_id,
|
|
110
|
+
"generation": generation,
|
|
111
|
+
"sha256": sha256.lower(),
|
|
112
|
+
}
|
|
113
|
+
self.workflow_meta_path(workflow_id).write_text(
|
|
114
|
+
json.dumps(meta, ensure_ascii=False, indent=2) + "\n",
|
|
115
|
+
encoding="utf-8",
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
def verify_local_zip(self, workflow_id: str, expected_sha256: str) -> bool:
|
|
119
|
+
path = self.workflow_zip_path(workflow_id)
|
|
120
|
+
if not path.is_file():
|
|
121
|
+
return False
|
|
122
|
+
actual = hashlib.sha256(path.read_bytes()).hexdigest()
|
|
123
|
+
return actual.lower() == expected_sha256.lower()
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Fetch public workflow catalog over HTTPS."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.request
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from btai_cli.cache import CATALOG_URL
|
|
11
|
+
|
|
12
|
+
UA = "btai-cli/0.1"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def fetch_catalog(*, if_none_match: str | None = None) -> tuple[int, dict[str, Any] | None, str | None]:
|
|
16
|
+
headers = {"User-Agent": UA, "Accept": "application/json"}
|
|
17
|
+
if if_none_match:
|
|
18
|
+
headers["If-None-Match"] = if_none_match
|
|
19
|
+
req = urllib.request.Request(CATALOG_URL, headers=headers)
|
|
20
|
+
try:
|
|
21
|
+
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
22
|
+
etag = resp.headers.get("ETag")
|
|
23
|
+
if resp.status == 304:
|
|
24
|
+
return 304, None, etag
|
|
25
|
+
body = json.loads(resp.read().decode("utf-8"))
|
|
26
|
+
if not isinstance(body, dict):
|
|
27
|
+
return 0, None, etag
|
|
28
|
+
return resp.status, body, etag
|
|
29
|
+
except urllib.error.HTTPError as exc:
|
|
30
|
+
if exc.code == 304:
|
|
31
|
+
return 304, None, exc.headers.get("ETag")
|
|
32
|
+
raise
|
|
33
|
+
except (urllib.error.URLError, json.JSONDecodeError) as exc:
|
|
34
|
+
raise RuntimeError(f"catalog fetch failed: {exc}") from exc
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def download_zip(url: str) -> bytes:
|
|
38
|
+
req = urllib.request.Request(url, headers={"User-Agent": UA})
|
|
39
|
+
try:
|
|
40
|
+
with urllib.request.urlopen(req, timeout=120) as resp:
|
|
41
|
+
return resp.read()
|
|
42
|
+
except urllib.error.URLError as exc:
|
|
43
|
+
raise RuntimeError(f"zip download failed: {exc}") from exc
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Entry: btai list | find | refresh | fetch | feedback."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import hashlib
|
|
7
|
+
import sys
|
|
8
|
+
from typing import Sequence
|
|
9
|
+
|
|
10
|
+
from btai_cli.cache import CatalogCache
|
|
11
|
+
from btai_cli.catalog import download_zip, fetch_catalog
|
|
12
|
+
from btai_cli.feedback_cmd import cmd_feedback
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _tokenize(words: str) -> list[str]:
|
|
16
|
+
return [w.lower() for w in words.split() if w.strip()]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _row_matches(row: dict, tokens: Sequence[str]) -> bool:
|
|
20
|
+
hay = " ".join(
|
|
21
|
+
str(row.get(k) or "") for k in ("id", "can", "cannot")
|
|
22
|
+
).lower()
|
|
23
|
+
return all(t in hay for t in tokens)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def cmd_list(cache: CatalogCache, *, force_network: bool) -> int:
|
|
27
|
+
if force_network or not cache.catalog_fresh():
|
|
28
|
+
_do_refresh(cache, force=True)
|
|
29
|
+
rows = cache.list_workflows()
|
|
30
|
+
if not rows:
|
|
31
|
+
print("No catalog in cache. Run: btai refresh", file=sys.stderr)
|
|
32
|
+
return 1
|
|
33
|
+
for row in rows:
|
|
34
|
+
wid = row.get("id", "")
|
|
35
|
+
has_zip = "zip" in row and row.get("sha256")
|
|
36
|
+
gen = row.get("generation", "-")
|
|
37
|
+
print(f"{wid}\tgen={gen}\tzip={'yes' if has_zip else 'no'}")
|
|
38
|
+
return 0
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def cmd_find(cache: CatalogCache, words: str, *, force_network: bool) -> int:
|
|
42
|
+
tokens = _tokenize(words)
|
|
43
|
+
if not tokens:
|
|
44
|
+
print("usage: btai find <words>", file=sys.stderr)
|
|
45
|
+
return 1
|
|
46
|
+
if force_network or not cache.catalog_fresh():
|
|
47
|
+
_do_refresh(cache, force=True)
|
|
48
|
+
matches = [r for r in cache.list_workflows() if _row_matches(r, tokens)]
|
|
49
|
+
if not matches:
|
|
50
|
+
print("No matching workflows.")
|
|
51
|
+
return 0
|
|
52
|
+
for row in matches:
|
|
53
|
+
print(f"{row.get('id')}\t{row.get('can', '')[:80]}")
|
|
54
|
+
return 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _do_refresh(cache: CatalogCache, *, force: bool) -> None:
|
|
58
|
+
etag = cache.etag_path().read_text(encoding="utf-8").strip() if cache.etag_path().is_file() else None
|
|
59
|
+
if not force and cache.catalog_fresh():
|
|
60
|
+
return
|
|
61
|
+
status, body, new_etag = fetch_catalog(if_none_match=etag)
|
|
62
|
+
if status == 304:
|
|
63
|
+
cache.fetched_at_path().write_text(
|
|
64
|
+
__import__("datetime").datetime.now(__import__("datetime").UTC).isoformat(),
|
|
65
|
+
encoding="utf-8",
|
|
66
|
+
)
|
|
67
|
+
return
|
|
68
|
+
if body is None:
|
|
69
|
+
raise RuntimeError("catalog fetch returned empty body")
|
|
70
|
+
cache.save_catalog(body, etag=new_etag)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def cmd_refresh(cache: CatalogCache) -> int:
|
|
74
|
+
try:
|
|
75
|
+
_do_refresh(cache, force=True)
|
|
76
|
+
except RuntimeError as exc:
|
|
77
|
+
print(str(exc), file=sys.stderr)
|
|
78
|
+
return 1
|
|
79
|
+
n = len(cache.list_workflows())
|
|
80
|
+
print(f"Catalog refreshed ({n} workflows).")
|
|
81
|
+
return 0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def cmd_fetch(cache: CatalogCache, workflow_id: str) -> int:
|
|
85
|
+
if not cache.catalog_fresh():
|
|
86
|
+
try:
|
|
87
|
+
_do_refresh(cache, force=False)
|
|
88
|
+
except RuntimeError as exc:
|
|
89
|
+
print(str(exc), file=sys.stderr)
|
|
90
|
+
return 1
|
|
91
|
+
row = cache.find_workflow(workflow_id)
|
|
92
|
+
if row is None:
|
|
93
|
+
try:
|
|
94
|
+
_do_refresh(cache, force=True)
|
|
95
|
+
except RuntimeError as exc:
|
|
96
|
+
print(str(exc), file=sys.stderr)
|
|
97
|
+
return 1
|
|
98
|
+
row = cache.find_workflow(workflow_id)
|
|
99
|
+
if row is None:
|
|
100
|
+
print(f"Unknown workflow id: {workflow_id}", file=sys.stderr)
|
|
101
|
+
return 1
|
|
102
|
+
zip_url = row.get("zip")
|
|
103
|
+
sha = row.get("sha256")
|
|
104
|
+
gen = row.get("generation", 1)
|
|
105
|
+
if not zip_url or not sha:
|
|
106
|
+
print(f"{workflow_id} has no public zip in catalog.", file=sys.stderr)
|
|
107
|
+
return 1
|
|
108
|
+
try:
|
|
109
|
+
data = download_zip(str(zip_url))
|
|
110
|
+
except RuntimeError as exc:
|
|
111
|
+
print(str(exc), file=sys.stderr)
|
|
112
|
+
return 1
|
|
113
|
+
actual = hashlib.sha256(data).hexdigest()
|
|
114
|
+
if actual.lower() != str(sha).lower():
|
|
115
|
+
print(f"sha256 mismatch for {workflow_id}", file=sys.stderr)
|
|
116
|
+
return 1
|
|
117
|
+
cache.save_workflow_zip(workflow_id, data, generation=int(gen), sha256=actual)
|
|
118
|
+
print(f"Stored {workflow_id} ({len(data)} bytes, gen={gen}, sha256 ok).")
|
|
119
|
+
return 0
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def main(argv: list[str] | None = None) -> int:
|
|
123
|
+
parser = argparse.ArgumentParser(prog="btai", description="btai.work workflow catalog CLI")
|
|
124
|
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
125
|
+
sub.add_parser("list", help="List cached catalog workflows")
|
|
126
|
+
f = sub.add_parser("find", help="Search id/can/cannot in cache")
|
|
127
|
+
f.add_argument("words", nargs="+", help="words to match")
|
|
128
|
+
sub.add_parser("refresh", help="Refresh catalog (ignore 24h TTL)")
|
|
129
|
+
fe = sub.add_parser("fetch", help="Download and verify one workflow zip")
|
|
130
|
+
fe.add_argument("workflow_id")
|
|
131
|
+
fb = sub.add_parser("feedback", help="Preview or send btai-feedback/2 to /v1/feedback")
|
|
132
|
+
fb.add_argument("--file", metavar="PATH", help="Read feedback JSON from file (default: stdin)")
|
|
133
|
+
fb.add_argument(
|
|
134
|
+
"--source",
|
|
135
|
+
choices=("internal", "user"),
|
|
136
|
+
default="user",
|
|
137
|
+
help="Feedback source (default: user; use internal only for house probes)",
|
|
138
|
+
)
|
|
139
|
+
fb.add_argument("--yes", action="store_true", help="POST after printing JSON (default: preview only)")
|
|
140
|
+
args = parser.parse_args(argv)
|
|
141
|
+
cache = CatalogCache.default()
|
|
142
|
+
if args.cmd == "list":
|
|
143
|
+
return cmd_list(cache, force_network=False)
|
|
144
|
+
if args.cmd == "find":
|
|
145
|
+
return cmd_find(cache, " ".join(args.words), force_network=False)
|
|
146
|
+
if args.cmd == "refresh":
|
|
147
|
+
return cmd_refresh(cache)
|
|
148
|
+
if args.cmd == "fetch":
|
|
149
|
+
return cmd_fetch(cache, args.workflow_id)
|
|
150
|
+
if args.cmd == "feedback":
|
|
151
|
+
return cmd_feedback(file_path=args.file, source=args.source, yes=args.yes)
|
|
152
|
+
return 1
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
if __name__ == "__main__":
|
|
156
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""`btai feedback`: preview or POST btai-feedback/2 to /v1/feedback."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.request
|
|
10
|
+
from typing import Any, Callable
|
|
11
|
+
|
|
12
|
+
from btai_cli.feedback_v2 import FEEDBACK_V2_FORMAT, validate_feedback_v2_document
|
|
13
|
+
|
|
14
|
+
DEFAULT_FEEDBACK_URL = "https://api.btai.work/v1/feedback"
|
|
15
|
+
UA = "btai-cli/0.1"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def feedback_url() -> str:
|
|
19
|
+
return os.environ.get("BTAI_FEEDBACK_URL", DEFAULT_FEEDBACK_URL).strip() or DEFAULT_FEEDBACK_URL
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def load_feedback_json(*, file_path: str | None, stdin: Any) -> dict[str, Any]:
|
|
23
|
+
if file_path:
|
|
24
|
+
raw = open(file_path, encoding="utf-8").read()
|
|
25
|
+
else:
|
|
26
|
+
raw = stdin.read()
|
|
27
|
+
if not raw.strip():
|
|
28
|
+
raise ValueError("empty")
|
|
29
|
+
doc = json.loads(raw)
|
|
30
|
+
if not isinstance(doc, dict):
|
|
31
|
+
raise ValueError("root")
|
|
32
|
+
return doc
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def post_feedback(
|
|
36
|
+
url: str,
|
|
37
|
+
payload: dict[str, Any],
|
|
38
|
+
*,
|
|
39
|
+
opener: Callable[..., Any] | None = None,
|
|
40
|
+
) -> tuple[int, dict[str, Any] | None]:
|
|
41
|
+
data = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
42
|
+
req = urllib.request.Request(
|
|
43
|
+
url,
|
|
44
|
+
data=data,
|
|
45
|
+
method="POST",
|
|
46
|
+
headers={
|
|
47
|
+
"User-Agent": UA,
|
|
48
|
+
"Content-Type": "application/json",
|
|
49
|
+
"Accept": "application/json",
|
|
50
|
+
},
|
|
51
|
+
)
|
|
52
|
+
open_fn = opener or urllib.request.urlopen
|
|
53
|
+
try:
|
|
54
|
+
with open_fn(req, timeout=60) as resp:
|
|
55
|
+
body_raw = resp.read().decode("utf-8")
|
|
56
|
+
try:
|
|
57
|
+
body = json.loads(body_raw) if body_raw.strip() else None
|
|
58
|
+
except json.JSONDecodeError:
|
|
59
|
+
body = None
|
|
60
|
+
return int(resp.status), body if isinstance(body, dict) else None
|
|
61
|
+
except urllib.error.HTTPError as exc:
|
|
62
|
+
raw = exc.read().decode(errors="replace")
|
|
63
|
+
try:
|
|
64
|
+
body = json.loads(raw) if raw.strip() else None
|
|
65
|
+
except json.JSONDecodeError:
|
|
66
|
+
body = None
|
|
67
|
+
return int(exc.code), body if isinstance(body, dict) else None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def cmd_feedback(
|
|
71
|
+
*,
|
|
72
|
+
file_path: str | None,
|
|
73
|
+
source: str,
|
|
74
|
+
yes: bool,
|
|
75
|
+
stdin: Any | None = None,
|
|
76
|
+
opener: Callable[..., Any] | None = None,
|
|
77
|
+
) -> int:
|
|
78
|
+
if source not in ("internal", "user"):
|
|
79
|
+
print("source must be internal or user", file=sys.stderr)
|
|
80
|
+
return 1
|
|
81
|
+
try:
|
|
82
|
+
doc = load_feedback_json(file_path=file_path, stdin=stdin or sys.stdin)
|
|
83
|
+
payload = validate_feedback_v2_document(doc, source=source)
|
|
84
|
+
except ValueError as exc:
|
|
85
|
+
key = str(exc)
|
|
86
|
+
if key == "pass":
|
|
87
|
+
print(
|
|
88
|
+
"Refusing to send feedback: outcome=pass (omit POST when all checks pass).",
|
|
89
|
+
file=sys.stderr,
|
|
90
|
+
)
|
|
91
|
+
return 2
|
|
92
|
+
if key in ("paths", "error_excerpt"):
|
|
93
|
+
print(
|
|
94
|
+
f"Refusing to send logic feedback locally: missing or invalid {key}.",
|
|
95
|
+
file=sys.stderr,
|
|
96
|
+
)
|
|
97
|
+
return 2
|
|
98
|
+
print(f"Invalid feedback JSON: {key}", file=sys.stderr)
|
|
99
|
+
return 1
|
|
100
|
+
except json.JSONDecodeError:
|
|
101
|
+
print("Invalid JSON input.", file=sys.stderr)
|
|
102
|
+
return 1
|
|
103
|
+
except OSError as exc:
|
|
104
|
+
print(f"Cannot read input: {exc}", file=sys.stderr)
|
|
105
|
+
return 1
|
|
106
|
+
|
|
107
|
+
line = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
|
108
|
+
print(line)
|
|
109
|
+
if not yes:
|
|
110
|
+
print("Preview only (use --yes to POST).", file=sys.stderr)
|
|
111
|
+
return 0
|
|
112
|
+
|
|
113
|
+
url = feedback_url()
|
|
114
|
+
status, body = post_feedback(url, payload, opener=opener)
|
|
115
|
+
if status == 202 and isinstance(body, dict) and body.get("accepted") is True:
|
|
116
|
+
print(f"Accepted HTTP {status}.", file=sys.stderr)
|
|
117
|
+
return 0
|
|
118
|
+
print(f"POST failed HTTP {status}.", file=sys.stderr)
|
|
119
|
+
if body:
|
|
120
|
+
print(json.dumps(body, ensure_ascii=False), file=sys.stderr)
|
|
121
|
+
return 1
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Pure btai-feedback/2 JSON builder (no network). CLI: `btai feedback`; future MCP tool: feedback."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
FEEDBACK_V2_FORMAT = "btai-feedback/2"
|
|
10
|
+
FEEDBACK_V2_MAX_BYTES = 12_288
|
|
11
|
+
_WORKFLOW_ID_RE = re.compile(r"^[a-z][a-z0-9_-]{1,63}$")
|
|
12
|
+
_CASE_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")
|
|
13
|
+
_SHA256_RE = re.compile(r"^[a-f0-9]{64}$")
|
|
14
|
+
_PATH_EXT = re.compile(r"\.(py|md|json|txt|csv|html|zip|ts|js)$", re.IGNORECASE)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def build_feedback_v2_payload(
|
|
18
|
+
*,
|
|
19
|
+
workflow_id: str,
|
|
20
|
+
generation: int,
|
|
21
|
+
sha256: str,
|
|
22
|
+
case_id: str,
|
|
23
|
+
kind: str,
|
|
24
|
+
source: str,
|
|
25
|
+
expected: str,
|
|
26
|
+
actual: str,
|
|
27
|
+
error_excerpt: str = "",
|
|
28
|
+
paths: list[str] | None = None,
|
|
29
|
+
) -> dict[str, Any]:
|
|
30
|
+
if kind not in ("logic", "env"):
|
|
31
|
+
raise ValueError("kind")
|
|
32
|
+
if source not in ("internal", "user"):
|
|
33
|
+
raise ValueError("source")
|
|
34
|
+
if not _WORKFLOW_ID_RE.match(workflow_id):
|
|
35
|
+
raise ValueError("workflow_id")
|
|
36
|
+
if generation < 1 or not _SHA256_RE.match(sha256):
|
|
37
|
+
raise ValueError("generation or sha256")
|
|
38
|
+
if not _CASE_ID_RE.match(case_id):
|
|
39
|
+
raise ValueError("case_id")
|
|
40
|
+
if len(expected) < 1 or len(expected) > 400:
|
|
41
|
+
raise ValueError("expected")
|
|
42
|
+
if len(actual) < 1 or len(actual) > 400:
|
|
43
|
+
raise ValueError("actual")
|
|
44
|
+
if len(error_excerpt) > 1200:
|
|
45
|
+
raise ValueError("error_excerpt")
|
|
46
|
+
normalized_paths: list[str] = []
|
|
47
|
+
for raw in paths or []:
|
|
48
|
+
rel = str(raw).strip().lstrip("./")
|
|
49
|
+
if not rel or ".." in rel.split("/") or not _PATH_EXT.search(rel):
|
|
50
|
+
raise ValueError("paths")
|
|
51
|
+
normalized_paths.append(rel)
|
|
52
|
+
if len(normalized_paths) > 8:
|
|
53
|
+
raise ValueError("paths")
|
|
54
|
+
if kind == "logic":
|
|
55
|
+
if len(error_excerpt) < 1:
|
|
56
|
+
raise ValueError("error_excerpt")
|
|
57
|
+
if len(normalized_paths) < 1:
|
|
58
|
+
raise ValueError("paths")
|
|
59
|
+
doc = {
|
|
60
|
+
"format": FEEDBACK_V2_FORMAT,
|
|
61
|
+
"workflow_id": workflow_id,
|
|
62
|
+
"generation": generation,
|
|
63
|
+
"sha256": sha256,
|
|
64
|
+
"case_id": case_id,
|
|
65
|
+
"outcome": "warning",
|
|
66
|
+
"kind": kind,
|
|
67
|
+
"source": source,
|
|
68
|
+
"expected": expected,
|
|
69
|
+
"actual": actual,
|
|
70
|
+
"error_excerpt": error_excerpt,
|
|
71
|
+
"paths": normalized_paths,
|
|
72
|
+
}
|
|
73
|
+
raw = json.dumps(doc, ensure_ascii=False, separators=(",", ":"))
|
|
74
|
+
if len(raw.encode("utf-8")) > FEEDBACK_V2_MAX_BYTES:
|
|
75
|
+
raise ValueError("payload too large")
|
|
76
|
+
return doc
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def validate_feedback_v2_document(doc: Any, *, source: str) -> dict[str, Any]:
|
|
80
|
+
"""Validate a parsed JSON object for POST /v1/feedback (no network)."""
|
|
81
|
+
if not isinstance(doc, dict):
|
|
82
|
+
raise ValueError("root")
|
|
83
|
+
if doc.get("format") != FEEDBACK_V2_FORMAT:
|
|
84
|
+
raise ValueError("format")
|
|
85
|
+
outcome = str(doc.get("outcome", ""))
|
|
86
|
+
if outcome == "pass":
|
|
87
|
+
raise ValueError("pass")
|
|
88
|
+
if outcome != "warning":
|
|
89
|
+
raise ValueError("outcome")
|
|
90
|
+
return build_feedback_v2_payload(
|
|
91
|
+
workflow_id=str(doc.get("workflow_id", "")),
|
|
92
|
+
generation=int(doc.get("generation", 0)),
|
|
93
|
+
sha256=str(doc.get("sha256", "")),
|
|
94
|
+
case_id=str(doc.get("case_id", "")),
|
|
95
|
+
kind=str(doc.get("kind", "")),
|
|
96
|
+
source=source,
|
|
97
|
+
expected=str(doc.get("expected", "")),
|
|
98
|
+
actual=str(doc.get("actual", "")),
|
|
99
|
+
error_excerpt=str(doc.get("error_excerpt", "") or ""),
|
|
100
|
+
paths=list(doc.get("paths") or []),
|
|
101
|
+
)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from btai_cli.cache import CatalogCache
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_save_and_list_catalog(tmp_path: Path) -> None:
|
|
10
|
+
cache = CatalogCache(tmp_path)
|
|
11
|
+
body = {
|
|
12
|
+
"format": "btai-workflows/1",
|
|
13
|
+
"workflows": [
|
|
14
|
+
{"id": "demo_a", "can": "x", "cannot": ""},
|
|
15
|
+
{"id": "demo_b", "can": "y", "cannot": "nope"},
|
|
16
|
+
],
|
|
17
|
+
}
|
|
18
|
+
cache.save_catalog(body)
|
|
19
|
+
rows = cache.list_workflows()
|
|
20
|
+
assert len(rows) == 2
|
|
21
|
+
assert cache.find_workflow("demo_b")["can"] == "y"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_workflow_zip_roundtrip(tmp_path: Path) -> None:
|
|
25
|
+
cache = CatalogCache(tmp_path)
|
|
26
|
+
data = b"zip-bytes"
|
|
27
|
+
import hashlib
|
|
28
|
+
|
|
29
|
+
sha = hashlib.sha256(data).hexdigest()
|
|
30
|
+
cache.save_workflow_zip("demo_a", data, generation=2, sha256=sha)
|
|
31
|
+
assert cache.verify_local_zip("demo_a", sha)
|
|
32
|
+
meta = json.loads(cache.workflow_meta_path("demo_a").read_text(encoding="utf-8"))
|
|
33
|
+
assert meta["generation"] == 2
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Unit tests for `btai feedback` (no live API)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
import unittest
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
from unittest import mock
|
|
12
|
+
|
|
13
|
+
_PKG = Path(__file__).resolve().parents[1] / "src"
|
|
14
|
+
sys.path.insert(0, str(_PKG))
|
|
15
|
+
|
|
16
|
+
from btai_cli.feedback_cmd import cmd_feedback, DEFAULT_FEEDBACK_URL # noqa: E402
|
|
17
|
+
from btai_cli.feedback_v2 import FEEDBACK_V2_FORMAT # noqa: E402
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _valid_logic_doc(**overrides: Any) -> dict[str, Any]:
|
|
21
|
+
base = {
|
|
22
|
+
"format": FEEDBACK_V2_FORMAT,
|
|
23
|
+
"workflow_id": "wf_test",
|
|
24
|
+
"generation": 1,
|
|
25
|
+
"sha256": "a" * 64,
|
|
26
|
+
"case_id": "task",
|
|
27
|
+
"outcome": "warning",
|
|
28
|
+
"kind": "logic",
|
|
29
|
+
"source": "internal",
|
|
30
|
+
"expected": "ok",
|
|
31
|
+
"actual": "fail",
|
|
32
|
+
"error_excerpt": "trace line",
|
|
33
|
+
"paths": ["main.py"],
|
|
34
|
+
}
|
|
35
|
+
base.update(overrides)
|
|
36
|
+
return base
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _FakeResponse:
|
|
40
|
+
def __init__(self, status: int, body: dict[str, Any]) -> None:
|
|
41
|
+
self.status = status
|
|
42
|
+
self._body = json.dumps(body).encode("utf-8")
|
|
43
|
+
|
|
44
|
+
def read(self) -> bytes:
|
|
45
|
+
return self._body
|
|
46
|
+
|
|
47
|
+
def __enter__(self) -> _FakeResponse:
|
|
48
|
+
return self
|
|
49
|
+
|
|
50
|
+
def __exit__(self, *args: object) -> None:
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class FeedbackCmdTests(unittest.TestCase):
|
|
55
|
+
def test_preview_does_not_post(self) -> None:
|
|
56
|
+
doc = _valid_logic_doc()
|
|
57
|
+
stdin = io.StringIO(json.dumps(doc))
|
|
58
|
+
posted: list[Any] = []
|
|
59
|
+
|
|
60
|
+
def _fake_open(req: Any, timeout: int = 0) -> _FakeResponse:
|
|
61
|
+
posted.append(req)
|
|
62
|
+
return _FakeResponse(202, {"accepted": True})
|
|
63
|
+
|
|
64
|
+
with mock.patch("btai_cli.feedback_cmd.urllib.request.urlopen", _fake_open):
|
|
65
|
+
rc = cmd_feedback(file_path=None, source="user", yes=False, stdin=stdin)
|
|
66
|
+
self.assertEqual(rc, 0)
|
|
67
|
+
self.assertEqual(posted, [])
|
|
68
|
+
|
|
69
|
+
def test_pass_outcome_rejected(self) -> None:
|
|
70
|
+
doc = _valid_logic_doc(outcome="pass")
|
|
71
|
+
stdin = io.StringIO(json.dumps(doc))
|
|
72
|
+
rc = cmd_feedback(file_path=None, source="user", yes=False, stdin=stdin)
|
|
73
|
+
self.assertEqual(rc, 2)
|
|
74
|
+
|
|
75
|
+
def test_logic_missing_paths_rejected_locally(self) -> None:
|
|
76
|
+
doc = _valid_logic_doc(paths=[])
|
|
77
|
+
stdin = io.StringIO(json.dumps(doc))
|
|
78
|
+
posted: list[Any] = []
|
|
79
|
+
|
|
80
|
+
def _fake_open(req: Any, timeout: int = 0) -> _FakeResponse:
|
|
81
|
+
posted.append(req)
|
|
82
|
+
return _FakeResponse(422, {"code": "SCHEMA_PATHS"})
|
|
83
|
+
|
|
84
|
+
with mock.patch("btai_cli.feedback_cmd.urllib.request.urlopen", _fake_open):
|
|
85
|
+
rc = cmd_feedback(file_path=None, source="user", yes=True, stdin=stdin)
|
|
86
|
+
self.assertEqual(rc, 2)
|
|
87
|
+
self.assertEqual(posted, [])
|
|
88
|
+
|
|
89
|
+
def test_yes_posts_to_feedback_endpoint(self) -> None:
|
|
90
|
+
doc = _valid_logic_doc()
|
|
91
|
+
stdin = io.StringIO(json.dumps(doc))
|
|
92
|
+
captured: dict[str, Any] = {}
|
|
93
|
+
|
|
94
|
+
def _fake_open(req: Any, timeout: int = 0) -> _FakeResponse:
|
|
95
|
+
captured["url"] = req.full_url
|
|
96
|
+
captured["body"] = json.loads(req.data.decode("utf-8"))
|
|
97
|
+
return _FakeResponse(202, {"accepted": True})
|
|
98
|
+
|
|
99
|
+
with mock.patch("btai_cli.feedback_cmd.urllib.request.urlopen", _fake_open):
|
|
100
|
+
rc = cmd_feedback(file_path=None, source="internal", yes=True, stdin=stdin)
|
|
101
|
+
self.assertEqual(rc, 0)
|
|
102
|
+
url = str(captured.get("url", ""))
|
|
103
|
+
self.assertIn("/v1/feedback", url)
|
|
104
|
+
self.assertTrue(url.endswith("/v1/feedback") or DEFAULT_FEEDBACK_URL in url)
|
|
105
|
+
body = captured["body"]
|
|
106
|
+
self.assertEqual(body["format"], FEEDBACK_V2_FORMAT)
|
|
107
|
+
self.assertEqual(body["source"], "internal")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == "__main__":
|
|
111
|
+
unittest.main()
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Contract: feedback v2 builder; CLI `feedback` subcommand."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
import unittest
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
_PKG = Path(__file__).resolve().parents[1] / "src"
|
|
10
|
+
sys.path.insert(0, str(_PKG))
|
|
11
|
+
|
|
12
|
+
from btai_cli.feedback_v2 import FEEDBACK_V2_FORMAT, build_feedback_v2_payload # noqa: E402
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class FeedbackContractTests(unittest.TestCase):
|
|
16
|
+
def test_build_v2_json(self) -> None:
|
|
17
|
+
doc = build_feedback_v2_payload(
|
|
18
|
+
workflow_id="wf_test",
|
|
19
|
+
generation=1,
|
|
20
|
+
sha256="a" * 64,
|
|
21
|
+
case_id="task",
|
|
22
|
+
kind="logic",
|
|
23
|
+
source="user",
|
|
24
|
+
expected="ok",
|
|
25
|
+
actual="fail",
|
|
26
|
+
error_excerpt="trace",
|
|
27
|
+
paths=["main.py"],
|
|
28
|
+
)
|
|
29
|
+
self.assertEqual(doc["format"], FEEDBACK_V2_FORMAT)
|
|
30
|
+
self.assertEqual(doc["outcome"], "warning")
|
|
31
|
+
|
|
32
|
+
def test_cli_has_feedback_subcommand(self) -> None:
|
|
33
|
+
cli_path = _PKG / "btai_cli" / "cli.py"
|
|
34
|
+
source = cli_path.read_text(encoding="utf-8")
|
|
35
|
+
self.assertIn('add_parser("feedback"', source)
|
|
36
|
+
doc = __import__("btai_cli.feedback_v2", fromlist=["x"]).__doc__ or ""
|
|
37
|
+
self.assertIn("btai feedback", doc)
|
|
38
|
+
self.assertIn("feedback", doc)
|
|
39
|
+
self.assertIn("MCP tool: feedback", doc)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
if __name__ == "__main__":
|
|
43
|
+
unittest.main()
|