sweatstack-cli 0.16.0__tar.gz → 0.17.0__tar.gz

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.
Files changed (101) hide show
  1. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/CHANGELOG.md +29 -0
  2. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/Makefile +7 -1
  3. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/PKG-INFO +1 -1
  4. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/pyproject.toml +1 -1
  5. sweatstack_cli-0.17.0/scripts/vendor_tool_template.sh +61 -0
  6. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/api/client.py +9 -0
  7. sweatstack_cli-0.17.0/src/sweatstack_cli/commands/tool.py +439 -0
  8. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/exceptions.py +4 -0
  9. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/project.py +44 -5
  10. sweatstack_cli-0.17.0/src/sweatstack_cli/templates/tool/index.html +353 -0
  11. sweatstack_cli-0.17.0/src/sweatstack_cli/templates/tool/vendor/duckdb.mjs +12652 -0
  12. sweatstack_cli-0.17.0/src/sweatstack_cli/templates/tool/vendor/licenses/apache-arrow.txt +2261 -0
  13. sweatstack_cli-0.17.0/src/sweatstack_cli/templates/tool/vendor/licenses/duckdb-wasm.txt +7 -0
  14. sweatstack_cli-0.17.0/src/sweatstack_cli/templates/tool/vendor/licenses/uplot.txt +21 -0
  15. sweatstack_cli-0.17.0/src/sweatstack_cli/templates/tool/vendor/sweatstack.js +44 -0
  16. sweatstack_cli-0.17.0/src/sweatstack_cli/templates/tool/vendor/uPlot.iife.min-1.6.31.js +2 -0
  17. sweatstack_cli-0.17.0/src/sweatstack_cli/templates/tool/vendor/uPlot.min-1.6.31.css +1 -0
  18. sweatstack_cli-0.17.0/src/sweatstack_cli/templates/tool/vendor.json +7 -0
  19. sweatstack_cli-0.17.0/src/sweatstack_cli/tools/deploy.py +174 -0
  20. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/tools/policy.json +3 -2
  21. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/tools/server.py +71 -9
  22. sweatstack_cli-0.17.0/src/sweatstack_cli/tools/signin.py +468 -0
  23. sweatstack_cli-0.17.0/src/sweatstack_cli/tools/template.py +110 -0
  24. sweatstack_cli-0.17.0/tests/e2e/fake_sweatstack.py +206 -0
  25. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/e2e/test_page_template.py +7 -177
  26. sweatstack_cli-0.17.0/tests/e2e/test_tool_template.py +177 -0
  27. sweatstack_cli-0.17.0/tests/test_commands/test_tool_commands.py +277 -0
  28. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_tools/test_check.py +1 -1
  29. sweatstack_cli-0.17.0/tests/test_tools/test_deploy.py +168 -0
  30. sweatstack_cli-0.17.0/tests/test_tools/test_signin.py +633 -0
  31. sweatstack_cli-0.17.0/tests/test_tools/test_template.py +140 -0
  32. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/uv.lock +1 -1
  33. sweatstack_cli-0.16.0/src/sweatstack_cli/commands/tool.py +0 -153
  34. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/.claude/settings.local.json +0 -0
  35. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/.claude/skills/sweatstack/SKILL.md +0 -0
  36. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/.claude/skills/sweatstack/api.md +0 -0
  37. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/.claude/skills/sweatstack/auth.md +0 -0
  38. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/.claude/skills/sweatstack/cli.md +0 -0
  39. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/.claude/skills/sweatstack/pyscript.md +0 -0
  40. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/.claude/skills/sweatstack/webapp.md +0 -0
  41. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/.gitignore +0 -0
  42. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/.python-version +0 -0
  43. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/CREATE_PRIVATE_APP.md +0 -0
  44. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/DEVELOPMENT.md +0 -0
  45. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/PLAN.md +0 -0
  46. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/README.md +0 -0
  47. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/plans/001-page-init-command.md +0 -0
  48. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/__init__.py +0 -0
  49. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/api/__init__.py +0 -0
  50. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/auth/__init__.py +0 -0
  51. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/auth/callback_server.py +0 -0
  52. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/auth/jwt.py +0 -0
  53. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/auth/pkce.py +0 -0
  54. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/auth/tokens.py +0 -0
  55. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/commands/__init__.py +0 -0
  56. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/commands/app.py +0 -0
  57. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/commands/auth.py +0 -0
  58. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/commands/page.py +0 -0
  59. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/config.py +0 -0
  60. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/console.py +0 -0
  61. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/go_live.py +0 -0
  62. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/main.py +0 -0
  63. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/py.typed +0 -0
  64. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/services/__init__.py +0 -0
  65. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/services/applications.py +0 -0
  66. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/templates/page/index.html +0 -0
  67. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/tools/__init__.py +0 -0
  68. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/tools/check.py +0 -0
  69. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/tools/content_types.json +0 -0
  70. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/tools/policy.py +0 -0
  71. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/tools/rewrite.py +0 -0
  72. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/src/sweatstack_cli/version_check.py +0 -0
  73. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/sweatstack.toml +0 -0
  74. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/__init__.py +0 -0
  75. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/conftest.py +0 -0
  76. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/e2e/__init__.py +0 -0
  77. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/e2e/test_tool_serve.py +0 -0
  78. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_api/__init__.py +0 -0
  79. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_api/test_client.py +0 -0
  80. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_auth/__init__.py +0 -0
  81. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_auth/test_authenticator.py +0 -0
  82. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_auth/test_authorize_url.py +0 -0
  83. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_auth/test_callback_server.py +0 -0
  84. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_auth/test_jwt.py +0 -0
  85. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_auth/test_pkce.py +0 -0
  86. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_auth/test_tokens.py +0 -0
  87. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_commands/__init__.py +0 -0
  88. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_commands/test_app.py +0 -0
  89. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_commands/test_auth.py +0 -0
  90. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_commands/test_cli.py +0 -0
  91. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_commands/test_page_deploy.py +0 -0
  92. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_commands/test_page_init.py +0 -0
  93. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_project.py +0 -0
  94. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_services/__init__.py +0 -0
  95. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_services/test_applications.py +0 -0
  96. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_tools/__init__.py +0 -0
  97. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_tools/test_policy.py +0 -0
  98. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_tools/test_rewrite.py +0 -0
  99. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_tools/test_server.py +0 -0
  100. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_version.py +0 -0
  101. {sweatstack_cli-0.16.0 → sweatstack_cli-0.17.0}/tests/test_version_check.py +0 -0
@@ -4,6 +4,35 @@ All notable changes to this project are documented here. The format is based on
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
5
5
  adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.17.0] - 2026-11-20
8
+
9
+ ### Added
10
+
11
+ - `sweatstack tool create` creates a private tool on SweatStack Tools, writes its
12
+ `[tool]` section to `sweatstack.toml`, and scaffolds the tool template. On a
13
+ developer's first tool it sets their handle and public name. Every prompt has an
14
+ option, so an agent can run it without a terminal.
15
+ - `sweatstack tool deploy` checks the folder against the Tools contract (paths, the
16
+ reserved `_gate` and `_sweatstack` prefixes, links outside the folder, size and file
17
+ limits) before anything is sent, then uploads only the files SweatStack does not
18
+ store yet, four at a time. An upload refused while another deploy of the tool runs
19
+ (409) or while the store is unavailable (503) is retried for half a minute.
20
+ `--allow-external` deploys despite
21
+ references `tool check` reports.
22
+ - `sweatstack tool deploys` lists a tool's kept deploys, newest first, with the one serving.
23
+ - `sweatstack tool rollback [DEPLOY_ID]` serves an earlier deploy again, and
24
+ `sweatstack tool publish [--unlisted]` makes a tool listed or unlisted.
25
+ - The tool template: one page, with SweatStack Tools' `sweatstack.js` and a pinned
26
+ DuckDB-WASM in the tool's own folder, that plots the latest activity. It has no OAuth
27
+ code: SweatStack Tools signs people in.
28
+ - `sweatstack tool serve` signs people in as SweatStack Tools does, at
29
+ `http://{slug}.localhost:{port}`, when `sweatstack.toml` gives the tool scopes beyond
30
+ `openid profile`. Chromium and Firefox; Safari keeps no `__Host-` cookie on plain http.
31
+
32
+ ### Fixed
33
+
34
+ - A name or title with a quote no longer breaks `sweatstack.toml`.
35
+
7
36
  ## [0.16.0] - 2026-11-20
8
37
 
9
38
  ### Added
@@ -1,4 +1,4 @@
1
- .PHONY: help install dev test test-e2e lint format typecheck check clean build publish refresh-policy
1
+ .PHONY: help install dev test test-e2e lint format typecheck check clean build publish refresh-policy vendor-tool-template
2
2
 
3
3
  help:
4
4
  @echo "SweatStack CLI Development Commands"
@@ -12,6 +12,7 @@ help:
12
12
  @echo " make typecheck Run type checker"
13
13
  @echo " make check Run all checks (lint, format, typecheck, test)"
14
14
  @echo " make refresh-policy Copy the live SweatStack Tools policy into the package"
15
+ @echo " make vendor-tool-template Rebuild the tool template's files and download pins (needs Node)"
15
16
  @echo " make clean Remove build artifacts"
16
17
  @echo " make build Build distribution packages"
17
18
  @echo " make publish Publish to PyPI"
@@ -54,6 +55,11 @@ refresh-policy:
54
55
  curl -fsS https://sweatstack.tools/v1/policy -o src/sweatstack_cli/tools/policy.json
55
56
  uv run python -c "import json; from sweatstack_cli.tools.policy import parse_policy; parse_policy(json.load(open('src/sweatstack_cli/tools/policy.json')), 'built-in')"
56
57
 
58
+ # The files the `tool create` template ships, and the SHA-256 pins of the files it downloads.
59
+ # Run after changing a version in scripts/vendor_tool_template.sh, and commit the result.
60
+ vendor-tool-template:
61
+ ./scripts/vendor_tool_template.sh
62
+
57
63
  build:
58
64
  rm -rf dist
59
65
  uv build
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sweatstack-cli
3
- Version: 0.16.0
3
+ Version: 0.17.0
4
4
  Summary: Command-line interface for SweatStack — the sports data platform for developers
5
5
  Project-URL: Homepage, https://sweatstack.no
6
6
  Project-URL: Documentation, https://docs.sweatstack.no
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sweatstack-cli"
3
- version = "0.16.0"
3
+ version = "0.17.0"
4
4
  description = "Command-line interface for SweatStack — the sports data platform for developers"
5
5
  readme = "README.md"
6
6
  authors = [{ name = "Aart Goossens", email = "aart@sweatstack.no" }]
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env bash
2
+ # Rebuilds the files the `tool create` template ships, and the pins of the files it downloads.
3
+ # Needs Node (npm, npx) and curl. Run from the repo root with `make vendor-tool-template`.
4
+ #
5
+ # Shipped in the package (small): the sign-in reference implementation, copied from the Tools app's
6
+ # contract (TOOLS_REPO, ../sweatstack-tools-v2 by default), uPlot, DuckDB-WASM's browser module
7
+ # bundled with esbuild (it imports apache-arrow by name), and their licences. Downloaded by `tool create` (large), each
8
+ # pinned by SHA-256 in vendor.json: DuckDB's EH WebAssembly, its worker, and the Parquet extension,
9
+ # which DuckDB otherwise fetches from extensions.duckdb.org, where SweatStack Tools blocks it.
10
+ set -euo pipefail
11
+
12
+ UPLOT=1.6.31
13
+ DUCKDB_WASM=1.32.0
14
+ DUCKDB=v1.4.3 # DuckDB's own version inside DuckDB-WASM $DUCKDB_WASM
15
+ ESBUILD=0.28.2
16
+
17
+ OUT=src/sweatstack_cli/templates/tool
18
+ TOOLS_REPO=${TOOLS_REPO:-../sweatstack-tools-v2}
19
+ REFERENCE="$TOOLS_REPO/contract/sign-in/sweatstack.js"
20
+ [ -f "$REFERENCE" ] || { echo "No $REFERENCE: set TOOLS_REPO to the Tools app's repository" >&2; exit 1; }
21
+ WORK=$(mktemp -d)
22
+ trap 'rm -rf "$WORK"' EXIT
23
+
24
+ (cd "$WORK" && npm init -y >/dev/null && npm install --no-audit --no-fund --save-exact \
25
+ "uplot@$UPLOT" "@duckdb/duckdb-wasm@$DUCKDB_WASM" "esbuild@$ESBUILD" >/dev/null)
26
+
27
+ rm -rf "$OUT/vendor" && mkdir -p "$OUT/vendor/licenses"
28
+ cp "$WORK/node_modules/uplot/dist/uPlot.iife.min.js" "$OUT/vendor/uPlot.iife.min-$UPLOT.js"
29
+ cp "$WORK/node_modules/uplot/dist/uPlot.min.css" "$OUT/vendor/uPlot.min-$UPLOT.css"
30
+ (cd "$WORK" && npx esbuild node_modules/@duckdb/duckdb-wasm/dist/duckdb-browser.mjs \
31
+ --bundle --format=esm --log-level=warning --outfile=duckdb.mjs)
32
+ cp "$WORK/duckdb.mjs" "$OUT/vendor/duckdb.mjs"
33
+ cp "$REFERENCE" "$OUT/vendor/sweatstack.js"
34
+ cp "$WORK/node_modules/uplot/LICENSE" "$OUT/vendor/licenses/uplot.txt"
35
+ # The npm package declares MIT but carries no licence file: take it from the release tag.
36
+ curl -fsSL "https://raw.githubusercontent.com/duckdb/duckdb-wasm/v$DUCKDB_WASM/LICENSE" -o "$OUT/vendor/licenses/duckdb-wasm.txt"
37
+ cp "$WORK/node_modules/apache-arrow/LICENSE.txt" "$OUT/vendor/licenses/apache-arrow.txt"
38
+
39
+ download() { # published path, URL: fetch it, and print its pin
40
+ local path=$1 url=$2 file="$WORK/download"
41
+ curl -fsSL "$url" -o "$file"
42
+ printf ' {"path": "%s", "url": "%s", "size": %s, "sha256": "%s"}' \
43
+ "$path" "$url" "$(wc -c < "$file" | tr -d ' ')" "$(shasum -a 256 "$file" | cut -d' ' -f1)"
44
+ }
45
+
46
+ {
47
+ echo '{'
48
+ echo ' "downloads": ['
49
+ download "vendor/duckdb-eh.wasm" "https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@$DUCKDB_WASM/dist/duckdb-eh.wasm"; echo ','
50
+ download "vendor/duckdb-browser-eh.worker.js" "https://cdn.jsdelivr.net/npm/@duckdb/duckdb-wasm@$DUCKDB_WASM/dist/duckdb-browser-eh.worker.js"; echo ','
51
+ download "vendor/duckdb-extensions/$DUCKDB/wasm_eh/parquet.duckdb_extension.wasm" "https://extensions.duckdb.org/$DUCKDB/wasm_eh/parquet.duckdb_extension.wasm"; echo
52
+ echo ' ]'
53
+ echo '}'
54
+ } > "$OUT/vendor.json"
55
+
56
+ # The npm package's files must be the ones jsDelivr serves.
57
+ for name in duckdb-eh.wasm duckdb-browser-eh.worker.js; do
58
+ local_sha=$(shasum -a 256 "$WORK/node_modules/@duckdb/duckdb-wasm/dist/$name" | cut -d' ' -f1)
59
+ grep -q "$local_sha" "$OUT/vendor.json" || { echo "jsDelivr's $name differs from the npm package" >&2; exit 1; }
60
+ done
61
+ echo "Wrote $OUT/vendor/ and $OUT/vendor.json"
@@ -172,6 +172,7 @@ class APIClient:
172
172
  status_code=response.status_code,
173
173
  code=code,
174
174
  detail=detail,
175
+ body=self._json_object(response),
175
176
  )
176
177
 
177
178
  # Handle empty responses
@@ -181,6 +182,14 @@ class APIClient:
181
182
  result: dict[str, Any] = response.json()
182
183
  return result
183
184
 
185
+ @staticmethod
186
+ def _json_object(response: httpx.Response) -> dict[str, object] | None:
187
+ try:
188
+ data = response.json()
189
+ except ValueError:
190
+ return None
191
+ return data if isinstance(data, dict) else None
192
+
184
193
  def _extract_error(self, response: httpx.Response) -> tuple[str, str | None]:
185
194
  """Extract the human-readable detail and optional machine-readable code.
186
195
 
@@ -0,0 +1,439 @@
1
+ """Tool commands: create a tool, serve and check it locally under the SweatStack Tools policy,
2
+ deploy it, roll it back and publish it. See plans/developer-kit/cli.md in sweatstack-tools.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import socket
8
+ import sys
9
+ from collections.abc import Iterator
10
+ from contextlib import contextmanager
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from typing import Any, cast
14
+
15
+ import typer
16
+ from rich.progress import BarColumn, MofNCompleteColumn, Progress, SpinnerColumn, TextColumn
17
+
18
+ from sweatstack_cli.api import APIClient
19
+ from sweatstack_cli.config import get_settings
20
+ from sweatstack_cli.console import console
21
+ from sweatstack_cli.exceptions import APIError, AuthenticationError
22
+ from sweatstack_cli.project import CONFIG_FILENAME, ProjectConfig, ToolConfig, write_config
23
+ from sweatstack_cli.tools.check import REMOVED_KINDS, Finding, check_folder
24
+ from sweatstack_cli.tools.deploy import DeployError, collect
25
+ from sweatstack_cli.tools.deploy import deploy as deploy_files
26
+ from sweatstack_cli.tools.policy import Policy, load_policy
27
+ from sweatstack_cli.tools.server import make_server
28
+ from sweatstack_cli.tools.signin import SignIn
29
+ from sweatstack_cli.tools.template import DownloadError, scaffold
30
+
31
+ DOCS_DEPENDENCIES = "https://docs.sweatstack.no/learn/sweatstack-tools/dependencies/"
32
+
33
+ app = typer.Typer(
34
+ name="tool",
35
+ help="Build tools for SweatStack Tools: create, serve, check, deploy and publish them.",
36
+ no_args_is_help=True,
37
+ )
38
+
39
+
40
+ def _directory(directory: Path) -> Path:
41
+ if not directory.is_dir():
42
+ console.print(f"[red]Error:[/red] '{directory}' is not a directory.")
43
+ raise typer.Exit(1)
44
+ return directory.resolve()
45
+
46
+
47
+ def _policy() -> Policy:
48
+ policy = load_policy()
49
+ if policy.source == "cached":
50
+ console.print(
51
+ "[yellow]sweatstack.tools is unreachable: using the policy from the last run.[/yellow]"
52
+ )
53
+ elif policy.source == "built-in":
54
+ console.print(
55
+ "[yellow]sweatstack.tools is unreachable: using the policy this CLI shipped with.[/yellow]"
56
+ )
57
+ return policy
58
+
59
+
60
+ def _free_port(start: int, attempts: int = 100) -> int:
61
+ for port in range(start, start + attempts):
62
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
63
+ try:
64
+ probe.bind(("localhost", port))
65
+ return port
66
+ except OSError:
67
+ continue
68
+ console.print(f"[red]Error:[/red] No free port from {start} to {start + attempts - 1}.")
69
+ raise typer.Exit(1)
70
+
71
+
72
+ @app.command()
73
+ def serve(
74
+ directory: Path | None = typer.Argument(
75
+ None, help="The tool's folder. From sweatstack.toml, or the current folder."
76
+ ),
77
+ port: int | None = typer.Option(
78
+ None, "--port", "-p", help="Port to serve on. The first free one from 8000 by default."
79
+ ),
80
+ slug: str | None = typer.Option(
81
+ None, "--slug", help="The tool's slug. From sweatstack.toml, or 'local'."
82
+ ),
83
+ ) -> None:
84
+ """Serve a tool locally, with the same network policy and sign-in as SweatStack Tools.
85
+
86
+ A tool in sweatstack.toml that declares data scopes signs in as it does on SweatStack Tools.
87
+ """
88
+ project = ProjectConfig.load()
89
+ tool = project.tool if project else None
90
+ root = _directory(directory or Path(tool.directory if tool and tool.directory else "."))
91
+ chosen_slug = slug or (tool.slug if tool and tool.slug else None) or "local"
92
+ sign_in = (
93
+ SignIn.for_tool(project.app.client_id, tool.scopes, get_settings().api_url)
94
+ if project and tool and tool.slug
95
+ else None
96
+ )
97
+ policy = _policy()
98
+ chosen = port if port is not None else _free_port(8000)
99
+ try:
100
+ server = make_server(root, policy, slug=chosen_slug, port=chosen, sign_in=sign_in)
101
+ except OSError as error:
102
+ console.print(f"[red]Error:[/red] Cannot serve on port {chosen}: {error.strerror}.")
103
+ raise typer.Exit(1)
104
+ console.print(
105
+ "Serving with the SweatStack Tools network policy: requests to other hosts are blocked, "
106
+ "as they will be when deployed. Blocked requests show in the browser console."
107
+ )
108
+ if sign_in:
109
+ console.print(
110
+ "Signing in as SweatStack Tools does, with the scopes in sweatstack.toml. "
111
+ "Use Chrome or Firefox: Safari keeps no sign-in cookie on http://localhost."
112
+ )
113
+ console.print(f" [cyan]{server.origin}[/cyan] ({root})")
114
+ try:
115
+ server.serve_forever()
116
+ except KeyboardInterrupt:
117
+ pass
118
+ finally:
119
+ server.server_close()
120
+
121
+
122
+ def say(text: str = "", *, highlight: bool = True) -> None:
123
+ """Print one line without wrapping."""
124
+ console.print(text, soft_wrap=True, highlight=highlight)
125
+
126
+
127
+ def print_findings(findings: list[Finding], directory: Path) -> None:
128
+ """The check's report, written for a person and for an agent: what, where, and the fix.
129
+
130
+ Lines never wrap, so each finding stays on one line with its whole URL, at any terminal width.
131
+ """
132
+ blocked = [f for f in findings if f.kind not in REMOVED_KINDS]
133
+ removed = [f for f in findings if f.kind in REMOVED_KINDS]
134
+ if blocked:
135
+ files = len({f.file for f in blocked})
136
+ say(
137
+ f"[red]✗[/red] {len(blocked)} load{'s' if len(blocked) != 1 else ''} in {files} "
138
+ f"file{'s' if files != 1 else ''} would be blocked on SweatStack Tools"
139
+ )
140
+ say()
141
+ width = max(len(f"{f.file}:{f.line}") for f in blocked)
142
+ kind_width = max(len(f.kind) for f in blocked)
143
+ for f in blocked:
144
+ say(
145
+ f" {f'{f.file}:{f.line}':<{width}} {f.kind:<{kind_width}} {f.url}",
146
+ highlight=False,
147
+ )
148
+ say()
149
+ say(" Tools can load only their own files and the SweatStack API.")
150
+ say(
151
+ " Download these files into your tool (for example into vendor/) and use relative paths."
152
+ )
153
+ say(f" How, including DuckDB and Pyodide: {DOCS_DEPENDENCIES}")
154
+ if removed:
155
+ if blocked:
156
+ say()
157
+ say(
158
+ f"[yellow]![/yellow] {len(removed)} element{'s' if len(removed) != 1 else ''} SweatStack Tools removes, so they do nothing there:"
159
+ )
160
+ say()
161
+ width = max(len(f"{f.file}:{f.line}") for f in removed)
162
+ for f in removed:
163
+ say(f" {f'{f.file}:{f.line}':<{width}} {f.kind} {f.url}", highlight=False)
164
+ say()
165
+ say(
166
+ " Speculation rules, preconnect and DNS prefetch are not available in SweatStack Tools."
167
+ )
168
+ if not findings:
169
+ say(f"[green]✓[/green] Nothing in {directory} loads from another site.")
170
+
171
+
172
+ @app.command()
173
+ def check(
174
+ directory: Path = typer.Argument(Path("."), help="The tool's folder."),
175
+ ) -> None:
176
+ """Check a tool for files it would load from other sites, which SweatStack Tools blocks.
177
+
178
+ Exits with 1 when anything would be blocked, so an agent's loop treats it as a failure to fix.
179
+ """
180
+ root = _directory(directory)
181
+ policy = _policy()
182
+ findings = check_folder(root, policy.load_origins())
183
+ print_findings(findings, directory)
184
+ if any(f.kind not in REMOVED_KINDS for f in findings):
185
+ raise typer.Exit(1)
186
+
187
+
188
+ # ---------------------------------------------------------------- the tool API
189
+
190
+ DEFAULT_SCOPES = ("activities:read",)
191
+
192
+
193
+ def _is_interactive() -> bool:
194
+ return sys.stdin.isatty()
195
+
196
+
197
+ @contextmanager
198
+ def _api() -> Iterator[APIClient]:
199
+ """An authenticated client. Any API error ends the command with its message."""
200
+ try:
201
+ yield APIClient()
202
+ except AuthenticationError as error:
203
+ console.print(f"[red]Error:[/red] {error}")
204
+ raise typer.Exit(2)
205
+ except APIError as error:
206
+ console.print(f"[red]Error:[/red] {error.detail or error}")
207
+ raise typer.Exit(3)
208
+
209
+
210
+ def _ask(value: str | None, prompt: str, option: str, default: str | None = None) -> str:
211
+ """An option's value, or a prompt for it. Without a terminal, a missing option is an error."""
212
+ if value:
213
+ return value
214
+ if not _is_interactive():
215
+ console.print(f"[red]Error:[/red] {option} is required when not running interactively.")
216
+ raise typer.Exit(1)
217
+ answer: str = typer.prompt(prompt, default=default)
218
+ return answer.strip()
219
+
220
+
221
+ def _project_tool() -> tuple[ProjectConfig, ToolConfig, str]:
222
+ project = ProjectConfig.load()
223
+ if not project or not project.tool.slug:
224
+ console.print(
225
+ f"[red]Error:[/red] No tool in {CONFIG_FILENAME} here. Run 'sweatstack tool create' first."
226
+ )
227
+ raise typer.Exit(1)
228
+ return project, project.tool, project.tool.slug
229
+
230
+
231
+ def _ensure_author(
232
+ client: APIClient, name: str, handle: str | None, public_name: str | None
233
+ ) -> str:
234
+ """The developer's handle, chosen now if this is their first tool."""
235
+ try:
236
+ return str(client.get("/api/v1/tools/author")["handle"])
237
+ except APIError as error:
238
+ if error.status_code != 404:
239
+ raise
240
+ console.print(
241
+ "Your first tool. Choose your handle: it is part of every tool's address, and cannot change."
242
+ )
243
+ handle = _ask(handle, "Handle (3 to 20 lowercase letters and digits)", "--handle")
244
+ public_name = _ask(public_name, "Public name, shown with your tools", "--public-name")
245
+ if _is_interactive():
246
+ typer.confirm(
247
+ f"Your tools will be at {name}-{handle}.sweatstack.tools. Continue?",
248
+ abort=True,
249
+ default=True,
250
+ )
251
+ return str(
252
+ client.put("/api/v1/tools/author", json={"handle": handle, "public_name": public_name})[
253
+ "handle"
254
+ ]
255
+ )
256
+
257
+
258
+ @app.command()
259
+ def create(
260
+ name: str | None = typer.Option(
261
+ None, "--name", help="The address part, such as power-duration. Fixed for good."
262
+ ),
263
+ title: str | None = typer.Option(
264
+ None, "--title", help="What people read, such as 'Power duration'."
265
+ ),
266
+ description: str | None = typer.Option(
267
+ None, "--description", help="One sentence on what the tool does."
268
+ ),
269
+ scopes: list[str] = typer.Option(
270
+ list(DEFAULT_SCOPES), "--scope", help="A scope the tool may ever get. Repeat for more."
271
+ ),
272
+ directory: Path = typer.Option(
273
+ Path("public"), "--dir", help="The tool's folder, scaffolded from the template."
274
+ ),
275
+ handle: str | None = typer.Option(None, "--handle", help="Your handle, on your first tool."),
276
+ public_name: str | None = typer.Option(
277
+ None, "--public-name", help="Your public name, on your first tool."
278
+ ),
279
+ force: bool = typer.Option(
280
+ False, "--force", help=f"Overwrite {CONFIG_FILENAME} and the template's files."
281
+ ),
282
+ ) -> None:
283
+ """Create a private tool, write sweatstack.toml, and scaffold the template.
284
+
285
+ The template signs in through SweatStack Tools and plots your latest activity. Run
286
+ 'sweatstack tool serve' to try it, and 'sweatstack tool deploy' to put it online.
287
+ """
288
+ config = Path(CONFIG_FILENAME)
289
+ if config.exists() and not force:
290
+ console.print(
291
+ f"[red]Error:[/red] {CONFIG_FILENAME} exists here. Use --force to replace it."
292
+ )
293
+ raise typer.Exit(1)
294
+ if directory.exists() and any(directory.iterdir()) and not force:
295
+ console.print(
296
+ f"[red]Error:[/red] {directory} is not empty. Use --force to write the template into it."
297
+ )
298
+ raise typer.Exit(1)
299
+
300
+ name = _ask(name, "Name, the address part (such as power-duration)", "--name")
301
+ title = _ask(title, "Title", "--title", default=name.replace("-", " ").capitalize())
302
+ description = _ask(description, "Description, one sentence", "--description")
303
+
304
+ with _api() as client:
305
+ handle = _ensure_author(client, name, handle, public_name)
306
+ # The template first: a failed download then leaves nothing behind on SweatStack.
307
+ with console.status("Writing the template, and downloading DuckDB-WASM..."):
308
+ try:
309
+ scaffold(directory, title=title)
310
+ except DownloadError as error:
311
+ console.print(f"[red]Error:[/red] {error}")
312
+ raise typer.Exit(1)
313
+ tool = client.post(
314
+ "/api/v1/tools",
315
+ json={"name": name, "title": title, "description": description, "scopes": scopes},
316
+ )
317
+
318
+ write_config(
319
+ config,
320
+ app_name=tool["title"],
321
+ client_id=tool["client_id"],
322
+ tool=ToolConfig(
323
+ slug=tool["slug"], directory=directory.as_posix(), scopes=tuple(tool["scopes"])
324
+ ),
325
+ )
326
+ console.print(
327
+ f"[green]✓[/green] Created [bold]{tool['slug']}[/bold], private: only you can open it."
328
+ )
329
+ console.print(f" Address: {tool['url']}")
330
+ console.print(f" Folder: {directory} (written to {CONFIG_FILENAME})")
331
+ console.print()
332
+ console.print("Next: 'sweatstack tool serve' to try it here, then 'sweatstack tool deploy'.")
333
+
334
+
335
+ @app.command()
336
+ def deploy(
337
+ allow_external: bool = typer.Option(
338
+ False,
339
+ "--allow-external",
340
+ help="Deploy even when files load from other sites, which will fail.",
341
+ ),
342
+ ) -> None:
343
+ """Deploy the tool in sweatstack.toml: check it, upload what changed, and make it current."""
344
+ _, tool, slug = _project_tool()
345
+ root = _directory(Path(tool.directory or "."))
346
+ findings = check_folder(root, _policy().load_origins())
347
+ if any(f.kind not in REMOVED_KINDS for f in findings):
348
+ print_findings(findings, root)
349
+ if not allow_external:
350
+ say()
351
+ say(
352
+ " Deploy anyway with --allow-external (these requests will fail for every visitor)."
353
+ )
354
+ raise typer.Exit(1)
355
+ try:
356
+ files = collect(root)
357
+ except DeployError as error:
358
+ console.print(f"[red]Error:[/red] {error}")
359
+ raise typer.Exit(1)
360
+
361
+ with (
362
+ _api() as client,
363
+ Progress(
364
+ SpinnerColumn(),
365
+ TextColumn("Uploading"),
366
+ BarColumn(),
367
+ MofNCompleteColumn(),
368
+ console=console,
369
+ transient=True,
370
+ ) as progress,
371
+ ):
372
+ task = progress.add_task("upload", total=None)
373
+ uploaded = 0
374
+
375
+ def on_upload(_: object) -> None:
376
+ nonlocal uploaded
377
+ uploaded += 1
378
+ progress.update(task, completed=uploaded)
379
+
380
+ try:
381
+ result: dict[str, Any] = deploy_files(client, slug, files, on_upload=on_upload)
382
+ except DeployError as error:
383
+ console.print(f"[red]Error:[/red] {error}")
384
+ raise typer.Exit(1)
385
+ console.print(
386
+ f"[green]✓[/green] Deployed [bold]{slug}[/bold]: {len(files)} files, {uploaded} uploaded."
387
+ )
388
+ console.print(f" {result['url']}")
389
+ for warning in result.get("warnings", []):
390
+ say(f"[yellow]![/yellow] {warning}")
391
+
392
+
393
+ @app.command()
394
+ def deploys() -> None:
395
+ """List the kept deploys of the tool in sweatstack.toml, newest first, for 'tool rollback'."""
396
+ _, _, slug = _project_tool()
397
+ with _api() as client:
398
+ kept = cast(list[dict[str, Any]], client.get(f"/api/v1/tools/{slug}/deploys"))
399
+ if not kept:
400
+ say(f"{slug} has no deploys yet. Run 'sweatstack tool deploy'.")
401
+ return
402
+ for item in kept:
403
+ created = datetime.fromisoformat(item["created_at"]).astimezone()
404
+ notes = [n for n, on in (("serving", item["current"]), ("flagged", item["flagged"])) if on]
405
+ say(f"{item['id']} {created:%Y-%m-%d %H:%M} {', '.join(notes)}".rstrip(), highlight=False)
406
+
407
+
408
+ @app.command()
409
+ def rollback(
410
+ deploy_id: str | None = typer.Argument(
411
+ None,
412
+ help="The deploy to serve again, from 'sweatstack tool deploys'. The previous one by default.",
413
+ ),
414
+ ) -> None:
415
+ """Serve an earlier deploy of the tool in sweatstack.toml again."""
416
+ _, _, slug = _project_tool()
417
+ with _api() as client:
418
+ tool = client.post(f"/api/v1/tools/{slug}/rollback", json={"deploy_id": deploy_id})
419
+ current = (tool.get("current_deploy") or {}).get("id", "?")
420
+ console.print(f"[green]✓[/green] {slug} serves deploy {current} again.")
421
+
422
+
423
+ @app.command()
424
+ def publish(
425
+ unlisted: bool = typer.Option(
426
+ False, "--unlisted", help="Anyone with the link, but not in the catalogue."
427
+ ),
428
+ ) -> None:
429
+ """Open the tool in sweatstack.toml to everyone, in the catalogue, or with --unlisted to anyone with the link."""
430
+ _, _, slug = _project_tool()
431
+ access = "unlisted" if unlisted else "listed"
432
+ with _api() as client:
433
+ tool = client.put(f"/api/v1/tools/{slug}/access", json={"access": access})
434
+ console.print(f"[green]✓[/green] {slug} is {tool['access']}: {tool['url']}")
435
+ missing = [item["label"] for item in tool.get("go_live_missing") or []]
436
+ if missing:
437
+ console.print("[yellow]Before anyone else can sign in:[/yellow]")
438
+ for label in missing:
439
+ say(f" - {label}", highlight=False)
@@ -59,11 +59,15 @@ class APIError(CLIError):
59
59
  code: str | None = None,
60
60
  detail: str | None = None,
61
61
  exit_code: int | None = None,
62
+ body: dict[str, object] | None = None,
62
63
  ) -> None:
63
64
  super().__init__(message, exit_code)
64
65
  self.status_code = status_code
65
66
  self.code = code
66
67
  self.detail = detail
68
+ #: The error response's JSON object, for an answer with more than a detail, such as the
69
+ #: files a tool deploy still needs (`missing`).
70
+ self.body = body or {}
67
71
 
68
72
 
69
73
  class ValidationError(CLIError):