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/registry.py ADDED
@@ -0,0 +1,1193 @@
1
+ """契约 → click 命令树(Issue-45 M4 方案 B:operationId 驱动命令生成)。
2
+
3
+ - operationId 首段 → 组名(`gitrepo_*` → `git-repo`),其余段 → 嵌套动词链。
4
+ 例:`tasks_mine` → `grape tasks mine`;`gitrepo_issues_list` → `grape git-repo issues list`。
5
+ - query/path 参数 → `--<name>`;requestBody → `--json '<body>'`;`--json-out` 机器可读输出。
6
+ - security 进契约 → 自动携带认证头(ApiClient 统一)。
7
+ - **新增 OpenAPI 接口 → 重建契约 → CLI 自动获得命令,零 CLI 源码改动**(R7)。
8
+ - 帮助语义:优先 `src/data/openapi.en.json` 的 operationId → 英文含义,回退契约 summary。
9
+ """
10
+ import base64
11
+ import binascii
12
+ import difflib
13
+ import json
14
+ import os
15
+ import re
16
+ import sys
17
+ from importlib.resources import files
18
+
19
+ import click
20
+
21
+ from grape_cli.client import ApiClient, CliError, WRITE_METHODS
22
+
23
+ GROUP_ALIAS = {"gitrepo": "git-repo"}
24
+
25
+ # Issue #2455:幂等写端点白名单——仅这些 operation 对瞬时失败状态(405/502/503)做
26
+ # 一次幂等退避重试(服务端 #725 幂等语义保证重试安全:重复调用短路返回 idempotent)。
27
+ # 不泛化到全部端点:413/422 等确定性 4xx 重试只会掩盖契约错误(Spec 决策表)。
28
+ _IDEMPOTENT_RETRY_OPS = {"issues_pending-review"}
29
+ _TRANSIENT_RETRY_STATUSES = (405, 502, 503)
30
+
31
+ # 组的固定引导行(首行=短帮助;帮助 agent 区分 demo 组语义)
32
+ _GROUP_INTRO = {
33
+ "git-repo": (
34
+ "Platform API by grape (gitcode / github / gitlab): branches, issues, "
35
+ "PRs, comments, merge & review, checks. No extra token setup - "
36
+ "use the grape session token."
37
+ ),
38
+ }
39
+
40
+ _EN_SUMMARIES: dict = {}
41
+
42
+
43
+ def _en_summary(op: dict) -> str:
44
+ """命令摘要:直接用服务端契约 summary(服务端已统一英文,单一事实源)。"""
45
+ return (op.get("summary") or "").strip()
46
+
47
+
48
+ def group_name(g: str) -> str:
49
+ return GROUP_ALIAS.get(g, g)
50
+
51
+
52
+ def parse_operations(schema: dict) -> list[dict]:
53
+ ops = []
54
+ schemas = schema.get("components", {}).get("schemas", {})
55
+ for path, methods in (schema.get("paths") or {}).items():
56
+ for method, op in methods.items():
57
+ if not isinstance(op, dict) or not op.get("operationId"):
58
+ continue
59
+ oid = op["operationId"]
60
+ # 过滤服务端 autogen 丑名(路径内嵌 "api_"),避免命令树混入 create/get 等噪音组
61
+ if "api_" in oid:
62
+ continue
63
+ parts = oid.split("_")
64
+ verb = parts[1:] or ["list"]
65
+ ops.append({
66
+ "operationId": oid,
67
+ "method": method.upper(),
68
+ "path": path,
69
+ "group": group_name(parts[0]),
70
+ "verb": verb,
71
+ "op": op,
72
+ "schemas": schemas,
73
+ })
74
+ return ops
75
+
76
+
77
+ def _params_by_in(op: dict, where: str) -> list[str]:
78
+ return [p["name"] for p in (op.get("parameters") or []) if p.get("in") == where]
79
+
80
+
81
+ def _body_schema(meta: dict) -> dict:
82
+ """解引用 requestBody schema 到 components(兼容 application/json 与 multipart)。"""
83
+ op = meta["op"]
84
+ content = (op.get("requestBody") or {}).get("content") or {}
85
+ ct = content.get("application/json") or content.get("multipart/form-data") or {}
86
+ sch = ct.get("schema") or {}
87
+ name = (sch.get("$ref") or "").rsplit("/", 1)[-1]
88
+ return meta.get("schemas", {}).get(name, {}) if name else (sch or {})
89
+
90
+
91
+ def _body_fields(meta: dict) -> list[str]:
92
+ """解析 requestBody schema 的字段清单($ref 解引用到 components)。
93
+
94
+ 兼容 application/json 与 multipart/form-data(上传类)。
95
+ """
96
+ return sorted(_body_schema(meta).get("properties") or {})
97
+
98
+
99
+ def _body_field_meta(meta: dict) -> list[dict]:
100
+ """字段元信息 [{name, required, type}]:required 读 schema.required(契约权威)。"""
101
+ schema = _body_schema(meta)
102
+ props = schema.get("properties") or {}
103
+ required = set(schema.get("required") or [])
104
+ return [
105
+ {
106
+ "name": k,
107
+ "required": k in required,
108
+ "type": (v.get("type") if isinstance(v, dict) else "") or "string",
109
+ }
110
+ for k, v in sorted(props.items())
111
+ ]
112
+
113
+
114
+ def _body_fields_help(meta: dict) -> str:
115
+ """Body fields 帮助行:`title* (required string), head* (required string), ...`(英文)。"""
116
+ out = ", ".join(
117
+ f"{f['name']}* (required {f['type']})" if f["required"] else f"{f['name']} ({f['type']})"
118
+ for f in _body_field_meta(meta)
119
+ )
120
+ return out or "(free-form JSON)"
121
+
122
+
123
+ _EXAMPLES: dict = {}
124
+
125
+
126
+ def _load_examples() -> dict:
127
+ global _EXAMPLES
128
+ if not _EXAMPLES:
129
+ try:
130
+ _EXAMPLES = json.loads(
131
+ files("grape_cli").joinpath("data", "examples.json").read_text(encoding="utf-8")
132
+ )
133
+ except Exception:
134
+ _EXAMPLES = {}
135
+ return _EXAMPLES
136
+
137
+
138
+ def _example_args(meta: dict, path_params: list[str], query_params: list[str],
139
+ body_fields: list[str]) -> list[str]:
140
+ """命令示例参数列表:优先 examples.json(str 或 list),否则自动生成占位示例。"""
141
+ raw = _load_examples().get(meta["operationId"])
142
+ if raw:
143
+ return raw if isinstance(raw, list) else [raw]
144
+ parts = [f"--{n} <{n}>" for n in path_params]
145
+ if body_fields:
146
+ parts.append(f"--json '{{\"{body_fields[0]}\":\"...\"}}'")
147
+ else:
148
+ parts += [f"--{n} <{n}>" for n in query_params[:2]]
149
+ return [" ".join(parts)]
150
+
151
+
152
+ # ---- token 作用域(docs/grape-token-scope-help.md)----
153
+ _TOKEN_SCOPE: dict | None = None
154
+
155
+
156
+ def _load_token_scope() -> dict:
157
+ """懒加载 token-scope.json:{user_only: [...], session_only: [...]}。"""
158
+ global _TOKEN_SCOPE
159
+ if _TOKEN_SCOPE is None:
160
+ try:
161
+ _TOKEN_SCOPE = json.loads(
162
+ files("grape_cli").joinpath("data", "token-scope.json").read_text(encoding="utf-8")
163
+ )
164
+ except Exception:
165
+ _TOKEN_SCOPE = {}
166
+ return _TOKEN_SCOPE
167
+
168
+
169
+ def _token_scope(meta: dict) -> str:
170
+ """operationId/op 的作用域:dual / user_only(D, session→403) / session_only(C)。
171
+
172
+ 优先读契约 `op.x-token-scope`(服务端权威),缺省回落静态表与 `gitrepo_*` 前缀。
173
+ """
174
+ _op = meta.get("op") or {}
175
+ xs = _op.get("x-token-scope")
176
+ if xs in ("dual", "user_only", "session_only"):
177
+ return xs
178
+ oid = meta.get("operationId") or ""
179
+ m = _load_token_scope()
180
+ if oid in m.get("user_only", []):
181
+ return "user_only"
182
+ if oid in m.get("session_only", []) or oid.startswith("gitrepo_"):
183
+ return "session_only"
184
+ return "dual"
185
+
186
+
187
+ def cli_mode() -> str:
188
+ """GRAPE_CLI_MODE:WORKER / USER / ALL(缺省/非法 → ALL,向后兼容)。"""
189
+ mode = (os.environ.get("GRAPE_CLI_MODE") or "ALL").strip().upper()
190
+ return mode if mode in ("WORKER", "USER", "ALL") else "ALL"
191
+
192
+
193
+ def allowed_by_mode(mode: str, scope: str) -> bool:
194
+ """scope 在当前模式下是否允许(用于过滤帮助/commands 与守卫)。"""
195
+ if mode == "ALL" or scope == "dual":
196
+ return True
197
+ if mode == "WORKER":
198
+ return scope in ("dual", "session_only")
199
+ if mode == "USER":
200
+ return scope in ("dual", "user_only")
201
+ return True
202
+
203
+
204
+ def _cmd_allowed(cmd) -> bool:
205
+ """命令/组在当前模式下是否至少有一个允许的叶子命令。"""
206
+ mode = cli_mode()
207
+ if isinstance(cmd, click.Group):
208
+ return any(_cmd_allowed(c) for c in cmd.commands.values())
209
+ scope = getattr(cmd, "token_scope", None) or "dual"
210
+ return allowed_by_mode(mode, scope)
211
+
212
+
213
+ # ---- 隐藏命令可发现性(grape-cli#183):过滤判定不变,仅汇总被过滤命令 ----
214
+
215
+ _UNLOCK_HINTS = {
216
+ "user_only": "set GRAPE_CLI_MODE=USER or ALL (or provide GRAPE_API_TOKEN)",
217
+ "session_only": "set GRAPE_CLI_MODE=WORKER or ALL (or provide GRAPE_SESSION_TOKEN)",
218
+ }
219
+
220
+
221
+ def hidden_leaves(subtree: dict, mode: str, prefix: str = "") -> list[tuple[str, str]]:
222
+ """子树中被 mode 过滤的叶子 [(动词路径, scope)](判定复用 _is_meta/_token_scope/allowed_by_mode,语义不变)。
223
+
224
+ `grape commands` 隐藏统计与组摘要隐藏计数共用;prefix 传组名即得完整命令路径。
225
+ """
226
+ if _is_meta(subtree):
227
+ scope = _token_scope(subtree)
228
+ return [] if allowed_by_mode(mode, scope) else [(prefix, scope)]
229
+ out: list[tuple[str, str]] = []
230
+ for key, val in sorted(subtree.items()):
231
+ out += hidden_leaves(val, mode, f"{prefix} {key}".strip())
232
+ return out
233
+
234
+
235
+ def hidden_commands_hint(hidden: list[tuple[str, str]], mode: str) -> str:
236
+ """grape commands 空匹配但存在被模式隐藏的匹配命令时的提示行(stdout;数量+模式+scope+开关)。"""
237
+ scopes = sorted({scope for _, scope in hidden})
238
+ label = scopes[0] if len(scopes) == 1 else "mixed"
239
+ return (f"hint: {len(hidden)} command(s) hidden by GRAPE_CLI_MODE={mode} "
240
+ f"(scope={label}); use --all to list")
241
+
242
+
243
+ def hidden_callout_lines(hidden_rows: list[tuple[str, str]]) -> list[str]:
244
+ """组帮助 Commands 段末的隐藏点名行(每 scope 一行;只统计本级子命令,不重复计数)。"""
245
+ by_scope: dict[str, list[str]] = {}
246
+ for name, scope in hidden_rows:
247
+ by_scope.setdefault(scope, []).append(name)
248
+ lines = []
249
+ for scope in sorted(by_scope):
250
+ names = sorted(by_scope[scope])
251
+ unlock = _UNLOCK_HINTS.get(scope, "set GRAPE_CLI_MODE=ALL")
252
+ lines.append(f"+{len(names)} hidden ({scope}): {', '.join(names)} — {unlock} to use")
253
+ return lines
254
+
255
+
256
+ def _cmd_display_scope(cmd) -> str:
257
+ """隐藏点名用的子命令 scope:叶子取 token_scope;子组取全部叶子 scope 聚合(mixed 兜底)。"""
258
+ if not isinstance(cmd, click.Group):
259
+ return getattr(cmd, "token_scope", None) or "dual"
260
+ scopes = set()
261
+
262
+ def _collect(g) -> None:
263
+ for c in g.commands.values():
264
+ if isinstance(c, click.Group):
265
+ _collect(c)
266
+ elif not getattr(c, "hidden", False):
267
+ scopes.add(getattr(c, "token_scope", None) or "dual")
268
+
269
+ _collect(cmd)
270
+ if len(scopes) == 1:
271
+ return next(iter(scopes))
272
+ return "mixed" if scopes else "dual"
273
+
274
+
275
+ def _read_json_arg(raw) -> str:
276
+ """--json 入参读取:`@file.json` 读文件、`@-`/`-` 读 stdin,其余原样返回。
277
+
278
+ Issue #347:裸 `-` 与 `@-` 等价,均显式声明从 stdin 读取请求体。
279
+ 文件/stdin 内容为空或纯空白时立即报错(含来源路径),
280
+ 避免与「非法 JSON」文案混淆导致排障困难。
281
+
282
+ """
283
+ if isinstance(raw, str) and raw.startswith("@"):
284
+ path = raw[1:]
285
+ try:
286
+ if path == "-":
287
+ return sys.stdin.read()
288
+ with open(path, encoding="utf-8") as f:
289
+ text = f.read()
290
+ except OSError as e:
291
+ raise CliError(f"cannot read --json file '{path}': {e}")
292
+ if not text.strip():
293
+ raise CliError(f"--json file '{path}' is empty")
294
+ return text
295
+ if raw == "-":
296
+ return sys.stdin.read()
297
+ return raw
298
+
299
+
300
+ def _read_json_file_arg(path: str) -> str:
301
+ """--json-file 入参读取:`<path>` 读文件、`-` 读 stdin(Issue #347)。"""
302
+ if path == "-":
303
+ return sys.stdin.read()
304
+ try:
305
+ with open(path, encoding="utf-8") as f:
306
+ return f.read()
307
+ except OSError as e:
308
+ raise CliError(f"cannot read --json-file '{path}': {e}")
309
+
310
+
311
+ def _parse_body_text(text: str, source_hint: str):
312
+ """JSON 文本 → 请求体;解析失败报错带行列号(Issue #347)。"""
313
+ try:
314
+ return json.loads(text)
315
+ except json.JSONDecodeError as e:
316
+ pos = f"line {e.lineno} column {e.colno}"
317
+ raise CliError(f"invalid JSON in {source_hint} ({pos}): {e.msg}")
318
+ except Exception:
319
+ raise CliError(f"invalid JSON in {source_hint}")
320
+
321
+
322
+ # 已知「能力位缺失」白名单:字段契约不支持时给出人读指引,避免 agent 原地试错(见 docs/grape-cli-help-and-hints-optimization.md §3.3)。
323
+ # 键:`group verb...`(空格分隔),值:{不支持的字段: 英文行动指引}。
324
+ _UNSUPPORTED_FIELD_HINTS: dict[str, dict[str, str]] = {
325
+ "git-repo pulls update": {
326
+ "state": "'state' is not supported here; closing/deprecating a PR is not available via this command",
327
+ },
328
+ }
329
+
330
+ # 契约选项名 → 直觉别名(#1210):键 `group verb...`,值为 {契约选项名: 别名}。
331
+ # 多名 click.Option(首名为契约名,参数名保持不变)→ 向后兼容,不改变既有调用。
332
+ _OPTION_ALIASES: dict[str, dict[str, str]] = {
333
+ "skills detail": {"--skill_id": "--skill"},
334
+ }
335
+
336
+
337
+ def _option_names(cmd_key: str, param: str) -> list[str]:
338
+ """契约参数的选项名列表:首名 = 契约名(决定参数名),后续 = 直觉别名。"""
339
+ alias = _OPTION_ALIASES.get(cmd_key, {}).get(f"--{param}")
340
+ return [f"--{param}", alias] if alias else [f"--{param}"]
341
+
342
+ # 已知「选项误用」指引表:未知选项命中时优先给行动指引,替代 click 冷冰冰的 Did you mean。
343
+ # 键:`group verb...`(空格分隔),值:{误用选项: 英文行动指引}。
344
+ # 背景(Issue grape#1643,反馈 2833/2824):commits 分支过滤参数是 --sha(分支/tag/sha),
345
+ # 部分环境曾对 --ref 静默吞掉返回空列表,导致「目标分支无提交」误判;contents/tree 才用 --ref。
346
+ _UNKNOWN_OPTION_HINTS: dict[str, dict[str, str]] = {
347
+ "git-repo commits": {
348
+ "--ref": "'--ref' is not a valid filter for `grape git-repo commits`; "
349
+ "filter by branch/tag/commit sha with `--sha <ref>` (e.g. `--sha main`). "
350
+ "Note: `--ref` only applies to contents/tree, not commits",
351
+ },
352
+ }
353
+
354
+
355
+ class _ContractCommand(click.Command):
356
+ """契约叶子命令:未知选项 fail-fast(click 默认拒绝,exit 2),命中指引表时增强文案。
357
+
358
+ 只改报错内容、不改判定结果:列出该命令合法选项,命中 _UNKNOWN_OPTION_HINTS
359
+ 时给行动指引(如 commits 过滤参数是 --sha 而非 --ref),避免 agent 原地试错。
360
+ """
361
+
362
+ def __init__(self, *args, hint_key: str, **kwargs):
363
+ super().__init__(*args, **kwargs)
364
+ self.hint_key = hint_key
365
+
366
+ def parse_args(self, ctx, args):
367
+ try:
368
+ return super().parse_args(ctx, args)
369
+ except click.UsageError as e:
370
+ option = getattr(e, "option_name", "") or ""
371
+ hint = _UNKNOWN_OPTION_HINTS.get(self.hint_key, {}).get(option)
372
+ if not hint:
373
+ raise
374
+ allowed = ", ".join(opt for p in self.params for opt in p.opts)
375
+ raise click.UsageError(
376
+ f"No such option '{option}' for `grape {self.hint_key}`\n\n"
377
+ f"{hint}\n"
378
+ f"allowed options: {allowed}\n"
379
+ f"see `grape {self.hint_key} --help`",
380
+ ctx,
381
+ ) from e
382
+
383
+
384
+ def _hint_key(meta: dict) -> str:
385
+ """契约命令在指引表中的键:`group verb...`(空格分隔,与命令路径一致)。"""
386
+ return f"{meta['group']} {' '.join(meta['verb'])}"
387
+
388
+
389
+ # 追加帮助行(operationId → ASCII 提示):契约描述被非 ASCII 过滤时的口径补充。
390
+ # #2293:milestone_id 取值口径 —— list/create 返回体 `id` 与 `number` 一一对应,
391
+ # 挂载用 `issues update --json '{"milestone_id": <id>}'`(id 优先,number 亦可)。
392
+ _HELP_HINTS: dict[str, str] = {
393
+ "gitrepo_milestones_create": (
394
+ "Scheduling: mount this milestone on an issue via "
395
+ "`grape git-repo issues update --json '{\"milestone_id\": <id>}'`; "
396
+ "use the returned `id` (or `number` - one-to-one mapping)."
397
+ ),
398
+ "gitrepo_milestones_update": (
399
+ "Identify the milestone by its `number` (from `grape git-repo milestones` "
400
+ "list/create output)."
401
+ ),
402
+ }
403
+
404
+
405
+ # 响应归一化:operationId → 后置处理函数(对齐 --state 过滤值与返回字段口径)。
406
+ # GitCode milestones 返回 state="active"(平台原值),但 --state 过滤只接受
407
+ # open/closed/all → CLI 归一化 active→open,保留 state_raw 供溯源。
408
+ _MILESTONE_STATE_MAP = {"active": "open", "closed": "closed", "open": "open"}
409
+
410
+
411
+ def _normalize_response(operation_id: str, data):
412
+ """对特定 operationId 的响应做字段口径归一化(不改变结构,仅映射值)。"""
413
+ if operation_id == "gitrepo_milestones" and isinstance(data, list):
414
+ for m in data:
415
+ if isinstance(m, dict) and "state" in m:
416
+ raw = m["state"]
417
+ m["state_raw"] = raw
418
+ m["state"] = _MILESTONE_STATE_MAP.get(raw, raw)
419
+ return data
420
+
421
+
422
+ def _validate_body(meta: dict, body, body_fields: list[str]) -> None:
423
+ """请求体守卫(通用):可枚举 schema 时,--json 内键必须都在允许集内。
424
+
425
+ 不支持的字段及时报错并列出允许字段,避免服务端 200 静默空转;服务端后续补字段后自动放行。
426
+ 追加:缺失必填字段(schema.required)报错 + 已知能力位缺失给行动指引。
427
+ """
428
+ if not body_fields or not isinstance(body, dict):
429
+ return
430
+ cmd_path = _hint_key(meta)
431
+ allowed = set(body_fields)
432
+ unknown = sorted(set(body) - allowed)
433
+ # 能力位缺失 → 优先给行动指引(白名单),替代冷冰冰 unknown field
434
+ for f in unknown:
435
+ hint = _UNSUPPORTED_FIELD_HINTS.get(cmd_path, {}).get(f)
436
+ if hint:
437
+ raise CliError(hint)
438
+ if unknown:
439
+ raise CliError(
440
+ "unknown request field(s): " + ", ".join(unknown) + "\n"
441
+ f"allowed for {meta['method']} {meta['path']}: " + ", ".join(body_fields) + "\n"
442
+ f"see `{cmd_path} --help` for the JSON request schema"
443
+ )
444
+ # 缺失必填字段(schema.required 契约权威)
445
+ required_meta = [f for f in _body_field_meta(meta) if f["required"]]
446
+ missing = sorted(f["name"] for f in required_meta if f["name"] not in body)
447
+ if missing:
448
+ raise CliError(
449
+ "missing required request field(s): " + ", ".join(missing) + "\n"
450
+ f"required for {meta['method']} {meta['path']}: " + ", ".join(f["name"] for f in required_meta) + "\n"
451
+ f"see `{cmd_path} --help` for the JSON request schema"
452
+ )
453
+
454
+
455
+ _A2A_HANDOFF_OPS = {"a2a_handoff", "pipeline_handoff"}
456
+
457
+
458
+ def _seq_int(value) -> int:
459
+ try:
460
+ return int(value)
461
+ except (TypeError, ValueError):
462
+ return 0
463
+
464
+
465
+ def _a2a_assign_downstream(data: dict, seq: int, status: str, **extra) -> None:
466
+ downstream = {"seq": seq, "status": status}
467
+ downstream.update({k: v for k, v in extra.items() if v not in (None, "")})
468
+ data["downstream"] = downstream
469
+
470
+
471
+ def _a2a_verify_dispatch(api: ApiClient, data: dict, body) -> None:
472
+ """回查 GET /api/a2a/status,补齐下游派发状态;status=failed 显式报错。
473
+
474
+ 旧服务端 handoff 响应只有 seq 时走本路径;新服务端带 event.status 时不重复请求。
475
+ """
476
+ seq = _seq_int(data.get("seq"))
477
+ payload = body.get("payload") if isinstance(body, dict) else {}
478
+ payload = payload if isinstance(payload, dict) else {}
479
+ repository = payload.get("repository") or ""
480
+ issue_number = payload.get("issue_number") or ""
481
+ agent = data.get("agent") or (body or {}).get("agent") or ""
482
+ if not (repository and issue_number and agent):
483
+ _a2a_assign_downstream(data, seq, "unknown",
484
+ warning="insufficient request fields to verify dispatch status")
485
+ return
486
+ params = {"repository": str(repository), "issue_number": str(issue_number), "agent": str(agent)}
487
+ idem = (body or {}).get("idempotency_key") or payload.get("idempotency_key")
488
+ if idem:
489
+ params["idempotency_key"] = str(idem)
490
+ try:
491
+ _status, status_data = api.request("GET", "/api/a2a/status", params=params)
492
+ except CliError as e:
493
+ _a2a_assign_downstream(data, seq, "unknown",
494
+ warning=f"dispatch status check failed: {e}")
495
+ return
496
+ events = status_data.get("events") if isinstance(status_data, dict) else None
497
+ event = next((e for e in (events or []) if _seq_int(e.get("seq")) == seq), None)
498
+ if not event:
499
+ _a2a_assign_downstream(data, seq, "unknown",
500
+ warning="event not found via /api/a2a/status yet")
501
+ return
502
+ ev_status = str(event.get("status") or "unknown")
503
+ _a2a_assign_downstream(data, seq, ev_status, agent=event.get("agent") or agent,
504
+ issue_id=event.get("issue_id") or "")
505
+ if ev_status.lower() in ("failed", "cancelled"):
506
+ raise CliError(
507
+ f"a2a handoff created seq={seq} but downstream dispatch is '{ev_status}'; "
508
+ "check target agent/engine availability and retry")
509
+
510
+
511
+ def _validate_a2a_result(api: ApiClient, data, body) -> object:
512
+ """handoff 成功语义校验:status/ok、seq>0、下游派发状态。"""
513
+ if not isinstance(data, dict):
514
+ return data
515
+ status = str(data.get("status") or "")
516
+ if data.get("ok") is False:
517
+ reason = data.get("error") or data.get("skipped") or data.get("message") or "ok=false"
518
+ raise CliError(f"a2a handoff failed: {reason}")
519
+ if status and status.lower() != "ok":
520
+ reason = data.get("error") or data.get("message") or status
521
+ raise CliError(f"a2a handoff failed ({status}): {reason}")
522
+ seq = _seq_int(data.get("seq"))
523
+ skipped = data.get("skipped") or ""
524
+ queued = bool(data.get("queued"))
525
+ if seq <= 0:
526
+ if skipped or queued:
527
+ _a2a_assign_downstream(
528
+ data, 0, "queued" if queued else "skipped",
529
+ reason=skipped or ("queued" if queued else ""),
530
+ existing_seq=data.get("existing_seq"),
531
+ queue_seq=data.get("queue_seq"),
532
+ )
533
+ return data
534
+ raise CliError(
535
+ "a2a handoff returned no dispatch event (seq=0); the target agent may be "
536
+ "unavailable or dispatch was rejected. Check the response error/skipped "
537
+ "fields and retry per runbook.")
538
+ event = data.get("event")
539
+ if isinstance(event, dict) and event.get("status"):
540
+ ev_status = str(event.get("status"))
541
+ _a2a_assign_downstream(data, seq, ev_status,
542
+ agent=event.get("agent") or data.get("agent"),
543
+ issue_id=event.get("issue_id") or "")
544
+ if ev_status.lower() in ("failed", "cancelled"):
545
+ raise CliError(
546
+ f"a2a handoff created seq={seq} but downstream dispatch is '{ev_status}'; "
547
+ "check target agent/engine availability and retry")
548
+ return data
549
+ _a2a_verify_dispatch(api, data, body)
550
+ return data
551
+
552
+
553
+ def build_command(meta: dict) -> click.Command:
554
+ op, method, path = meta["op"], meta["method"], meta["path"]
555
+ path_params = _params_by_in(op, "path")
556
+ query_params = _params_by_in(op, "query")
557
+ has_body = "requestBody" in op
558
+ # multipart/form-data 上传类(如 skills upload):--file + 表单字段,不走 --json
559
+ _content = ((op.get("requestBody") or {}).get("content") or {})
560
+ is_multipart = bool(_content.get("multipart/form-data"))
561
+ multipart_fields = []
562
+ if is_multipart:
563
+ _sch = _content["multipart/form-data"].get("schema") or {}
564
+ _ref = (_sch.get("$ref") or "").rsplit("/", 1)[-1]
565
+ _props = (meta.get("schemas", {}).get(_ref, {}) or {}).get("properties", {}) if _ref else (_sch.get("properties") or {})
566
+ multipart_fields = [k for k in sorted(_props) if k != "file"]
567
+
568
+ cmd_key = f"{meta['group']} {' '.join(meta['verb'])}"
569
+ options = [click.Option(_option_names(cmd_key, n), default=None, help=f"parameter {n}") for n in path_params]
570
+ # Issue #400:分页参数按 int 生成(契约 schema type=integer),避免字符串 query
571
+ _int_q = _INTEGER_QUERY_OVERRIDES.get(meta["operationId"], set())
572
+ for n in query_params:
573
+ if n in _int_q:
574
+ options.append(click.Option(_option_names(cmd_key, n), default=None, type=int,
575
+ help=f"parameter {n} (integer)"))
576
+ else:
577
+ options.append(click.Option(_option_names(cmd_key, n), default=None,
578
+ help=f"parameter {n}"))
579
+ # Issue #400:pulls files 的分页选项不依赖契约——remote 契约未定义
580
+ # page/per_page 时也强制注入(服务端 API 原生支持分页,契约滞后不阻塞 CLI 能力)。
581
+ if meta["operationId"] in _PAGINATED_OPS:
582
+ _have = {p.name for p in options}
583
+ if "page" not in _have:
584
+ options.append(click.Option(["--page"], default=None, type=int,
585
+ help="page number; omit to auto-fetch all pages"))
586
+ if "per_page" not in _have:
587
+ options.append(click.Option(["--per_page"], default=None, type=int,
588
+ help="results per page (1-100, default 100)"))
589
+ if is_multipart:
590
+ options.append(click.Option(["--file"], default=None, help="upload file path (multipart)"))
591
+ options += [click.Option([f"--{f}"], default="", help=f"form field {f}") for f in multipart_fields]
592
+ elif has_body:
593
+ options.append(click.Option(["--json"], default=None,
594
+ help="JSON string request body (or @file.json, or - for stdin)"))
595
+ options.append(click.Option(["--json-file"], default=None,
596
+ help="read request body JSON from <path> ('-' for stdin)"))
597
+ options.append(click.Option(["--json-out"], is_flag=True, help="machine-readable JSON output"))
598
+ # Issue #2662:写命令统一注入 --dry-run(method 判定,一处挂全量写命令,
599
+ # 新增契约写端点自动继承;GET 只读命令不挂)。
600
+ if method.upper() in WRITE_METHODS:
601
+ options.append(click.Option(
602
+ ["--dry-run"], is_flag=True,
603
+ help="preview the request (method/path/query/body, redacted) and exit "
604
+ "without sending it — zero side effects; with --json-out the last "
605
+ "line is a machine-readable JSON preview"))
606
+ if meta["operationId"] == "gitrepo_contents":
607
+ options.append(click.Option(
608
+ ["--raw"], is_flag=True,
609
+ help="base64-decode single-file content to raw bytes (text only: binary "
610
+ "content is rejected — use --json-out and decode the 'content' field; "
611
+ "dir listing falls back to JSON)"))
612
+
613
+ def _run(**kw):
614
+ api = ApiClient()
615
+ url = path
616
+ for name in path_params:
617
+ v = kw.get(name)
618
+ if v is None:
619
+ if _OPTIONAL_EMPTY_PATH.get(meta["operationId"]) == name:
620
+ v = ""
621
+ else:
622
+ raise CliError(f"Missing required parameter --{name}")
623
+ # Issue(grape)#1634:issues pending-review 的 issue_id 空/非 [0-9] 纯数字本地拦截——
624
+ # 报错退出且不发送 HTTP 请求(空值拼出 /api/issues//pending-review 曾被服务端 405 误导排障)。
625
+ # re.fullmatch([0-9]+) 而非 str.isdigit():isdigit 对 Unicode 数字("²"/"٥")也为 True,
626
+ # 会把非 ASCII 数字当纯数字放行发请求(两轴审查镜像弱点同修)。
627
+ if meta["operationId"] == "issues_pending-review" and name == "issue_id":
628
+ _v = str(v).strip()
629
+ if not re.fullmatch(r"[0-9]+", _v):
630
+ raise CliError(
631
+ f"invalid --issue_id '{v}': must be ASCII digits [0-9]+; "
632
+ "use the issue_id field from `grape issues detail` "
633
+ "(not the `.id` field), request not sent"
634
+ )
635
+ v = _v
636
+ url = url.replace("{" + name + "}", str(v))
637
+ # contents 缺省空 path → 规整到根路由(/contents/ 去尾斜杠 → /contents)
638
+ if meta["operationId"] == "gitrepo_contents" and url.endswith("/contents/"):
639
+ url = url[:-1]
640
+ params = {n: kw.get(n) for n in query_params if kw.get(n) is not None}
641
+ # Issue #400:分页参数由 _run_paginated 接管(page/per_page 强制注入),
642
+ # 不作为普通 query 透传,避免与聚合循环的请求参数冲突。
643
+ if meta["operationId"] in _PAGINATED_OPS:
644
+ params.pop("page", None)
645
+ params.pop("per_page", None)
646
+ if not allowed_by_mode(cli_mode(), _token_scope(meta)):
647
+ _scope = _token_scope(meta)
648
+ _mode = cli_mode()
649
+ _hint = ("set GRAPE_CLI_MODE=USER or ALL (or provide GRAPE_API_TOKEN)"
650
+ if _scope == "user_only" else
651
+ "set GRAPE_CLI_MODE=WORKER or ALL (or provide GRAPE_SESSION_TOKEN)")
652
+ raise CliError(
653
+ f"command requires token scope '{_scope}', not available in "
654
+ f"GRAPE_CLI_MODE={_mode}; {_hint}"
655
+ )
656
+ body = None
657
+ files = None
658
+ form_data = None
659
+ if is_multipart:
660
+ _f = kw.get("file")
661
+ if not _f:
662
+ raise CliError("Missing required --file")
663
+ try:
664
+ with open(_f, "rb") as fh:
665
+ fb = fh.read()
666
+ except OSError as e:
667
+ raise CliError(f"cannot read --file '{_f}': {e}")
668
+ fname = _f.replace("\\", "/").rsplit("/", 1)[-1]
669
+ files = {"file": (fname, fb, "application/zip")}
670
+ form_data = {f: kw.get(f) for f in multipart_fields if kw.get(f)}
671
+ else:
672
+ raw = kw.get("json")
673
+ json_file = kw.get("json_file")
674
+ if has_body and raw and json_file:
675
+ raise CliError(
676
+ "--json and --json-file are mutually exclusive; "
677
+ "provide only one body source"
678
+ )
679
+ if has_body and json_file:
680
+ body = _parse_body_text(
681
+ _read_json_file_arg(json_file), f"--json-file '{json_file}'")
682
+ if body_fields and not isinstance(body, dict):
683
+ raise CliError(
684
+ f"--json-file body must be a JSON object for this endpoint "
685
+ f"(allowed fields: {', '.join(body_fields)})"
686
+ )
687
+ _validate_body(meta, body, body_fields)
688
+ elif has_body and raw is not None:
689
+ if not str(raw).strip():
690
+ raise CliError(
691
+ "--json value is empty; provide a JSON string or @file.json"
692
+ )
693
+ _src = (f"--json file '{raw[1:]}'" if str(raw).startswith("@")
694
+ else ("--json stdin" if str(raw).strip() in ("-", "@-")
695
+ else "inline --json string"))
696
+ try:
697
+ body = _parse_body_text(_read_json_arg(raw), _src)
698
+ except CliError:
699
+ raise
700
+ except Exception:
701
+ raise CliError("--json is not a valid JSON string")
702
+ if body_fields and not isinstance(body, dict):
703
+ raise CliError(
704
+ f"--json must be a JSON object for this endpoint "
705
+ f"(allowed fields: {', '.join(body_fields)})"
706
+ )
707
+ _validate_body(meta, body, body_fields)
708
+ # Issue #2455:幂等白名单端点附带瞬时失败重试参数(405/502/503 一次,指数退避)。
709
+ _retry_kw = ({"retry_statuses": _TRANSIENT_RETRY_STATUSES, "retry_max": 1}
710
+ if meta["operationId"] in _IDEMPOTENT_RETRY_OPS else {})
711
+ # Issue #2662:--dry-run 短路——ApiClient 统一出口打印脱敏预览并返回 (0, preview),
712
+ # 不发起 HTTP;--json-out 时追加机器可读 JSON 末行,普通模式保持预览块为全部输出。
713
+ if kw.get("dry_run"):
714
+ _s, _preview = api.request(method, url, params=params, json_body=body,
715
+ files=files, data=form_data, dry_run=True)
716
+ if kw.get("json_out"):
717
+ click.echo(json.dumps(_preview, ensure_ascii=False))
718
+ return
719
+ try:
720
+ if meta["operationId"] in _PAGINATED_OPS:
721
+ # Issue #400:pulls files 分页执行(单页 / 聚合)。
722
+ out, _warn = _run_paginated(api, method, url, params,
723
+ kw.get("page"), kw.get("per_page"))
724
+ if _warn:
725
+ click.echo(_warn, err=True)
726
+ data = out
727
+ else:
728
+ _status, data = api.request(method, url, params=params, json_body=body,
729
+ files=files, data=form_data, **_retry_kw)
730
+ except CliError as e:
731
+ # D 类(user_only):会话 token 403 时追加英文行动指引,帮 agent 立即换钥
732
+ if e.code == 403 and _token_scope(meta) == "user_only":
733
+ raise CliError(
734
+ f"{e}; use GRAPE_API_TOKEN / Web JWT — "
735
+ "session token (tk_) is rejected for this scope",
736
+ code=403,
737
+ )
738
+ raise
739
+ if meta["operationId"] in _A2A_HANDOFF_OPS:
740
+ data = _validate_a2a_result(api, data, body)
741
+ if meta["operationId"] == "gitrepo_contents" and kw.get("raw") and isinstance(data, dict):
742
+ _c = data.get("content")
743
+ if _c:
744
+ # #1626:--raw 只服务文本文件——二进制(NUL/非 UTF-8)明确报错引导
745
+ # --json-out,绝不静默输出损坏字节;文本按原始字节输出、不追加换行
746
+ # (回归 #1623/#2758)。
747
+ # 坏 padding 等非法 base64 同样按拒绝处理(CliError+行动指引),不裸抛
748
+ try:
749
+ _bytes = base64.b64decode(_c)
750
+ except binascii.Error:
751
+ raise CliError(_RAW_BINARY_HINT)
752
+ if b"\x00" in _bytes:
753
+ raise CliError(_RAW_BINARY_HINT)
754
+ try:
755
+ _bytes.decode("utf-8")
756
+ except UnicodeDecodeError:
757
+ raise CliError(_RAW_BINARY_HINT)
758
+ click.echo(_bytes, nl=False)
759
+ return
760
+ data = _normalize_response(meta["operationId"], data)
761
+ click.echo(json.dumps(data, ensure_ascii=False,
762
+ indent=None if kw.get("json_out") else 2))
763
+
764
+ summary = _en_summary(op)
765
+ desc = (op.get("description") or "").strip()
766
+ # 描述仅保留 ASCII(契约描述多为中文,帮助统一英文)
767
+ if desc and not desc.isascii():
768
+ desc = ""
769
+ has_body_flag = "yes" if has_body else "no"
770
+ method_path = f"Invoke grape API: {method} {path}"
771
+ scope = _token_scope(meta)
772
+ scope_suffix = {"user_only": " (session 403 → grape_/JWT)",
773
+ "session_only": " (session-only)"}.get(scope, "")
774
+ # 首行=实际含义 + 方法与是否需要 body + token 作用域(短帮助/命令列表直接展示)
775
+ first = f"{summary or f'{method} {path}'} ({method}, body: {has_body_flag}){scope_suffix}"
776
+ help_lines = [first, "", method_path]
777
+ if scope == "user_only":
778
+ help_lines.append("Token scope: session (tk_) → 403; use GRAPE_API_TOKEN / Web JWT")
779
+ elif scope == "session_only":
780
+ help_lines.append("Token scope: session (tk_) only; API key / JWT → 403")
781
+ if meta["operationId"] in _PAGINATED_OPS:
782
+ help_lines += [
783
+ "",
784
+ "Pagination (auto): without --page this command auto-fetches ALL pages and",
785
+ "merges them, so changed_files > per_page is no longer silently truncated.",
786
+ "Output shape: {\"_pagination\": {page, per_page, total_pages, changed_files,",
787
+ "has_more}, \"files\": [...]}. With --page N it returns that single page only",
788
+ "and warns on stderr when the page is full (results may be truncated).",
789
+ "Default --per_page is 100 (max 100); service-side default page size is 30.",
790
+ ]
791
+ body_fields = _body_fields(meta)
792
+ if body_fields:
793
+ help_lines.append(f"Body fields: {_body_fields_help(meta)}")
794
+ help_lines.append(
795
+ "Long JSON body hint: use --json-file <path> (recommended), "
796
+ "--json @file.json, or --json - for stdin (multi-line, no escaping)")
797
+ elif has_body:
798
+ help_lines.append("Body fields: (free-form JSON)")
799
+ help_lines.append(
800
+ "Long JSON body hint: use --json-file <path> (recommended), "
801
+ "--json @file.json, or --json - for stdin (multi-line, no escaping)")
802
+ example_lines = _example_args(meta, path_params, query_params, body_fields)
803
+ if example_lines:
804
+ help_lines += ["", "Examples:"]
805
+ command_path = f"grape {_hint_key(meta)}"
806
+ for e in example_lines:
807
+ help_lines.append(f" {command_path} {e}")
808
+ # operationId 专属响应口径说明
809
+ if meta["operationId"] == "gitrepo_milestones":
810
+ help_lines += ["",
811
+ "Response state mapping: platform 'active' normalized to 'open' "
812
+ "(original preserved in 'state_raw'). --state accepts open/closed/all."]
813
+ hint = _HELP_HINTS.get(meta["operationId"])
814
+ if hint:
815
+ help_lines += ["", hint]
816
+ if desc and desc != summary:
817
+ help_lines += ["", desc]
818
+ help_text = "\n".join(help_lines)
819
+ cmd = _ContractCommand(name="", callback=_run, params=options, help=help_text,
820
+ hint_key=_hint_key(meta))
821
+ cmd.token_scope = _token_scope(meta)
822
+ return cmd
823
+
824
+
825
+ def build_groups(schema: dict) -> dict[str, click.Group]:
826
+ """返回 {组名: click.Group},嵌套动词链按段建子组。"""
827
+ return {gname: _materialize(subtree, gname)
828
+ for gname, subtree in sorted(contract_tree(schema).items())}
829
+
830
+
831
+ def contract_tree(schema: dict) -> dict[str, dict]:
832
+ """契约原始子树 {组名: subtree}(materialize 前的 holder,供隐藏统计复用)。"""
833
+ holder: dict = {}
834
+ for meta in parse_operations(schema):
835
+ _insert(holder, meta)
836
+ return holder
837
+
838
+
839
+ def _insert(holder: dict, meta: dict):
840
+ """插入一条 operationId 到命令树(#2293:容忍前缀重叠)。
841
+
842
+ - 叶子(命令)与分组(子命令节点)共用 dict 键位,靠 `_is_meta` 区分;
843
+ - 前缀重叠时(`gitrepo_milestones` 与 `gitrepo_milestones_create`),bare 叶子
844
+ 迁移为该组的默认命令(`_BARE_MARKER` 存放、hidden 子命令物化),子命令正常挂载,
845
+ 两种插入顺序结果一致。
846
+ """
847
+ node = holder.setdefault(meta["group"], {})
848
+ for seg in meta["verb"][:-1]:
849
+ nxt = node.get(seg)
850
+ if nxt is None:
851
+ nxt = {}
852
+ node[seg] = nxt
853
+ elif _is_meta(nxt):
854
+ # 已存在叶子命令与本段冲突 → 降级为「组 + 默认命令」
855
+ nxt = {_BARE_MARKER: nxt}
856
+ node[seg] = nxt
857
+ node = nxt
858
+ last = meta["verb"][-1]
859
+ existing = node.get(last)
860
+ if existing is None or _is_meta(existing):
861
+ node[last] = meta # 叶子:命令(同链重复 operationId 保留后写者,与旧行为一致)
862
+ else:
863
+ # 已存在子命令分组:本 operationId 是它们的公共前缀 → 默认命令位
864
+ existing[_BARE_MARKER] = meta
865
+
866
+
867
+ def _is_meta(v) -> bool:
868
+ return isinstance(v, dict) and "operationId" in v
869
+
870
+
871
+ # 前缀重叠时 bare 叶子的存放键(内部保留字,不进入帮助/命令列表)
872
+ _BARE_MARKER = "__bare__"
873
+ # bare 组默认命令的物化名(hidden;裸调用/前置选项经 parse_args 重写路由到此命令)
874
+ _BARE_CMD_NAME = "__default__"
875
+
876
+
877
+ # 常见 git 概念 → 契约动词 的别名建议(agent 猜名时的兜底)
878
+ _ALIAS_SUGGESTIONS = {
879
+ "files": ["tree", "contents"],
880
+ "file": ["contents"],
881
+ "branch": ["branches"],
882
+ "branches": ["branches"],
883
+ "commit": ["commits"],
884
+ "commits": ["commits"],
885
+ "log": ["commits"],
886
+ "repo": ["repo"],
887
+ }
888
+
889
+ # 可省略的 path 参数:缺省按服务端空 path 语义(如 contents 缺省 → 根目录列表)
890
+ _OPTIONAL_EMPTY_PATH = {
891
+ "gitrepo_contents": "path",
892
+ }
893
+
894
+ # ---- Issue #400:pulls files 分页(auto-paginate)----
895
+ # 契约补充 page/per_page 后,这两个 query 参数按 int 生成选项(其余 query 仍为 str)。
896
+ _PAGINATED_OPS = {"gitrepo_pulls_files"}
897
+ _INTEGER_QUERY_OVERRIDES = {
898
+ "gitrepo_pulls_files": {"page", "per_page"},
899
+ }
900
+ # 聚合模式安全上限:50 页 × per_page(max 100) = 5000 文件,超过报错防失控。
901
+ _PAGINATION_MAX_PAGES = 50
902
+ # 服务端 GitHub 兼容分页的每页硬上限。
903
+ _PER_PAGE_MAX = 100
904
+
905
+
906
+ def _clamp_per_page(v) -> int:
907
+ """per_page 归一:未给 → 100(减少轮次);超上限 → clamp 100;非法 → 100。"""
908
+ try:
909
+ n = int(v)
910
+ except (TypeError, ValueError):
911
+ return 100
912
+ if n < 1:
913
+ return 100
914
+ return min(n, _PER_PAGE_MAX)
915
+
916
+
917
+ def _pagination_meta(page: int, per_page: int, total_pages: int,
918
+ changed_files: int, has_more: bool) -> dict:
919
+ """_pagination 元信息(Agent 判断结果完整性)。"""
920
+ return {
921
+ "page": page,
922
+ "per_page": per_page,
923
+ "total_pages": total_pages,
924
+ "changed_files": changed_files,
925
+ "has_more": has_more,
926
+ }
927
+
928
+
929
+ def _fetch_paginated(api, method: str, url: str, params: dict,
930
+ page: int, per_page: int):
931
+ """单次分页请求(page/per_page 以 int 注入 query)。"""
932
+ q = dict(params)
933
+ q["page"] = page
934
+ q["per_page"] = per_page
935
+ _status, data = api.request(method, url, params=q)
936
+ return data
937
+
938
+
939
+ def _run_paginated(api, method: str, url: str, params: dict,
940
+ page, per_page) -> tuple:
941
+ """pulls files 分页执行(Issue #400 方案 A)。
942
+
943
+ - --page 指定 → 单页模式:仅请求该页;满页(结果数 == per_page)时
944
+ stderr 告警可能截断。
945
+ - 未指定 → 聚合模式:循环请求 page=1..N 直至短页/空页,合并全量。
946
+
947
+ 返回 (out, warning):out 为 {"_pagination": {...}, "files": [...]};
948
+ 响应非数组(错误信封等)→ 原样返回 (data, ""),不套 _pagination。
949
+ """
950
+ per_page = _clamp_per_page(per_page)
951
+ # 单页模式:--page 给定 → 直接请求该页;否则先取第 1 页再决定是否聚合
952
+ if page is not None:
953
+ try:
954
+ page_n = int(page)
955
+ except (TypeError, ValueError):
956
+ page_n = 1
957
+ if page_n < 1:
958
+ raise CliError("--page must be >= 1")
959
+ data = _fetch_paginated(api, method, url, params, page_n, per_page)
960
+ if not isinstance(data, list):
961
+ return data, ""
962
+ count = len(data)
963
+ has_more = count == per_page and count > 0
964
+ warning = ""
965
+ if has_more:
966
+ warning = (f"warning: page {page_n} is full ({count} results); "
967
+ "more pages may exist — rerun without --page to fetch all, "
968
+ f"or increment --page (next: --page {page_n + 1})")
969
+ out = {
970
+ "_pagination": _pagination_meta(
971
+ page=page_n, per_page=per_page,
972
+ total_pages=page_n, changed_files=count,
973
+ has_more=has_more),
974
+ "files": data,
975
+ }
976
+ return out, warning
977
+ _s, first = api.request(method, url, params={**params, "page": 1,
978
+ "per_page": per_page})
979
+ if not isinstance(first, list):
980
+ return first, ""
981
+ # 聚合模式:first 为第 1 页
982
+ files = list(first)
983
+ pages_fetched = 1
984
+ while len(first) == per_page and files:
985
+ if pages_fetched >= _PAGINATION_MAX_PAGES:
986
+ raise CliError(
987
+ f"auto-pagination aborted: more than {_PAGINATION_MAX_PAGES} pages "
988
+ f"({pages_fetched * per_page}+ files) — narrow the query or use "
989
+ "--page/--per_page explicitly"
990
+ )
991
+ data = _fetch_paginated(api, method, url, params,
992
+ pages_fetched + 1, per_page)
993
+ if not isinstance(data, list):
994
+ break # 异常形状:保留已聚合内容
995
+ if not data:
996
+ break
997
+ files += data
998
+ first = data
999
+ pages_fetched += 1
1000
+ total = len(files)
1001
+ out = {
1002
+ "_pagination": _pagination_meta(
1003
+ page=1, per_page=per_page, total_pages=pages_fetched,
1004
+ changed_files=total, has_more=False),
1005
+ "files": files,
1006
+ }
1007
+ return out, ""
1008
+
1009
+ # #1626:contents --raw 命中二进制(NUL 字节/非 UTF-8)时的明确报错文案(英文行动指引):
1010
+ # 不落盘损坏内容,引导改用 --json-out 并解码 content 字段获取原始字节。
1011
+ _RAW_BINARY_HINT = (
1012
+ "contents --raw: binary content detected (NUL byte or non-UTF-8 bytes); "
1013
+ "--raw only supports text files and refuses to emit corrupted bytes. "
1014
+ "Use --json-out and base64-decode the 'content' field to get the exact original bytes"
1015
+ )
1016
+
1017
+
1018
+ class _ContractGroup(click.Group):
1019
+ """契约组:agent 友好。
1020
+
1021
+ - 未知子命令 → 非零退出:difflib/别名给出 `Did you mean: ...` 并列出可用子命令(#2293);
1022
+ - 组被带未知选项调用(无首个子命令令牌)→ 打印组帮助而非报错;
1023
+ - bare 组(前缀重叠修复产物):裸调用/选项前置调用重写到默认命令,保留原叶子行为(#2293)。
1024
+ """
1025
+
1026
+ bare_meta: dict | None = None
1027
+
1028
+ def _visible_subcommands(self, ctx) -> list[str]:
1029
+ """当前 GRAPE_CLI_MODE 下可见(非 hidden、模式允许)的子命令名。"""
1030
+ out = []
1031
+ for name in self.list_commands(ctx):
1032
+ cmd = self.get_command(ctx, name)
1033
+ if cmd is None or getattr(cmd, "hidden", False):
1034
+ continue
1035
+ if not _cmd_allowed(cmd):
1036
+ continue
1037
+ out.append(name)
1038
+ return out
1039
+
1040
+ def resolve_command(self, ctx, args):
1041
+ try:
1042
+ rv = super().resolve_command(ctx, args)
1043
+ except click.UsageError as e:
1044
+ msg = e.message or ""
1045
+ if msg.startswith("No such command"):
1046
+ m = re.match(r"No such command ['\"]([^'\"]+)['\"]", msg)
1047
+ if m:
1048
+ name = m.group(1)
1049
+ cands = [c for c in set(self.commands) | set(self.list_commands(ctx))
1050
+ if c != _BARE_CMD_NAME]
1051
+ sugg = difflib.get_close_matches(name, cands, n=3, cutoff=0.55)
1052
+ sugg += [s for s in _ALIAS_SUGGESTIONS.get(name, []) if s not in sugg and s in cands]
1053
+ parts = [f"No such command '{name}'."]
1054
+ if sugg:
1055
+ parts.append("Did you mean: " + ", ".join(sugg) + "?")
1056
+ avail = self._visible_subcommands(ctx)
1057
+ if avail:
1058
+ parts.append("Available subcommands: " + ", ".join(avail) + ".")
1059
+ raise click.UsageError(" ".join(parts), ctx)
1060
+ raise
1061
+ # 默认命令展示为组名(Usage 行不泄漏内部保留字 __default__)
1062
+ if rv and rv[0] == _BARE_CMD_NAME:
1063
+ return (self.name, rv[1], rv[2])
1064
+ return rv
1065
+
1066
+ def parse_args(self, ctx, args):
1067
+ if self.bare_meta is not None:
1068
+ if not args:
1069
+ args = [_BARE_CMD_NAME]
1070
+ elif args[0].startswith("-"):
1071
+ # 裸调用带前置选项(--owner o ...)→ 路由给默认命令解析(保留原叶子行为)
1072
+ args = [_BARE_CMD_NAME, *args]
1073
+ try:
1074
+ return super().parse_args(ctx, args)
1075
+ except click.UsageError as e:
1076
+ msg = e.message or ""
1077
+ if msg.startswith(("No such option", "Got unexpected extra argument")):
1078
+ click.echo(ctx.get_help())
1079
+ ctx.exit(0)
1080
+ raise
1081
+
1082
+ def format_commands(self, ctx, formatter):
1083
+ """按 GRAPE_CLI_MODE 过滤:只列当前模式允许的动词;被隐藏子命令在段末点名(可发现性)。
1084
+
1085
+ 点名行只统计本级子命令(多级组在各自 --help 各自统计,不重复计数);
1086
+ 隐式 click hidden 命令不计入,避免与模式过滤语义混淆。
1087
+ """
1088
+ rows = []
1089
+ hidden_rows: list[tuple[str, str]] = []
1090
+ for name in self.list_commands(ctx):
1091
+ cmd = self.get_command(ctx, name)
1092
+ if cmd is None or getattr(cmd, "hidden", False):
1093
+ continue
1094
+ if _cmd_allowed(cmd):
1095
+ rows.append((name, cmd))
1096
+ else:
1097
+ hidden_rows.append((name, _cmd_display_scope(cmd)))
1098
+ if not rows and not hidden_rows:
1099
+ return
1100
+ max_name = max((len(n) for n, _ in rows), default=0)
1101
+ limit = formatter.width - 10 - max_name
1102
+ with formatter.section("Commands"):
1103
+ if rows:
1104
+ formatter.write_dl([(n, c.get_short_help_str(limit)) for n, c in rows])
1105
+ for line in hidden_callout_lines(hidden_rows):
1106
+ formatter.write_text(line)
1107
+ formatter.write_paragraph()
1108
+
1109
+
1110
+ def _subtree_allowed(subtree) -> bool:
1111
+ """子树叶子中是否有任何一个在当前 GRAPE_CLI_MODE 下允许(用于组摘要过滤)。"""
1112
+ if _is_meta(subtree):
1113
+ return allowed_by_mode(cli_mode(), _token_scope(subtree))
1114
+ return any(_subtree_allowed(v) for v in subtree.values())
1115
+
1116
+
1117
+ def _materialize(subtree: dict, name: str) -> click.Group:
1118
+ """按子命令摘要聚合出“实际含义”,作为组帮助首行(方便 agent 快速理解)。
1119
+
1120
+ 摘要按 GRAPE_CLI_MODE 过滤:只列当前模式允许的动词,避免 user_only 命令在
1121
+ WORKER 帮助下泄漏(commands 列表已过滤,首行摘要需同步);
1122
+ 被过滤数量以 (+N hidden by GRAPE_CLI_MODE) 补注(只计数不点名,点名在 Commands 段)。
1123
+
1124
+ 前缀重叠(#2293):bare 叶子以 `(default) <summary>` 列在含义行首位,物化为
1125
+ hidden 默认命令 `_BARE_CMD_NAME`,子命令照常挂载。
1126
+ """
1127
+ bare = subtree.get(_BARE_MARKER)
1128
+ mode = cli_mode()
1129
+ meaning = []
1130
+ for key, val in sorted(subtree.items()):
1131
+ if key == _BARE_MARKER:
1132
+ continue
1133
+ if not _subtree_allowed(val):
1134
+ continue
1135
+ if _is_meta(val):
1136
+ s = _en_summary(val["op"])
1137
+ meaning.append(f"{key}: {s}" if s else key)
1138
+ else:
1139
+ meaning.append(key)
1140
+ if bare is not None and _subtree_allowed(bare):
1141
+ s = _en_summary(bare["op"])
1142
+ meaning.insert(0, f"(default) {s}" if s else "(default)")
1143
+ summary = ", ".join(meaning)
1144
+ hidden_count = len(hidden_leaves(subtree, mode))
1145
+ if hidden_count:
1146
+ tag = f"+{hidden_count} hidden by GRAPE_CLI_MODE"
1147
+ summary = f"{summary} ({tag})" if summary else f"({tag})"
1148
+ lines = []
1149
+ intro = _GROUP_INTRO.get(name)
1150
+ if intro:
1151
+ lines += [intro, ""]
1152
+ lines += [summary, ""]
1153
+ if bare is not None:
1154
+ lines += [
1155
+ f"Bare `grape <group> {name}` runs the default command above; "
1156
+ "invoke a subcommand (verb) via "
1157
+ f"`grape <group> {name} <verb>` (see `--help`).",
1158
+ ]
1159
+ else:
1160
+ lines += [
1161
+ "Invoke a subcommand (verb) of this group: "
1162
+ f"`grape <group> {name} <verb>`; bare invocation shows this help.",
1163
+ ]
1164
+ grp = _ContractGroup(
1165
+ name=name,
1166
+ help="\n".join(lines),
1167
+ context_settings=dict(help_option_names=["-h", "--help"]),
1168
+ )
1169
+ if bare is not None:
1170
+ grp.bare_meta = bare
1171
+ for key, val in sorted(subtree.items()):
1172
+ if key == _BARE_MARKER:
1173
+ continue
1174
+ if _is_meta(val):
1175
+ cmd = build_command(val)
1176
+ cmd.name = key
1177
+ grp.add_command(cmd, name=key)
1178
+ else:
1179
+ grp.add_command(_materialize(val, key), name=key)
1180
+ if bare is not None:
1181
+ default_cmd = build_command(bare)
1182
+ default_cmd.name = _BARE_CMD_NAME
1183
+ default_cmd.hidden = True
1184
+ grp.add_command(default_cmd, name=_BARE_CMD_NAME)
1185
+ return grp
1186
+
1187
+
1188
+ def command_tree(schema: dict) -> dict[str, list[str]]:
1189
+ """{组: [动词链]} 便于 --list / commands 展示。"""
1190
+ tree: dict[str, set] = {}
1191
+ for meta in parse_operations(schema):
1192
+ tree.setdefault(meta["group"], set()).add(meta["operationId"].split("_", 1)[1] or "list")
1193
+ return {g: sorted(v) for g, v in sorted(tree.items())}