grape-cli 0.3.4__py3-none-any.whl

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.
grape_cli/contracts.py ADDED
@@ -0,0 +1,281 @@
1
+ """契约加载:优先 static/openapi.json → /openapi.json → 缓存 ~/.grape → 内置快照。
2
+
3
+ 拉取优先级(docs/grape-contract-static-fetch-design.md):
4
+ 1) `{base}/static/openapi.json` —— 服务端固定下载 URL(公开、no-cache、绕过 nginx 封禁)
5
+ 2) `{base}/openapi.json` —— 兼容未提供 static 的部署
6
+ 3) 安装包内置快照 `src/data/openapi.json`(方案 C 兜底,命令发现不依赖网络)
7
+
8
+ Issue #2080(F-22 剩余半面):契约内容指纹纳入刷新比对——缓存命中后比对远端与缓存的
9
+ `(info.version, x-endpoint-count, x-groups)`,内容变即重拉覆盖(同版本号不同端点数
10
+ 如 175 vs 243 同叫 2.1.0 也拉新,不等版本号 bump);远端不可达时回退缓存
11
+ (离线可用性不降级),无缓存才退内置快照。旧服务端契约(无 x- 扩展位)向后兼容,
12
+ 回退仅版本比对。
13
+ """
14
+ import json
15
+ from importlib.resources import files
16
+ from pathlib import Path
17
+
18
+ from grape_cli import config
19
+ from grape_cli.client import ApiClient, CliError
20
+
21
+ # 内置快照来源信息:kind ∈ {"remote", "cache", "bundled"}
22
+ _last_source = {"kind": "", "detail": ""}
23
+
24
+ _CONTRACT_PATHS = ("/static/openapi.json", "/openapi.json")
25
+
26
+
27
+ def cache_path(version: str = "") -> Path:
28
+ return config.CONFIG_DIR / f"openapi-{version}.json" if version else config.CONFIG_DIR / "openapi-current.json"
29
+
30
+
31
+ def version_key(version: str) -> tuple:
32
+ """'0.10.0' -> (0, 10, 0);非点分数字(如 'unknown')-> (0,)。
33
+
34
+ 版本号按点分数字段比较,避免字典序在 0.9.0 vs 0.10.0 时选错。
35
+ 公开接口(QA 复审 Standards 3):doctor 版本对比与缓存校验复用,
36
+ 不再私有导入 _version_key 各自维护口径。
37
+ """
38
+ parts = version.split(".")
39
+ if parts and all(p.isdigit() for p in parts):
40
+ return tuple(int(p) for p in parts)
41
+ return (0,)
42
+
43
+
44
+ def _cache_version_key(name: str) -> tuple:
45
+ """'openapi-0.10.0.json' -> (0, 10, 0);非版本化(openapi-current.json)-> (0,)。"""
46
+ stem = name[len("openapi-"):]
47
+ if stem.endswith(".json"):
48
+ stem = stem[:-len(".json")]
49
+ return version_key(stem)
50
+
51
+
52
+ def _fmt_key(key: tuple) -> str:
53
+ """版本键可读化:(2, 5, 0) -> '2.5.0';未知 (0,) -> 'unknown'。"""
54
+ return ".".join(str(p) for p in key) if key != (0,) else "unknown"
55
+
56
+
57
+ def validate_cache() -> dict:
58
+ """契约缓存校验(#2438 污染口径的公开接口;doctor 检查复用,不再各自重实现)。
59
+
60
+ 返回 {"files": [文件名], "polluted": [说明], "unreadable": [文件名], "latest_key": tuple}:
61
+ - polluted:文件名版本 ≠ 内容 info.version 的伪高版污染(与 _cleanup_polluted_caches
62
+ 同一判定,refresh 自愈时会清理);
63
+ - unreadable:JSON 解析失败或顶层非对象;
64
+ - latest_key:可读缓存的内容版本最大键(无可读缓存 → (0,))。
65
+ """
66
+ files = sorted(config.CONFIG_DIR.glob("openapi-*.json"))
67
+ report: dict = {"files": [f.name for f in files], "polluted": [],
68
+ "unreadable": [], "latest_key": (0,)}
69
+ for f in files:
70
+ try:
71
+ data = json.loads(f.read_text(encoding="utf-8"))
72
+ except Exception:
73
+ report["unreadable"].append(f.name)
74
+ continue
75
+ if not isinstance(data, dict):
76
+ report["unreadable"].append(f.name)
77
+ continue
78
+ content_key = version_key(str((data.get("info") or {}).get("version", "")))
79
+ file_key = _cache_version_key(f.name)
80
+ if file_key != (0,) and file_key != content_key:
81
+ report["polluted"].append(
82
+ f"{f.name} claims v{_fmt_key(file_key)} but content is v{_fmt_key(content_key)}")
83
+ report["latest_key"] = max(report["latest_key"], content_key)
84
+ return report
85
+
86
+
87
+ def _read_cache() -> dict | None:
88
+ """读取缓存:校验文件内容 info.version 与文件名版本一致,按内容版本倒序取最高。
89
+
90
+ 文件名版本与内容版本不一致的缓存(如 openapi-9.9.9.json 实为 2.1.0 内容)视为
91
+ 损坏缓存跳过,避免伪高版永久压过真实版本。
92
+ """
93
+ candidates = []
94
+ for f in sorted(config.CONFIG_DIR.glob("openapi-*.json"),
95
+ key=lambda p: _cache_version_key(p.name), reverse=True):
96
+ try:
97
+ data = json.loads(f.read_text(encoding="utf-8"))
98
+ except Exception:
99
+ continue
100
+ if not isinstance(data, dict):
101
+ continue
102
+ file_key = _cache_version_key(f.name)
103
+ content_key = version_key(str(data.get("info", {}).get("version", "")))
104
+ if file_key != (0,) and file_key != content_key:
105
+ continue # 文件名版本 != 内容版本 -> 损坏缓存,跳过
106
+ candidates.append((content_key, data))
107
+ if not candidates:
108
+ return None
109
+ return max(candidates, key=lambda c: c[0])[1]
110
+
111
+
112
+ def _version_of(schema: dict) -> str:
113
+ return str((schema.get("info") or {}).get("version", ""))
114
+
115
+
116
+ def _contract_fingerprint(schema: dict) -> tuple | None:
117
+ """契约内容指纹(Issue #2080):契约根 (x-endpoint-count, x-groups)。
118
+
119
+ 服务端自 PR #1151 起在契约根透出 x- 扩展位;缺任一(旧服务端/旧缓存)返回
120
+ None,调用方回退仅版本比对(向后兼容)。
121
+ """
122
+ if not isinstance(schema, dict):
123
+ return None
124
+ count = schema.get("x-endpoint-count")
125
+ groups = schema.get("x-groups")
126
+ if (not isinstance(count, int) or isinstance(count, bool)
127
+ or not isinstance(groups, list)):
128
+ return None
129
+ return (count, tuple(sorted(str(g) for g in groups)))
130
+
131
+
132
+ def _contract_changed(cached: dict, remote: dict) -> str:
133
+ """远端契约较缓存是否需拉新,返回变更说明('' = 无需拉新)。
134
+
135
+ - 版本号不同 → 常规版本拉新;
136
+ - 版本号相同:远端有内容指纹 → 比对 (x-endpoint-count, x-groups),不一致即拉新
137
+ (同号不同容,F-22;缓存无指纹视为陈旧一并拉新升级);远端无指纹
138
+ (旧服务端契约)→ 回退仅版本比对,同版本不重拉。
139
+ """
140
+ cv, rv = _version_of(cached), _version_of(remote)
141
+ if cv != rv:
142
+ return f"version {cv or '?'} -> {rv or '?'}"
143
+ fp_remote = _contract_fingerprint(remote)
144
+ if fp_remote is None:
145
+ return ""
146
+ fp_cached = _contract_fingerprint(cached)
147
+ if fp_cached is None:
148
+ return f"cache predates content fingerprint (remote has {fp_remote[0]} endpoints)"
149
+ if fp_cached != fp_remote:
150
+ (n_c, _g_c), (n_r, _g_r) = fp_cached, fp_remote
151
+ if n_c != n_r:
152
+ return f"same version {rv or '?'}, x-endpoint-count {n_c} -> {n_r}"
153
+ return f"same version {rv or '?'}, x-groups changed"
154
+ return ""
155
+
156
+
157
+ def _write_cache(schema: dict, version: str) -> None:
158
+ try:
159
+ config.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
160
+ cache_path(version).write_text(json.dumps(schema, ensure_ascii=False), encoding="utf-8")
161
+ except Exception:
162
+ pass
163
+
164
+
165
+ def _cleanup_polluted_caches() -> None:
166
+ """清理文件名版本与内容 info.version 不一致的伪高版缓存文件(如 openapi-9.9.9.json 实为 2.1.0)。"""
167
+ try:
168
+ for f in config.CONFIG_DIR.glob("openapi-*.json"):
169
+ file_key = _cache_version_key(f.name)
170
+ if file_key == (0,):
171
+ continue # 非版本化文件名(openapi-current.json)无从比对,不清理
172
+ try:
173
+ data = json.loads(f.read_text(encoding="utf-8"))
174
+ except Exception:
175
+ continue
176
+ if not isinstance(data, dict):
177
+ continue
178
+ if version_key(str(data.get("info", {}).get("version", ""))) != file_key:
179
+ f.unlink(missing_ok=True)
180
+ except Exception:
181
+ pass
182
+
183
+
184
+ def fetch_schema(base_url: str, token: str) -> dict:
185
+ """按优先级尝试拉取契约:static/openapi.json → /openapi.json。
186
+
187
+ 契约端点为公开资源(/static/openapi.json),无需 token 即可拉取。
188
+ """
189
+ api = ApiClient(base_url=base_url, token=token, require_token=False)
190
+ last_error: Exception | None = None
191
+ for path in _CONTRACT_PATHS:
192
+ try:
193
+ _s, data = api.request("GET", path)
194
+ if isinstance(data, dict) and "paths" in data:
195
+ return data
196
+ raise CliError(f"contract malformed (missing 'paths'): {path}")
197
+ except Exception as e:
198
+ last_error = e
199
+ raise CliError(f"contract unreachable from any of {_CONTRACT_PATHS} ({last_error})")
200
+
201
+
202
+ def load_bundled() -> dict | None:
203
+ """读取安装包内置的契约快照(方案 C 兜底),失败返回 None。"""
204
+ try:
205
+ schema = json.loads(
206
+ files("grape_cli").joinpath("data", "openapi.json").read_text(encoding="utf-8")
207
+ )
208
+ if isinstance(schema, dict) and "paths" in schema:
209
+ return schema
210
+ except Exception:
211
+ pass
212
+ return None
213
+
214
+
215
+ def load_contract(base_url: str = "", token: str = "", refresh: bool = False) -> dict:
216
+ """返回 OpenAPI schema:缓存 > 远端 > 内置快照兜底。
217
+
218
+ 缓存命中后向远端比对内容指纹(Issue #2080,F-22):`info.version` 或契约根
219
+ `x-endpoint-count`/`x-groups` 任一变化即重拉覆盖(同号不同容也拉新);
220
+ 远端不可达时回退缓存(离线可用性不降级),无缓存才退安装包内置快照,
221
+ 并通过 `contract_source()` 暴露本次来源。
222
+ """
223
+ global _last_source
224
+ base_url, token = config.resolve(base_url, token)
225
+ cached = _read_cache()
226
+
227
+ if cached is not None and not refresh:
228
+ _ver = _version_of(cached)
229
+ if cache_path(_ver).exists():
230
+ # Issue #2080:缓存命中后比对远端内容指纹——同版本号不同内容
231
+ # (如 175 vs 243 端点同叫 2.1.0)即重拉覆盖;远端不可达维持缓存
232
+ # (离线回退缓存优先,不降级到内置快照)。
233
+ try:
234
+ remote = fetch_schema(base_url, token)
235
+ except Exception as e:
236
+ _last_source = {"kind": "cache",
237
+ "detail": f"{_ver or 'current'} (remote unreachable: {e})"}
238
+ return cached
239
+ change = _contract_changed(cached, remote)
240
+ if change:
241
+ _write_cache(remote, _version_of(remote))
242
+ _last_source = {"kind": "remote", "detail": (
243
+ f"{_version_of(remote) or 'current'} (content changed: {change})")}
244
+ return remote
245
+ _last_source = {"kind": "cache", "detail": _ver or "current"}
246
+ return cached
247
+ # 命中的缓存无版本化落盘(如 openapi-current.json 兜底)→ 走远端拉取
248
+
249
+ try:
250
+ schema = fetch_schema(base_url, token)
251
+ except Exception as e:
252
+ # Issue #2080:离线回退缓存优先(可用性不联网时不降级),无缓存才退内置快照
253
+ if cached is not None:
254
+ _ver = _version_of(cached)
255
+ _last_source = {"kind": "cache",
256
+ "detail": f"{_ver or 'current'} (remote unreachable: {e})"}
257
+ return cached
258
+ bundled = load_bundled()
259
+ if bundled is None:
260
+ raise
261
+ _ver = _version_of(bundled)
262
+ _last_source = {
263
+ "kind": "bundled",
264
+ "detail": f"v{_ver} (remote unreachable: {e})",
265
+ }
266
+ return bundled
267
+
268
+ _ver = _version_of(schema)
269
+ change = _contract_changed(cached, schema) if cached is not None else ""
270
+ _write_cache(schema, _ver)
271
+ _cleanup_polluted_caches()
272
+ detail = _ver or "current"
273
+ if change:
274
+ detail += f" (content changed: {change})"
275
+ _last_source = {"kind": "remote", "detail": detail}
276
+ return schema
277
+
278
+
279
+ def contract_source() -> dict:
280
+ """返回最近一次 load_contract 的契约来源:{"kind": remote|cache|bundled, "detail": str}。"""
281
+ return dict(_last_source)
@@ -0,0 +1,85 @@
1
+ {
2
+ "tasks_mine": "--status active --json-out",
3
+ "tasks_complete": "--json '{\"result_text\":\"<summary>\",\"next_step\":\"a2a_issue\"}'",
4
+ "tasks_status": "--task_id 7 --json '{\"status\":\"processing\"}'",
5
+ "tasks_status_get": "--task_id 7 --json-out",
6
+ "tasks_start": "--task_id 7",
7
+ "tasks_close": "--json '{\"repo_key\":\"owner/repo\",\"issue_number\":7}'",
8
+ "tasks_notify": "--json '{\"assignee\":\"<user>\",\"repo_key\":\"owner/repo\",\"issue_number\":7}'",
9
+ "tasks_clarify": "--task_id 7 --json '{\"message\":\"<your reply>\"}'",
10
+ "tasks_clarifications": "--task_id 7 --json-out",
11
+ "tasks_repo_all": "--owner o --repo r --json-out",
12
+ "issues_list": "--owner o --repo r --json-out",
13
+ "issues_create": "--owner o --repo r --json '{\"title\":\"<title>\",\"body\":\"<body>\"}'",
14
+ "issues_detail": "--owner o --repo r --number 7 --json-out",
15
+ "issues_events": "--owner o --repo r --number 7 --json-out",
16
+ "issues_pipeline": "--owner o --repo r --number 7 --json-out",
17
+ "gitrepo_repo": "--owner o --repo r --json-out",
18
+ "repos_workspace": "--owner o --repo r --json-out",
19
+ "repos_git_credential": "--owner o --repo r --json-out",
20
+ "gitrepo_branches": "--owner o --repo r --json-out",
21
+ "gitrepo_commits": "--owner o --repo r --json-out",
22
+ "gitrepo_tree": "--owner o --repo r --ref main --json-out",
23
+ "gitrepo_contents_root": "--owner o --repo r --json-out",
24
+ "gitrepo_contents": [
25
+ "--owner o --repo r --path \"\" --json-out",
26
+ "--owner o --repo r --path README.md --ref main --json-out"
27
+ ],
28
+ "gitrepo_labels_list": "--owner o --repo r --json-out",
29
+ "gitrepo_labels_create": "--owner o --repo r --json '{\"name\":\"<label>\",\"color\":\"#d73a4a\"}'",
30
+ "gitrepo_milestones": "--owner o --repo r",
31
+ "gitrepo_milestones_create": "--owner o --repo r --json '{\"title\":\"<title>\",\"due_on\":\"<YYYY-MM-DD>\"}' --json-out",
32
+ "gitrepo_milestones_update": "--owner o --repo r --number 7 --json '{\"state\":\"closed\"}' --json-out",
33
+ "gitrepo_issues_list": "--owner o --repo r --state open --json-out",
34
+ "gitrepo_issues_create": "--owner o --repo r --json '{\"title\":\"<title>\",\"body\":\"<body>\"}'",
35
+ "gitrepo_issues_get": "--owner o --repo r --number 7 --json-out",
36
+ "gitrepo_issues_update": "--owner o --repo r --number 7 --json '{\"state\":\"closed\",\"labels\":\"bug\"}'",
37
+ "gitrepo_issues_comments_list": "--owner o --repo r --number 7 --json-out",
38
+ "gitrepo_issues_comments_create": "--owner o --repo r --number 7 --json '{\"body\":\"<comment>\"}'",
39
+ "gitrepo_pulls_list": "--owner o --repo r --state open --json-out",
40
+ "gitrepo_pulls_create": [
41
+ "--owner o --repo r --json '{\"title\":\"<title>\",\"head\":\"feat/x\",\"base\":\"main\",\"inner_issue_nums\":\"o/r#5\",\"close_related_issue\":true}' --json-out",
42
+ "--owner o --repo r --json @pr.json --json-out"
43
+ ],
44
+ "gitrepo_pulls_get": "--owner o --repo r --number 7 --json-out",
45
+ "gitrepo_pulls_update": [
46
+ "--owner o --repo r --number 7 --json '{\"title\":\"<new title>\"}'",
47
+ "--owner o --repo r --number 7 --json '{\"body\":\"<PR description>\"}'"
48
+ ],
49
+ "gitrepo_pulls_merge": "--owner o --repo r --number 7 --json-out",
50
+ "gitrepo_pulls_comments_list": "--owner o --repo r --number 7 --json-out",
51
+ "gitrepo_pulls_comments_create": "--owner o --repo r --number 7 --json '{\"body\":\"<comment>\"}'",
52
+ "gitrepo_pulls_files": [
53
+ "--owner o --repo r --number 7 --json-out",
54
+ "--owner o --repo r --number 7 --page 2 --per_page 30 --json-out"
55
+ ],
56
+ "a2a_handoff": "--json '{\"agent\":\"issue\",\"payload\":{\"repository\":\"o/r\",\"account\":\"<user>\",\"issue_number\":7,\"pr_number\":0,\"context\":\"<ctx>\"}}'",
57
+ "skills_list": "--json-out",
58
+ "skills_detail": "--skill_id <id> --json-out",
59
+ "skills_featured": "--repo o/r --json-out",
60
+ "skills_stats": "--json-out",
61
+ "skills_search": "--q <keyword> --json-out",
62
+ "skills_download": "--skill_id <id>",
63
+ "skills_upload": "--file /path/to/skill.zip --scope user --agent_type coding",
64
+ "skills_convert": "--json '{\"skill_name\":\"<name>\",\"repo\":\"o/r\"}'",
65
+ "skills_delete": "--skill_id <id>",
66
+ "skills_like": "--skill_id <id>",
67
+ "skills_sub_list": "--skill_id <id> --json-out",
68
+ "skills_sub_read": "--skill_id <id> --sub_name SKILL.md --json-out",
69
+ "skills_sub_package": "--pkg_id <id> --sub_name SKILL.md --json-out",
70
+ "scenes_list": "--json-out",
71
+ "scenes_detail": "--scene_id <id> --json-out",
72
+ "events_detail": "--event_id <id> --json-out",
73
+ "agents_detail": "--json-out",
74
+ "chat_conversations": "--json-out",
75
+ "chat_messages": "--conversation_id <id> --json-out",
76
+ "repos_member": "--json-out",
77
+ "repos_managed": "--json-out",
78
+ "repos_deploy_url": "--owner o --repo r --json-out",
79
+ "knowledge_list": "--json-out",
80
+ "knowledge_content": "--knowledge_id <id> --json-out",
81
+ "knowledge_context": "--json-out",
82
+ "knowledge_detail": "--knowledge_id <id> --json-out",
83
+ "knowledge_stats": "--json-out",
84
+ "auth_profile_get": "--json-out"
85
+ }