Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
".": "0.21.0",
"adk": "0.21.0"
".": "0.22.0",
"adk": "0.22.0"
}
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,24 @@

* **tracing:** emit OTel metrics for async span queue depth, batch drain, and SGP export success/failure (HTTP status labels). Disable SDK-side recording with ``AGENTEX_TRACING_METRICS=0``.

## 0.22.0 (2026-07-29)

Full Changelog: [agentex-client-v0.21.0...agentex-client-v0.22.0](https://github.com/scaleapi/scale-agentex-python/compare/agentex-client-v0.21.0...agentex-client-v0.22.0)

### Features

* **lib:** capture client-attested build provenance ([#454](https://github.com/scaleapi/scale-agentex-python/issues/454)) ([8964044](https://github.com/scaleapi/scale-agentex-python/commit/896404475a1e93955eabd562caa1670364335c29))


### Bug Fixes

* **lib:** default 'agentex agents build' to --no-cache so stale layers can't ship stale source ([#476](https://github.com/scaleapi/scale-agentex-python/issues/476)) ([632d82c](https://github.com/scaleapi/scale-agentex-python/commit/632d82c2e4eeb1f7113b575b8666ffd53a1ab2eb))


### Refactors

* **lib:** remove the dead build-info.json registration read-path ([#455](https://github.com/scaleapi/scale-agentex-python/issues/455)) ([2078f9f](https://github.com/scaleapi/scale-agentex-python/commit/2078f9fabb3099fa2d5d02f67ed5af50b8efbc09))

## 0.21.0 (2026-07-28)

Full Changelog: [agentex-client-v0.20.0...agentex-client-v0.21.0](https://github.com/scaleapi/scale-agentex-python/compare/agentex-client-v0.20.0...agentex-client-v0.21.0)
Expand Down
8 changes: 8 additions & 0 deletions adk/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Changelog

## 0.22.0 (2026-07-29)

Full Changelog: [agentex-sdk-v0.21.0...agentex-sdk-v0.22.0](https://github.com/scaleapi/scale-agentex-python/compare/agentex-sdk-v0.21.0...agentex-sdk-v0.22.0)

### Chores

* **agentex-sdk:** Synchronize agentex versions

## 0.21.0 (2026-07-28)

Full Changelog: [agentex-sdk-v0.20.0...agentex-sdk-v0.21.0](https://github.com/scaleapi/scale-agentex-python/compare/agentex-sdk-v0.20.0...agentex-sdk-v0.21.0)
Expand Down
2 changes: 1 addition & 1 deletion adk/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# (agentex/{__init__.py, _*.py, types/, resources/}) ships from the slim
# sibling package `agentex-client` which is pinned as a runtime dep.
name = "agentex-sdk"
version = "0.21.0"
version = "0.22.0"
description = "Agent Development Kit (ADK) overlay for the Agentex API β€” FastACP server, Temporal workflows, LLM provider integrations, observability"
license = "Apache-2.0"
authors = [
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# overlay (formerly `src/agentex/lib/*`) now lives in `adk/` and ships
# as the sibling `agentex-sdk` package β€” see `adk/pyproject.toml`.
name = "agentex-client"
version = "0.21.0"
version = "0.22.0"
description = "The official Python REST client for the Agentex API"
dynamic = ["readme"]
license = "Apache-2.0"
Expand Down
2 changes: 1 addition & 1 deletion src/agentex/_version.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.

__title__ = "agentex"
__version__ = "0.21.0" # x-release-please-version
__version__ = "0.22.0" # x-release-please-version
8 changes: 8 additions & 0 deletions src/agentex/lib/cli/commands/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,13 @@ def build(
None,
help="Docker build argument in the format 'KEY=VALUE' (can be used multiple times)",
),
cache: bool = typer.Option(
False,
"--cache/--no-cache",
help="Whether to use the build cache. Defaults to off so a stale cached layer "
"can't silently ship source that no longer matches the checkout (notably when "
"republishing a moving tag like ':latest'). Pass --cache to opt back in.",
),
):
"""
Build an agent image locally from the given manifest.
Expand Down Expand Up @@ -155,6 +162,7 @@ def build(
secret=secret or "", # Provide default empty string
tag=tag or "latest", # Provide default
build_args=build_arg or [], # Provide default empty list
cache=cache,
)
if image_url:
typer.echo(f"Successfully built image: {image_url}")
Expand Down
8 changes: 8 additions & 0 deletions src/agentex/lib/cli/handlers/agent_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def build_agent(
secret: str | None = None,
tag: str | None = None,
build_args: list[str] | None = None,
cache: bool = False,
) -> str:
"""Build the agent locally and optionally push to registry

Expand All @@ -49,6 +50,10 @@ def build_agent(
secret: Docker build secret in format 'id=secret-id,src=path-to-secret-file'
tag: Image tag to use (defaults to 'latest')
build_args: List of Docker build arguments in format 'KEY=VALUE'
cache: Whether to use the build cache. Defaults to False (passes --no-cache to
buildx) so a stale cached layer can't silently ship source that no longer
matches the checkout, notably when republishing a moving tag like ':latest'.
Pass True to opt back in for faster local rebuilds.

Returns:
The image URL
Expand Down Expand Up @@ -85,7 +90,10 @@ def build_agent(
"file": str(build_context.path / build_context.dockerfile_path), # type: ignore[operator]
"tags": [image_name],
"platforms": platforms,
"cache": cache, # cache=False -> `docker buildx build --no-cache`
}
if not cache:
logger.info("Build cache disabled (--no-cache)")

# Add Docker build args if provided
if build_args:
Expand Down
4 changes: 0 additions & 4 deletions src/agentex/lib/environment_variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ class EnvVarKeys(str, Enum):
HEALTH_CHECK_PORT = "HEALTH_CHECK_PORT"
# Auth Configuration
AUTH_PRINCIPAL_B64 = "AUTH_PRINCIPAL_B64"
# Build Information
BUILD_INFO_PATH = "BUILD_INFO_PATH"
AGENT_INPUT_TYPE = "AGENT_INPUT_TYPE"
# Deployment
AGENTEX_DEPLOYMENT_ID = "AGENTEX_DEPLOYMENT_ID"
Expand Down Expand Up @@ -87,8 +85,6 @@ class EnvironmentVariables(BaseModel):
HEALTH_CHECK_PORT: int = 80
# Auth Configuration
AUTH_PRINCIPAL_B64: str | None = None
# Build Information
BUILD_INFO_PATH: str | None = None
# Deployment
AGENTEX_DEPLOYMENT_ID: str | None = None
# Claude Agents SDK Configuration
Expand Down
10 changes: 5 additions & 5 deletions src/agentex/lib/sdk/config/agent_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from agentex.lib.utils.io import load_yaml_file
from agentex.lib.utils.logging import make_logger
from agentex.config.agent_manifest import AgentManifest # noqa: F401
from agentex.lib.utils.build_provenance import iter_context_files

logger = make_logger(__name__)

Expand Down Expand Up @@ -189,12 +190,11 @@ def zipped(root_path: Path | None = None) -> Iterator[IO[bytes]]:

tar_buffer = io.BytesIO()

# Sorted, relpath-stable enumeration (shared with the content hash) so the
# archive's member order is deterministic across machines.
with tarfile.open(fileobj=tar_buffer, mode="w:gz") as tar_file:
for path in Path(root_path).rglob(
"*"
): # Recursively add files to the tar.gz
if path.is_file(): # Ensure that we're only adding files
tar_file.add(path, arcname=path.relative_to(root_path))
for path in iter_context_files(Path(root_path)):
tar_file.add(path, arcname=path.relative_to(root_path))
Comment thread
deepthi-rao-scale marked this conversation as resolved.

tar_buffer.seek(0) # Reset the buffer position to the beginning
yield tar_buffer
Expand Down
13 changes: 0 additions & 13 deletions src/agentex/lib/sdk/fastacp/fastacp.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
from __future__ import annotations

import os
import inspect
from typing import Any, Literal
from pathlib import Path
from typing_extensions import deprecated

from agentex.lib.types.fastacp import (
Expand Down Expand Up @@ -82,14 +79,6 @@ def create_agentic_acp(config: AgenticACPConfig, **kwargs) -> BaseACPServer:
"""
return FastACP.create_async_acp(config, **kwargs)

@staticmethod
def locate_build_info_path() -> None:
"""If a build-info.json file is present, set the BUILD_INFO_PATH environment variable"""
acp_root = Path(inspect.stack()[2].filename).resolve().parents[0]
build_info_path = acp_root / "build-info.json"
if build_info_path.exists():
os.environ["BUILD_INFO_PATH"] = str(build_info_path)

@staticmethod
def create(
acp_type: Literal["sync", "async", "agentic"],
Expand All @@ -105,8 +94,6 @@ def create(
**kwargs: Additional configuration parameters
"""

FastACP.locate_build_info_path()

if acp_type == "sync":
sync_config = config if isinstance(config, SyncACPConfig) else None
instance = FastACP.create_sync_acp(sync_config, **kwargs)
Expand Down
189 changes: 189 additions & 0 deletions src/agentex/lib/utils/build_provenance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
"""Capture client-attested source identity without failing agent builds."""

from __future__ import annotations

import os
import stat
import hashlib
import subprocess
from typing import Optional
from pathlib import Path
from datetime import datetime, timezone
from dataclasses import dataclass

from agentex.lib.utils.logging import make_logger

logger = make_logger(__name__)

_GIT_TIMEOUT_S = 5
_HASH_CHUNK_BYTES = 1 << 20


@dataclass(frozen=True)
class BuildProvenance:
"""Source identity for one build; unavailable fields degrade to ``None``."""

repo: Optional[str] = None
commit: Optional[str] = None
ref: Optional[str] = None
subpath: Optional[str] = None
working_tree_hash: Optional[str] = None
dirty: Optional[bool] = None
author_name: Optional[str] = None
author_email: Optional[str] = None
build_timestamp: Optional[str] = None

def source_fields(self) -> dict[str, object]:
"""The ``source_*`` form fields for the cloud-build upload (None omitted)."""
fields = {
"source_repo": self.repo,
"source_commit": self.commit,
"source_ref": self.ref,
"source_subpath": self.subpath,
"working_tree_hash": self.working_tree_hash,
"source_dirty": self.dirty,
}
return {key: value for key, value in fields.items() if value is not None}

def build_info(self) -> dict[str, object]:
"""Return provenance using the runtime registration metadata field names."""
info = {
"repo": self.repo,
"commit_hash": self.commit,
"branch_name": self.ref,
"subpath": self.subpath,
"working_tree_hash": self.working_tree_hash,
"dirty": self.dirty,
"author_name": self.author_name,
"author_email": self.author_email,
"build_timestamp": self.build_timestamp,
}
return {key: value for key, value in info.items() if value is not None}


def _git(repo_root: Path, *args: str) -> Optional[str]:
"""Run a git command under ``repo_root``; return stripped stdout or None."""
try:
proc = subprocess.run(
("git", "-C", str(repo_root), *args),
capture_output=True,
text=True,
timeout=_GIT_TIMEOUT_S,
check=False,
)
except (OSError, subprocess.SubprocessError):
return None
if proc.returncode != 0:
return None
return proc.stdout.strip() or None


def normalize_remote(url: Optional[str]) -> Optional[str]:
"""Strip credentials and scheme from a remote, returning ``host/path``."""
if not url:
return None
candidate = url.strip()
# scp-like syntax: git@host:org/repo(.git) β€” no scheme, host/path split on ':'
if "://" not in candidate and ":" in candidate and "/" not in candidate.split(":", 1)[0]:
candidate = candidate.split("@", 1)[-1].replace(":", "/", 1)
else:
if "://" in candidate:
candidate = candidate.split("://", 1)[1]
candidate = candidate.split("@", 1)[-1]
if candidate.endswith(".git"):
candidate = candidate[: -len(".git")]
candidate = candidate.strip("/")
if not candidate:
return None
host, slash, path = candidate.partition("/")
return f"{host.lower()}{slash}{path}"


def _sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with open(path, "rb") as handle:
while chunk := handle.read(_HASH_CHUNK_BYTES):
digest.update(chunk)
return digest.hexdigest()


def iter_context_files(root: Path) -> list[Path]:
"""Return files and symlinks under ``root``, sorted by POSIX relative path."""
return sorted(
(path for path in root.rglob("*") if path.is_symlink() or path.is_file()),
key=lambda path: path.relative_to(root).as_posix(),
)


def working_tree_hash(root: Path) -> str:
"""Hash sorted build inputs, normalized modes, and symlink target strings."""
lines: list[str] = []
for path in iter_context_files(root):
relpath = path.relative_to(root).as_posix()
if path.is_symlink():
mode = "120000"
content_digest = hashlib.sha256(os.readlink(path).encode("utf-8")).hexdigest()
else:
executable = bool(path.stat().st_mode & stat.S_IXUSR)
mode = "100755" if executable else "100644"
content_digest = _sha256_file(path)
lines.append(f"{relpath}\x00{mode}\x00{content_digest}")
return hashlib.sha256("\n".join(lines).encode("utf-8")).hexdigest()


def _safe_working_tree_hash(root: Path) -> Optional[str]:
"""Compute the context hash without allowing capture to fail a build."""
try:
return working_tree_hash(root)
except Exception:
logger.warning("build-provenance: content hash failed; omitting", exc_info=True)
return None


def capture_build_provenance(
repo_path: Path, context_root: Path, content_root: Optional[Path] = None
) -> BuildProvenance:
"""Capture git coordinates and the staged build-context hash."""
timestamp = datetime.now(timezone.utc).isoformat()
hash_root = content_root if content_root is not None else context_root
tree_hash = _safe_working_tree_hash(hash_root)

repo_root = _git(repo_path, "rev-parse", "--show-toplevel")
if repo_root is None:
# No git β€” the content hash is the only identity available.
logger.info("build-provenance: %s is not a git work tree; content hash only", repo_path)
return BuildProvenance(working_tree_hash=tree_hash, build_timestamp=timestamp)

repo_root_path = Path(repo_root)
commit = _git(repo_root_path, "rev-parse", "HEAD")
# symbolic-ref fails on a detached HEAD (β†’ None); fall back to an exact tag.
ref = _git(repo_root_path, "symbolic-ref", "--short", "HEAD") or _git(
repo_root_path, "describe", "--tags", "--exact-match"
)
remote = normalize_remote(_git(repo_root_path, "remote", "get-url", "origin"))
author_name = _git(repo_root_path, "log", "-1", "--format=%an")
author_email = _git(repo_root_path, "log", "-1", "--format=%ae")

subpath: Optional[str] = None
try:
relative = context_root.resolve().relative_to(repo_root_path.resolve()).as_posix()
subpath = relative if relative != "." else None
except ValueError:
subpath = None

status_args = ("status", "--porcelain")
if subpath is not None:
status_args += ("--", subpath)
dirty = _git(repo_root_path, *status_args) is not None
Comment thread
deepthi-rao-scale marked this conversation as resolved.

return BuildProvenance(
repo=remote,
commit=commit,
ref=ref,
subpath=subpath,
working_tree_hash=tree_hash,
dirty=dirty,
author_name=author_name,
author_email=author_email,
build_timestamp=timestamp,
)
Loading
Loading