-
Notifications
You must be signed in to change notification settings - Fork 670
Expand file tree
/
Copy pathrun_utils.py
More file actions
689 lines (584 loc) · 25.6 KB
/
Copy pathrun_utils.py
File metadata and controls
689 lines (584 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
import json
import os
import re
import sys
import site
import subprocess
import shutil
import platform as platform_module
from pathlib import Path
_GITHUB_OWNER_PATTERN = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?")
_GITHUB_REPOSITORY_NAME_PATTERN = re.compile(r"[A-Za-z0-9._-]{1,100}")
def _openswarm_state_root() -> Path:
override = os.getenv("OPENSWARM_STATE_ROOT", "").strip()
if override:
return Path(override).expanduser().resolve()
if sys.platform == "win32":
return Path(os.getenv("APPDATA") or (Path.home() / "AppData" / "Roaming")) / "OpenSwarm"
return Path.home() / ".openswarm"
def _load_openswarm_dotenv(*, override: bool = False) -> bool:
from dotenv import load_dotenv
return bool(load_dotenv(dotenv_path=_openswarm_state_root() / ".env", override=override))
def _product_root_candidates() -> list[Path]:
roots = (Path(__file__).resolve().parent, Path(sys.prefix), Path(site.USER_BASE))
return list(dict.fromkeys(root.resolve() for root in roots))
def _openswarm_product_roots() -> list[Path]:
return [root for root in _product_root_candidates() if (root / "package.json").exists() and any((root / name).exists() for name in ("openswarm.config.mjs", "openswarm.product-env.json"))]
def _product_env_from_config() -> dict[str, str]:
config = config_package = fallback = fallback_package = None
for root in _product_root_candidates():
candidate_config = root / "openswarm.config.mjs"
candidate_fallback = root / "openswarm.product-env.json"
candidate_package = root / "package.json"
if not fallback and candidate_fallback.exists() and candidate_package.exists():
fallback = candidate_fallback
fallback_package = candidate_package
if candidate_config.exists() and candidate_package.exists():
config = candidate_config
config_package = candidate_package
break
node = shutil.which("node")
if node and config and config_package:
return _product_env_from_mjs(node, config)
if fallback and fallback_package:
return _product_env_from_json(fallback, fallback_package)
if not node and config and config_package:
raise RuntimeError("OpenSwarm product config requires Node.js or openswarm.product-env.json. Reinstall OpenSwarm through npm or npx.")
if not config and not fallback:
raise RuntimeError("OpenSwarm product config files are missing. Reinstall OpenSwarm through npm or npx.")
raise RuntimeError("OpenSwarm package metadata is missing. Reinstall OpenSwarm through npm or npx.")
def _product_env_from_mjs(node: str, config: Path) -> dict[str, str]:
script = (
"const {pathToFileURL}=require('url');"
"import(pathToFileURL(process.argv[1]).href).then((cfg)=>{"
"process.stdout.write(JSON.stringify(cfg.getProductEnv({stateRoot:process.argv[2]})));"
"}).catch((err)=>{console.error(err&&err.stack||err);process.exit(1);});"
)
result = subprocess.run(
[node, "-e", script, str(config), str(_openswarm_state_root())],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
timeout=15,
check=False,
)
if result.returncode != 0:
raise RuntimeError(f"OpenSwarm product config failed to load: {result.stderr.strip()}")
return {key: str(value) for key, value in json.loads(result.stdout).items()}
def _product_env_from_json(fallback: Path, package: Path) -> dict[str, str]:
try:
values = json.loads(fallback.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise RuntimeError(f"OpenSwarm product config fallback failed to load: {exc}") from exc
try:
package_values = json.loads(package.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise RuntimeError(f"OpenSwarm package metadata failed to load: {exc}") from exc
if not isinstance(values, dict):
raise RuntimeError("OpenSwarm product config fallback is invalid. Reinstall OpenSwarm through npm or npx.")
if not isinstance(package_values, dict) or not package_values.get("version"):
raise RuntimeError("OpenSwarm package metadata is invalid. Reinstall OpenSwarm through npm or npx.")
env = {key: str(value) for key, value in values.items()}
marketplace_env = _marketplace_env_from_json(fallback.parent, Path.cwd())
if marketplace_env:
for key in (
"AGENTSWARM_MARKETPLACE_SWARM_ID",
"AGENTSWARM_MARKETPLACE_PARENT_SWARM_ID",
"AGENTSWARM_MARKETPLACE_SWARM_ORIGIN",
):
env.pop(key, None)
env.update(marketplace_env)
env["AGENTSWARM_PRODUCT_STATE_ROOT"] = str(_openswarm_state_root())
env["AGENTSWARM_PRODUCT_VERSION"] = str(package_values["version"])
return env
def _marketplace_env_from_json(root: Path, project: Path | None = None) -> dict[str, str]:
paths = []
if project:
paths.append(project / "openswarm.marketplace.json")
paths.append(root / "openswarm.marketplace.json")
path = next((item for item in dict.fromkeys(paths) if item.exists()), None)
if path is None:
return {}
try:
values = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise RuntimeError(f"OpenSwarm marketplace metadata failed to load: {exc}") from exc
if not isinstance(values, dict):
raise RuntimeError("OpenSwarm marketplace metadata must be a JSON object.")
return _marketplace_env_from_values(values)
def _marketplace_env_from_values(values: dict[str, object]) -> dict[str, str]:
swarm_id = _marketplace_repo(values, "swarmId")
parent_swarm_id = _marketplace_repo(values, "parentSwarmId", required=False)
swarm_origin = _metadata_string(values, "swarmOrigin")
if swarm_origin not in {"original", "fork", "unknown"}:
raise RuntimeError("OpenSwarm marketplace metadata swarmOrigin must be original, fork, or unknown.")
if swarm_origin == "fork" and parent_swarm_id is None:
raise RuntimeError("OpenSwarm marketplace metadata parentSwarmId is required for fork swarms.")
env = {
"AGENTSWARM_MARKETPLACE_SWARM_ID": swarm_id,
"AGENTSWARM_MARKETPLACE_SWARM_ORIGIN": swarm_origin,
}
if parent_swarm_id:
env["AGENTSWARM_MARKETPLACE_PARENT_SWARM_ID"] = parent_swarm_id
else:
env.pop("AGENTSWARM_MARKETPLACE_PARENT_SWARM_ID", None)
return env
def _metadata_string(values: dict[str, object], key: str, *, required: bool = True) -> str | None:
value = values.get(key)
if (value is None or value == "") and not required:
return None
if not isinstance(value, str) or not value.strip():
raise RuntimeError(f"OpenSwarm marketplace metadata {key} must be a non-empty string.")
return value.strip()
def _marketplace_repo(values: dict[str, object], key: str, *, required: bool = True) -> str | None:
repo = _metadata_string(values, key, required=required)
if repo is None:
return None
parts = repo.split("/")
if len(parts) != 2:
raise RuntimeError(f"OpenSwarm marketplace metadata {key} must be a GitHub owner/repo.")
owner, name = parts
if name.lower().endswith(".git"):
raise RuntimeError(f"OpenSwarm marketplace metadata {key} must be a GitHub owner/repo.")
if not _GITHUB_OWNER_PATTERN.fullmatch(owner) or "--" in owner or not _GITHUB_REPOSITORY_NAME_PATTERN.fullmatch(name):
raise RuntimeError(f"OpenSwarm marketplace metadata {key} must be a GitHub owner/repo.")
return repo
def _disables_telemetry(value: str | None) -> bool:
return value is not None and value.strip().lower() in {"0", "false", "off", "no"}
def _configure_product_env() -> None:
product_env = _product_env_from_config()
for key, value in product_env.items():
if key in {
"AGENTSWARM_PRODUCT_STATE_ROOT",
"AGENTSWARM_PRODUCT_VERSION",
"AGENTSWARM_MARKETPLACE_SWARM_ID",
"AGENTSWARM_MARKETPLACE_PARENT_SWARM_ID",
"AGENTSWARM_MARKETPLACE_SWARM_ORIGIN",
}:
os.environ[key] = value
else:
os.environ.setdefault(key, value)
if "AGENTSWARM_MARKETPLACE_PARENT_SWARM_ID" not in product_env:
os.environ.pop("AGENTSWARM_MARKETPLACE_PARENT_SWARM_ID", None)
if _disables_telemetry(os.environ.get("ENABLE_TELEMETRY")):
os.environ["OPEN_SWARM_TELEMETRY"] = "0"
os.environ["AGENTSWARM_TELEMETRY"] = "0"
def _openswarm_package_names(platform: str, arch: str, *, musl: bool, baseline: bool) -> list[str]:
base = f"@vrsen/openswarm-cli-{platform}-{arch}"
if platform == "linux":
if arch == "x64":
if musl:
if baseline:
return [f"{base}-baseline-musl", f"{base}-musl", f"{base}-baseline", base]
return [f"{base}-musl", f"{base}-baseline-musl", base, f"{base}-baseline"]
if baseline:
return [f"{base}-baseline", base, f"{base}-baseline-musl", f"{base}-musl"]
return [base, f"{base}-baseline", f"{base}-musl", f"{base}-baseline-musl"]
if musl:
return [f"{base}-musl", base]
return [base, f"{base}-musl"]
if arch == "x64":
if baseline:
return [f"{base}-baseline", base]
return [base, f"{base}-baseline"]
return [base]
def _openswarm_platform() -> str:
if sys.platform == "win32":
return "windows"
if sys.platform == "darwin":
return "darwin"
return "linux"
def _openswarm_arch() -> str:
machine = platform_module.machine().lower()
if machine in {"arm64", "aarch64"}:
return "arm64"
return "x64"
def _supports_avx2(platform: str, arch: str) -> bool:
if arch != "x64":
return False
if platform == "linux":
try:
return " avx2 " in f" {Path('/proc/cpuinfo').read_text(encoding='utf-8').lower()} "
except OSError:
return False
if platform == "darwin":
try:
result = subprocess.run(
["sysctl", "-n", "hw.optional.avx2_0"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
timeout=1.5,
check=False,
)
except OSError:
return False
return result.returncode == 0 and result.stdout.strip() == "1"
if platform == "windows":
cmd = (
'(Add-Type -MemberDefinition "[DllImport(""kernel32.dll"")] public static extern bool '
'IsProcessorFeaturePresent(int ProcessorFeature);" -Name Kernel32 -Namespace Win32 '
"-PassThru)::IsProcessorFeaturePresent(40)"
)
for exe in ("powershell.exe", "pwsh.exe", "pwsh", "powershell"):
try:
result = subprocess.run(
[exe, "-NoProfile", "-NonInteractive", "-Command", cmd],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
timeout=3,
check=False,
)
except OSError:
continue
if result.returncode != 0:
continue
value = result.stdout.strip().lower()
if value in {"true", "1"}:
return True
if value in {"false", "0"}:
return False
return False
def _is_musl() -> bool:
if sys.platform != "linux":
return False
if Path("/etc/alpine-release").exists():
return True
try:
result = subprocess.run(
["ldd", "--version"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
timeout=1.5,
check=False,
)
except OSError:
return False
return "musl" in f"{result.stdout}{result.stderr}".lower()
def _openswarm_platform_packages() -> list[tuple[str, str]]:
platform = _openswarm_platform()
arch = _openswarm_arch()
baseline = arch == "x64" and not _supports_avx2(platform, arch)
binary = "agentswarm.exe" if platform == "windows" else "agentswarm"
names = _openswarm_package_names(platform, arch, musl=_is_musl(), baseline=baseline)
return [(name, binary) for name in names]
def _node_module_starts(repo: Path | None) -> list[Path]:
roots = ([] if repo is None else [repo]) + _openswarm_product_roots()
roots.append(Path(__file__).resolve().parent)
return list(dict.fromkeys(root.resolve() for root in roots))
def _resolve_openswarm_tui_binary(repo: Path | None = None) -> Path | None:
for name, binary in _openswarm_platform_packages():
scope, package = name.split("/", 1)
for start in _node_module_starts(repo):
current = start
while True:
candidate = current / "node_modules" / scope / package / "bin" / binary
if candidate.is_file():
return candidate
parent = current.parent
if parent == current:
break
current = parent
return None
def _preload_agentswarm_bin(repo: Path | None = None) -> None:
# Bootstrap may install python-dotenv, so preserve this one override with stdlib.
if "AGENTSWARM_BIN" in os.environ:
return
roots = [_openswarm_state_root()]
seen: set[Path] = set()
for root in roots:
if root is None:
continue
path = root.resolve() / ".env"
if path in seen:
continue
seen.add(path)
try:
lines = path.read_text(encoding="utf-8").splitlines()
except OSError:
continue
for line in lines:
value = line.strip()
if not value or value.startswith("#"):
continue
if value.startswith("export "):
value = value.removeprefix("export ").lstrip()
key, sep, raw = value.partition("=")
if sep != "=" or key.strip() != "AGENTSWARM_BIN":
continue
raw = raw.strip()
if raw[:1] in {"'", '"'}:
quote = raw[0]
end = raw.find(quote, 1)
raw = raw[1:end] if end != -1 else raw[1:]
else:
raw = raw.split(" #", 1)[0].strip()
os.environ["AGENTSWARM_BIN"] = raw
return
binary = _resolve_openswarm_tui_binary(repo)
if binary:
os.environ["AGENTSWARM_BIN"] = str(binary)
_REQUIRED_SLIDES_NODE_PACKAGES = (
"dom-to-pptx",
"playwright",
"pptxgenjs",
"react",
"react-dom",
"react-icons",
"sharp",
)
def _warn_slides_setup(message: str) -> None:
print(
f"Warning: {message}\n"
" OpenSwarm will continue, but Slides Agent export features may be unavailable.\n"
)
def _run_optional_node_command(
cmd: list[str],
repo: Path,
label: str,
env: dict[str, str] | None = None,
) -> bool:
try:
result = subprocess.run(cmd, cwd=str(repo), env=env)
except Exception as exc:
_warn_slides_setup(f"{label} failed: {exc}")
return False
if result.returncode != 0:
_warn_slides_setup(f"{label} exited with code {result.returncode}")
return False
return True
def _ensure_node_playwright_browsers(repo: Path) -> bool:
"""Install Node Playwright browsers where the HTML-to-PPTX runner looks for them."""
npx = shutil.which("npx")
if not npx:
_warn_slides_setup(
"npm is available but npx was not found; cannot install Node Playwright browsers"
)
return False
env = os.environ.copy()
env["PLAYWRIGHT_BROWSERS_PATH"] = str(repo / ".playwright-browsers")
return _run_optional_node_command(
[npx, "-y", "playwright", "install", "chromium", "chromium-headless-shell"],
repo,
"Node Playwright browser install",
env=env,
)
def _ensure_node_dependencies(repo: Path, npm: str) -> bool:
_node_modules = repo / "node_modules"
_pkg_lock = repo / "package-lock.json"
_npm_marker = _node_modules / ".package-lock.json"
_need_npm = (
not _node_modules.exists()
or not _npm_marker.exists()
or (_pkg_lock.exists() and _pkg_lock.stat().st_mtime > _npm_marker.stat().st_mtime)
or any(not (_node_modules / name).exists() for name in _REQUIRED_SLIDES_NODE_PACKAGES)
)
_npm_ok = True
if _need_npm:
print("Installing Node.js dependencies, please wait…\n")
_npm_ok = _run_optional_node_command(
[npm, "install", "--legacy-peer-deps"],
repo,
"Node.js dependency install",
)
if _npm_ok:
print("\nDone.\n")
_browsers_ok = _ensure_node_playwright_browsers(repo)
return _npm_ok and _browsers_ok
def _uv_env() -> dict[str, str]:
env = os.environ.copy()
env.setdefault("UV_LINK_MODE", "copy")
env.setdefault("PYTHONUTF8", "1")
env.setdefault("PYTHONIOENCODING", "utf-8")
return env
# ── Bootstrap: create venv + install deps automatically on first run ─────────
# Only stdlib imports above. _bootstrap() is called explicitly — either from
# swarm.py (via `from run_utils import _bootstrap; _bootstrap()`) or from the
# __main__ guard below — never at module level, so `from run_utils import _bootstrap`
# is safe to call from outside the venv.
def _bootstrap() -> None:
_module = Path(__file__).resolve().parent
_repo = next(iter(_openswarm_product_roots()), _module)
# Ensure deps are present.
try:
import dotenv # noqa: F401
import rich # noqa: F401
import questionary # noqa: F401
import agency_swarm # noqa: F401
except ImportError:
print("Installing dependencies, please wait…\n")
if not shutil.which("uv"):
subprocess.check_call([sys.executable, "-m", "pip", "install", "uv"])
uv_cmd = ["uv", "pip", "install", "--system", "--python", sys.executable, str(_module)]
if sys.platform != "win32":
uv_cmd.append("--break-system-packages")
subprocess.check_call(uv_cmd, env=_uv_env())
print("\nDone.\n")
# Ensure the Playwright browser binary for the installed playwright version
# is present. playwright install is idempotent — it exits quickly if the
# right revision is already downloaded.
try:
subprocess.check_call(
[sys.executable, "-m", "playwright", "install", "chromium"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except Exception:
pass
# Install LibreOffice and Poppler if missing (used by Slides Agent).
# Auto-installs when a known package manager is available; silently skips otherwise.
_soffice = "soffice.com" if sys.platform == "win32" else "soffice"
if not shutil.which(_soffice):
if sys.platform == "darwin" and shutil.which("brew"):
print("Installing LibreOffice (required for Slides Agent), please wait…\n")
subprocess.check_call(["brew", "install", "--cask", "libreoffice"])
print("\nDone.\n")
elif sys.platform.startswith("linux") and shutil.which("apt-get"):
print("Installing LibreOffice (required for Slides Agent), please wait…\n")
subprocess.check_call(["sudo", "apt-get", "install", "-y", "libreoffice-impress"])
print("\nDone.\n")
elif sys.platform == "win32" and shutil.which("winget"):
print("Installing LibreOffice (required for Slides Agent), please wait…\n")
subprocess.check_call(["winget", "install", "--id", "TheDocumentFoundation.LibreOffice", "-e", "--silent"])
print("\nDone.\n")
else:
print(
"Warning: LibreOffice not found — Slides Agent thumbnail and export features "
"will be unavailable.\n"
" Install it from: https://www.libreoffice.org/download/download-libreoffice/\n"
)
if not shutil.which("pdftoppm"):
if sys.platform == "darwin" and shutil.which("brew"):
print("Installing Poppler (required for Slides Agent), please wait…\n")
subprocess.check_call(["brew", "install", "poppler"])
print("\nDone.\n")
elif sys.platform.startswith("linux") and shutil.which("apt-get"):
print("Installing Poppler (required for Slides Agent), please wait…\n")
subprocess.check_call(["sudo", "apt-get", "install", "-y", "poppler-utils"])
print("\nDone.\n")
elif sys.platform == "win32" and shutil.which("winget"):
print("Installing Poppler (required for Slides Agent), please wait…\n")
subprocess.check_call(["winget", "install", "--id", "oschwartz10612.Poppler", "-e", "--silent"])
print("\nDone.\n")
else:
print(
"Warning: Poppler (pdftoppm) not found — Slides Agent thumbnail and export "
"features will be unavailable.\n"
" Install it from: https://poppler.freedesktop.org\n"
)
# Install Node.js dependencies if node_modules is missing, incomplete, or outdated.
_npm = shutil.which("npm")
if _npm and (_repo / "package.json").exists():
_ensure_node_dependencies(_repo, _npm)
elif (_repo / "package.json").exists():
_warn_slides_setup(
"npm was not found; cannot install Slides Agent Node.js dependencies"
)
_preload_agentswarm_bin(_repo)
# ─────────────────────────────────────────────────────────────────────────────
_OPTIONAL_INTEGRATIONS = [
("Composio (10,000+ external integrations)", ["COMPOSIO_API_KEY", "COMPOSIO_USER_ID"]),
("Anthropic / Claude models", ["ANTHROPIC_API_KEY"]),
("Search", ["SEARCH_API_KEY"]),
("Fal.ai (video & audio generation)", ["FAL_KEY"]),
("Google AI / Gemini", ["GOOGLE_API_KEY"]),
("Pexels (stock images)", ["PEXELS_API_KEY"]),
("Pixabay (stock images)", ["PIXABAY_API_KEY"]),
("Unsplash (stock images)", ["UNSPLASH_ACCESS_KEY"]),
]
def build_integration_summary() -> str:
lines = ["Optional integrations:"]
for name, keys in _OPTIONAL_INTEGRATIONS:
active = [k for k in keys if os.getenv(k)]
if active:
lines.append(f" ✓ {name}")
else:
lines.append(f" ✗ {name} (missing: {', '.join(keys)})")
return "\n".join(lines)
def _configure_demo_console() -> None:
"""
Terminal demo runs can stream stdout/stderr into a UI that expects structured output.
Some third-party libs emit warnings that can corrupt that stream, so we suppress the
known noisy ones here and apply the recommended Windows event-loop policy for pyzmq.
"""
import warnings
# By default, silence *all* console output for demo runs.
# Opt out by setting OPENSWARM_DEMO_SILENCE_CONSOLE=0 / false / off.
silence_env = os.getenv("OPENSWARM_DEMO_SILENCE_CONSOLE", "").strip().lower()
silence_console = silence_env not in {"0", "false", "no", "off"}
if silence_console:
try:
import logging
devnull = open(os.devnull, "w", encoding="utf-8") # noqa: SIM115
sys.stdout = devnull # type: ignore[assignment]
sys.stderr = devnull # type: ignore[assignment]
logging.disable(logging.CRITICAL)
except Exception:
pass
return
# Keep this opt-in so developers can still see warnings when needed.
if os.getenv("OPENSWARM_DEMO_SHOW_WARNINGS", "").strip().lower() in {"1", "true", "yes", "on"}:
return
# pyzmq RuntimeWarning on Windows ProactorEventLoop (common with Python 3.8+ / 3.12)
warnings.filterwarnings(
"ignore",
message=r".*Proactor event loop does not implement add_reader.*",
category=RuntimeWarning,
)
# Pydantic v2 serializer warnings can be very noisy for streamed/typed objects.
warnings.filterwarnings(
"ignore",
message=r"^Pydantic serializer warnings:.*",
category=UserWarning,
)
# Prefer preventing the pyzmq warning entirely on Windows.
if os.name == "nt":
try:
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
except Exception:
pass
def main() -> None:
_preload_agentswarm_bin()
_bootstrap()
_load_openswarm_dotenv()
os.environ.setdefault("PYTHONUTF8", "1")
os.environ.setdefault("PYTHONIOENCODING", "utf-8")
_configure_product_env()
# Disable OpenAI Agents SDK tracing for terminal demo runs.
try:
from agents import set_tracing_disabled
set_tracing_disabled(True)
except Exception:
pass
from swarm import create_agency
import logging
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
logging.disable(logging.NOTSET)
print("\nStarting OpenSwarm… this may take a few seconds.")
_configure_demo_console()
# Suppress OS-level stderr (fd 2) to prevent GLib/GIO UWP-app
# warnings from appearing in the terminal during startup and TUI.
_saved_stderr_fd = None
try:
_saved_stderr_fd = os.dup(2)
_dn = os.open(os.devnull, os.O_WRONLY)
os.dup2(_dn, 2)
os.close(_dn)
except OSError:
pass
print(build_integration_summary())
print()
agency = create_agency()
agency.tui(show_reasoning=True, reload=False)
if _saved_stderr_fd is not None:
try:
os.dup2(_saved_stderr_fd, 2)
os.close(_saved_stderr_fd)
except OSError:
pass
if __name__ == "__main__":
main()