-
Notifications
You must be signed in to change notification settings - Fork 224
Expand file tree
/
Copy pathbuild.py
More file actions
executable file
·1111 lines (967 loc) · 37.4 KB
/
build.py
File metadata and controls
executable file
·1111 lines (967 loc) · 37.4 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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Single-entry build helper for agent-server images.
- Targets: binary | binary-minimal | source | source-minimal
- Multi-tagging via CUSTOM_TAGS (comma-separated)
- Versioned tags for custom tags: {SDK_VERSION}-{CUSTOM_TAG}
- Branch-scoped cache keys
- CI (push) vs local (load) behavior
- sdist-based builds: Uses `uv build` to create clean build contexts
- One entry: build(opts: BuildOptions)
- Automatically detects sdk_project_root (no manual arg)
- No local artifacts left behind (uses tempfile dirs only)
"""
import argparse
import hashlib
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import threading
import time
import tomllib
from contextlib import chdir
from pathlib import Path
from pydantic import BaseModel, Field, field_validator
from openhands.sdk.logger import IN_CI, get_logger, rolling_log_view
from openhands.sdk.workspace import PlatformType, TargetType
logger = get_logger(__name__)
VALID_TARGETS = {
"binary",
"binary-minimal",
"source",
"source-minimal",
"base-image-minimal",
"base-image",
"builder",
}
_BUILDKIT_STEP_RE = re.compile(r"^#(?P<step>\d+)\s+(?P<message>.+)$")
_BUILDKIT_DONE_RE = re.compile(r"^DONE\s+(?P<seconds>\d+(?:\.\d+)?)s$")
_BUILDKIT_INLINE_DONE_RE = re.compile(
r"^(?P<description>.+?)\s+(?P<seconds>\d+(?:\.\d+)?)s done$"
)
# --- helpers ---
def _default_sdk_project_root() -> Path:
"""
Resolve top-level OpenHands UV workspace root:
Order:
1) Walk up from CWD
2) Walk up from this file location
Reject anything in site/dist-packages (installed wheels).
"""
site_markers = ("site-packages", "dist-packages")
def _is_workspace_root(d: Path) -> bool:
"""Detect if d is the root of the Agent-SDK repo UV workspace."""
_EXPECTED = (
"openhands-sdk/pyproject.toml",
"openhands-tools/pyproject.toml",
"openhands-workspace/pyproject.toml",
"openhands-agent-server/pyproject.toml",
)
py = d / "pyproject.toml"
if not py.exists():
return False
try:
cfg = tomllib.loads(py.read_text(encoding="utf-8"))
except Exception:
cfg = {}
members = (
cfg.get("tool", {}).get("uv", {}).get("workspace", {}).get("members", [])
or []
)
# Accept either explicit UV members or structural presence of all subprojects
if members:
norm = {str(Path(m)) for m in members}
return {
"openhands-sdk",
"openhands-tools",
"openhands-workspace",
"openhands-agent-server",
}.issubset(norm)
return all((d / p).exists() for p in _EXPECTED)
def _climb(start: Path) -> Path | None:
cur = start.resolve()
if not cur.is_dir():
cur = cur.parent
while True:
if _is_workspace_root(cur):
return cur
if cur.parent == cur:
return None
cur = cur.parent
def validate(p: Path, src: str) -> Path:
if any(s in str(p) for s in site_markers):
raise RuntimeError(
f"{src}: points inside site-packages; need the source checkout."
)
root = _climb(p) or p
if not _is_workspace_root(root):
raise RuntimeError(
f"{src}: couldn't find the OpenHands UV workspace root "
f"starting at '{p}'.\n\n"
"Expected setup (repo root):\n"
" pyproject.toml # has [tool.uv.workspace] with members\n"
" openhands-sdk/pyproject.toml\n"
" openhands-tools/pyproject.toml\n"
" openhands-workspace/pyproject.toml\n"
" openhands-agent-server/pyproject.toml\n\n"
"Fix:\n"
" - Run from anywhere inside the repo."
)
return root
if root := _climb(Path.cwd()):
return validate(root, "CWD discovery")
try:
here = Path(__file__).resolve()
if root := _climb(here):
return validate(root, "__file__ discovery")
except NameError:
pass
# Final, user-facing guidance
raise RuntimeError(
"Could not resolve the OpenHands UV workspace root.\n\n"
"Expected repo layout:\n"
" pyproject.toml (with [tool.uv.workspace].members "
"including openhands/* subprojects)\n"
" openhands-sdk/pyproject.toml\n"
" openhands-tools/pyproject.toml\n"
" openhands-workspace/pyproject.toml\n"
" openhands-agent-server/pyproject.toml\n\n"
"Run this from inside the repo."
)
def _run(
cmd: list[str],
cwd: str | None = None,
) -> subprocess.CompletedProcess:
"""
Stream stdout and stderr concurrently into the rolling logger,
while capturing FULL stdout/stderr.
Returns CompletedProcess(stdout=<full>, stderr=<full>).
Raises CalledProcessError with both output and stderr on failure.
"""
logger.info(f"$ {' '.join(cmd)} (cwd={cwd})")
proc = subprocess.Popen(
cmd,
cwd=cwd,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE, # keep separate
bufsize=1, # line-buffered
)
assert proc.stdout is not None and proc.stderr is not None
out_lines: list[str] = []
err_lines: list[str] = []
def pump(stream, sink: list[str], log_fn, prefix: str) -> None:
for line in stream:
line = line.rstrip("\n")
sink.append(line)
log_fn(f"{prefix}{line}")
with rolling_log_view(
logger,
header="$ " + " ".join(cmd) + (f" (cwd={cwd})" if cwd else ""),
):
t_out = threading.Thread(
target=pump, args=(proc.stdout, out_lines, logger.info, "[stdout] ")
)
t_err = threading.Thread(
target=pump, args=(proc.stderr, err_lines, logger.warning, "[stderr] ")
)
t_out.start()
t_err.start()
t_out.join()
t_err.join()
rc = proc.wait()
stdout = ("\n".join(out_lines) + "\n") if out_lines else ""
stderr = ("\n".join(err_lines) + "\n") if err_lines else ""
result = subprocess.CompletedProcess(cmd, rc, stdout=stdout, stderr=stderr)
if rc != 0:
# Include full outputs on failure
raise subprocess.CalledProcessError(rc, cmd, output=stdout, stderr=stderr)
return result
def _sanitize_branch(ref: str) -> str:
ref = re.sub(r"^refs/heads/", "", ref or "unknown")
return re.sub(r"[^a-zA-Z0-9.-]+", "-", ref).lower()
def _truncate_ident(repo: str, tag: str, budget: int) -> str:
"""
Truncate repo+tag to fit budget, prioritizing tag preservation.
Strategy:
1. If both fit: return both
2. If tag fits but repo doesn't: truncate repo, keep full tag
3. If tag doesn't fit: truncate tag, discard repo
4. If no tag: truncate repo
"""
tag_suffix = f"_tag_{tag}" if tag else ""
full_ident = repo + tag_suffix
if len(full_ident) <= budget:
return full_ident
if not tag:
return repo[:budget]
if len(tag_suffix) <= budget:
repo_budget = budget - len(tag_suffix)
return repo[:repo_budget] + tag_suffix
return tag_suffix[:budget]
def _base_slug(image: str, max_len: int = 64) -> str:
"""
If the slug is too long, keep the most identifiable parts:
- repository name (last path segment)
- tag (if present)
Then append a short digest for uniqueness.
Format preserved with existing separators: '_s_' for '/', '_tag_' for ':'.
Example:
'ghcr.io_s_org_s/very-long-repo_tag_v1.2.3-extra'
-> 'very-long-repo_tag_v1.2.3-<digest>'
"""
base_slug = image.replace("/", "_s_").replace(":", "_tag_")
if len(base_slug) <= max_len:
return base_slug
digest = hashlib.sha256(base_slug.encode()).hexdigest()[:12]
suffix = f"-{digest}"
# Parse components from the slug form
if "_tag_" in base_slug:
left, tag = base_slug.rsplit("_tag_", 1) # Split on last : (rightmost tag)
else:
left, tag = base_slug, ""
parts = left.split("_s_") if left else []
repo = parts[-1] if parts else left # last path segment is the repo
# Fit within budget, reserving space for the digest suffix
visible_budget = max_len - len(suffix)
assert visible_budget > 0, (
f"max_len too small to fit digest suffix with length {len(suffix)}"
)
ident = _truncate_ident(repo, tag, visible_budget)
return ident + suffix
def _git_info() -> tuple[str, str]:
"""
Get git info (ref, sha) for the current working directory.
Priority order for SHA:
1. SDK_SHA - Explicit override (e.g., for submodule builds)
2. GITHUB_SHA - GitHub Actions environment
3. git rev-parse HEAD - Local development
Priority order for REF:
1. SDK_REF - Explicit override (e.g., for submodule builds)
2. GITHUB_REF - GitHub Actions environment
3. git symbolic-ref HEAD - Local development
"""
sdk_root = _default_sdk_project_root()
git_sha = os.environ.get("SDK_SHA") or os.environ.get("GITHUB_SHA")
if not git_sha:
try:
git_sha = _run(
["git", "rev-parse", "--verify", "HEAD"],
cwd=str(sdk_root),
).stdout.strip()
except subprocess.CalledProcessError:
git_sha = "unknown"
git_ref = os.environ.get("SDK_REF") or os.environ.get("GITHUB_REF")
if not git_ref:
try:
git_ref = _run(
["git", "symbolic-ref", "-q", "--short", "HEAD"],
cwd=str(sdk_root),
).stdout.strip()
except subprocess.CalledProcessError:
git_ref = "unknown"
return git_ref, git_sha
def _package_version() -> str:
"""
Get the semantic version from the openhands-sdk package.
This is used for versioned tags during releases.
"""
try:
from importlib.metadata import version
return version("openhands-sdk")
except Exception:
# If package is not installed, try reading from pyproject.toml
try:
sdk_root = _default_sdk_project_root()
pyproject_path = sdk_root / "openhands-sdk" / "pyproject.toml"
if pyproject_path.exists():
cfg = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))
return cfg.get("project", {}).get("version", "unknown")
except Exception:
pass
return "unknown"
_DEFAULT_GIT_REF, _DEFAULT_GIT_SHA = _git_info()
_DEFAULT_PACKAGE_VERSION = _package_version()
class BuildOptions(BaseModel):
# NOTE: Using Python 3.12 due to PyInstaller+libtmux compatibility issue
# with Python 3.13. See issue #1886 for details.
base_image: str = Field(default="nikolaik/python-nodejs:python3.12-nodejs22-slim")
custom_tags: str = Field(
default="", description="Comma-separated list of custom tags."
)
image: str = Field(default="ghcr.io/openhands/agent-server")
target: TargetType = Field(default="binary")
platforms: list[PlatformType] = Field(default=["linux/amd64"])
push: bool | None = Field(
default=None, description="None=auto (CI push, local load)"
)
arch: str | None = Field(
default=None,
description="Architecture suffix (e.g., 'amd64', 'arm64') to append to tags",
)
include_base_tag: bool = Field(
default=True,
description=(
"Whether to include the automatically generated base tag "
"based on git SHA and base image name in all_tags output."
),
)
include_versioned_tag: bool = Field(
default=False,
description=(
"Whether to include the versioned tag (e.g., v1.0.0_...) in all_tags "
"output. Should only be True for release builds."
),
)
git_sha: str = Field(
default=_DEFAULT_GIT_SHA,
description="Git commit SHA.We will need it to tag the built image.",
)
git_ref: str = Field(default=_DEFAULT_GIT_REF)
sdk_project_root: Path = Field(
default_factory=_default_sdk_project_root,
description="Path to OpenHands SDK root. Auto if None.",
)
prebuilt_sdist: Path | None = Field(
default=None,
description=(
"Path to a pre-built SDK sdist tarball to reuse when creating the "
"clean Docker build context. If unset, the SDK will run "
"`uv build --sdist` itself."
),
)
sdk_version: str = Field(
default=_DEFAULT_PACKAGE_VERSION,
description=(
"SDK package version. "
"We will need it to tag the built image. "
"Note this is only used if include_versioned_tag is True "
"(e.g., at each release)."
),
)
@property
def short_sha(self) -> str:
return self.git_sha[:7] if self.git_sha != "unknown" else "unknown"
@field_validator("target")
@classmethod
def _valid_target(cls, v: str) -> str:
if v not in VALID_TARGETS:
raise ValueError(f"target must be one of {sorted(VALID_TARGETS)}")
return v
@property
def custom_tag_list(self) -> list[str]:
return [t.strip() for t in self.custom_tags.split(",") if t.strip()]
@property
def base_image_slug(self) -> str:
return _base_slug(self.base_image)
@property
def versioned_tags(self) -> list[str]:
"""
Generate simple version tags for each custom tag variant.
Returns tags like: 1.2.0-python, 1.2.0-java, 1.2.0-golang
"""
return [f"{self.sdk_version}-{t}" for t in self.custom_tag_list]
@property
def base_tag(self) -> str:
return f"{self.short_sha}-{self.base_image_slug}"
@property
def cache_tags(self) -> tuple[str, str]:
base = f"buildcache-{self.target}-{self.base_image_slug}"
if self.git_ref in ("main", "refs/heads/main"):
return f"{base}-main", base
elif self.git_ref != "unknown":
return f"{base}-{_sanitize_branch(self.git_ref)}", base
else:
return base, base
@property
def all_tags(self) -> list[str]:
tags: list[str] = []
arch_suffix = f"-{self.arch}" if self.arch else ""
# Use git commit SHA for commit-based tags
for t in self.custom_tag_list:
tags.append(f"{self.image}:{self.short_sha}-{t}{arch_suffix}")
if self.git_ref in ("main", "refs/heads/main"):
for t in self.custom_tag_list:
tags.append(f"{self.image}:main-{t}{arch_suffix}")
if self.include_base_tag:
tags.append(f"{self.image}:{self.base_tag}{arch_suffix}")
if self.include_versioned_tag:
for versioned_tag in self.versioned_tags:
tags.append(f"{self.image}:{versioned_tag}{arch_suffix}")
# Append target suffix for clarity (binary is default, no suffix needed)
if self.target != "binary":
tags = [f"{t}-{self.target}" for t in tags]
return tags
class BuildTelemetry(BaseModel):
build_context_seconds: float = 0.0
buildx_wall_clock_seconds: float = 0.0
cleanup_seconds: float = 0.0
cache_import_seconds: float = 0.0
cache_import_miss_count: int = 0
cache_export_seconds: float = 0.0
image_export_seconds: float = 0.0
push_layers_seconds: float = 0.0
export_manifest_seconds: float = 0.0
cached_step_count: int = 0
class BuildResult(BaseModel):
tags: list[str]
telemetry: BuildTelemetry = Field(default_factory=BuildTelemetry)
class BuildCommandError(subprocess.CalledProcessError):
def __init__(
self,
returncode: int,
cmd: list[str],
*,
output: str,
stderr: str,
telemetry: BuildTelemetry,
) -> None:
super().__init__(returncode, cmd, output=output, stderr=stderr)
self.telemetry = telemetry
# --- build helpers ---
def _extract_tarball(tarball: Path, dest: Path) -> None:
dest = dest.resolve()
dest.mkdir(parents=True, exist_ok=True)
with tarfile.open(tarball, "r:gz") as tar, chdir(dest):
# Pre-validate entries
for m in tar.getmembers():
name = m.name.lstrip("./")
p = Path(name)
if p.is_absolute() or ".." in p.parts:
raise RuntimeError(f"Unsafe path in sdist: {m.name}")
# Safe(-r) extraction: no symlinks/devices
tar.extractall(path=".", filter="data")
def _make_build_context(
sdk_project_root: Path,
prebuilt_sdist: Path | None = None,
) -> Path:
dockerfile_path = _get_dockerfile_path(sdk_project_root)
tmp_root = Path(tempfile.mkdtemp(prefix="agent-build-", dir=None)).resolve()
sdist_dir: Path | None = None
try:
if prebuilt_sdist is None:
sdist_dir = Path(
tempfile.mkdtemp(prefix="agent-sdist-", dir=None)
).resolve()
_run(
["uv", "build", "--sdist", "--out-dir", str(sdist_dir.resolve())],
cwd=str(sdk_project_root.resolve()),
)
sdists = sorted(sdist_dir.glob("*.tar.gz"), key=lambda p: p.stat().st_mtime)
logger.info(
f"[build] Built {len(sdists)} sdists for "
f"clean context: {', '.join(str(s) for s in sdists)}"
)
assert len(sdists) == 1, "Expected exactly one sdist"
sdist = sdists[0]
else:
sdist = Path(prebuilt_sdist).expanduser().resolve()
if not sdist.is_file():
raise FileNotFoundError(f"Pre-built sdist not found at {sdist}")
logger.info(f"[build] Reusing pre-built sdist for clean context: {sdist}")
logger.debug(f"[build] Extracting sdist {sdist} to clean context {tmp_root}")
_extract_tarball(sdist, tmp_root)
# assert only one folder created
entries = list(tmp_root.iterdir())
assert len(entries) == 1 and entries[0].is_dir(), (
"Expected single folder in sdist"
)
tmp_root = entries[0].resolve()
# copy Dockerfile into place
shutil.copy2(dockerfile_path, tmp_root / "Dockerfile")
logger.debug(f"[build] Clean context ready at {tmp_root}")
return tmp_root
except Exception:
shutil.rmtree(tmp_root, ignore_errors=True)
raise
finally:
if sdist_dir is not None:
shutil.rmtree(sdist_dir, ignore_errors=True)
def _active_buildx_driver() -> str | None:
try:
out = _run(["docker", "buildx", "inspect", "--bootstrap"]).stdout
for line in out.splitlines():
s = line.strip()
if s.startswith("Driver:"):
return s.split(":", 1)[1].strip()
except Exception:
pass
return None
def _default_local_cache_dir() -> Path:
# keep cache outside repo; override with BUILD_CACHE_DIR if wanted
root = os.environ.get("BUILD_CACHE_DIR")
if root:
return Path(root).expanduser().resolve()
xdg = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
return Path(xdg) / "openhands" / "buildx-cache"
def _get_dockerfile_path(sdk_project_root: Path) -> Path:
dockerfile_path = (
sdk_project_root
/ "openhands-agent-server"
/ "openhands"
/ "agent_server"
/ "docker"
/ "Dockerfile"
)
if not dockerfile_path.exists():
raise FileNotFoundError(f"Dockerfile not found at {dockerfile_path}")
return dockerfile_path
def _round_seconds(value: float) -> float:
return round(value, 3)
def _classify_buildkit_description(description: str) -> str | None:
normalized = description.strip().lower()
if normalized.startswith("importing cache manifest from "):
return "cache_import"
if normalized.startswith("exporting cache to "):
return "cache_export"
if normalized == "exporting to image":
return "image_export"
if normalized == "pushing layers":
return "push_layers"
if normalized.startswith("exporting manifest"):
return "export_manifest"
if normalized.startswith("exporting manifest list"):
return "export_manifest"
if normalized.startswith("exporting config"):
return "export_manifest"
return None
def _add_buildkit_duration(
telemetry: BuildTelemetry, description: str, duration_seconds: float
) -> None:
phase = _classify_buildkit_description(description)
if phase == "cache_import":
telemetry.cache_import_seconds += duration_seconds
elif phase == "cache_export":
telemetry.cache_export_seconds += duration_seconds
elif phase == "image_export":
telemetry.image_export_seconds += duration_seconds
elif phase == "push_layers":
telemetry.push_layers_seconds += duration_seconds
elif phase == "export_manifest":
telemetry.export_manifest_seconds += duration_seconds
def _parse_buildkit_telemetry(stderr: str) -> BuildTelemetry:
telemetry = BuildTelemetry()
step_descriptions: dict[str, str] = {}
for raw_line in stderr.splitlines():
line = raw_line.strip()
match = _BUILDKIT_STEP_RE.match(line)
if not match:
continue
step = match.group("step")
message = match.group("message").strip()
if message == "CACHED":
telemetry.cached_step_count += 1
continue
if message.startswith("ERROR:"):
description = step_descriptions.get(step, "")
if (
_classify_buildkit_description(description) == "cache_import"
and "not found" in message.lower()
):
telemetry.cache_import_miss_count += 1
continue
if " ERROR:" in message:
description = message.split(" ERROR:", 1)[0].strip()
if (
_classify_buildkit_description(description) == "cache_import"
and "not found" in message.lower()
):
telemetry.cache_import_miss_count += 1
step_descriptions[step] = description
continue
done_match = _BUILDKIT_DONE_RE.match(message)
if done_match:
description = step_descriptions.get(step)
if description:
_add_buildkit_duration(
telemetry, description, float(done_match.group("seconds"))
)
continue
inline_done_match = _BUILDKIT_INLINE_DONE_RE.match(message)
if inline_done_match:
_add_buildkit_duration(
telemetry,
inline_done_match.group("description"),
float(inline_done_match.group("seconds")),
)
continue
# Only update step description if there isn't already a classified one.
# This prevents sub-operations (like "preparing build cache for export")
# from overwriting the main operation (like "exporting cache to registry").
new_desc = message.removesuffix(" ...").strip()
existing_desc = step_descriptions.get(step)
if (
existing_desc is None
or _classify_buildkit_description(existing_desc) is None
):
step_descriptions[step] = new_desc
telemetry.build_context_seconds = _round_seconds(telemetry.build_context_seconds)
telemetry.buildx_wall_clock_seconds = _round_seconds(
telemetry.buildx_wall_clock_seconds
)
telemetry.cleanup_seconds = _round_seconds(telemetry.cleanup_seconds)
telemetry.cache_import_seconds = _round_seconds(telemetry.cache_import_seconds)
telemetry.cache_export_seconds = _round_seconds(telemetry.cache_export_seconds)
telemetry.image_export_seconds = _round_seconds(telemetry.image_export_seconds)
telemetry.push_layers_seconds = _round_seconds(telemetry.push_layers_seconds)
telemetry.export_manifest_seconds = _round_seconds(
telemetry.export_manifest_seconds
)
return telemetry
# --- single entry point ---
def build_with_telemetry(opts: BuildOptions) -> BuildResult:
"""Build the agent-server image and return tags plus phase telemetry."""
dockerfile_path = _get_dockerfile_path(opts.sdk_project_root)
push = opts.push
if push is None:
push = IN_CI
tags = opts.all_tags
cache_tag, cache_tag_base = opts.cache_tags
telemetry = BuildTelemetry()
build_context_started = time.monotonic()
# Base-image targets don't need SDK source (no COPY from build context),
# so use an empty temp dir instead of running the expensive uv build --sdist.
is_base_only = opts.target in ("base-image-minimal", "base-image")
if is_base_only:
ctx = Path(tempfile.mkdtemp(prefix="agent-base-ctx-"))
shutil.copy2(dockerfile_path, ctx / "Dockerfile")
else:
ctx = _make_build_context(opts.sdk_project_root, opts.prebuilt_sdist)
telemetry.build_context_seconds = _round_seconds(
time.monotonic() - build_context_started
)
logger.info(f"[build] {'Empty' if is_base_only else 'Clean'} build context: {ctx}")
args = [
"docker",
"buildx",
"build",
"--file",
str(dockerfile_path),
"--target",
opts.target,
"--build-arg",
f"BASE_IMAGE={opts.base_image}",
"--build-arg",
f"OPENHANDS_BUILD_GIT_SHA={opts.git_sha}",
"--build-arg",
f"OPENHANDS_BUILD_GIT_REF={opts.git_ref}",
]
if push:
args += ["--platform", ",".join(opts.platforms), "--push"]
else:
if len(opts.platforms) == 1:
args += ["--platform", opts.platforms[0]]
args += ["--load"]
for t in tags:
args += ["--tag", t]
# -------- cache strategy --------
driver = _active_buildx_driver() or "unknown"
local_cache_dir = _default_local_cache_dir()
cache_args: list[str] = []
# Cache export mode: "max" (default), "min", or "off"
# Default to "max" to preserve existing behavior; set to "off" in batch builds
# to avoid contention when building many images in parallel
cache_export_mode = os.environ.get("OPENHANDS_BUILDKIT_CACHE_MODE", "max").lower()
if cache_export_mode not in ("off", "max", "min"):
logger.warning(
f"[build] Invalid OPENHANDS_BUILDKIT_CACHE_MODE='{cache_export_mode}', "
"defaulting to 'max'"
)
cache_export_mode = "max"
if push:
# Remote/CI builds: always read from registry cache
cache_args += [
"--cache-from",
f"type=registry,ref={opts.image}:{cache_tag}",
"--cache-from",
f"type=registry,ref={opts.image}:{cache_tag_base}-main",
]
# Only export cache if explicitly enabled (avoids contention in batch builds)
if cache_export_mode in ("max", "min"):
cache_args += [
"--cache-to",
f"type=registry,ref={opts.image}:{cache_tag},mode={cache_export_mode}",
]
logger.info(
f"[build] Cache: registry read + export mode={cache_export_mode}"
)
else:
logger.info("[build] Cache: registry read only (export disabled)")
else:
# Local/dev builds: prefer local dir cache if
# driver supports it; otherwise inline-only.
if driver == "docker-container":
local_cache_dir.mkdir(parents=True, exist_ok=True)
cache_args += [
"--cache-from",
f"type=local,src={str(local_cache_dir)}",
"--cache-to",
f"type=local,dest={str(local_cache_dir)},mode=max",
]
logger.info(
f"[build] Cache: local dir at {local_cache_dir} (driver={driver})"
)
else:
logger.warning(
f"[build] WARNING: Active buildx driver is '{driver}', "
"which does not support local dir caching. Fallback to INLINE CACHE\n"
" Consider running the following commands to set up a "
"compatible buildx environment:\n"
" 1. docker buildx create --name openhands-builder "
"--driver docker-container --use\n"
" 2. docker buildx inspect --bootstrap\n"
)
# docker driver can't export caches; fall back to inline metadata only.
cache_args += ["--build-arg", "BUILDKIT_INLINE_CACHE=1"]
logger.info(f"[build] Cache: inline only (driver={driver})")
args += cache_args + [str(ctx)]
logger.info(
f"[build] Building target='{opts.target}' image='{opts.image}' "
f"custom_tags='{opts.custom_tags}' from base='{opts.base_image}' "
f"for platforms='{opts.platforms}'"
)
logger.info(
f"[build] Git ref='{opts.git_ref}' sha='{opts.git_sha}' "
f"package_version='{opts.sdk_version}'"
)
logger.info(f"[build] Cache tag: {cache_tag}")
buildx_started = time.monotonic()
try:
res = _run(args, cwd=str(ctx))
telemetry.buildx_wall_clock_seconds = _round_seconds(
time.monotonic() - buildx_started
)
parsed = _parse_buildkit_telemetry(res.stderr)
parsed.build_context_seconds = telemetry.build_context_seconds
parsed.buildx_wall_clock_seconds = telemetry.buildx_wall_clock_seconds
telemetry = parsed
sys.stdout.write(res.stdout or "")
except subprocess.CalledProcessError as e:
telemetry.buildx_wall_clock_seconds = _round_seconds(
time.monotonic() - buildx_started
)
parsed = _parse_buildkit_telemetry(e.stderr or "")
parsed.build_context_seconds = telemetry.build_context_seconds
parsed.buildx_wall_clock_seconds = telemetry.buildx_wall_clock_seconds
telemetry = parsed
logger.error(f"[build] ERROR: Build failed with exit code {e.returncode}")
logger.error(f"[build] Command: {' '.join(e.cmd)}")
logger.error(f"[build] Full stdout:\n{e.output}")
logger.error(f"[build] Full stderr:\n{e.stderr}")
raise BuildCommandError(
e.returncode,
e.cmd,
output=e.output or "",
stderr=e.stderr or "",
telemetry=telemetry,
) from e
finally:
cleanup_started = time.monotonic()
logger.info(f"[build] Cleaning {ctx}")
shutil.rmtree(ctx, ignore_errors=True)
telemetry.cleanup_seconds = _round_seconds(time.monotonic() - cleanup_started)
logger.info("[build] Done. Tags:")
for t in tags:
logger.info(f" - {t}")
logger.info("[build] Telemetry: %s", telemetry.model_dump_json())
return BuildResult(tags=tags, telemetry=telemetry)
def build(opts: BuildOptions) -> list[str]:
"""Single entry point for building the agent-server image."""
return build_with_telemetry(opts).tags
# --- CLI shim ---
def _env(name: str, default: str) -> str:
v = os.environ.get(name)
return v if v else default
def main(argv: list[str]) -> int:
# ---- argparse ----
parser = argparse.ArgumentParser(
description="Single-entry build helper for agent-server images."
)
parser.add_argument(
"--base-image",
# NOTE: Using Python 3.12 due to PyInstaller+libtmux compatibility issue
# with Python 3.13. See issue #1886.
default=_env("BASE_IMAGE", "nikolaik/python-nodejs:python3.12-nodejs22-slim"),
help="Base image to use (default from $BASE_IMAGE).",
)
parser.add_argument(
"--custom-tags",
default=_env("CUSTOM_TAGS", ""),
help="Comma-separated custom tags (default from $CUSTOM_TAGS).",
)
parser.add_argument(
"--image",
default=_env("IMAGE", "ghcr.io/openhands/agent-server"),
help="Image repo/name (default from $IMAGE).",
)
parser.add_argument(
"--target",
default=_env("TARGET", "binary"),
choices=sorted(VALID_TARGETS),
help="Build target (default from $TARGET).",
)
parser.add_argument(
"--platforms",
default=_env("PLATFORMS", "linux/amd64,linux/arm64"),
help="Comma-separated platforms (default from $PLATFORMS).",
)
parser.add_argument(
"--arch",
default=_env("ARCH", ""),
help=(
"Architecture suffix for tags (e.g., 'amd64', 'arm64', default from $ARCH)."
),
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--push",
action="store_true",
help="Force push via buildx (overrides env).",
)
group.add_argument(
"--load",
action="store_true",
help="Force local load (overrides env).",
)
parser.add_argument(
"--sdk-project-root",
type=Path,
default=None,
help="Path to OpenHands SDK root (default: auto-detect).",
)
parser.add_argument(
"--prebuilt-sdist",
type=Path,
default=None,
help="Path to a pre-built SDK sdist tarball to reuse for the build context.",
)
parser.add_argument(
"--build-ctx-only",
action="store_true",
help="Only create the clean build context directory and print its path.",
)
parser.add_argument(
"--versioned-tag",
action="store_true",
help=(
"Include versioned tag (e.g., v1.0.0_...) in output. "
"Should only be used for release builds."
),
)
args = parser.parse_args(argv)
# ---- resolve sdk project root ----
sdk_project_root = args.sdk_project_root
if sdk_project_root is None:
try:
sdk_project_root = _default_sdk_project_root()
except Exception as e:
logger.error(str(e))
return 1
# ---- build-ctx-only path ----
if args.build_ctx_only: