bujang 0.1.1__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 (61) hide show
  1. bujang/__init__.py +9 -0
  2. bujang/cli/__init__.py +62 -0
  3. bujang/cli/cleanup.py +184 -0
  4. bujang/cli/dev.py +172 -0
  5. bujang/cli/serve/__init__.py +49 -0
  6. bujang/cli/serve/app.py +105 -0
  7. bujang/cli/serve/static/assets/index-Bjyezt0r.js +107 -0
  8. bujang/cli/serve/static/assets/index-H6REUvAg.css +1 -0
  9. bujang/cli/serve/static/index.html +13 -0
  10. bujang/cli/ssh/__init__.py +39 -0
  11. bujang/cli/ssh/common.py +94 -0
  12. bujang/cli/ssh/install.py +68 -0
  13. bujang/cli/ssh/remove.py +39 -0
  14. bujang/cli/ssh/show.py +45 -0
  15. bujang/cli/ssh/test.py +97 -0
  16. bujang/config.py +194 -0
  17. bujang/constant.py +10 -0
  18. bujang/defaults/profiles.yaml +12 -0
  19. bujang/defaults/scripts/common/hello_world.sh +47 -0
  20. bujang/defaults/scripts/common/job_array.sh +46 -0
  21. bujang/defaults/scripts/common/pipeline/two_step_pipeline.json +23 -0
  22. bujang/defaults/scripts/common/pipeline_prepare.sh +37 -0
  23. bujang/defaults/scripts/common/pipeline_use.sh +36 -0
  24. bujang/errors.py +16 -0
  25. bujang/fastapi.py +90 -0
  26. bujang/flask.py +49 -0
  27. bujang/mcp_server.py +839 -0
  28. bujang/models.py +115 -0
  29. bujang/scripts/__init__.py +1 -0
  30. bujang/scripts/dm_runner.sh +52 -0
  31. bujang/scripts/epilogue.sh +22 -0
  32. bujang/scripts/hook_end.sh +4 -0
  33. bujang/scripts/hook_epilogue.sh +10 -0
  34. bujang/scripts/hook_proxy.sh +14 -0
  35. bujang/scripts/hook_start.sh +19 -0
  36. bujang/scripts/prologue.sh +22 -0
  37. bujang/scripts/ssh_runner.sh +143 -0
  38. bujang/scripts/submit_epilogue.sh +9 -0
  39. bujang/scripts/submit_prologue.sh +11 -0
  40. bujang/server/__init__.py +1 -0
  41. bujang/server/agent.py +308 -0
  42. bujang/server/cache.py +47 -0
  43. bujang/server/commands.py +58 -0
  44. bujang/server/jsonutil.py +36 -0
  45. bujang/server/paths.py +23 -0
  46. bujang/server/pipeline.py +411 -0
  47. bujang/server/routes.py +186 -0
  48. bujang/server/scheduled.py +417 -0
  49. bujang/server/secrets.py +386 -0
  50. bujang/server/service.py +2446 -0
  51. bujang/server/slurm.py +543 -0
  52. bujang/server/sources.py +300 -0
  53. bujang/server/templates.py +180 -0
  54. bujang/sshcheck.py +203 -0
  55. bujang/sshconfig.py +398 -0
  56. bujang-0.1.1.dist-info/METADATA +384 -0
  57. bujang-0.1.1.dist-info/RECORD +61 -0
  58. bujang-0.1.1.dist-info/WHEEL +5 -0
  59. bujang-0.1.1.dist-info/entry_points.txt +2 -0
  60. bujang-0.1.1.dist-info/licenses/LICENSE +21 -0
  61. bujang-0.1.1.dist-info/top_level.txt +1 -0
bujang/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """bujang: Slurm job management over SSH (jobs, pipelines, scheduled jobs, secrets, agent activity)."""
2
+
3
+ from .config import BujangConfig
4
+ from .errors import BujangError
5
+ from .server.service import Bujang, JSONFile
6
+ from .server.sources import BujangPlugin
7
+
8
+ __all__ = ["Bujang", "BujangConfig", "BujangError", "BujangPlugin", "JSONFile"]
9
+ __version__ = "0.1.1"
bujang/cli/__init__.py ADDED
@@ -0,0 +1,62 @@
1
+ """`bujang` command line: argklass commands listed in the COMMANDS of the cli modules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from argklass.argformat import HelpAction, HelpActionException
9
+ from argklass.command import ParentCommand
10
+
11
+
12
+ def discover_commands() -> dict:
13
+ from .cleanup import COMMANDS as cleanup
14
+ from .dev import COMMANDS as dev
15
+ from .serve import COMMANDS as serve
16
+ from .ssh import COMMANDS as ssh
17
+
18
+ commands = {}
19
+ for group in (serve, dev, cleanup, ssh):
20
+ for cls in group if isinstance(group, list) else [group]:
21
+ commands[cls.name] = cls()
22
+ return commands
23
+
24
+
25
+ def build_parser(commands):
26
+ parser = argparse.ArgumentParser(add_help=False, description="Slurm job management over SSH")
27
+ parser.add_argument("-h", "--help", action=HelpAction, help="show this help message and exit")
28
+
29
+ subparsers = parser.add_subparsers(dest="command")
30
+
31
+ ParentCommand.dispatch = dict()
32
+ for command in commands.values():
33
+ command.arguments(subparsers)
34
+
35
+ return parser
36
+
37
+
38
+ def main(argv=None):
39
+ """Entry point for the command line interface."""
40
+ commands = discover_commands()
41
+
42
+ try:
43
+ parser = build_parser(commands)
44
+ parsed_args = parser.parse_args(argv)
45
+ except HelpActionException:
46
+ return 0
47
+
48
+ command = commands.get(parsed_args.command)
49
+ if command is None:
50
+ parser.print_help()
51
+ return 1
52
+
53
+ returncode = command.execute(parsed_args)
54
+ return returncode if returncode is not None else 0
55
+
56
+
57
+ def main_force(argv=None):
58
+ sys.exit(main(argv))
59
+
60
+
61
+ if __name__ == "__main__":
62
+ main_force()
bujang/cli/cleanup.py ADDED
@@ -0,0 +1,184 @@
1
+ """`bujang cleanup`: remove old job folders of the local cache that never produced any data.
2
+
3
+ A job folder "has data" when one of the ``--marker`` globs (relative to the job folder, default
4
+ ``output/*``) matches a non-empty file. A YAML marker also needs at least one top level key
5
+ besides the ``--ignore-key`` ones (default: ``version``), so a stub written at start does not count.
6
+
7
+ Job folders with data are kept whatever their age. The age of a folder is the time since its
8
+ ``cmd.sh`` was written (at submission, never touched again), else the folder's mtime.
9
+
10
+ Examples::
11
+
12
+ bujang cleanup --dry-run # preview, default cutoff: 7 days
13
+ bujang cleanup --min-age-days 14 # with a confirmation prompt
14
+ bujang cleanup --yes --marker 'runs/*.yaml' # non-interactive (cron)
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import glob
20
+ import os
21
+ import shutil
22
+ import time
23
+ from dataclasses import dataclass
24
+
25
+ from argklass.command import Command, newparser
26
+
27
+
28
+ @dataclass
29
+ class RunInfo:
30
+ path: str
31
+ name: str
32
+ age_days: float
33
+ has_data: bool
34
+ reason: str
35
+
36
+
37
+ def _submission_time(run_dir: str) -> float:
38
+ """Submission timestamp of a job folder: cmd.sh is written once at sbatch time"""
39
+ try:
40
+ return os.path.getmtime(os.path.join(run_dir, "cmd.sh"))
41
+ except OSError:
42
+ return os.path.getmtime(run_dir)
43
+
44
+
45
+ def _marker_has_data(path: str, ignore_keys=("version",)) -> bool:
46
+ try:
47
+ if os.path.getsize(path) == 0:
48
+ return False
49
+ except OSError:
50
+ return False
51
+
52
+ if not path.endswith((".yaml", ".yml")):
53
+ return True
54
+
55
+ import yaml
56
+
57
+ try:
58
+ with open(path) as fp:
59
+ content = yaml.safe_load(fp)
60
+ except Exception:
61
+ return False
62
+
63
+ if not isinstance(content, dict):
64
+ return bool(content)
65
+ return any(key not in ignore_keys for key in content.keys())
66
+
67
+
68
+ def inspect_run(data_dir: str, name: str, markers=("output/*",), ignore_keys=("version",)) -> RunInfo:
69
+ run_dir = os.path.join(data_dir, name)
70
+ age_days = (time.time() - _submission_time(run_dir)) / 86400
71
+
72
+ found = []
73
+ for marker in markers:
74
+ found.extend(p for p in glob.glob(os.path.join(run_dir, marker)) if os.path.isfile(p))
75
+
76
+ if not found:
77
+ return RunInfo(run_dir, name, age_days, False, f"no {' / '.join(markers)}")
78
+
79
+ for path in found:
80
+ if _marker_has_data(path, ignore_keys):
81
+ return RunInfo(run_dir, name, age_days, True, f"{os.path.relpath(path, run_dir)} has data")
82
+
83
+ return RunInfo(run_dir, name, age_days, False, "markers are empty stubs")
84
+
85
+
86
+ class Cleanup(Command):
87
+ """Remove old job folders without data from the local cache."""
88
+
89
+ name: str = "cleanup"
90
+
91
+ @staticmethod
92
+ def arguments(subparsers):
93
+ parser = newparser(subparsers, Cleanup)
94
+ parser.add_argument(
95
+ "--data-dir", type=str, default=None, help="Folder of the job folders (default: the local cache)"
96
+ )
97
+ parser.add_argument(
98
+ "--min-age-days", type=float, default=7.0, help="Only remove folders at least this many days old (7)"
99
+ )
100
+ parser.add_argument(
101
+ "--marker",
102
+ action="append",
103
+ default=None,
104
+ help="glob, relative to the job folder, of the files that hold its data (output/*), repeatable",
105
+ )
106
+ parser.add_argument(
107
+ "--ignore-key",
108
+ action="append",
109
+ default=None,
110
+ help="top level key of a YAML marker that does not count as data (version), repeatable",
111
+ )
112
+ parser.add_argument("--yes", "-y", action="store_true", help="Skip interactive confirmation")
113
+ parser.add_argument("--dry-run", action="store_true", help="Print what would be removed; delete nothing")
114
+
115
+ @staticmethod
116
+ def execute(args):
117
+ data_dir = args.data_dir
118
+ if not data_dir:
119
+ from ..config import BujangConfig
120
+
121
+ data_dir = BujangConfig.from_env().local_cache_path
122
+
123
+ markers = tuple(args.marker or ["output/*"])
124
+ ignore_keys = tuple(args.ignore_key or ["version"])
125
+
126
+ if not os.path.isdir(data_dir):
127
+ print(f"[cleanup] No such directory: {data_dir}")
128
+ return 1
129
+
130
+ names = sorted(
131
+ n for n in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, n)) and not n.startswith(".")
132
+ )
133
+
134
+ to_remove = []
135
+ kept_data = 0
136
+ kept_young = 0
137
+
138
+ for name in names:
139
+ info = inspect_run(data_dir, name, markers, ignore_keys)
140
+
141
+ if info.has_data:
142
+ kept_data += 1
143
+ continue
144
+
145
+ if info.age_days < args.min_age_days:
146
+ kept_young += 1
147
+ continue
148
+
149
+ to_remove.append(info)
150
+
151
+ print(f"[cleanup] Scanned {len(names)} job folder(s) in {data_dir}")
152
+ print(f"[cleanup] Kept (has data): {kept_data}")
153
+ print(f"[cleanup] Kept (younger than {args.min_age_days:g}d): {kept_young}")
154
+ print(f"[cleanup] Candidates for removal: {len(to_remove)}")
155
+
156
+ if not to_remove:
157
+ return 0
158
+
159
+ for info in to_remove:
160
+ print(f" - {info.name} ({info.age_days:.1f}d old, {info.reason})")
161
+
162
+ if args.dry_run:
163
+ print("[cleanup] Dry run -- nothing deleted.")
164
+ return 0
165
+
166
+ if not args.yes:
167
+ answer = input(f"Delete {len(to_remove)} job folder(s)? [y/N] ").strip().lower()
168
+ if answer not in ("y", "yes"):
169
+ print("[cleanup] Aborted.")
170
+ return 1
171
+
172
+ removed = 0
173
+ for info in to_remove:
174
+ try:
175
+ shutil.rmtree(info.path)
176
+ removed += 1
177
+ except OSError as exc:
178
+ print(f"[cleanup] Failed to remove {info.path}: {exc}")
179
+
180
+ print(f"[cleanup] Removed {removed}/{len(to_remove)} job folder(s).")
181
+ return 0
182
+
183
+
184
+ COMMANDS = [Cleanup]
bujang/cli/dev.py ADDED
@@ -0,0 +1,172 @@
1
+ """`bujang dev`: the API with auto-reload and the UI Vite dev server (HMR), from a source checkout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import signal
8
+ import subprocess
9
+ import sys
10
+ import threading
11
+ import time
12
+ from pathlib import Path
13
+
14
+ from argklass.command import Command, newparser
15
+
16
+ PACKAGE_DIR = Path(__file__).resolve().parent.parent
17
+ UI_DIR = PACKAGE_DIR.parent / "ui"
18
+
19
+
20
+ def _pump(stream, prefix, out):
21
+ """Copy the lines of a child's output, prefixed"""
22
+ for line in iter(stream.readline, ""):
23
+ out.write(f"{prefix} {line}")
24
+ out.flush()
25
+ stream.close()
26
+
27
+
28
+ def api_command(host, port):
29
+ return [
30
+ sys.executable,
31
+ "-m",
32
+ "uvicorn",
33
+ "bujang.cli.serve.app:create_app",
34
+ "--factory",
35
+ "--reload",
36
+ "--reload-dir",
37
+ str(PACKAGE_DIR),
38
+ "--host",
39
+ host,
40
+ "--port",
41
+ str(port),
42
+ ]
43
+
44
+
45
+ def ui_command(npm, host, ui_port):
46
+ return [npm, "run", "dev", "--", "--host", host, "--port", str(ui_port), "--strictPort"]
47
+
48
+
49
+ def child_env(config_paths, plugins, host, port, ui_port=None, mcp=True):
50
+ env = dict(os.environ)
51
+ if config_paths:
52
+ paths = [os.path.abspath(p) for p in config_paths]
53
+ if env.get("BUJANG_CONFIG"):
54
+ paths = env["BUJANG_CONFIG"].split(os.pathsep) + paths
55
+ env["BUJANG_CONFIG"] = os.pathsep.join(paths)
56
+ if plugins is not None:
57
+ env["BUJANG_PLUGINS"] = plugins
58
+ env["BUJANG_API"] = f"http://{host}:{port}"
59
+ # the /mcp endpoint of the API: links given to the agent open the Vite UI
60
+ env["BUJANG_SERVE_MCP"] = "1" if mcp else "0"
61
+ env["BUJANG_HOST"] = host
62
+ env["BUJANG_URL"] = f"http://{host}:{port}"
63
+ if ui_port is not None:
64
+ env["BUJANG_UI_URL"] = f"http://{host}:{ui_port}"
65
+ env["PYTHONUNBUFFERED"] = "1"
66
+ return env
67
+
68
+
69
+ def _stop(procs, timeout=10):
70
+ for proc in procs:
71
+ if proc.poll() is None:
72
+ try:
73
+ proc.send_signal(signal.SIGINT)
74
+ except OSError:
75
+ pass
76
+ deadline = time.time() + timeout
77
+ for proc in procs:
78
+ try:
79
+ proc.wait(max(0.1, deadline - time.time()))
80
+ except subprocess.TimeoutExpired:
81
+ proc.kill()
82
+ proc.wait()
83
+
84
+
85
+ def run_dev(
86
+ host="127.0.0.1", port=8000, ui_port=5173, config_paths=(), plugins=None, ui_dir=UI_DIR, out=None, mcp=True
87
+ ):
88
+ """Run both children until Ctrl-C or one of them exits; returns the exit code"""
89
+ out = out or sys.stdout
90
+ ui_dir = Path(ui_dir)
91
+ if not (ui_dir / "package.json").is_file():
92
+ print(
93
+ f"bujang dev needs a source checkout of bujang: no UI found at {ui_dir}.\n"
94
+ "Clone the repository and install it in editable mode, or use `bujang serve`.",
95
+ file=sys.stderr,
96
+ )
97
+ return 2
98
+
99
+ npm = shutil.which("npm")
100
+ if npm is None:
101
+ print("bujang dev needs npm (Node.js) to run the UI dev server", file=sys.stderr)
102
+ return 2
103
+
104
+ env = child_env(config_paths, plugins, host, port, ui_port, mcp)
105
+
106
+ if not (ui_dir / "node_modules").is_dir():
107
+ print("[ui] node_modules missing, running npm install", file=out)
108
+ result = subprocess.run([npm, "install"], cwd=ui_dir, env=env)
109
+ if result.returncode != 0:
110
+ print("[ui] npm install failed", file=sys.stderr)
111
+ return result.returncode or 1
112
+
113
+ children = [
114
+ ("[api]", api_command(host, port), None),
115
+ ("[ui]", ui_command(npm, host, ui_port), ui_dir),
116
+ ]
117
+ procs = []
118
+ threads = []
119
+ try:
120
+ for prefix, cmd, cwd in children:
121
+ proc = subprocess.Popen(
122
+ cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1
123
+ )
124
+ procs.append(proc)
125
+ if proc.stdout is not None:
126
+ thread = threading.Thread(target=_pump, args=(proc.stdout, prefix, out), daemon=True)
127
+ thread.start()
128
+ threads.append(thread)
129
+
130
+ print(f"bujang dev: API on http://{host}:{port}, open the UI at http://{host}:{ui_port}", file=out)
131
+ if mcp:
132
+ print(f"bujang dev: MCP endpoint on http://{host}:{port}/mcp", file=out)
133
+ out.flush()
134
+
135
+ while True:
136
+ for (prefix, _, _), proc in zip(children, procs, strict=True):
137
+ code = proc.poll()
138
+ if code is not None:
139
+ print(f"{prefix} exited with code {code}, stopping", file=sys.stderr)
140
+ _stop(procs)
141
+ return code or 1
142
+ time.sleep(0.2)
143
+ except KeyboardInterrupt:
144
+ _stop(procs)
145
+ return 0
146
+ finally:
147
+ _stop(procs)
148
+ for thread in threads:
149
+ thread.join(timeout=1)
150
+
151
+
152
+ class Dev(Command):
153
+ """Development: the API with auto-reload and the UI dev server with hot reload."""
154
+
155
+ name: str = "dev"
156
+
157
+ @staticmethod
158
+ def arguments(subparsers):
159
+ parser = newparser(subparsers, Dev)
160
+ parser.add_argument("--host", type=str, default="127.0.0.1", help="interface to listen on (127.0.0.1)")
161
+ parser.add_argument("--port", type=int, default=8000, help="API port (8000)")
162
+ parser.add_argument("--ui-port", type=int, default=5173, help="UI dev server port (5173)")
163
+ parser.add_argument("--config", action="append", default=[], help="YAML file or config directory, repeatable")
164
+ parser.add_argument("--plugins", type=str, default=None, help="comma separated plugins to load (all)")
165
+ parser.add_argument("--no-mcp", action="store_true", help="do not serve the MCP endpoint at /mcp")
166
+
167
+ @staticmethod
168
+ def execute(args):
169
+ return run_dev(args.host, args.port, args.ui_port, args.config, args.plugins, mcp=not args.no_mcp)
170
+
171
+
172
+ COMMANDS = [Dev]
@@ -0,0 +1,49 @@
1
+ """`bujang serve`: the default standalone server (FastAPI app + bundled UI)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from argklass.command import Command, newparser
6
+
7
+
8
+ class Serve(Command):
9
+ """Start the bujang server (API on /api/slurm and the UI) on this machine."""
10
+
11
+ name: str = "serve"
12
+
13
+ @staticmethod
14
+ def arguments(subparsers):
15
+ parser = newparser(subparsers, Serve)
16
+ parser.add_argument("--host", type=str, default="127.0.0.1", help="interface to listen on (127.0.0.1)")
17
+ parser.add_argument("--port", type=int, default=8000, help="port (8000)")
18
+ parser.add_argument(
19
+ "--config",
20
+ action="append",
21
+ default=[],
22
+ help="YAML file or config directory, repeatable (added to BUJANG_CONFIG)",
23
+ )
24
+ parser.add_argument("--plugins", type=str, default=None, help="comma separated plugins to load (all)")
25
+ parser.add_argument("--log-level", type=str, default="info")
26
+ parser.add_argument("--no-mcp", action="store_true", help="do not serve the MCP endpoint at /mcp")
27
+
28
+ @staticmethod
29
+ def execute(args):
30
+ import uvicorn
31
+
32
+ from ...config import BujangConfig
33
+ from .app import create_app
34
+
35
+ config = BujangConfig.from_env()
36
+ config.config_paths = [*config.config_paths, *args.config]
37
+ if args.plugins is not None:
38
+ config.plugins = [p.strip() for p in args.plugins.split(",") if p.strip()]
39
+
40
+ url = f"http://{'127.0.0.1' if args.host in ('0.0.0.0', '::') else args.host}:{args.port}"
41
+ app = create_app(config, mcp=not args.no_mcp, mcp_host=args.host, mcp_url=url)
42
+ print(f"[bujang] UI and API on {url}")
43
+ if app.state.mcp:
44
+ print(f"[bujang] MCP endpoint on {url}/mcp (claude mcp add --transport http bujang {url}/mcp)")
45
+ uvicorn.run(app, host=args.host, port=args.port, log_level=args.log_level)
46
+ return 0
47
+
48
+
49
+ COMMANDS = [Serve]
@@ -0,0 +1,105 @@
1
+ """FastAPI application factory of the standalone server: the bujang router plus the bundled UI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ from contextlib import AsyncExitStack, asynccontextmanager
8
+ from pathlib import Path
9
+
10
+ from fastapi import FastAPI, HTTPException
11
+ from fastapi.responses import FileResponse, HTMLResponse
12
+ from fastapi.staticfiles import StaticFiles
13
+
14
+ from ... import __version__
15
+ from ...config import BujangConfig
16
+ from ...fastapi import create_router
17
+ from ...server.service import Bujang
18
+
19
+ _BUNDLED_STATIC = Path(__file__).parent / "static"
20
+
21
+ log = logging.getLogger("bujang")
22
+
23
+
24
+ def _mcp_default() -> bool:
25
+ """BUJANG_SERVE_MCP=0 turns the /mcp endpoint off (the `--no-mcp` of serve and dev)"""
26
+ return os.environ.get("BUJANG_SERVE_MCP", "1") not in ("", "0", "false")
27
+
28
+
29
+ def create_app(
30
+ config: BujangConfig | None = None,
31
+ *,
32
+ bujang: Bujang | None = None,
33
+ start: bool = True,
34
+ mcp: bool | None = None,
35
+ mcp_host: str | None = None,
36
+ mcp_url: str | None = None,
37
+ ) -> FastAPI:
38
+ """Standalone app; `config` defaults to BujangConfig.from_env() with a sqlite database.
39
+
40
+ `mcp`: also serve the MCP endpoint at /mcp (default on, BUJANG_SERVE_MCP=0 to turn it off;
41
+ skipped with a warning when the mcp package is missing). `mcp_host`: the interface the
42
+ server listens on (BUJANG_HOST, 127.0.0.1); `mcp_url`: where the app is reachable, for the
43
+ links given to the agent (BUJANG_URL).
44
+ """
45
+ if bujang is None:
46
+ config = config or BujangConfig.from_env()
47
+ if config.database is None:
48
+ config.create_tables = True
49
+ bujang = Bujang(config)
50
+
51
+ mcp_manager = None
52
+ want_mcp = _mcp_default() if mcp is None else mcp
53
+
54
+ @asynccontextmanager
55
+ async def lifespan(app: FastAPI):
56
+ async with AsyncExitStack() as stack:
57
+ if mcp_manager is not None:
58
+ await stack.enter_async_context(mcp_manager.run())
59
+ if start:
60
+ bujang.start()
61
+ stack.callback(bujang.stop)
62
+ yield
63
+
64
+ app = FastAPI(title="bujang", version=__version__, lifespan=lifespan)
65
+ app.state.bujang = bujang
66
+ app.include_router(create_router(bujang))
67
+
68
+ if want_mcp:
69
+ try:
70
+ from ... import mcp_server
71
+ except ImportError:
72
+ log.warning("bujang: the mcp package is not installed, no /mcp endpoint (pip install 'mcp>=2')")
73
+ else:
74
+ mcp_manager = mcp_server.mount(
75
+ app,
76
+ host=mcp_host or os.environ.get("BUJANG_HOST", "127.0.0.1"),
77
+ url=mcp_url or os.environ.get("BUJANG_URL"),
78
+ )
79
+ app.state.mcp = mcp_manager is not None
80
+
81
+ # ── Bundled UI static files ───────────────────────────────
82
+ static_dir = _BUNDLED_STATIC
83
+ index_html = static_dir / "index.html"
84
+
85
+ if static_dir.is_dir() and index_html.is_file():
86
+ if (static_dir / "assets").is_dir():
87
+ app.mount("/assets", StaticFiles(directory=str(static_dir / "assets")), name="static-assets")
88
+
89
+ @app.get("/favicon.ico", include_in_schema=False)
90
+ async def favicon():
91
+ path = static_dir / "favicon.ico"
92
+ if path.is_file():
93
+ return FileResponse(str(path))
94
+ raise HTTPException(status_code=404)
95
+
96
+ @app.get("/{full_path:path}", include_in_schema=False)
97
+ async def serve_spa(full_path: str):
98
+ if full_path.startswith(("api/",)):
99
+ raise HTTPException(status_code=404)
100
+ requested = (static_dir / full_path).resolve()
101
+ if full_path and requested.is_file() and static_dir.resolve() in requested.parents:
102
+ return FileResponse(str(requested))
103
+ return HTMLResponse(index_html.read_text())
104
+
105
+ return app