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/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ """grape CLI 独立包(Issue-45 M4)。"""
2
+ __version__ = "0.3.4"
grape_cli/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """python -m grape_cli 入口。"""
2
+ import sys
3
+
4
+ from grape_cli.cli import main
5
+
6
+ if __name__ == "__main__":
7
+ sys.exit(main(prog_name="grape"))
grape_cli/cli.py ADDED
@@ -0,0 +1,354 @@
1
+ """grape CLI 入口:契约驱动命令 + 内置(git/refresh/commands/wait)。"""
2
+ import json
3
+ import sys
4
+ import time
5
+
6
+ import click
7
+
8
+ from grape_cli import __version__, config, update_check
9
+ from grape_cli.client import ApiClient, CliError
10
+ from grape_cli.commands.doctor import doctor_command
11
+ from grape_cli.commands.git import git_command
12
+ from grape_cli.contracts import load_contract
13
+ from grape_cli.registry import (
14
+ _BARE_CMD_NAME,
15
+ _cmd_allowed,
16
+ build_groups,
17
+ cli_mode,
18
+ command_tree,
19
+ contract_tree,
20
+ hidden_commands_hint,
21
+ hidden_leaves,
22
+ )
23
+
24
+
25
+ def wait_command() -> click.Command:
26
+ """grape tasks wait:轮询任务状态直至终态(复用 GET /api/tasks/{id}/status,契约驱动)。"""
27
+ @click.command(name="wait",
28
+ help="Wait until a task reaches a terminal state (completed / failed / cancelled)")
29
+ @click.option("--task-id", required=True, help="task id")
30
+ @click.option("--timeout", default=120, help="max wait seconds (default 120)")
31
+ @click.option("--interval", default=3, help="poll interval seconds (default 3)")
32
+ @click.option("--json-out", is_flag=True, help="machine-readable JSON output")
33
+ def _wait(task_id: str, timeout: int, interval: int, json_out: bool):
34
+ api = ApiClient()
35
+ _terminal = {"completed", "failed", "cancelled"}
36
+ deadline = time.time() + max(0, timeout)
37
+ data = {}
38
+ while True:
39
+ _s, data = api.request("GET", f"/api/tasks/{task_id}/status")
40
+ st = data.get("status", "")
41
+ if st in _terminal or time.time() >= deadline:
42
+ break
43
+ time.sleep(max(0, interval))
44
+ out = json.dumps(data, ensure_ascii=False, indent=None if json_out else 2)
45
+ click.echo(out)
46
+ if data.get("status") not in _terminal:
47
+ raise CliError(
48
+ f"wait timeout (> {timeout}s), current status {st or 'unknown'}"
49
+ )
50
+
51
+ return _wait
52
+
53
+
54
+ class ContractGroup(click.Group):
55
+ """加载 /openapi.json 动态生成命令组(方案 B):新增契约 → 自动获得命令。"""
56
+
57
+ # ---- 帮助类别分组(按意图 × 读写角色,docs/grape-help-category-redesign.md)----
58
+ CATEGORY_MAP = {
59
+ # Core workflows:agent 驱动的流程(会变更)
60
+ "tasks": "Core workflows",
61
+ "a2a": "Core workflows",
62
+ # Agent Context:执行 agent 只读上下文(改状态属 user 层)
63
+ "issues": "Agent Context",
64
+ "events": "Agent Context",
65
+ "knowledge": "Agent Context",
66
+ # Code & repositories
67
+ "git": "Code & repositories",
68
+ "git-repo": "Code & repositories",
69
+ # Account & platform:用户级平台资源(管理导向,含 skills/scenes)
70
+ "agents": "Account & platform",
71
+ "auth": "Account & platform",
72
+ "chat": "Account & platform",
73
+ "repos": "Account & platform",
74
+ "scenes": "Account & platform",
75
+ "skills": "Account & platform",
76
+ # CLI utilities:元命令
77
+ "commands": "CLI utilities",
78
+ "refresh": "CLI utilities",
79
+ "doctor": "CLI utilities",
80
+ }
81
+ CATEGORY_ORDER = [
82
+ "Core workflows",
83
+ "Code & repositories",
84
+ "Agent Context",
85
+ "Account & platform",
86
+ "CLI utilities",
87
+ ]
88
+ DEFAULT_CATEGORY = "Account & platform"
89
+ CATEGORY_INTRO = {
90
+ "Core workflows": "task actions & agent handoffs",
91
+ "Agent Context": "issue / events / knowledge",
92
+ "Code & repositories": "run git locally / platform repo API",
93
+ "Account & platform": "user-level platform resources",
94
+ "CLI utilities": "manage the contract & commands",
95
+ }
96
+
97
+ def __init__(self, *a, **kw):
98
+ super().__init__(*a, **kw)
99
+ self._groups: dict = {}
100
+ self._loaded = False
101
+ self._load_error = ""
102
+ self.contract_version = ""
103
+
104
+ def format_commands(self, ctx, formatter):
105
+ """按类别渲染 Commands,便于 agent/人扫读。"""
106
+ rows_by_cat: dict[str, list] = {}
107
+ for name in self.list_commands(ctx):
108
+ cmd = self.get_command(ctx, name)
109
+ if cmd is None or getattr(cmd, "hidden", False):
110
+ continue
111
+ if not _cmd_allowed(cmd):
112
+ continue
113
+ cat = self.CATEGORY_MAP.get(name, self.DEFAULT_CATEGORY)
114
+ rows_by_cat.setdefault(cat, []).append((name, cmd))
115
+ if not rows_by_cat:
116
+ return
117
+ with formatter.section("Commands"):
118
+ for cat in self.CATEGORY_ORDER:
119
+ items = rows_by_cat.get(cat)
120
+ if not items:
121
+ continue
122
+ max_name = max(len(n) for n, _ in items)
123
+ limit = formatter.width - 10 - max_name
124
+ rows = [(n, c.get_short_help_str(limit)) for n, c in items]
125
+ intro = self.CATEGORY_INTRO.get(cat)
126
+ header = f"{cat} ({intro}):" if intro else f"{cat}:"
127
+ # git 风格:分类说明单独一段,其下命令名对齐成列并缩进一级
128
+ formatter.write_text(header)
129
+ with formatter.indentation():
130
+ formatter.write_dl(rows)
131
+ formatter.write_paragraph()
132
+ formatter.write_paragraph()
133
+
134
+ def _ensure(self, refresh: bool = False):
135
+ if self._loaded and not refresh:
136
+ return
137
+ try:
138
+ schema = load_contract(refresh=refresh)
139
+ self.contract_version = str(schema.get("info", {}).get("version", ""))
140
+ self._groups = build_groups(schema)
141
+ # 注入静态 wait 子命令(非契约):grape tasks wait --task-id x
142
+ _tasks = self._groups.get("tasks")
143
+ if _tasks is not None:
144
+ try:
145
+ _tasks.add_command(wait_command(), name="wait")
146
+ except Exception:
147
+ pass
148
+ self._loaded = True
149
+ except Exception as e:
150
+ self._load_error = str(e)
151
+ self._groups = {}
152
+ self._loaded = True
153
+
154
+ def get_command(self, ctx, cmd_name):
155
+ cmd = super().get_command(ctx, cmd_name)
156
+ if cmd is not None:
157
+ return cmd
158
+ if not cmd_name.startswith(("-", "_")):
159
+ self._ensure()
160
+ return self._groups.get(cmd_name)
161
+
162
+ def resolve_command(self, ctx, args):
163
+ # click 在子命令解析期(早于组回调 set_cli_params)就可能拉取契约;
164
+ # --no-proxy 先在此接线,保证绕过开关对契约请求同样生效(grape#2252)
165
+ if ctx.params.get("no_proxy"):
166
+ from grape_cli.config import set_cli_params
167
+ set_cli_params(no_proxy=True)
168
+ return super().resolve_command(ctx, args)
169
+
170
+ def list_commands(self, ctx):
171
+ cmds = list(super().list_commands(ctx))
172
+ try:
173
+ self._ensure()
174
+ cmds += list(self._groups.keys())
175
+ except Exception:
176
+ pass
177
+ return sorted(set(cmds))
178
+
179
+
180
+ @click.group(cls=ContractGroup, invoke_without_command=True,
181
+ context_settings=dict(help_option_names=["-h", "--help"]))
182
+ @click.version_option(__version__, "--version", "-v", prog_name="grape",
183
+ message="%(prog)s %(version)s")
184
+ @click.option("--base-url", default=None, help="server base URL (one-shot, highest priority)")
185
+ @click.option("--token", "--grape-api-token", "--grape_api_token", default=None,
186
+ help="token (one-shot, highest priority; tk_ session / grape_ user key)")
187
+ @click.option("--timeout", default=None, type=int,
188
+ help="request timeout seconds (default 30; not applied to git)")
189
+ @click.option("--no-version-check", is_flag=True,
190
+ help="skip the async new-version check (also: GRAPE_NO_VERSION_CHECK=1 or config version_check=false)")
191
+ @click.option("--no-proxy", is_flag=True, default=False,
192
+ help="ignore *_proxy/NO_PROXY environment variables and connect directly "
193
+ "(same as GRAPE_TRUST_ENV=0)")
194
+ @click.pass_context
195
+ def cli(ctx, base_url: str | None, token: str | None, timeout: int | None,
196
+ no_proxy: bool, no_version_check: bool = False):
197
+ """Grape CLI: contract-driven commands (new API endpoint -> new command automatically)
198
+ plus local git passthrough (platform token stays in-process).
199
+
200
+ \b
201
+ One-shot usage:
202
+ grape --token tk_xxx tasks mine --status active
203
+ grape --base-url https://grape.example.com --grape-api-token grape_xxx skills list --json-out
204
+ grape --timeout 120 tasks wait --task-id 56
205
+ grape --no-proxy issues list # ignore *_proxy/NO_PROXY env vars
206
+ """
207
+ from grape_cli.config import set_cli_params
208
+ set_cli_params(base_url=base_url or "", token=token or "",
209
+ timeout=timeout or 0, no_proxy=no_proxy)
210
+ if ctx.invoked_subcommand is None:
211
+ click.echo(ctx.get_help())
212
+ return
213
+ checker = update_check.start(no_version_check=no_version_check)
214
+ if checker is not None:
215
+ ctx.call_on_close(lambda: update_check.emit(checker))
216
+
217
+
218
+ def _walk_commands(grp, prefix, out):
219
+ for name in sorted(grp.commands):
220
+ cmd = grp.commands[name]
221
+ if getattr(cmd, "hidden", False):
222
+ continue
223
+ full = f"{prefix} {name}"
224
+ if isinstance(cmd, click.Group):
225
+ if not _cmd_allowed(cmd):
226
+ continue
227
+ _walk_commands(cmd, full, out)
228
+ # #2293 前缀重叠组:裸调用可执行(默认命令)→ 该组自身路径也是可调用命令
229
+ default_cmd = cmd.commands.get(_BARE_CMD_NAME)
230
+ if default_cmd is not None and _cmd_allowed(default_cmd):
231
+ out.append(full)
232
+ elif _cmd_allowed(cmd):
233
+ out.append(full)
234
+
235
+
236
+ def _tree_lines(pattern: str = "",
237
+ include_hidden: bool = False) -> tuple[list[str], list[tuple[str, str]]]:
238
+ """列出【真实可调用】的契约命令(空格分隔、叶子展开),供 grape commands。
239
+
240
+ 返回 (展示行, 隐藏叶子 [(完整命令路径, scope)]);include_hidden 时展示集合并入
241
+ 隐藏叶子(带 [scope] 标注,仅列出不放行——运行守卫不变)。
242
+ """
243
+ try:
244
+ schema = load_contract()
245
+ groups = build_groups(schema)
246
+ raw_groups = contract_tree(schema)
247
+ except Exception as e:
248
+ return [f"contract load failed: {e} (check base_url/token or run grape refresh)"], []
249
+ mode = cli_mode()
250
+ lines = []
251
+ for gname in sorted(groups):
252
+ _walk_commands(groups[gname], gname, lines)
253
+ lines = sorted(set(lines))
254
+ hidden: list[tuple[str, str]] = []
255
+ for gname in sorted(raw_groups):
256
+ hidden += hidden_leaves(raw_groups[gname], mode, gname)
257
+ hidden = sorted(set(hidden))
258
+ if pattern:
259
+ lines = [n for n in lines if pattern in n]
260
+ hidden = [(p, s) for p, s in hidden if pattern in p]
261
+ if include_hidden:
262
+ lines = sorted(set(lines) | {f"{p} [{s}]" for p, s in hidden})
263
+ return lines, hidden
264
+
265
+
266
+ @cli.command("refresh")
267
+ def refresh_cmd():
268
+ """Force re-fetch the latest OpenAPI contract and cache it."""
269
+ schema = load_contract(refresh=True)
270
+ cli._groups = build_groups(schema)
271
+ cli._loaded = True
272
+ cli.contract_version = str(schema.get("info", {}).get("version", ""))
273
+ from grape_cli.contracts import contract_source
274
+
275
+ src_info = contract_source()
276
+ src_note = f" (source: {src_info['kind']} {src_info['detail']})" if src_info.get("kind") else ""
277
+ click.echo(
278
+ f"contract refreshed: v{schema.get('info', {}).get('version', '?')} "
279
+ f"({len(schema.get('paths', {}))} endpoints){src_note}"
280
+ )
281
+
282
+
283
+ @cli.command(name="commands")
284
+ @click.argument("pattern", default="")
285
+ @click.option("--all", "all_", is_flag=True,
286
+ help="also list commands hidden by GRAPE_CLI_MODE (annotated [scope]; "
287
+ "listing only, execution still guarded)")
288
+ def commands_cmd(pattern: str, all_: bool):
289
+ """List contract commands; filter with a pattern, e.g. 'grape commands issue'."""
290
+ lines, hidden = _tree_lines(pattern, include_hidden=all_)
291
+ for line in lines:
292
+ click.echo(line)
293
+ if not pattern:
294
+ click.echo("hint: filter commands with: grape commands <pattern>", err=True)
295
+ if all_ and hidden:
296
+ click.echo("hint: [scope]-marked commands are hidden by GRAPE_CLI_MODE "
297
+ "(listing only; execution still guarded)")
298
+ if not lines:
299
+ if hidden:
300
+ click.echo(hidden_commands_hint(hidden, cli_mode()))
301
+ else:
302
+ click.echo("no contract commands matched (run grape refresh or check base_url/token)")
303
+
304
+
305
+ refresh_cmd.token_scope = "dual"
306
+ commands_cmd.token_scope = "dual"
307
+
308
+ git_cmd = git_command()
309
+ git_cmd.token_scope = "session_only"
310
+ cli.add_command(git_cmd)
311
+
312
+ # Issue #2662:grape doctor 一站式环境自检——无需 token 即可运行(自诊入口),
313
+ # 三通道任一可用即过;status=WARN 不阻断、FAIL 才非零退出。
314
+ doctor_cmd = doctor_command()
315
+ doctor_cmd.token_scope = "dual"
316
+ cli.add_command(doctor_cmd)
317
+
318
+
319
+ def main(argv=None, *args, **kw):
320
+ """入口:返回退出码(console script 中 sys.exit(main()) 消费)。
321
+
322
+ - 0 成功
323
+ - 1 通用/配置错误(缺 token、网络、超时等)
324
+ - 2 click 用法错误
325
+ - =HTTP(≥400) CliError 透传(401 等)
326
+ - 130 Ctrl+C 用户中断
327
+ """
328
+ # Windows GBK 控制台兜底:统一 UTF-8 输出,非 ASCII(如 ✅)逐字降级而非抛异常
329
+ try:
330
+ for _s in (sys.stdout, sys.stderr):
331
+ _s.reconfigure(encoding="utf-8", errors="replace")
332
+ except Exception:
333
+ pass
334
+ _argv = list(sys.argv[1:]) if argv is None else list(argv)
335
+ try:
336
+ rv = cli(_argv, standalone_mode=False, *args, **kw)
337
+ return 0 if rv is None else int(rv)
338
+ except click.exceptions.Abort:
339
+ # Ctrl+C(click 把 KeyboardInterrupt 转 Abort)→ 规范化 130
340
+ click.echo("Error: interrupted", err=True)
341
+ return 130
342
+ except KeyboardInterrupt:
343
+ click.echo("Error: interrupted", err=True)
344
+ return 130
345
+ except CliError as e:
346
+ click.echo(f"Error: {e}", err=True)
347
+ return e.code or 1
348
+ except click.exceptions.ClickException as e:
349
+ e.show()
350
+ return int(getattr(e, "exit_code", 1)) or 1
351
+
352
+
353
+ if __name__ == "__main__":
354
+ sys.exit(main(prog_name="grape"))