xiii-cli-core 0.1.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.
xiii_cli_core/skill.py ADDED
@@ -0,0 +1,89 @@
1
+ import os
2
+ import sys
3
+ import tempfile
4
+ from pathlib import Path
5
+ from typing import Annotated
6
+
7
+ from cyclopts import App, Parameter
8
+ from rich.console import Console
9
+
10
+ from xiii_cli_core.config import Product
11
+ from xiii_cli_core.errors import CliError
12
+ from xiii_cli_core.render import render_json
13
+
14
+ console = Console()
15
+
16
+
17
+ def register_skill_commands(app: App, product: Product) -> None:
18
+ """`claude-code install|show` for the skill an entrypoint ships, if any.
19
+
20
+ Not under `agent`: that group runs the workspace agent.
21
+ """
22
+ if product.skill is None:
23
+ return
24
+ skill = product.skill
25
+ group = app.command(
26
+ App(name="claude-code", help="Set up Claude Code to work with this CLI.")
27
+ )
28
+
29
+ @group.command
30
+ def install(
31
+ *,
32
+ project: Annotated[
33
+ bool,
34
+ Parameter(
35
+ negative=(),
36
+ help=(
37
+ "Install into .claude/skills/ of the current directory, for "
38
+ "everyone working in it, instead of ~/.claude/skills/."
39
+ ),
40
+ ),
41
+ ] = False,
42
+ force: Annotated[
43
+ bool,
44
+ Parameter(negative=(), help="Replace a skill file that was changed."),
45
+ ] = False,
46
+ json_output: Annotated[
47
+ bool,
48
+ Parameter(name="--json", negative=(), help="Print the result as JSON."),
49
+ ] = False,
50
+ ) -> None:
51
+ """Install the skill that teaches Claude Code to use this CLI."""
52
+ base = Path.cwd() if project else Path.home()
53
+ target = base / ".claude" / "skills" / product.name / "SKILL.md"
54
+ status = install_skill(skill.read_text(encoding="utf-8"), target, force=force)
55
+ if json_output:
56
+ render_json({"status": status, "path": str(target)})
57
+ else:
58
+ console.print(f"[green]Skill {status}[/green]: {target}")
59
+
60
+ @group.command
61
+ def show() -> None:
62
+ """Print the skill, for an agent that reads instructions from stdin."""
63
+ # Verbatim: a Rich console would wrap lines at the terminal width.
64
+ sys.stdout.write(skill.read_text(encoding="utf-8"))
65
+
66
+
67
+ def install_skill(content: str, target: Path, *, force: bool) -> str:
68
+ """Write the skill atomically; never overwrite local edits without --force."""
69
+ try:
70
+ current = target.read_text(encoding="utf-8")
71
+ except FileNotFoundError:
72
+ current = None
73
+ except OSError as exc:
74
+ raise CliError(f"Could not read {target}: {exc}") from exc
75
+ if current == content:
76
+ return "unchanged"
77
+ if current is not None and not force:
78
+ raise CliError(f"{target} differs from this version's skill; pass --force")
79
+ try:
80
+ target.parent.mkdir(parents=True, exist_ok=True)
81
+ descriptor, temporary = tempfile.mkstemp(
82
+ prefix=".SKILL.", suffix=".part", dir=target.parent
83
+ )
84
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
85
+ handle.write(content)
86
+ os.replace(temporary, target)
87
+ except OSError as exc:
88
+ raise CliError(f"Could not write {target}: {exc}") from exc
89
+ return "installed" if current is None else "updated"
@@ -0,0 +1,230 @@
1
+ import json
2
+ from collections import Counter
3
+ from collections.abc import Iterable, Mapping
4
+ from dataclasses import asdict, dataclass
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from xiii_cli_core.errors import ThreadExpectationError, ThreadProtocolError
9
+
10
+ ERROR_TYPES = frozenset({"STREAM_ERROR"})
11
+ TERMINAL_TYPES = frozenset(
12
+ {
13
+ "CANCELLED",
14
+ "COMPLETE",
15
+ "RUN_FINISHED",
16
+ "RUN_INTERRUPTED",
17
+ "STREAM_ERROR",
18
+ }
19
+ )
20
+ SECRET_KEYS = frozenset(
21
+ {
22
+ "api_key",
23
+ "authorization",
24
+ "cookie",
25
+ "password",
26
+ "session_token",
27
+ "set-cookie",
28
+ "token",
29
+ }
30
+ )
31
+
32
+
33
+ def parse_sse(lines: Iterable[str]) -> Iterable[dict[str, Any]]:
34
+ data_lines: list[str] = []
35
+ for line in lines:
36
+ if line == "":
37
+ if data_lines:
38
+ yield _parse_event(data_lines)
39
+ data_lines.clear()
40
+ continue
41
+ if line.startswith(":"):
42
+ continue
43
+ field, separator, value = line.partition(":")
44
+ if field == "data":
45
+ data_lines.append(
46
+ value[1:] if separator and value.startswith(" ") else value
47
+ )
48
+ if data_lines:
49
+ yield _parse_event(data_lines)
50
+
51
+
52
+ def _parse_event(data_lines: list[str]) -> dict[str, Any]:
53
+ raw = "\n".join(data_lines)
54
+ try:
55
+ event = json.loads(raw)
56
+ except json.JSONDecodeError as exc:
57
+ raise ThreadProtocolError(f"Invalid SSE JSON: {exc.msg}") from exc
58
+ if not isinstance(event, dict) or not isinstance(event.get("type"), str):
59
+ raise ThreadProtocolError("SSE event must be an object with a string `type`")
60
+ return event
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class ThreadRunSummary:
65
+ test_run_id: str
66
+ status: str
67
+ terminal_type: str | None
68
+ thread_id: str | None
69
+ event_count: int
70
+ event_types: dict[str, int]
71
+ tool_names: list[str]
72
+ errors: list[dict[str, Any]]
73
+
74
+ def to_dict(self) -> dict[str, Any]:
75
+ return asdict(self)
76
+
77
+
78
+ def summarize_run(events: list[dict[str, Any]], test_run_id: str) -> ThreadRunSummary:
79
+ event_types = Counter(str(event["type"]) for event in events)
80
+ terminal_types = [
81
+ str(event["type"]) for event in events if event["type"] in TERMINAL_TYPES
82
+ ]
83
+ # The backend closes an interrupted run with COMPLETE after RUN_INTERRUPTED
84
+ # (thread_backend.agents.streaming); the interrupt is the run's outcome.
85
+ if "RUN_INTERRUPTED" in terminal_types:
86
+ terminal_type: str | None = "RUN_INTERRUPTED"
87
+ else:
88
+ terminal_type = terminal_types[-1] if terminal_types else None
89
+ thread_id = next(
90
+ (
91
+ str(event["thread_id"])
92
+ for event in reversed(events)
93
+ if event.get("thread_id")
94
+ ),
95
+ None,
96
+ )
97
+ errors = [redact_secrets(event) for event in events if event["type"] in ERROR_TYPES]
98
+ if errors or terminal_type in ERROR_TYPES:
99
+ status = "error"
100
+ elif terminal_type == "RUN_INTERRUPTED":
101
+ status = "interrupted"
102
+ elif terminal_type == "CANCELLED":
103
+ status = "cancelled"
104
+ elif terminal_type in {"COMPLETE", "RUN_FINISHED"}:
105
+ status = "completed"
106
+ else:
107
+ status = "incomplete"
108
+ tools = sorted(
109
+ {str(event["tool_name"]) for event in events if event.get("tool_name")}
110
+ )
111
+ return ThreadRunSummary(
112
+ test_run_id=test_run_id,
113
+ status=status,
114
+ terminal_type=terminal_type,
115
+ thread_id=thread_id,
116
+ event_count=len(events),
117
+ event_types=dict(sorted(event_types.items())),
118
+ tool_names=tools,
119
+ errors=errors,
120
+ )
121
+
122
+
123
+ def assistant_text(events: Iterable[Mapping[str, Any]]) -> str:
124
+ """Join model text deltas without treating tool or status events as content."""
125
+ return "".join(
126
+ str(event["delta"])
127
+ for event in events
128
+ if event.get("type") == "MESSAGE_DELTA" and event.get("delta") is not None
129
+ )
130
+
131
+
132
+ def latest_interrupt(events: Iterable[Mapping[str, Any]]) -> dict[str, Any] | None:
133
+ """Return the newest validated HITL payload from a stream."""
134
+ for event in reversed(list(events)):
135
+ if event.get("type") != "RUN_INTERRUPTED":
136
+ continue
137
+ payload = event.get("interrupt_data")
138
+ if not isinstance(payload, dict):
139
+ raise ThreadProtocolError("RUN_INTERRUPTED is missing `interrupt_data`")
140
+ requests = payload.get("action_requests")
141
+ if not isinstance(requests, list) or not requests:
142
+ raise ThreadProtocolError(
143
+ "RUN_INTERRUPTED must contain at least one action request"
144
+ )
145
+ return payload
146
+ return None
147
+
148
+
149
+ def redact_secrets(value: Any) -> Any:
150
+ if isinstance(value, Mapping):
151
+ return {
152
+ str(key): "[REDACTED]"
153
+ if str(key).lower() in SECRET_KEYS
154
+ else redact_secrets(item)
155
+ for key, item in value.items()
156
+ }
157
+ if isinstance(value, list):
158
+ return [redact_secrets(item) for item in value]
159
+ return value
160
+
161
+
162
+ def write_artifacts(
163
+ directory: Path,
164
+ events: list[dict[str, Any]],
165
+ summary: ThreadRunSummary,
166
+ interactions: Any = None,
167
+ ) -> None:
168
+ directory.mkdir(parents=True, exist_ok=True)
169
+ safe_events = [redact_secrets(event) for event in events]
170
+ event_text = "".join(
171
+ f"{json.dumps(event, ensure_ascii=False, separators=(',', ':'))}\n"
172
+ for event in safe_events
173
+ )
174
+ (directory / "events.jsonl").write_text(event_text, encoding="utf-8")
175
+ _write_json(directory / "summary.json", summary.to_dict())
176
+ if interactions is not None:
177
+ _write_json(
178
+ directory / "persisted-interactions.json", redact_secrets(interactions)
179
+ )
180
+
181
+
182
+ def assert_expectations(
183
+ summary: ThreadRunSummary,
184
+ *,
185
+ terminal_type: str | None = None,
186
+ required_event_types: Iterable[str] = (),
187
+ forbidden_event_types: Iterable[str] = (),
188
+ required_tools: Iterable[str] = (),
189
+ require_persisted_interactions: bool = False,
190
+ interactions: Any = None,
191
+ ) -> None:
192
+ failures: list[str] = []
193
+ if summary.status == "incomplete":
194
+ failures.append("stream has no terminal event")
195
+ if terminal_type and summary.terminal_type != terminal_type:
196
+ failures.append(
197
+ f"terminal event is {summary.terminal_type!r}, expected {terminal_type!r}"
198
+ )
199
+ for event_type in required_event_types:
200
+ if event_type not in summary.event_types:
201
+ failures.append(f"missing event type {event_type!r}")
202
+ for event_type in forbidden_event_types:
203
+ if event_type in summary.event_types:
204
+ failures.append(f"unexpected event type {event_type!r}")
205
+ for tool_name in required_tools:
206
+ if tool_name not in summary.tool_names:
207
+ failures.append(f"missing tool {tool_name!r}")
208
+ if summary.errors:
209
+ failures.append("stream contains an error event")
210
+ if require_persisted_interactions and not _has_interactions(interactions):
211
+ failures.append("no persisted interactions were returned")
212
+ if failures:
213
+ raise ThreadExpectationError(
214
+ "Thread expectations failed: " + "; ".join(failures)
215
+ )
216
+
217
+
218
+ def _has_interactions(payload: Any) -> bool:
219
+ if isinstance(payload, list):
220
+ return bool(payload)
221
+ if isinstance(payload, dict):
222
+ items = payload.get("interactions")
223
+ return isinstance(items, list) and bool(items)
224
+ return False
225
+
226
+
227
+ def _write_json(path: Path, payload: Any) -> None:
228
+ path.write_text(
229
+ json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
230
+ )
@@ -0,0 +1,115 @@
1
+ """The bearer token a command sends, refreshed before it runs out.
2
+
3
+ A browser or device login stores an hour-long bearer token and a refresh token
4
+ (RFC 6749 §6). The refresh token is single use: the server spends it on every
5
+ refresh and ends the whole login when a spent one comes back (RFC 9700
6
+ §4.14.2). Two CLI processes refreshing with the same stored token would
7
+ therefore log the user out — an agent running commands in parallel does exactly
8
+ that. Refreshing happens under an exclusive file lock, and the keyring is read
9
+ again once the lock is held, so the second process finds the token the first
10
+ one just stored instead of spending the old one a second time.
11
+ """
12
+
13
+ import fcntl
14
+ import os
15
+ import time
16
+ from collections.abc import Iterator
17
+ from contextlib import contextmanager
18
+
19
+ import httpx
20
+
21
+ from xiii_cli_core.config import (
22
+ Product,
23
+ ProductConfig,
24
+ StoredLogin,
25
+ WorkspaceRef,
26
+ read_login,
27
+ require_explicit_secret_endpoint,
28
+ resolve_workspace,
29
+ state_path,
30
+ store_token,
31
+ )
32
+ from xiii_cli_core.errors import AuthenticationError, ConfigurationError
33
+ from xiii_cli_core.oauth import refresh_login
34
+
35
+ # Refresh this long before the deadline, so a request that starts just before
36
+ # it does not arrive just after it.
37
+ REFRESH_MARGIN_SECONDS = 60.0
38
+ REFRESH_LOCK_FILENAME = "refresh.lock"
39
+
40
+
41
+ def get_token(
42
+ config: ProductConfig, *, transport: httpx.BaseTransport | None = None
43
+ ) -> tuple[str, str]:
44
+ if token := os.getenv(config.token_env):
45
+ require_explicit_secret_endpoint(config, config.token_env)
46
+ return token, config.token_env
47
+ workspace = resolve_workspace(config)
48
+ if workspace is None:
49
+ raise AuthenticationError(
50
+ f"Not authenticated. Run `{config.entrypoint} login` or set "
51
+ f"{config.token_env}."
52
+ )
53
+ login = read_login(config, workspace)
54
+ if _due_refresh_token(login) is not None:
55
+ with _refresh_lock(config.product):
56
+ login = read_login(config, workspace)
57
+ if (refresh_token := _due_refresh_token(login)) is not None:
58
+ login = _refresh(config, workspace, refresh_token, transport=transport)
59
+ return login.access_token, "OS keyring"
60
+
61
+
62
+ def _due_refresh_token(login: StoredLogin) -> str | None:
63
+ """The refresh token, if the bearer token beside it is about to run out."""
64
+ if login.refresh_token is None or login.access_expires_at is None:
65
+ return None
66
+ if login.access_expires_at - time.time() >= REFRESH_MARGIN_SECONDS:
67
+ return None
68
+ return login.refresh_token
69
+
70
+
71
+ def _refresh(
72
+ config: ProductConfig,
73
+ workspace: WorkspaceRef,
74
+ refresh_token: str,
75
+ *,
76
+ transport: httpx.BaseTransport | None,
77
+ ) -> StoredLogin:
78
+ result = refresh_login(config, refresh_token, transport=transport)
79
+ if result.workspace_id != workspace.id or result.refresh_token is None:
80
+ raise AuthenticationError(
81
+ f"Unexpected token refresh response. Run `{config.entrypoint} login` again."
82
+ )
83
+ # Stored before anything else: the refresh token sent above is spent now.
84
+ access_expires_at = time.time() + result.expires_in
85
+ store_token(
86
+ config,
87
+ result.token,
88
+ workspace.id,
89
+ refresh_token=result.refresh_token,
90
+ access_expires_at=access_expires_at,
91
+ )
92
+ return StoredLogin(
93
+ access_token=result.token,
94
+ refresh_token=result.refresh_token,
95
+ access_expires_at=access_expires_at,
96
+ )
97
+
98
+
99
+ @contextmanager
100
+ def _refresh_lock(product: Product) -> Iterator[None]:
101
+ path = state_path(product).with_name(REFRESH_LOCK_FILENAME)
102
+ try:
103
+ path.parent.mkdir(parents=True, exist_ok=True)
104
+ handle = path.open("a")
105
+ except OSError as exc:
106
+ raise ConfigurationError(f"Could not open {path}: {exc}") from exc
107
+ with handle:
108
+ fcntl.flock(handle, fcntl.LOCK_EX)
109
+ try:
110
+ yield
111
+ finally:
112
+ fcntl.flock(handle, fcntl.LOCK_UN)
113
+
114
+
115
+ __all__ = ["REFRESH_MARGIN_SECONDS", "get_token"]
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: xiii-cli-core
3
+ Version: 0.1.0
4
+ Summary: The product-neutral core of the XIII product command-line tools
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Classifier: Environment :: Console
8
+ Classifier: Operating System :: MacOS
9
+ Classifier: Operating System :: POSIX :: Linux
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.14
12
+ Classifier: Typing :: Typed
13
+ Requires-Dist: cyclopts>=4.11,<5
14
+ Requires-Dist: httpx>=0.28,<1
15
+ Requires-Dist: keyring>=25.7,<26
16
+ Requires-Dist: rich>=15,<16
17
+ Requires-Dist: tldextract>=5.3,<6
18
+ Requires-Python: >=3.14, <3.15
19
+ Project-URL: Source, https://github.com/xiii-hq/xiii-cli-core
20
+ Project-URL: Issues, https://github.com/xiii-hq/xiii-cli-core/issues
21
+ Description-Content-Type: text/markdown
22
+
23
+ # xiii-cli-core
24
+
25
+ The product-neutral core of the XIII product command-line tools: browser and
26
+ device login with keyring storage, workspaces, the typed commands generated
27
+ from a product's OpenAPI document, the raw `api` escape hatch, `agent run`,
28
+ `describe`, `doctor` and the Claude Code skill installer.
29
+
30
+ This package has no command of its own; it is installed with a product CLI.
31
+
32
+ ## Entrypoints
33
+
34
+ A product package builds a `Product` and hands it to the core; nothing in the
35
+ core knows which products exist:
36
+
37
+ ```python
38
+ from importlib.metadata import version
39
+ from importlib.resources import files
40
+
41
+ from xiii_cli_core.config import Product, Surface
42
+ from xiii_cli_core.main import build_app, run
43
+
44
+ PRODUCT = Product(
45
+ name="example",
46
+ display_name="Example",
47
+ api_url="https://api.example.com/v1/app",
48
+ oauth_client_id="example-cli",
49
+ manifest=files(__name__).joinpath("spec.json"),
50
+ version=version("example"),
51
+ skill=files(__name__).joinpath("skill/SKILL.md"),
52
+ )
53
+
54
+
55
+ def main() -> None:
56
+ run(lambda: build_app(PRODUCT, Surface.CUSTOMER))
57
+ ```
58
+
59
+ `name` names the command, its environment variables (`EXAMPLE_API_URL`,
60
+ `EXAMPLE_API_TOKEN`, `EXAMPLE_WORKSPACE`, `EXAMPLE_TIMEOUT`), the keyring service
61
+ (`example-cli`), the state directory (`~/.config/example/`) and the project file
62
+ (`.example.toml`). The manifest is written by
63
+ `xiii_cli_core.openapi.write_command_manifest` from the app API's OpenAPI
64
+ document. The exit codes and the JSON error shape are a public contract,
65
+ listed in `xiii_cli_core.errors` and in each product's README.
66
+
67
+ ## Development
68
+
69
+ ```console
70
+ uv sync --locked
71
+ uv run pytest --cov=xiii_cli_core
72
+ uv run ruff check && uv run ruff format --check && uv run pyright
73
+ ```
74
+
75
+ The tests hand the core a product whose manifest is a snapshot of a real
76
+ product's (`tests/fixtures/spec.json`), so they exercise the shapes a real backend
77
+ produces and do not move when a product's API does.
78
+
79
+ A release is a GitHub release whose tag is `v<version>` from `pyproject.toml`;
80
+ `.github/workflows/publish.yml` builds, verifies and publishes it to PyPI with
81
+ an attestation. A product package pins a compatible range (`>=0.1,<0.2`), so a
82
+ breaking change raises the minor version while the major one is 0.
83
+
84
+ ## License
85
+
86
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,18 @@
1
+ xiii_cli_core/__init__.py,sha256=ActF5fzjCckNwuhXxbiG6PFbSYqJ4tZiqwtRHuMDsrM,79
2
+ xiii_cli_core/client.py,sha256=I9ZPMFIOiTlnElWc4WnszV43qr6Ttg74ynARQt0HM58,19806
3
+ xiii_cli_core/config.py,sha256=laMM0xuVvv5yDZhrHkenbKUmbjBn0TPMpZeJbYO5zj0,18787
4
+ xiii_cli_core/describe.py,sha256=puzA8bDNc4r3Hy6Mvqw7mJze_smlSDtgOgHH-mdpcu4,6804
5
+ xiii_cli_core/direct.py,sha256=dhQ3p-_MTGq1nf20IqNx3FxkKn2-ROIDKrt9norc57U,42196
6
+ xiii_cli_core/errors.py,sha256=BHbhiKeE-JSWZ3y_KFnolIpz4oavE62tOungecjPUc0,2596
7
+ xiii_cli_core/main.py,sha256=pxkh-iFjRfd3SKMscFhcpo7vlUN3lTQJ082kq0oSHEE,26897
8
+ xiii_cli_core/oauth.py,sha256=JUTRrWxgoTQW44ZVpNXoVl30T6uSLgFp_vojOgXozIg,27262
9
+ xiii_cli_core/openapi.py,sha256=QuIO0aOD2Ufizj_gqdUEm8dw-RsKxTqgWi4iI51kL4E,23410
10
+ xiii_cli_core/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ xiii_cli_core/render.py,sha256=HadNsnW0bkiE5l-DVMhjOJD9sbC__W15FfWnGEosjQw,1175
12
+ xiii_cli_core/skill.py,sha256=o3A7M-gePMsGxUhm-DZqsD-okrxWFBw1Nfz9wzmV6Fk,3150
13
+ xiii_cli_core/thread.py,sha256=HSxcQQRLZGO8A-9j6lpzZNCPqBegqewoonBrVP6UAcw,7568
14
+ xiii_cli_core/tokens.py,sha256=YOW9C1_PhjeUKRC-EzLM_NTFInMuh-FXx2xUCgrnkqg,3993
15
+ xiii_cli_core-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
16
+ xiii_cli_core-0.1.0.dist-info/WHEEL,sha256=i9aSRDivn5iP9LaR1BLQX2GNAuriQWPsFwbbWygTX2k,81
17
+ xiii_cli_core-0.1.0.dist-info/METADATA,sha256=g5nDISaIOjXxhukRpndM8UVmpmKyKaFPvNoM4FBu6hM,3044
18
+ xiii_cli_core-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.11.15
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any