File size: 5,329 Bytes
5873600 b710f09 5873600 b710f09 5873600 b710f09 5873600 a9b5504 5873600 32084d2 5873600 a9b5504 5873600 | 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 | """Optional build-time sidecar installation in an owned generated task copy."""
from __future__ import annotations
import hashlib
import json
import shutil
import tomllib
from pathlib import Path
import yaml
def install(task):
task = Path(task)
compose_path = task / "environment/docker-compose.yaml"
compose = yaml.safe_load(compose_path.read_text())
if "model-compat" in compose["services"]:
raise ValueError("Compatibility sidecar already exists")
if "main" not in compose["services"] or "default" not in compose.get(
"networks", {}
):
raise ValueError("Expected generated main/default network")
if any(key in compose["services"]["main"] for key in ("networks", "network_mode")):
raise ValueError("Main must use Harbor-controlled phase networking")
task_config = task / "task.toml"
if task_config.is_file():
policy = tomllib.loads(task_config.read_text())
agent = policy.get("agent", {})
if (agent.get("network_mode") != "allowlist"
or agent.get("allowed_hosts") != ["team", "model-compat"]
or policy.get("environment", {}).get("network_mode") != "public"):
raise ValueError("Task must preserve public install and restricted agent network phases")
owned = task / "environment/model-compat"
owned.mkdir(exist_ok=False)
source = Path(__file__).with_name("model_gateway.py")
shutil.copyfile(source, owned / "model_gateway.py")
(
owned / "Dockerfile"
).write_text("""FROM python:3.13-slim-bookworm@sha256:281d39ff02e3b389401586134ff9e6572954687822a58055ec07a60ded4e0b7f
COPY model_gateway.py /app/model_gateway.py
RUN chmod 644 /app/model_gateway.py
USER 65534:65534
ENTRYPOINT ["python", "-B", "/app/model_gateway.py"]
""")
compose["services"]["model-compat"] = {
"build": {"context": "./model-compat"},
"networks": ["default"],
# Provider base URL (with version prefix); no credential ever goes here.
"environment": {
"CI_MODEL_UPSTREAM": "${CI_MODEL_UPSTREAM:-https://generativelanguage.googleapis.com/v1beta/openai}",
"CI_MODEL_HEADERS": "${CI_MODEL_HEADERS:-}",
"CI_MODEL_BODY": "${CI_MODEL_BODY:-}",
"CI_MODEL_NAME": "${CI_EVALUATED_MODEL:-}",
},
"read_only": True,
"cap_drop": ["ALL"],
"security_opt": ["no-new-privileges:true"],
"healthcheck": {
"test": [
"CMD",
"python",
"-c",
"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8003/health')",
],
"interval": "1s",
"timeout": "3s",
"retries": 30,
},
}
compose["services"]["main"].setdefault("depends_on", {})["model-compat"] = {
"condition": "service_healthy"
}
compose_path.write_text(yaml.safe_dump(compose, sort_keys=False))
receipt = {
"schema_version": 1,
"optional": True,
"role": "provider-neutral model gateway for the evaluated agent and its private final-answer readout",
"paths": ["/v1/chat/completions", "/v1/responses", "/v1/messages"],
"stock_legion_base_url": "http://model-compat:8003/v1",
"upstream": "CI_MODEL_UPSTREAM, default https://generativelanguage.googleapis.com/v1beta/openai",
"request_change": "remove only top-level store, and only for Google's endpoint; add the operator's "
"CI_MODEL_BODY provider options when set",
"provider_library_history_tools_caps_changes": False,
"credentials_owned_by_sidecar": False,
"agent_phase_allowed_hosts": ["team", "model-compat"],
"agent_main_explicit_networks": False,
"source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
}
(owned / "compatibility.json").write_text(json.dumps(receipt, indent=2) + "\n")
config_path = task / "environment/team/task.json"
if config_path.is_file():
from .compact_runtime import _atomic
from .provenance import task_code_identity
config = json.loads(config_path.read_text())
if config.get("effective_code") is not None:
config["effective_code"] = task_code_identity(task)
_atomic(config_path, (json.dumps(config, indent=2) + "\n").encode())
return receipt
def main():
"""Build-time helper for an owned generated task tree before Hub release."""
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--tasks", type=Path, required=True)
args = parser.parse_args()
root = args.tasks.resolve()
manifest = json.loads((root / "manifest.json").read_text())
selected = {entry["path"] for entry in manifest["tasks"]}
for relative in sorted(selected):
path = Path(relative)
if (
path.is_absolute()
or ".." in path.parts
or not (root / path).resolve().is_relative_to(root)
):
raise ValueError("Unsafe generated task path")
install(root / path)
print(
json.dumps(
{
"tasks": len(selected),
"optional_model_compat": True,
}
)
)
if __name__ == "__main__":
main()
|