tool4seller-cli 1.0.0__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.
tool4seller_cli/cli.py ADDED
@@ -0,0 +1,383 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import requests
9
+ import typer
10
+
11
+ from tool4seller_cli import __version__
12
+ from tool4seller_cli.auth.login import login_with_browser
13
+ from tool4seller_cli.auth.oauth import CLIENT_ID, refresh_access_token
14
+ from tool4seller_cli.auth.token_store import FileTokenStore, TokenSet
15
+ from tool4seller_cli.config import Environment, resolve_config_dir, resolve_environment
16
+ from tool4seller_cli.dynamic import parse_dynamic_params
17
+ from tool4seller_cli.http_client import APIError, Client
18
+ from tool4seller_cli.schema.registry import Operation, Registry, load_bundled_registry
19
+ from tool4seller_cli.skills_installer import (
20
+ inspect_default_agent_dirs,
21
+ install_packaged_skills,
22
+ install_skills_to_default_agent_dirs,
23
+ )
24
+
25
+
26
+ BUILTIN_NAMES = {"auth", "schema", "api", "skills", "profile"}
27
+
28
+ app = typer.Typer(name="tool4seller", add_completion=False, no_args_is_help=False)
29
+ auth_app = typer.Typer(add_completion=False)
30
+ schema_app = typer.Typer(add_completion=False)
31
+ skills_app = typer.Typer(add_completion=False)
32
+ registry = load_bundled_registry()
33
+
34
+
35
+ @app.callback(invoke_without_command=True)
36
+ def root(
37
+ ctx: typer.Context,
38
+ version: bool = typer.Option(
39
+ False,
40
+ "--version",
41
+ is_eager=True,
42
+ help="Print version and exit.",
43
+ ),
44
+ env: str = typer.Option("", "--env", help="Environment name."),
45
+ base_url: str = typer.Option("", "--base-url", help="Override API base URL."),
46
+ ) -> None:
47
+ if version:
48
+ typer.echo(__version__)
49
+ raise typer.Exit()
50
+
51
+ environment = _resolve_environment(env, base_url)
52
+ ctx.obj = {
53
+ "environment": environment,
54
+ "config_dir": resolve_config_dir(os.environ),
55
+ }
56
+
57
+ if ctx.invoked_subcommand is None:
58
+ _echo_startup_message()
59
+ raise typer.Exit()
60
+
61
+
62
+ @auth_app.command("status")
63
+ def auth_status(ctx: typer.Context) -> None:
64
+ environment, store = _environment_and_store(ctx)
65
+ token = store.load(environment.name)
66
+ _echo_json(
67
+ {
68
+ "authenticated": bool(token.access_token),
69
+ "environment": environment.name,
70
+ "baseUrl": environment.base_url,
71
+ }
72
+ )
73
+
74
+
75
+ @auth_app.command("logout")
76
+ def auth_logout(ctx: typer.Context) -> None:
77
+ environment, store = _environment_and_store(ctx)
78
+ store.clear(environment.name)
79
+ _echo_json({"ok": True, "environment": environment.name})
80
+
81
+
82
+ @auth_app.command("login")
83
+ def auth_login(ctx: typer.Context) -> None:
84
+ environment, store = _environment_and_store(ctx)
85
+ token = login_with_browser(environment.base_url)
86
+ store.save(environment.name, token)
87
+ _echo_json({"ok": True, "environment": environment.name})
88
+
89
+
90
+ @schema_app.command("list")
91
+ def schema_list(
92
+ domain: str = typer.Option("", "--domain", help="Filter operations by schema domain."),
93
+ ) -> None:
94
+ operations = registry.list_operations()
95
+ if domain:
96
+ operations = [operation for operation in operations if operation.domain == domain]
97
+ _echo_json([_operation_summary(operation) for operation in operations])
98
+
99
+
100
+ @schema_app.command("show")
101
+ def schema_show(ref: str) -> None:
102
+ operation = registry.find(ref)
103
+ if operation is None:
104
+ typer.echo("operation not found")
105
+ raise typer.Exit(code=1)
106
+ _echo_json(_operation_detail(operation))
107
+
108
+
109
+ @skills_app.command("install")
110
+ def skills_install(
111
+ destination: Path | None = typer.Option(
112
+ None,
113
+ "--destination",
114
+ help="Destination directory for installed skills. Omit to install skills for existing Codex, Claude, and WorkBuddy directories.",
115
+ ),
116
+ ) -> None:
117
+ _install_skills(destination)
118
+
119
+
120
+ @skills_app.command("update")
121
+ def skills_update(
122
+ destination: Path | None = typer.Option(
123
+ None,
124
+ "--destination",
125
+ help="Destination directory for installed skills. Omit to install skills for existing Codex, Claude, and WorkBuddy directories.",
126
+ ),
127
+ ) -> None:
128
+ _install_skills(destination)
129
+
130
+
131
+ @app.command("api")
132
+ def api_command(
133
+ ctx: typer.Context,
134
+ method: str,
135
+ path: str,
136
+ params: str = typer.Option("{}", "--params", help="JSON query parameters."),
137
+ data: str = typer.Option("null", "--data", help="JSON request body."),
138
+ ) -> None:
139
+ parsed_params = _parse_json_option(params, "--params")
140
+ parsed_data = _parse_json_option(data, "--data")
141
+ result = _run_api_request(ctx, method, path, parsed_params, parsed_data)
142
+ _echo_json(result)
143
+
144
+
145
+ @app.command("profile")
146
+ def profile_command(ctx: typer.Context) -> None:
147
+ result = _run_api_request(ctx, "GET", "/api/v2/me", {}, None)
148
+ _echo_json(result)
149
+
150
+
151
+ def _api_client_from_context(ctx: typer.Context) -> Client:
152
+ environment, store = _environment_and_store(ctx)
153
+ refreshed_token: TokenSet | None = None
154
+
155
+ def token_provider() -> str:
156
+ if refreshed_token is not None:
157
+ return refreshed_token.access_token
158
+ env_token = os.environ.get("TOOL4SELLER_ACCESS_TOKEN", "").strip()
159
+ if env_token:
160
+ return env_token
161
+ return store.load(environment.name).access_token
162
+
163
+ def refresh_provider() -> TokenSet | None:
164
+ nonlocal refreshed_token
165
+ stored = store.load(environment.name)
166
+ refresh_token = os.environ.get("TOOL4SELLER_REFRESH_TOKEN", "").strip() or stored.refresh_token
167
+ if not refresh_token:
168
+ return None
169
+ refreshed = refresh_access_token(
170
+ environment.base_url,
171
+ refresh_token=refresh_token,
172
+ client_id=CLIENT_ID,
173
+ )
174
+ if refreshed.refresh_token:
175
+ token = refreshed
176
+ else:
177
+ token = TokenSet(
178
+ access_token=refreshed.access_token,
179
+ refresh_token=refresh_token,
180
+ expires_at=refreshed.expires_at,
181
+ )
182
+ store.save(environment.name, token)
183
+ refreshed_token = token
184
+ return token
185
+
186
+ return Client(
187
+ environment.base_url,
188
+ token_provider=token_provider,
189
+ refresh_token_provider=refresh_provider,
190
+ )
191
+
192
+
193
+ def _run_api_request(
194
+ ctx: typer.Context,
195
+ method: str,
196
+ path: str,
197
+ params: dict[str, Any] | None,
198
+ body: Any,
199
+ ) -> Any:
200
+ try:
201
+ return _api_client_from_context(ctx).request(method, path, params, body)
202
+ except APIError as exc:
203
+ _emit_request_error(exc.error_type, str(exc), exc.status_code)
204
+ except requests.RequestException as exc:
205
+ _emit_request_error("transport_error", str(exc), None)
206
+
207
+
208
+ def _emit_request_error(error_type: str, message: str, status_code: int | None) -> None:
209
+ _echo_json(
210
+ {
211
+ "ok": False,
212
+ "error": {
213
+ "type": error_type,
214
+ "message": message,
215
+ "statusCode": status_code,
216
+ },
217
+ }
218
+ )
219
+ raise typer.Exit(code=1)
220
+
221
+
222
+ def register_dynamic_commands(root_app: typer.Typer, bundled_registry: Registry) -> None:
223
+ groups: dict[str, typer.Typer] = {}
224
+ for operation in bundled_registry.list_operations():
225
+ if operation.domain in BUILTIN_NAMES:
226
+ continue
227
+ group = groups.get(operation.domain)
228
+ if group is None:
229
+ group = typer.Typer(add_completion=False)
230
+ groups[operation.domain] = group
231
+ root_app.add_typer(group, name=operation.domain)
232
+ _register_dynamic_command(group, operation)
233
+
234
+
235
+ def _register_dynamic_command(group: typer.Typer, operation: Operation) -> None:
236
+ def command(ctx: typer.Context) -> None:
237
+ try:
238
+ query_params, resolved_path = parse_dynamic_params(operation, list(ctx.args))
239
+ except ValueError as exc:
240
+ typer.echo(str(exc))
241
+ raise typer.Exit(code=1) from exc
242
+ result = _run_api_request(
243
+ ctx,
244
+ operation.method,
245
+ resolved_path,
246
+ query_params,
247
+ None,
248
+ )
249
+ _echo_json(result)
250
+
251
+ command.__name__ = operation.name.replace("-", "_")
252
+ group.command(
253
+ name=operation.name,
254
+ help=_dynamic_command_help(operation),
255
+ context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
256
+ )(command)
257
+
258
+
259
+ def _environment_and_store(ctx: typer.Context) -> tuple[Environment, FileTokenStore]:
260
+ obj = ctx.obj if isinstance(ctx.obj, dict) else {}
261
+ environment = obj.get("environment")
262
+ if not isinstance(environment, Environment):
263
+ environment = _resolve_environment("", "")
264
+ config_dir = obj.get("config_dir") or resolve_config_dir(os.environ)
265
+ return environment, FileTokenStore(config_dir)
266
+
267
+
268
+ def _resolve_environment(env: str, base_url: str) -> Environment:
269
+ try:
270
+ return resolve_environment(flag_env=env, flag_base_url=base_url, env=os.environ)
271
+ except ValueError as exc:
272
+ raise typer.BadParameter(str(exc)) from exc
273
+
274
+
275
+ def _operation_summary(operation: Operation) -> dict[str, str]:
276
+ return {
277
+ "domain": operation.domain,
278
+ "name": operation.name,
279
+ "method": operation.method,
280
+ "path": operation.path,
281
+ "operationId": operation.operation_id,
282
+ "summary": operation.summary,
283
+ }
284
+
285
+
286
+ def _operation_detail(operation: Operation) -> dict[str, Any]:
287
+ detail: dict[str, Any] = _operation_summary(operation)
288
+ detail["parameters"] = operation.raw.get("parameters", [])
289
+ detail["raw"] = operation.raw
290
+ return detail
291
+
292
+
293
+ def _install_skills(destination: Path | None) -> None:
294
+ if destination is None:
295
+ result = install_skills_to_default_agent_dirs()
296
+ installations = result["installations"]
297
+ skipped = result["skipped"]
298
+ _echo_json(
299
+ {
300
+ "ok": True,
301
+ "skillsInstalled": sum(int(item["skillsInstalled"]) for item in installations),
302
+ "installations": installations,
303
+ "skipped": skipped,
304
+ }
305
+ )
306
+ return
307
+
308
+ expanded_destination = destination.expanduser()
309
+ count = install_packaged_skills(expanded_destination)
310
+ _echo_json(
311
+ {
312
+ "ok": True,
313
+ "skillsInstalled": count,
314
+ "destination": str(expanded_destination),
315
+ }
316
+ )
317
+
318
+
319
+ def _dynamic_command_help(operation: Operation) -> str:
320
+ flags = []
321
+ for parameter in operation.raw.get("parameters", []):
322
+ if not isinstance(parameter, dict) or parameter.get("in") not in {"path", "query"}:
323
+ continue
324
+ flag = "--" + _to_flag_name(str(parameter.get("name", "")))
325
+ if parameter.get("required"):
326
+ flag = f"{flag} (required)"
327
+ flags.append(flag)
328
+ if not flags:
329
+ return operation.summary
330
+ summary = operation.summary or f"{operation.method} {operation.path}"
331
+ return summary + "\n\nOptions: " + ", ".join(flags)
332
+
333
+
334
+ def _to_flag_name(name: str) -> str:
335
+ out: list[str] = []
336
+ for index, char in enumerate(name):
337
+ if index and char.isupper():
338
+ out.append("-")
339
+ if char.isalnum():
340
+ out.append(char.lower())
341
+ elif out and out[-1] != "-":
342
+ out.append("-")
343
+ return "".join(out).strip("-")
344
+
345
+
346
+ def _parse_json_option(value: str, option_name: str) -> Any:
347
+ try:
348
+ return json.loads(value)
349
+ except json.JSONDecodeError as exc:
350
+ raise typer.BadParameter(f"{option_name} must be valid JSON") from exc
351
+
352
+
353
+ def _echo_json(value: Any) -> None:
354
+ typer.echo(json.dumps(value, ensure_ascii=False, sort_keys=True))
355
+
356
+
357
+ def _echo_startup_message() -> None:
358
+ typer.echo(f"Tool4Seller CLI {__version__}")
359
+ typer.echo("")
360
+ typer.echo("Agent skills are not installed automatically by pip.")
361
+ typer.echo("Run: tool4seller skills install")
362
+ typer.echo("")
363
+ typer.echo("Detected agent directories:")
364
+ for item in inspect_default_agent_dirs():
365
+ label = _agent_label(str(item["agent"]))
366
+ if item["exists"]:
367
+ typer.echo(f"- {label}: {item['agentDirectory']} -> {item['destination']}")
368
+ else:
369
+ typer.echo(f"- {label}: not found")
370
+
371
+
372
+ def _agent_label(agent: str) -> str:
373
+ return {
374
+ "codex": "Codex",
375
+ "claude": "Claude",
376
+ "workbuddy": "WorkBuddy",
377
+ }.get(agent, agent)
378
+
379
+
380
+ app.add_typer(auth_app, name="auth")
381
+ app.add_typer(schema_app, name="schema")
382
+ app.add_typer(skills_app, name="skills")
383
+ register_dynamic_commands(app, registry)
@@ -0,0 +1,49 @@
1
+ from dataclasses import dataclass
2
+ from pathlib import Path
3
+ from typing import Mapping
4
+
5
+
6
+ PROD_BASE_URL = "https://das-server.tool4seller.com"
7
+ TEST_BASE_URL = "https://das-server.ite.tool4seller.com"
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Environment:
12
+ name: str
13
+ base_url: str
14
+
15
+
16
+ def resolve_environment(
17
+ *,
18
+ flag_env: str = "",
19
+ flag_base_url: str = "",
20
+ env: Mapping[str, str] | None = None,
21
+ ) -> Environment:
22
+ env = env or {}
23
+ flag_base_url = flag_base_url.strip()
24
+ flag_env = flag_env.strip()
25
+ env_base_url = (env.get("TOOL4SELLER_BASE_URL") or "").strip()
26
+ env_name = (env.get("TOOL4SELLER_ENV") or "prod").strip()
27
+ if flag_base_url:
28
+ return Environment("custom", flag_base_url.rstrip("/"))
29
+ if flag_env:
30
+ return _named_environment(flag_env)
31
+ if env_base_url:
32
+ return Environment("custom", env_base_url.rstrip("/"))
33
+ return _named_environment(env_name)
34
+
35
+
36
+ def _named_environment(name: str) -> Environment:
37
+ name = name.lower()
38
+ if name == "prod":
39
+ return Environment("prod", PROD_BASE_URL)
40
+ if name == "test":
41
+ return Environment("test", TEST_BASE_URL)
42
+ raise ValueError(f"unsupported environment: {name}")
43
+
44
+
45
+ def resolve_config_dir(env: Mapping[str, str] | None = None) -> Path:
46
+ env = env or {}
47
+ if env.get("TOOL4SELLER_CONFIG_DIR"):
48
+ return Path(env["TOOL4SELLER_CONFIG_DIR"].strip()).expanduser()
49
+ return Path.home() / ".tool4seller"