sdk-release-kit 0.2.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.
Files changed (39) hide show
  1. sdk_release_kit/__init__.py +3 -0
  2. sdk_release_kit/_data/examples/custom.example.yaml +18 -0
  3. sdk_release_kit/_data/examples/keys.example.yaml +18 -0
  4. sdk_release_kit/_data/examples/outputs.example.yaml +19 -0
  5. sdk_release_kit/_data/examples/repos.example.yaml +33 -0
  6. sdk_release_kit/_data/recipes/sdks.yaml +222 -0
  7. sdk_release_kit/_data/web/app.js +305 -0
  8. sdk_release_kit/_data/web/index.html +142 -0
  9. sdk_release_kit/_data/web/styles.css +93 -0
  10. sdk_release_kit/builders/__init__.py +24 -0
  11. sdk_release_kit/builders/android.py +86 -0
  12. sdk_release_kit/builders/base.py +217 -0
  13. sdk_release_kit/builders/flutter.py +16 -0
  14. sdk_release_kit/builders/generic.py +56 -0
  15. sdk_release_kit/builders/ios.py +204 -0
  16. sdk_release_kit/builders/reactnative.py +32 -0
  17. sdk_release_kit/cli.py +198 -0
  18. sdk_release_kit/mcp_server.py +240 -0
  19. sdk_release_kit/models.py +306 -0
  20. sdk_release_kit/paths.py +85 -0
  21. sdk_release_kit/pipeline.py +446 -0
  22. sdk_release_kit/recipes.py +110 -0
  23. sdk_release_kit/runlog.py +62 -0
  24. sdk_release_kit/server.py +331 -0
  25. sdk_release_kit/store/__init__.py +29 -0
  26. sdk_release_kit/store/_yaml.py +46 -0
  27. sdk_release_kit/store/custom.py +34 -0
  28. sdk_release_kit/store/keys.py +111 -0
  29. sdk_release_kit/store/outputs.py +15 -0
  30. sdk_release_kit/store/repos.py +15 -0
  31. sdk_release_kit/uploaders/__init__.py +20 -0
  32. sdk_release_kit/uploaders/onedrive.py +129 -0
  33. sdk_release_kit/uploaders/play.py +108 -0
  34. sdk_release_kit/uploaders/testflight.py +105 -0
  35. sdk_release_kit-0.2.0.dist-info/METADATA +307 -0
  36. sdk_release_kit-0.2.0.dist-info/RECORD +39 -0
  37. sdk_release_kit-0.2.0.dist-info/WHEEL +4 -0
  38. sdk_release_kit-0.2.0.dist-info/entry_points.txt +2 -0
  39. sdk_release_kit-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,204 @@
1
+ """iOS: simulator ``.app`` for the shared folder, archive + IPA export for TestFlight, and
2
+ XCFramework packages. All steps need macOS and Xcode.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import plistlib
8
+ import re
9
+ import shutil
10
+ from pathlib import Path
11
+
12
+ from ..models import XcframeworkStep, XcodeIpaStep, XcodeSimulatorStep
13
+ from ..paths import expand
14
+ from ..store.keys import resolve_secret
15
+ from .base import BuildContext, Command, Produced, StepError, StepPlan, handler
16
+
17
+
18
+ def _slug(text: str) -> str:
19
+ return re.sub(r"[^A-Za-z0-9._-]+", "-", text).strip("-") or "build"
20
+
21
+
22
+ def _container(step) -> list[str]:
23
+ if step.workspace:
24
+ return ["-workspace", step.workspace]
25
+ if step.project:
26
+ return ["-project", step.project]
27
+ return []
28
+
29
+
30
+ def _pod(step, cwd: Path) -> list[Command]:
31
+ return [Command(["pod", "install"], cwd)] if step.pod_install else []
32
+
33
+
34
+ def asc_auth_args(ctx: BuildContext) -> list[str]:
35
+ """Let xcodebuild manage signing with the App Store Connect API key when available."""
36
+ tf = ctx.settings.keys.testflight
37
+ key_path = expand(tf.key_path)
38
+ key_id = resolve_secret(tf.key_id)
39
+ issuer = resolve_secret(tf.issuer_id)
40
+ args = ["-allowProvisioningUpdates"]
41
+ if key_path and key_path.is_file() and key_id and issuer:
42
+ args += [
43
+ "-authenticationKeyPath",
44
+ str(key_path),
45
+ "-authenticationKeyID",
46
+ key_id,
47
+ "-authenticationKeyIssuerID",
48
+ issuer,
49
+ ]
50
+ return args
51
+
52
+
53
+ @handler("xcode-simulator")
54
+ def simulator_app(ctx: BuildContext, step: XcodeSimulatorStep, cwd: Path) -> StepPlan:
55
+ derived = ctx.work_dir / "DerivedData" / _slug(step.scheme)
56
+ products = derived / "Build" / "Products" / f"{step.configuration}-iphonesimulator"
57
+ argv = [
58
+ "xcodebuild",
59
+ *_container(step),
60
+ "-scheme",
61
+ step.scheme,
62
+ "-configuration",
63
+ step.configuration,
64
+ "-sdk",
65
+ "iphonesimulator",
66
+ "-destination",
67
+ "generic/platform=iOS Simulator",
68
+ "-derivedDataPath",
69
+ str(derived),
70
+ "CODE_SIGNING_ALLOWED=NO",
71
+ "build",
72
+ ]
73
+
74
+ def finish() -> list[Produced]:
75
+ if step.app_name:
76
+ apps = [
77
+ products
78
+ / (step.app_name if step.app_name.endswith(".app") else step.app_name + ".app")
79
+ ]
80
+ else:
81
+ apps = [p for p in sorted(products.glob("*.app")) if "Tests" not in p.name]
82
+ apps = [a for a in apps if a.is_dir()]
83
+ if not apps:
84
+ raise StepError(f"no .app found in {products}; set app_name in the recipe")
85
+ return [Produced(apps[0], "app", step.target)]
86
+
87
+ return StepPlan(
88
+ commands=[*_pod(step, cwd), Command(argv, cwd)],
89
+ roots={"derived_data": derived},
90
+ finish=finish,
91
+ )
92
+
93
+
94
+ @handler("xcode-ipa")
95
+ def archive_ipa(ctx: BuildContext, step: XcodeIpaStep, cwd: Path) -> StepPlan:
96
+ base = ctx.work_dir / "ipa" / _slug(step.scheme)
97
+ archive = base / f"{_slug(step.scheme)}.xcarchive"
98
+ export_dir = base / "export"
99
+ options = base / "ExportOptions.plist"
100
+ auth = asc_auth_args(ctx)
101
+ team = [f"DEVELOPMENT_TEAM={step.team_id}"] if step.team_id else []
102
+
103
+ def prepare() -> None:
104
+ shutil.rmtree(base, ignore_errors=True)
105
+ base.mkdir(parents=True)
106
+ opts = {
107
+ "method": step.export_method,
108
+ "signingStyle": "automatic",
109
+ "destination": "export",
110
+ "uploadSymbols": True,
111
+ }
112
+ if step.team_id:
113
+ opts["teamID"] = step.team_id
114
+ options.write_bytes(plistlib.dumps(opts))
115
+
116
+ archive_cmd = Command(
117
+ [
118
+ "xcodebuild",
119
+ *_container(step),
120
+ "-scheme",
121
+ step.scheme,
122
+ "-configuration",
123
+ step.configuration,
124
+ "-destination",
125
+ "generic/platform=iOS",
126
+ "-archivePath",
127
+ str(archive),
128
+ *team,
129
+ *auth,
130
+ "archive",
131
+ ],
132
+ cwd,
133
+ )
134
+ export_cmd = Command(
135
+ [
136
+ "xcodebuild",
137
+ "-exportArchive",
138
+ "-archivePath",
139
+ str(archive),
140
+ "-exportPath",
141
+ str(export_dir),
142
+ "-exportOptionsPlist",
143
+ str(options),
144
+ *auth,
145
+ ],
146
+ cwd,
147
+ )
148
+ return StepPlan(
149
+ commands=[*_pod(step, cwd), archive_cmd, export_cmd],
150
+ prepare=prepare,
151
+ roots={"export": export_dir},
152
+ finish=lambda: [Produced(p, "ipa") for p in sorted(export_dir.glob("*.ipa"))],
153
+ )
154
+
155
+
156
+ @handler("xcframework")
157
+ def xcframework(ctx: BuildContext, step: XcframeworkStep, cwd: Path) -> StepPlan:
158
+ base = ctx.work_dir / "xcframework" / _slug(step.scheme)
159
+ out = base / f"{step.framework_name}.xcframework"
160
+ zipped = base / f"{step.framework_name}-{ctx.version}.xcframework.zip"
161
+ commands = list(_pod(step, cwd))
162
+ framework_args: list[str] = []
163
+ for dest, name in (("generic/platform=iOS", "ios"), ("generic/platform=iOS Simulator", "sim")):
164
+ archive = base / f"{name}.xcarchive"
165
+ commands.append(
166
+ Command(
167
+ [
168
+ "xcodebuild",
169
+ "archive",
170
+ *_container(step),
171
+ "-scheme",
172
+ step.scheme,
173
+ "-configuration",
174
+ step.configuration,
175
+ "-destination",
176
+ dest,
177
+ "-archivePath",
178
+ str(archive),
179
+ "SKIP_INSTALL=NO",
180
+ "BUILD_LIBRARY_FOR_DISTRIBUTION=YES",
181
+ ],
182
+ cwd,
183
+ )
184
+ )
185
+ framework_args += [
186
+ "-framework",
187
+ str(
188
+ archive / "Products" / "Library" / "Frameworks" / f"{step.framework_name}.framework"
189
+ ),
190
+ ]
191
+ commands.append(
192
+ Command(["xcodebuild", "-create-xcframework", *framework_args, "-output", str(out)], cwd)
193
+ )
194
+ commands.append(Command(["ditto", "-c", "-k", "--keepParent", str(out), str(zipped)], cwd))
195
+
196
+ def prepare() -> None:
197
+ shutil.rmtree(base, ignore_errors=True)
198
+ base.mkdir(parents=True)
199
+
200
+ return StepPlan(
201
+ commands=commands,
202
+ prepare=prepare,
203
+ finish=lambda: [Produced(zipped, "zip")],
204
+ )
@@ -0,0 +1,32 @@
1
+ """React Native: ``npm pack`` for the package.
2
+
3
+ RN demo apps reuse the ``run``, ``gradle`` and ``xcode-*`` steps with ``workdir`` pointing at
4
+ the demo's ``android/`` and ``ios/`` folders; see ``recipes/sdks.yaml``.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import shutil
10
+ from pathlib import Path
11
+
12
+ from ..models import NpmPackStep
13
+ from .base import BuildContext, Command, Produced, StepPlan, handler
14
+
15
+
16
+ @handler("npm-pack")
17
+ def npm_pack(ctx: BuildContext, step: NpmPackStep, cwd: Path) -> StepPlan:
18
+ dest = ctx.work_dir / "npm-pack"
19
+ commands = []
20
+ if step.install:
21
+ commands.append(Command(["npm", "install"], cwd))
22
+ commands.append(Command(["npm", "pack", "--pack-destination", str(dest)], cwd))
23
+
24
+ def prepare() -> None:
25
+ shutil.rmtree(dest, ignore_errors=True)
26
+ dest.mkdir(parents=True)
27
+
28
+ return StepPlan(
29
+ commands=commands,
30
+ prepare=prepare,
31
+ finish=lambda: [Produced(p, "tgz") for p in sorted(dest.glob("*.tgz"))],
32
+ )
sdk_release_kit/cli.py ADDED
@@ -0,0 +1,198 @@
1
+ """Command line interface. Mirrors the Run page of the Settings UI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import getpass
6
+ import json
7
+ import os
8
+ import shutil
9
+ import sys
10
+
11
+ import typer
12
+
13
+ from . import __version__
14
+ from .models import DESTINATIONS
15
+ from .paths import data_dir, key_files_dir, settings_file, user_home
16
+ from .recipes import RecipeError, load_recipes, recipe_sources
17
+ from .runlog import RunLog
18
+
19
+ app = typer.Typer(
20
+ add_completion=False,
21
+ no_args_is_help=True,
22
+ help="Build mobile SDK demo apps and packages, then publish them.",
23
+ )
24
+ keys_app = typer.Typer(no_args_is_help=True, help="Manage secrets in the OS keychain.")
25
+ app.add_typer(keys_app, name="keys")
26
+
27
+
28
+ def _split(value: str | None) -> list[str] | None:
29
+ if value is None:
30
+ return None
31
+ items = [v.strip() for v in value.split(",") if v.strip()]
32
+ return items
33
+
34
+
35
+ @app.command()
36
+ def version() -> None:
37
+ """Print the tool version."""
38
+ typer.echo(__version__)
39
+
40
+
41
+ @app.command()
42
+ def init(force: bool = typer.Option(False, help="Overwrite existing settings files.")) -> None:
43
+ """Create user settings from the shipped examples."""
44
+ home = user_home()
45
+ home.mkdir(parents=True, exist_ok=True)
46
+ os.chmod(home, 0o700)
47
+ key_files_dir().mkdir(exist_ok=True)
48
+ os.chmod(key_files_dir(), 0o700)
49
+ examples = data_dir("examples")
50
+ for kind in ("repos", "outputs", "keys", "custom"):
51
+ target = settings_file(kind)
52
+ source = examples / f"{kind}.example.yaml"
53
+ if target.exists() and not force:
54
+ typer.echo(f"keep {target}")
55
+ continue
56
+ target.parent.mkdir(parents=True, exist_ok=True)
57
+ shutil.copyfile(source, target)
58
+ os.chmod(target, 0o600)
59
+ typer.echo(f"created {target}")
60
+ typer.echo("\nNext: run 'sdk-release-kit serve' and fill in Repositories, Outputs and Keys.")
61
+
62
+
63
+ @app.command()
64
+ def serve(
65
+ port: int = typer.Option(8765, help="Port on 127.0.0.1."),
66
+ host: str = typer.Option("127.0.0.1", help="Bind address (loopback only by default)."),
67
+ no_browser: bool = typer.Option(False, "--no-browser", help="Do not open a browser."),
68
+ ) -> None:
69
+ """Open the Settings UI."""
70
+ from .server import serve as run_server
71
+
72
+ run_server(host=host, port=port, open_browser=not no_browser)
73
+
74
+
75
+ @app.command()
76
+ def mcp() -> None:
77
+ """Run the MCP server on stdio, for AI agents (Claude, Cursor, Copilot and others)."""
78
+ from .mcp_server import run as run_mcp
79
+
80
+ run_mcp()
81
+
82
+
83
+ @app.command()
84
+ def recipes() -> None:
85
+ """List recipe ids and where recipes were loaded from."""
86
+ try:
87
+ loaded = load_recipes()
88
+ except RecipeError as exc:
89
+ typer.echo(str(exc), err=True)
90
+ raise typer.Exit(2) from exc
91
+ for src in recipe_sources():
92
+ typer.echo(f"# {src}")
93
+ for rid, r in loaded.recipes.items():
94
+ stores = [s for s in ("play", "testflight") if getattr(r.store, s)]
95
+ typer.echo(
96
+ f"{rid:22} {r.platform:12} demos:{len(r.demos)} packages:{len(r.packages)}"
97
+ f" stores:{','.join(stores) or '-'} {r.label}"
98
+ )
99
+
100
+
101
+ @app.command()
102
+ def status() -> None:
103
+ """Show settings files, key status (never values) and tool availability."""
104
+ from .store import keys as keys_store
105
+ from .store import load_all
106
+
107
+ typer.echo(f"settings directory: {user_home()}")
108
+ for kind in ("repos", "outputs", "keys", "custom"):
109
+ f = settings_file(kind)
110
+ typer.echo(f" {kind:8} {'ok ' if f.exists() else 'missing'} {f}")
111
+ settings = load_all()
112
+ typer.echo("repositories:")
113
+ for rid, entry in settings.repos.repos.items():
114
+ from .paths import expand
115
+
116
+ p = expand(entry.path)
117
+ state = "disabled" if not entry.enabled else ("ok" if p and p.is_dir() else "missing")
118
+ typer.echo(f" {rid:22} {state:9} {entry.path}")
119
+ typer.echo("keys:")
120
+ for name, st in keys_store.status(settings.keys).items():
121
+ typer.echo(
122
+ f" {name:24} {'configured' if st['configured'] else 'missing '} {st['detail']}"
123
+ )
124
+ typer.echo("tools:")
125
+ for tool in ("git", "java", "flutter", "xcodebuild", "pod", "npm", "fastlane"):
126
+ typer.echo(f" {tool:12} {shutil.which(tool) or 'not found'}")
127
+
128
+
129
+ @app.command()
130
+ def build(
131
+ sdks: str = typer.Option(None, help="Comma-separated recipe ids. Default: all enabled repos."),
132
+ artifacts: str = typer.Option("both", help="demos, packages or both."),
133
+ dest: str = typer.Option(
134
+ None,
135
+ help=f"Comma-separated destinations ({', '.join(DESTINATIONS)}). Default: enabled ones.",
136
+ ),
137
+ dry_run: bool = typer.Option(False, "--dry-run", help="Print the plan only."),
138
+ skip_upload: bool = typer.Option(False, "--skip-upload", help="Build only, publish nothing."),
139
+ json_out: bool = typer.Option(False, "--json", help="Print the report as JSON at the end."),
140
+ ) -> None:
141
+ """Build the selected SDKs and publish to the chosen destinations."""
142
+ from .pipeline import Pipeline, RunOptions
143
+
144
+ if artifacts not in ("demos", "packages", "both"):
145
+ raise typer.BadParameter("must be demos, packages or both", param_hint="--artifacts")
146
+ log = RunLog()
147
+ log.subscribe(lambda line: print(line, flush=True))
148
+ opts = RunOptions(
149
+ sdks=_split(sdks),
150
+ artifacts=artifacts,
151
+ destinations=_split(dest),
152
+ dry_run=dry_run,
153
+ skip_upload=skip_upload,
154
+ )
155
+ try:
156
+ report = Pipeline(log=log).run(opts)
157
+ except (RecipeError, ValueError) as exc:
158
+ typer.echo(f"error: {exc}", err=True)
159
+ raise typer.Exit(2) from exc
160
+ if json_out:
161
+ typer.echo(json.dumps(report, indent=2))
162
+ if not dry_run and not report.get("ok"):
163
+ raise typer.Exit(1)
164
+
165
+
166
+ @keys_app.command("set")
167
+ def keys_set(
168
+ name: str = typer.Argument(..., help="Keychain entry name, e.g. android.store_password"),
169
+ ) -> None:
170
+ """Store a secret in the OS keychain (prompted, never echoed)."""
171
+ from .store.keys import set_keychain_secret
172
+
173
+ value = getpass.getpass(f"value for {name}: ")
174
+ if not value:
175
+ typer.echo("empty value, nothing stored", err=True)
176
+ raise typer.Exit(1)
177
+ set_keychain_secret(name, value)
178
+ typer.echo(f"stored keychain entry '{name}' (service sdk-release-kit)")
179
+
180
+
181
+ @keys_app.command("delete")
182
+ def keys_delete(name: str) -> None:
183
+ """Remove a secret from the OS keychain."""
184
+ from .store.keys import delete_keychain_secret
185
+
186
+ delete_keychain_secret(name)
187
+ typer.echo(f"deleted keychain entry '{name}'")
188
+
189
+
190
+ def main() -> None:
191
+ try:
192
+ app()
193
+ except KeyboardInterrupt:
194
+ sys.exit(130)
195
+
196
+
197
+ if __name__ == "__main__":
198
+ main()
@@ -0,0 +1,240 @@
1
+ """MCP server: lets AI agents inspect, plan and run SDK releases.
2
+
3
+ Start with ``sdk-release-kit mcp`` (stdio). Nothing here returns a secret value: key status is
4
+ reported as configured or missing, and run logs pass through the same redactor as the CLI.
5
+ Stdout belongs to the MCP protocol, so this module must never print.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import functools
11
+ import json
12
+ import shutil
13
+ from collections.abc import Callable
14
+ from typing import Any, Literal, TypeVar
15
+
16
+ from mcp.server.mcpserver import MCPServer
17
+ from mcp.server.mcpserver.exceptions import ToolError
18
+ from mcp.types import ToolAnnotations
19
+
20
+ from . import __version__
21
+ from .models import DESTINATIONS, RepoEntry
22
+ from .paths import expand, settings_file, user_home
23
+ from .pipeline import Pipeline, RunOptions
24
+ from .recipes import load_recipes, recipe_sources
25
+ from .runlog import RunLog
26
+ from .store import keys as keys_store
27
+ from .store import load_all
28
+ from .store import repos as repos_store
29
+
30
+ INSTRUCTIONS = """\
31
+ SDK Release Kit builds mobile SDK demo apps and SDK packages (Android, iOS, Flutter,
32
+ React Native) from local checkouts and publishes them to a synced shared folder,
33
+ Google Play internal testing and TestFlight.
34
+
35
+ Suggested flow:
36
+ 1. get_status: see which recipes have a checkout, which keys are configured and which
37
+ destinations are ready. Secret values are never returned.
38
+ 2. list_recipes: recipe ids and what each builds.
39
+ 3. plan_build: a dry run that shows the exact commands, collected files and destinations.
40
+ 4. run_build: only when the user asked for a build or release. Builds can take minutes.
41
+ 5. list_runs / get_run_report: inspect previous runs.
42
+
43
+ Store uploads soft-skip when credentials are missing. Recipes live in git; machine paths
44
+ and keys live in the user's settings directory. Ask the user to fill keys in the Settings UI
45
+ (`sdk-release-kit serve`); never ask them to paste passwords into the chat.
46
+ """
47
+
48
+ server = MCPServer(
49
+ name="sdk-release-kit",
50
+ title="SDK Release Kit",
51
+ instructions=INSTRUCTIONS,
52
+ version=__version__,
53
+ website_url="https://github.com/yehyatt/sdk-release-kit",
54
+ )
55
+
56
+ F = TypeVar("F", bound=Callable[..., Any])
57
+
58
+
59
+ def agent_errors(fn: F) -> F:
60
+ """Turn expected failures into ToolError so the agent sees the reason, not a generic error."""
61
+
62
+ @functools.wraps(fn)
63
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
64
+ try:
65
+ return fn(*args, **kwargs)
66
+ except (ValueError, OSError) as exc: # RecipeError is a ValueError
67
+ raise ToolError(str(exc)) from exc
68
+
69
+ return wrapper # type: ignore[return-value]
70
+
71
+
72
+ READ_ONLY = ToolAnnotations(readOnlyHint=True, openWorldHint=False)
73
+ Artifacts = Literal["demos", "packages", "both"]
74
+
75
+
76
+ def _log_tail(log: RunLog, limit: int = 300) -> list[str]:
77
+ lines = log.lines
78
+ return lines[-limit:] if len(lines) > limit else lines
79
+
80
+
81
+ @server.tool(annotations=READ_ONLY)
82
+ @agent_errors
83
+ def get_status() -> dict[str, Any]:
84
+ """Settings files, repository checkouts, key status (configured or missing, never values),
85
+ destination readiness and build tools found on PATH."""
86
+ settings = load_all()
87
+ pipeline = Pipeline(settings=settings)
88
+ repos = {}
89
+ for rid, entry in settings.repos.repos.items():
90
+ p = expand(entry.path)
91
+ repos[rid] = {
92
+ "path": entry.path,
93
+ "enabled": entry.enabled,
94
+ "exists": bool(p and p.is_dir()),
95
+ }
96
+ destinations = pipeline.destination_status(RunOptions(destinations=list(DESTINATIONS)))
97
+ return {
98
+ "version": __version__,
99
+ "settings_dir": str(user_home()),
100
+ "settings_files": {
101
+ k: {"path": str(settings_file(k)), "exists": settings_file(k).exists()}
102
+ for k in ("repos", "outputs", "keys", "custom")
103
+ },
104
+ "repos": repos,
105
+ "keys": keys_store.status(settings.keys),
106
+ "destinations": {
107
+ d: ("ready" if reason is None else f"skipped: {reason}")
108
+ for d, reason in destinations.items()
109
+ },
110
+ "tools": {
111
+ t: shutil.which(t)
112
+ for t in ("git", "java", "flutter", "xcodebuild", "pod", "npm", "fastlane")
113
+ },
114
+ "staging": str(expand(settings.outputs.staging)),
115
+ }
116
+
117
+
118
+ @server.tool(annotations=READ_ONLY)
119
+ @agent_errors
120
+ def list_recipes() -> dict[str, Any]:
121
+ """Recipe ids with platform, steps and store flags, plus whether each has a checkout."""
122
+ recipes = load_recipes()
123
+ repos = load_all().repos.repos
124
+ out = {}
125
+ for rid, r in recipes.recipes.items():
126
+ entry = repos.get(rid)
127
+ out[rid] = {
128
+ "platform": r.platform,
129
+ "label": r.label,
130
+ "demo_steps": [s.name or s.type for s in r.demos],
131
+ "package_steps": [s.name or s.type for s in r.packages],
132
+ "store": {"play": r.store.play, "testflight": r.store.testflight},
133
+ "checkout": entry.path if entry else None,
134
+ "enabled": bool(entry and entry.enabled),
135
+ }
136
+ return {"sources": [str(s) for s in recipe_sources()], "recipes": out}
137
+
138
+
139
+ @server.tool(annotations=READ_ONLY)
140
+ @agent_errors
141
+ def plan_build(
142
+ sdks: list[str] | None = None,
143
+ artifacts: Artifacts = "both",
144
+ destinations: list[str] | None = None,
145
+ ) -> dict[str, Any]:
146
+ """Dry run. Shows the commands that would run, the files that would be collected and
147
+ which destinations are ready or skipped. Builds nothing.
148
+
149
+ sdks: recipe ids; default is every enabled repository.
150
+ destinations: subset of onedrive, play, testflight; default is those enabled in Outputs.
151
+ """
152
+ log = RunLog()
153
+ result = Pipeline(log=log).run(
154
+ RunOptions(sdks=sdks, artifacts=artifacts, destinations=destinations, dry_run=True)
155
+ )
156
+ return {**result, "plan": log.lines}
157
+
158
+
159
+ @server.tool(annotations=ToolAnnotations(destructiveHint=False, openWorldHint=True))
160
+ @agent_errors
161
+ def run_build(
162
+ sdks: list[str],
163
+ artifacts: Artifacts = "both",
164
+ destinations: list[str] | None = None,
165
+ skip_upload: bool = False,
166
+ ) -> dict[str, Any]:
167
+ """Build the given recipes and publish to the given destinations. Run plan_build first
168
+ and only call this when the user asked for a build. Can take several minutes. Uploads to
169
+ Google Play or TestFlight reach real testers.
170
+
171
+ Returns the run report (artifacts, upload results, ok flag) and the end of the log.
172
+ """
173
+ log = RunLog()
174
+ report = Pipeline(log=log).run(
175
+ RunOptions(
176
+ sdks=sdks, artifacts=artifacts, destinations=destinations, skip_upload=skip_upload
177
+ )
178
+ )
179
+ return {"report": report, "log_tail": _log_tail(log)}
180
+
181
+
182
+ @server.tool(annotations=READ_ONLY)
183
+ @agent_errors
184
+ def list_runs(limit: int = 10) -> list[dict[str, Any]]:
185
+ """Most recent runs with their outcome."""
186
+ staging = expand(load_all().outputs.staging)
187
+ runs_dir = staging / "runs" if staging else None
188
+ if not runs_dir or not runs_dir.is_dir():
189
+ return []
190
+ out = []
191
+ for run in sorted((p for p in runs_dir.iterdir() if p.is_dir()), reverse=True)[:limit]:
192
+ report_file = run / "report.json"
193
+ if report_file.exists():
194
+ report = json.loads(report_file.read_text(encoding="utf-8"))
195
+ out.append(
196
+ {
197
+ "run": run.name,
198
+ "ok": report.get("ok"),
199
+ "sdks": report.get("options", {}).get("sdks"),
200
+ "builds": {b["recipe"]: b["status"] for b in report.get("builds", [])},
201
+ }
202
+ )
203
+ else:
204
+ out.append({"run": run.name, "ok": None, "note": "no report (interrupted run?)"})
205
+ return out
206
+
207
+
208
+ @server.tool(annotations=READ_ONLY)
209
+ @agent_errors
210
+ def get_run_report(run: str, log_lines: int = 200) -> dict[str, Any]:
211
+ """Full report.json and the last lines of log.txt for one run id from list_runs."""
212
+ staging = expand(load_all().outputs.staging)
213
+ if staging is None or "/" in run or run.startswith("."):
214
+ raise ValueError("invalid run id")
215
+ run_dir = staging / "runs" / run
216
+ if not run_dir.is_dir():
217
+ raise ValueError(f"no run named {run}")
218
+ report_file, log_file = run_dir / "report.json", run_dir / "log.txt"
219
+ report = json.loads(report_file.read_text(encoding="utf-8")) if report_file.exists() else None
220
+ lines = log_file.read_text(encoding="utf-8").splitlines() if log_file.exists() else []
221
+ return {"report": report, "log_tail": lines[-log_lines:]}
222
+
223
+
224
+ @server.tool(annotations=ToolAnnotations(destructiveHint=False, idempotentHint=True))
225
+ @agent_errors
226
+ def set_repo_path(recipe_id: str, path: str, enabled: bool = True) -> dict[str, Any]:
227
+ """Point a recipe at its local checkout (Repositories settings). The folder must exist."""
228
+ if recipe_id not in load_recipes().recipes:
229
+ raise ValueError(f"unknown recipe id {recipe_id}")
230
+ resolved = expand(path)
231
+ if resolved is None or not resolved.is_dir():
232
+ raise ValueError(f"folder not found: {path}")
233
+ settings = repos_store.load()
234
+ settings.repos[recipe_id] = RepoEntry(path=path, enabled=enabled)
235
+ repos_store.save(settings)
236
+ return {"recipe": recipe_id, "path": path, "resolved": str(resolved), "enabled": enabled}
237
+
238
+
239
+ def run() -> None:
240
+ server.run("stdio")