@magpiecloud/mags 1.8.16 → 1.8.17

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 (44) hide show
  1. package/API.md +388 -0
  2. package/Mags-API.postman_collection.json +374 -0
  3. package/QUICKSTART.md +295 -0
  4. package/README.md +378 -95
  5. package/bin/mags.js +23 -2
  6. package/deploy-page.sh +171 -0
  7. package/index.js +0 -2
  8. package/mags +0 -0
  9. package/mags.sh +270 -0
  10. package/nodejs/README.md +197 -0
  11. package/nodejs/bin/mags.js +1882 -0
  12. package/nodejs/index.js +603 -0
  13. package/nodejs/package.json +45 -0
  14. package/package.json +3 -18
  15. package/python/INTEGRATION.md +800 -0
  16. package/python/README.md +161 -0
  17. package/python/dist/magpie_mags-1.3.8-py3-none-any.whl +0 -0
  18. package/python/dist/magpie_mags-1.3.8.tar.gz +0 -0
  19. package/python/examples/demo.py +181 -0
  20. package/python/pyproject.toml +39 -0
  21. package/python/src/magpie_mags.egg-info/PKG-INFO +186 -0
  22. package/python/src/magpie_mags.egg-info/SOURCES.txt +9 -0
  23. package/python/src/magpie_mags.egg-info/dependency_links.txt +1 -0
  24. package/python/src/magpie_mags.egg-info/requires.txt +1 -0
  25. package/python/src/magpie_mags.egg-info/top_level.txt +1 -0
  26. package/python/src/mags/__init__.py +6 -0
  27. package/python/src/mags/client.py +527 -0
  28. package/python/test_sdk.py +78 -0
  29. package/skill.md +153 -0
  30. package/website/api.html +1095 -0
  31. package/website/claude-skill.html +481 -0
  32. package/website/cookbook/hn-marketing.html +410 -0
  33. package/website/cookbook/hn-marketing.sh +42 -0
  34. package/website/cookbook.html +282 -0
  35. package/website/docs.html +677 -0
  36. package/website/env.js +4 -0
  37. package/website/index.html +801 -0
  38. package/website/llms.txt +334 -0
  39. package/website/login.html +108 -0
  40. package/website/mags.md +210 -0
  41. package/website/script.js +453 -0
  42. package/website/styles.css +1075 -0
  43. package/website/tokens.html +169 -0
  44. package/website/usage.html +185 -0
@@ -0,0 +1,527 @@
1
+ """Mags client for interacting with the Magpie VM infrastructure API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import time
7
+ from pathlib import Path
8
+ from typing import Any, Dict, List, Optional
9
+
10
+ import requests
11
+
12
+
13
+ class MagsError(Exception):
14
+ """Raised when the Mags API returns an error."""
15
+
16
+ def __init__(self, message: str, status_code: int | None = None):
17
+ super().__init__(message)
18
+ self.status_code = status_code
19
+
20
+
21
+ class Mags:
22
+ """Client for the Mags API.
23
+
24
+ Args:
25
+ api_token: API token. Falls back to ``MAGS_API_TOKEN`` or ``MAGS_TOKEN`` env vars.
26
+ api_url: API base URL. Falls back to ``MAGS_API_URL`` env var or
27
+ ``https://api.magpiecloud.com``.
28
+ timeout: Default request timeout in seconds.
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ api_token: str | None = None,
34
+ api_url: str | None = None,
35
+ timeout: int = 30,
36
+ ):
37
+ self.api_url = (
38
+ api_url
39
+ or os.environ.get("MAGS_API_URL")
40
+ or "https://api.magpiecloud.com"
41
+ ).rstrip("/")
42
+
43
+ self.api_token = (
44
+ api_token
45
+ or os.environ.get("MAGS_API_TOKEN")
46
+ or os.environ.get("MAGS_TOKEN")
47
+ )
48
+ if not self.api_token:
49
+ raise MagsError(
50
+ "API token required. Set MAGS_API_TOKEN env var or pass api_token."
51
+ )
52
+
53
+ self.timeout = timeout
54
+ self._session = requests.Session()
55
+ self._session.headers.update(
56
+ {
57
+ "Authorization": f"Bearer {self.api_token}",
58
+ "Content-Type": "application/json",
59
+ }
60
+ )
61
+
62
+ # ── helpers ──────────────────────────────────────────────────────
63
+
64
+ def _request(
65
+ self,
66
+ method: str,
67
+ path: str,
68
+ json: Any = None,
69
+ params: dict | None = None,
70
+ timeout: int | None = None,
71
+ ) -> Any:
72
+ url = f"{self.api_url}/api/v1{path}"
73
+ resp = self._session.request(
74
+ method,
75
+ url,
76
+ json=json,
77
+ params=params,
78
+ timeout=timeout or self.timeout,
79
+ )
80
+ if resp.status_code >= 400:
81
+ try:
82
+ body = resp.json()
83
+ msg = body.get("error") or body.get("message") or resp.text
84
+ except Exception:
85
+ msg = resp.text
86
+ raise MagsError(msg, status_code=resp.status_code)
87
+ if not resp.content:
88
+ return {}
89
+ return resp.json()
90
+
91
+ # ── jobs ─────────────────────────────────────────────────────────
92
+
93
+ def run(
94
+ self,
95
+ script: str,
96
+ *,
97
+ name: str | None = None,
98
+ workspace_id: str | None = None,
99
+ base_workspace_id: str | None = None,
100
+ persistent: bool = False,
101
+ no_sleep: bool = False,
102
+ ephemeral: bool = False,
103
+ startup_command: str | None = None,
104
+ environment: Dict[str, str] | None = None,
105
+ file_ids: List[str] | None = None,
106
+ disk_gb: int | None = None,
107
+ no_sync: bool = False,
108
+ rootfs_type: str | None = None,
109
+ ) -> dict:
110
+ """Submit a job for execution.
111
+
112
+ Args:
113
+ script: Shell script to execute inside the VM.
114
+ name: Optional job name.
115
+ workspace_id: Persistent workspace name (synced to S3).
116
+ base_workspace_id: Read-only base workspace to mount.
117
+ persistent: Keep VM alive after script finishes.
118
+ no_sleep: Never auto-sleep this VM (requires persistent=True).
119
+ The VM stays running 24/7 and auto-recovers if its host goes down.
120
+ ephemeral: No S3 sync (faster, truly ephemeral).
121
+ startup_command: Command to run when VM wakes from sleep.
122
+ environment: Key-value env vars injected into the VM.
123
+ file_ids: File IDs to download into VM before script runs.
124
+ disk_gb: Custom disk size in GB (default 2GB).
125
+ no_sync: Skip S3 sync, use local disk only.
126
+ rootfs_type: VM rootfs type: ``"standard"``, ``"claude"``, or ``"pi"``.
127
+
128
+ Returns ``{"request_id": ..., "status": "accepted"}``.
129
+ """
130
+ if ephemeral and workspace_id:
131
+ raise MagsError("Cannot use ephemeral with workspace_id")
132
+ if ephemeral and persistent:
133
+ raise MagsError("Cannot use ephemeral with persistent")
134
+ if no_sleep and not persistent:
135
+ raise MagsError("no_sleep requires persistent=True")
136
+
137
+ payload = {
138
+ "script": script,
139
+ "type": "inline",
140
+ "persistent": persistent,
141
+ }
142
+ if no_sleep:
143
+ payload["no_sleep"] = True
144
+ if no_sync:
145
+ payload["no_sync"] = True
146
+ if name:
147
+ payload["name"] = name
148
+ if not ephemeral and workspace_id:
149
+ payload["workspace_id"] = workspace_id
150
+ if base_workspace_id:
151
+ payload["base_workspace_id"] = base_workspace_id
152
+ if startup_command:
153
+ payload["startup_command"] = startup_command
154
+ if environment:
155
+ payload["environment"] = environment
156
+ if file_ids:
157
+ payload["file_ids"] = file_ids
158
+ if disk_gb:
159
+ payload["disk_gb"] = disk_gb
160
+ if rootfs_type:
161
+ payload["rootfs_type"] = rootfs_type
162
+
163
+ return self._request("POST", "/mags-jobs", json=payload)
164
+
165
+ def run_and_wait(
166
+ self,
167
+ script: str,
168
+ *,
169
+ timeout: float = 60.0,
170
+ poll_interval: float = 1.0,
171
+ **run_kwargs: Any,
172
+ ) -> dict:
173
+ """Submit a job and block until it completes or times out.
174
+
175
+ Returns a dict with ``request_id``, ``status``, ``exit_code``,
176
+ ``duration_ms``, and ``logs``.
177
+ """
178
+ result = self.run(script, **run_kwargs)
179
+ request_id = result["request_id"]
180
+
181
+ deadline = time.monotonic() + timeout
182
+ while time.monotonic() < deadline:
183
+ status = self.status(request_id)
184
+ if status["status"] in ("completed", "error"):
185
+ logs_resp = self.logs(request_id)
186
+ return {
187
+ "request_id": request_id,
188
+ "status": status["status"],
189
+ "exit_code": status.get("exit_code", 0),
190
+ "duration_ms": status.get("script_duration_ms", 0),
191
+ "logs": logs_resp.get("logs", []),
192
+ }
193
+ time.sleep(poll_interval)
194
+
195
+ raise MagsError(f"Job {request_id} timed out after {timeout}s")
196
+
197
+ def status(self, request_id: str) -> dict:
198
+ """Get the status of a job."""
199
+ return self._request("GET", f"/mags-jobs/{request_id}/status")
200
+
201
+ def logs(self, request_id: str) -> dict:
202
+ """Get logs for a job. Returns ``{"logs": [...]}`."""
203
+ return self._request("GET", f"/mags-jobs/{request_id}/logs")
204
+
205
+ def list_jobs(self, *, page: int = 1, page_size: int = 20) -> dict:
206
+ """List recent jobs. Returns ``{"jobs": [...], "total": N, ...}``."""
207
+ return self._request(
208
+ "GET", "/mags-jobs", params={"page": page, "page_size": page_size}
209
+ )
210
+
211
+ def update_job(
212
+ self,
213
+ request_id: str,
214
+ *,
215
+ startup_command: str | None = None,
216
+ no_sleep: bool | None = None,
217
+ ) -> dict:
218
+ """Update a job's settings.
219
+
220
+ Args:
221
+ request_id: The job/workspace ID to update.
222
+ startup_command: Command to run when VM wakes from sleep.
223
+ no_sleep: If True, VM never auto-sleeps. If False, re-enables auto-sleep.
224
+ """
225
+ payload: dict = {}
226
+ if startup_command is not None:
227
+ payload["startup_command"] = startup_command
228
+ if no_sleep is not None:
229
+ payload["no_sleep"] = no_sleep
230
+ return self._request("PATCH", f"/mags-jobs/{request_id}", json=payload)
231
+
232
+ def enable_access(self, request_id: str, *, port: int = 8080) -> dict:
233
+ """Enable external access (URL or SSH) for a persistent job's VM.
234
+
235
+ Use ``port=22`` for SSH access, or ``port=8080`` (default) for HTTP/URL access.
236
+ """
237
+ return self._request(
238
+ "POST", f"/mags-jobs/{request_id}/access", json={"port": port}
239
+ )
240
+
241
+ def stop(self, name_or_id: str) -> dict:
242
+ """Stop a running job.
243
+
244
+ Accepts a job ID, job name, or workspace ID.
245
+ """
246
+ request_id = self._resolve_job_id(name_or_id)
247
+ return self._request("POST", f"/mags-jobs/{request_id}/stop")
248
+
249
+ def resize(
250
+ self,
251
+ workspace: str,
252
+ disk_gb: int,
253
+ *,
254
+ timeout: float = 30.0,
255
+ poll_interval: float = 1.0,
256
+ ) -> dict:
257
+ """Resize a workspace's disk. Stops the existing VM, then creates a new one.
258
+
259
+ Workspace files are preserved in S3.
260
+ Returns ``{"request_id": ..., "status": "running"}``.
261
+ """
262
+ existing = self.find_job(workspace)
263
+ if existing and existing.get("status") == "running":
264
+ self._request("POST", f"/mags-jobs/{existing['request_id']}/sync")
265
+ self._request("POST", f"/mags-jobs/{existing['request_id']}/stop")
266
+ time.sleep(1)
267
+ elif existing and existing.get("status") == "sleeping":
268
+ self._request("POST", f"/mags-jobs/{existing['request_id']}/stop")
269
+ time.sleep(1)
270
+
271
+ return self.new(workspace, persistent=True, disk_gb=disk_gb,
272
+ timeout=timeout, poll_interval=poll_interval)
273
+
274
+ def new(
275
+ self,
276
+ name: str,
277
+ *,
278
+ persistent: bool = False,
279
+ base_workspace_id: str | None = None,
280
+ disk_gb: int | None = None,
281
+ timeout: float = 30.0,
282
+ poll_interval: float = 1.0,
283
+ ) -> dict:
284
+ """Create a new VM sandbox and wait until it's running.
285
+
286
+ By default, data lives on local disk only (no S3 sync).
287
+ Pass ``persistent=True`` to enable S3 data persistence.
288
+
289
+ Equivalent to ``mags new <name>`` or ``mags new <name> -p``.
290
+
291
+ Returns ``{"request_id": ..., "status": "running"}``.
292
+ """
293
+ result = self.run(
294
+ "sleep infinity",
295
+ workspace_id=name,
296
+ persistent=True,
297
+ no_sync=not persistent,
298
+ base_workspace_id=base_workspace_id,
299
+ disk_gb=disk_gb,
300
+ )
301
+ request_id = result["request_id"]
302
+
303
+ deadline = time.monotonic() + timeout
304
+ while time.monotonic() < deadline:
305
+ st = self.status(request_id)
306
+ if st["status"] == "running" and st.get("vm_id"):
307
+ return {"request_id": request_id, "status": "running"}
308
+ if st["status"] in ("completed", "error"):
309
+ raise MagsError(f"Job {request_id} ended unexpectedly: {st['status']}")
310
+ time.sleep(poll_interval)
311
+
312
+ raise MagsError(f"Job {request_id} did not start within {timeout}s")
313
+
314
+ def find_job(self, name_or_id: str) -> dict | None:
315
+ """Find a running or sleeping job by name, workspace ID, or job ID.
316
+
317
+ Uses the same resolution priority as the CLI:
318
+ running/sleeping exact name → workspace ID → any status exact name.
319
+ Returns the job dict or ``None``.
320
+ """
321
+ jobs = self.list_jobs(page_size=50).get("jobs", [])
322
+
323
+ # Priority 1: exact name match, running/sleeping
324
+ for j in jobs:
325
+ if j.get("name") == name_or_id and j.get("status") in ("running", "sleeping"):
326
+ return j
327
+
328
+ # Priority 2: workspace_id match, running/sleeping
329
+ for j in jobs:
330
+ if j.get("workspace_id") == name_or_id and j.get("status") in ("running", "sleeping"):
331
+ return j
332
+
333
+ # Priority 3: exact name match, any status
334
+ for j in jobs:
335
+ if j.get("name") == name_or_id:
336
+ return j
337
+
338
+ # Priority 4: workspace_id match, any status
339
+ for j in jobs:
340
+ if j.get("workspace_id") == name_or_id:
341
+ return j
342
+
343
+ return None
344
+
345
+ def url(self, name_or_id: str, *, port: int = 8080) -> dict:
346
+ """Enable public URL access for a job's VM.
347
+
348
+ Accepts a job ID, job name, or workspace ID.
349
+ Returns dict with ``url`` and access details.
350
+ """
351
+ request_id = self._resolve_job_id(name_or_id)
352
+ st = self.status(request_id)
353
+ resp = self.enable_access(request_id, port=port)
354
+ subdomain = st.get("subdomain") or resp.get("subdomain")
355
+ if subdomain:
356
+ resp["url"] = f"https://{subdomain}.apps.magpiecloud.com"
357
+ return resp
358
+
359
+ def exec(self, name_or_id: str, command: str, *, timeout: int = 30) -> dict:
360
+ """Execute a command on an existing running/sleeping sandbox.
361
+
362
+ Equivalent to ``mags exec <workspace> '<command>'``.
363
+
364
+ Returns ``{"exit_code": int, "output": str, "stderr": str}``.
365
+ """
366
+ job = self.find_job(name_or_id)
367
+ if not job:
368
+ raise MagsError(f"No running or sleeping VM found for '{name_or_id}'")
369
+ if job["status"] not in ("running", "sleeping"):
370
+ raise MagsError(
371
+ f"VM for '{name_or_id}' is {job['status']}, needs to be running or sleeping"
372
+ )
373
+
374
+ request_id = job.get("request_id") or job.get("id")
375
+ resp = self._request(
376
+ "POST",
377
+ f"/mags-jobs/{request_id}/exec",
378
+ json={"command": command, "timeout": timeout},
379
+ timeout=timeout + 10, # HTTP timeout > command timeout
380
+ )
381
+ return {
382
+ "exit_code": resp.get("exit_code", -1),
383
+ "output": resp.get("stdout", ""),
384
+ "stderr": resp.get("stderr", ""),
385
+ }
386
+
387
+ def usage(self, *, window_days: int = 30) -> dict:
388
+ """Get aggregated usage summary."""
389
+ return self._request(
390
+ "GET", "/mags-jobs/usage", params={"window_days": window_days}
391
+ )
392
+
393
+ # ── internal helpers ─────────────────────────────────────────────
394
+
395
+ def _resolve_job_id(self, name_or_id: str) -> str:
396
+ """Resolve a job name, workspace ID, or UUID to a request_id."""
397
+ # If it looks like a UUID, use directly
398
+ if len(name_or_id) >= 32 and "-" in name_or_id:
399
+ return name_or_id
400
+ job = self.find_job(name_or_id)
401
+ if not job:
402
+ raise MagsError(f"No job found for '{name_or_id}'")
403
+ return job.get("request_id") or job.get("id")
404
+
405
+ # ── file uploads ─────────────────────────────────────────────────
406
+
407
+ def upload_file(self, file_path: str) -> str:
408
+ """Upload a single file. Returns the file ID."""
409
+ p = Path(file_path)
410
+ if not p.exists():
411
+ raise MagsError(f"File not found: {file_path}")
412
+
413
+ url = f"{self.api_url}/api/v1/mags-files"
414
+ # Use a fresh request without the JSON content-type
415
+ resp = requests.post(
416
+ url,
417
+ files={"file": (p.name, p.read_bytes(), "application/octet-stream")},
418
+ headers={"Authorization": f"Bearer {self.api_token}"},
419
+ timeout=self.timeout,
420
+ )
421
+ if resp.status_code >= 400:
422
+ raise MagsError(resp.text, status_code=resp.status_code)
423
+ data = resp.json()
424
+ file_id = data.get("file_id")
425
+ if not file_id:
426
+ raise MagsError(f"Upload failed for {p.name}: {data}")
427
+ return file_id
428
+
429
+ def upload_files(self, file_paths: List[str]) -> List[str]:
430
+ """Upload multiple files. Returns a list of file IDs."""
431
+ return [self.upload_file(fp) for fp in file_paths]
432
+
433
+ # ── workspaces ────────────────────────────────────────────────────
434
+
435
+ def list_workspaces(self) -> dict:
436
+ """List all workspaces. Returns ``{"workspaces": [...], "total": N}``."""
437
+ return self._request("GET", "/mags-workspaces")
438
+
439
+ def delete_workspace(self, workspace_id: str) -> dict:
440
+ """Delete a workspace and all its stored data.
441
+
442
+ This permanently removes the workspace filesystem from S3.
443
+ Active jobs using the workspace must be stopped first.
444
+ """
445
+ return self._request("DELETE", f"/mags-workspaces/{workspace_id}")
446
+
447
+ def sync(self, request_id: str) -> dict:
448
+ """Sync a running job's workspace to S3 without stopping the VM.
449
+
450
+ Use this to persist workspace changes immediately, e.g. after
451
+ setting up a base image.
452
+ """
453
+ return self._request("POST", f"/mags-jobs/{request_id}/sync")
454
+
455
+ # ── cron jobs ────────────────────────────────────────────────────
456
+
457
+ def cron_create(
458
+ self,
459
+ *,
460
+ name: str,
461
+ cron_expression: str,
462
+ script: str,
463
+ workspace_id: str | None = None,
464
+ environment: Dict[str, str] | None = None,
465
+ persistent: bool = False,
466
+ ) -> dict:
467
+ """Create a scheduled cron job."""
468
+ payload = {
469
+ "name": name,
470
+ "cron_expression": cron_expression,
471
+ "script": script,
472
+ "persistent": persistent,
473
+ }
474
+ if workspace_id:
475
+ payload["workspace_id"] = workspace_id
476
+ if environment:
477
+ payload["environment"] = environment
478
+ return self._request("POST", "/mags-cron", json=payload)
479
+
480
+ def cron_list(self) -> dict:
481
+ """List all cron jobs."""
482
+ return self._request("GET", "/mags-cron")
483
+
484
+ def cron_get(self, cron_id: str) -> dict:
485
+ """Get a cron job by ID."""
486
+ return self._request("GET", f"/mags-cron/{cron_id}")
487
+
488
+ def cron_update(self, cron_id: str, **updates: Any) -> dict:
489
+ """Update a cron job. Pass fields as keyword arguments."""
490
+ return self._request("PATCH", f"/mags-cron/{cron_id}", json=updates)
491
+
492
+ def cron_delete(self, cron_id: str) -> dict:
493
+ """Delete a cron job."""
494
+ return self._request("DELETE", f"/mags-cron/{cron_id}")
495
+
496
+ # ── URL aliases ──────────────────────────────────────────────────
497
+
498
+ def url_alias_create(
499
+ self,
500
+ subdomain: str,
501
+ workspace_id: str,
502
+ domain: str = "apps.magpiecloud.com",
503
+ ) -> dict:
504
+ """Create a stable URL alias for a workspace.
505
+
506
+ The alias maps ``subdomain.<domain>`` to the active job in the workspace.
507
+ Use ``domain="app.lfg.run"`` for the LFG domain.
508
+
509
+ Returns ``{"id": ..., "subdomain": ..., "url": ...}``.
510
+ """
511
+ return self._request(
512
+ "POST",
513
+ "/mags-url-aliases",
514
+ json={
515
+ "subdomain": subdomain,
516
+ "workspace_id": workspace_id,
517
+ "domain": domain,
518
+ },
519
+ )
520
+
521
+ def url_alias_list(self) -> dict:
522
+ """List all URL aliases. Returns ``{"aliases": [...], "total": N}``."""
523
+ return self._request("GET", "/mags-url-aliases")
524
+
525
+ def url_alias_delete(self, subdomain: str) -> dict:
526
+ """Delete a URL alias by subdomain."""
527
+ return self._request("DELETE", f"/mags-url-aliases/{subdomain}")
@@ -0,0 +1,78 @@
1
+ """Test the Mags Python SDK: new, exec, url."""
2
+
3
+ import os
4
+ import sys
5
+ import time
6
+
7
+ os.environ["MAGS_API_TOKEN"] = "da214df72c164bda47970491fd839247a864c2599305ce90b38512d43ed034ea"
8
+
9
+ # Use local src/ instead of installed package
10
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
11
+
12
+ from mags import Mags
13
+
14
+ m = Mags()
15
+ WS = "sdk-test-" + str(int(time.time()))
16
+
17
+ print(f"=== Test 1: Create new VM ({WS}) ===")
18
+ result = m.new(WS)
19
+ print(f" request_id: {result['request_id']}")
20
+ print(f" status: {result['status']}")
21
+ assert result["status"] == "running"
22
+ print(" PASS\n")
23
+
24
+ print("=== Test 2: find_job ===")
25
+ job = m.find_job(WS)
26
+ print(f" found: workspace={job.get('workspace_id')} status={job.get('status')}")
27
+ assert job is not None
28
+ assert job["status"] == "running"
29
+ print(" PASS\n")
30
+
31
+ print("=== Test 3: exec - simple command ===")
32
+ try:
33
+ result = m.exec(WS, "echo HELLO_FROM_SDK && uname -a", timeout=15)
34
+ print(f" exit_code: {result['exit_code']}")
35
+ print(f" output: {result['output'].strip()}")
36
+ if result["stderr"]:
37
+ print(f" stderr: {result['stderr'].strip()}")
38
+ assert "HELLO_FROM_SDK" in result["output"]
39
+ print(" PASS\n")
40
+ except Exception as e:
41
+ print(f" FAIL: {e}\n")
42
+
43
+ print("=== Test 4: exec - create HTML file ===")
44
+ html = "<html><body><h1>Mags SDK Test</h1><p>Served from a microVM!</p></body></html>"
45
+ try:
46
+ result = m.exec(WS, f"echo '{html}' > /root/index.html", timeout=15)
47
+ print(f" exit_code: {result['exit_code']}")
48
+ result = m.exec(WS, "cat /root/index.html", timeout=15)
49
+ print(f" content: {result['output'].strip()[:80]}...")
50
+ print(" PASS\n")
51
+ except Exception as e:
52
+ print(f" FAIL: {e}\n")
53
+
54
+ print("=== Test 5: exec - start python HTTP server ===")
55
+ try:
56
+ result = m.exec(WS, "nohup python3 -m http.server 8080 --directory /root > /tmp/srv.log 2>&1 & echo PID=$!", timeout=15)
57
+ print(f" output: {result['output'].strip()}")
58
+ time.sleep(1)
59
+ # Verify it's running
60
+ result = m.exec(WS, "curl -s http://localhost:8080/index.html | head -1", timeout=15)
61
+ print(f" curl: {result['output'].strip()[:80]}")
62
+ print(" PASS\n")
63
+ except Exception as e:
64
+ print(f" FAIL: {e}\n")
65
+
66
+ print("=== Test 6: url - enable public URL ===")
67
+ try:
68
+ info = m.url(WS, port=8080)
69
+ print(f" success: {info.get('success')}")
70
+ print(f" url: {info.get('url', 'N/A')}")
71
+ if info.get("url"):
72
+ print(f"\n >>> Visit: {info['url']} <<<")
73
+ print(" PASS\n")
74
+ except Exception as e:
75
+ print(f" FAIL: {e}\n")
76
+
77
+ print("=== All tests complete ===")
78
+ print(f"Workspace: {WS}")