Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246"""Private, fail-closed transport build for real Antigravity adapter scenarios.
The runner still owns startup and teardown. Only the copied HTTP clients'seams are replaced: the streaming transport's destination is redirected andthe buffered client's httpc call refused. Production source, profiles andendpoint policy are unchanged."""
import jsonfrom pathlib import Pathimport reimport shleximport shutilimport subprocess
from harness import Albedo, Provider, Reply, ROOT
ENDPOINT = "https://daily-cloudcode-pa.googleapis.com"INFERENCE = ENDPOINT + "/v1internal:streamGenerateContent?alt=sse"TOKEN = "fixture-antigravity"SIGNATURE = "Zml4dHVyZS1zaWduYXR1cmU="GEMINI = "gemini-3-flash"CLAUDE = "claude-opus-5-5"GUARD = Path(__file__).with_name("albedo_antigravity_offline.erl")TRANSPORT = "albedo_http"BUFFERED = "albedo_http@buffered"# The OTP application each replaced module ships in.APPLICATIONS = {TRANSPORT: "albedo_http", BUFFERED: "albedo_http"}
# The streaming client's routing seam, `destination` in albedo_http.gleam,# as its generated Erlang: the identity on its first argument.SEAM = ( "[{function, _, destination, 2, Clauses}] = [F || {function, _, destination, 2, _} = F <- Forms], " "[{clause, _, [{var, _, Url}, {var, _, '_'}], [], [{var, _, Url}]}] = Clauses")
# The buffered client's one call into httpc, `exchange` in# albedo_http/buffered.gleam. No inets entry point in the private build may# contact a provider, so no other function may call httpc or capture one of# its functions: one that does is an added front door, and setup fails.EXCHANGE = ( "Names = fun Names({remote, _, {atom, _, httpc}, _}) -> true; " "Names({function, {atom, _, httpc}, _, _}) -> true; " "Names(T) when is_tuple(T) -> Names(tuple_to_list(T)); " "Names([H | Rest]) -> Names(H) orelse Names(Rest); " "Names(_) -> false end, " "[{function, _, exchange, 3, [{clause, _, [_, _, _], [], Body}]}] = " "[F || {function, _, exchange, 3, _} = F <- Forms], " "true = Names(Body), " "[] = [N || {function, _, N, _, _} = F <- Forms, N =/= exchange, Names(F)]")
def compile_offline(ebin: Path, source: Path, home: Path, target: str) -> None: """Compile replacements without touching the checkout or a running VM.""" route = re.fullmatch(r"http://127\.0\.0\.1:([0-9]+)/t/[0-9]+", target) if not home.is_absolute() or route is None or not 0 < int(route[1]) < 65536: raise ValueError("offline fixture requires an absolute home and loopback route")
def literal(value: str) -> str: return "<<" + ",".join(str(byte) for byte in value.encode()) + ">>"
def chars(value: str) -> str: return f"unicode:characters_to_list({literal(value)})"
routed = ( "destination(Url, Headers) -> albedo_antigravity_offline:route(" f"Url, Headers, {literal(target)}, {literal(str(home))})." ) offline = "exchange(_, _, _) -> {error, offline_fixture}." # Rewrite the build's generated Erlang for each module, read back from # its debug info, so only its seam differs from production. for module, check, name, replacement in [ (TRANSPORT, SEAM, "destination", routed), (BUFFERED, EXCHANGE, "exchange", offline), ]: built = ( ROOT / f"apps/albedo/build/dev/erlang/{APPLICATIONS[module]}/ebin/{module}.beam" ) patch = f""" {{ok, {{Module, [{{debug_info, {{debug_info_v1, Backend, Data}}}}]}}}} = beam_lib:chunks({chars(str(built))}, [debug_info]), {{ok, Forms}} = Backend:debug_info(erlang_v1, Module, Data, []), Seam = try {check}, ok catch error:_ -> changed end, Seam =:= ok orelse begin io:format(standard_error, "{module} interception point changed~n", []), halt(1) end, {{ok, Tokens, _}} = erl_scan:string({chars(replacement)}), {{ok, Replaced}} = erl_parse:parse_form(Tokens), Patched = [case F of {{function, _, {name}, _, _}} -> Replaced; _ -> F end || F <- Forms], {{ok, Module, Beam}} = compile:forms(Patched, [debug_info, binary, return_errors]), ok = file:write_file({chars(str(ebin / (module + ".beam")))}, Beam), halt(). """ patched = subprocess.run( ["erl", "-noshell", "-eval", patch], capture_output=True, text=True ) if patched.returncode != 0: raise AssertionError(patched.stderr or patched.stdout) source.mkdir() subprocess.run( [ "erlc", "-Wall", "-Werror", "-o", str(ebin), str(GUARD), *map(str, source.glob("*.erl")), ], check=True, text=True, )
def prepare(app: Albedo, provider: Provider) -> None: """Install a sealed private build and dummy accounts before exclusive boot.""" if app.daemon.concurrent or app.daemon.booted: raise AssertionError("Antigravity fixture requires a fresh exclusive daemon") original = Path(app.env["ALBEDO_DAEMON"]).parent for module, application in APPLICATIONS.items(): built = ROOT / f"apps/albedo/build/dev/erlang/{application}/ebin/{module}.beam" if ( original / f"{application}/ebin/{module}.beam" ).read_bytes() != built.read_bytes(): raise AssertionError("snapshot differs from the current daemon build") snapshot = app.root / "antigravity-daemon" shutil.copytree(original, snapshot) for module, application in APPLICATIONS.items(): directory = snapshot / application / "ebin" directory.chmod(directory.stat().st_mode | 0o200) (directory / f"{module}.beam").unlink() # Every replacement goes in albedo's ebin, which the boot code path holds # beside albedo_http's. ebin = snapshot / "albedo/ebin" (app.home / ".antigravity-offline").write_text("offline fixture\n") compile_offline(ebin, app.root / "offline-source", app.home, provider.url) subprocess.run( [ str(ROOT / "apps/albedo/priv/bin/albedo-daemon"), "erl", "-pa", *map(str, snapshot.glob("*/ebin")), "-noshell", "-eval", 'application:ensure_all_started(crypto), {ok, nil} = albedo@lifecycle@build_identity:seal_build(unicode:characters_to_binary(os:getenv("ALBEDO_BUILD_APP"))), halt().', ], check=True, capture_output=True, text=True, env={**app.env, "ALBEDO_BUILD_APP": str(snapshot / "albedo")}, ) launcher = snapshot / "albedo-daemon" launcher.write_text( "#!/bin/sh\nset -eu\n" f'test "${{ALBEDO_HOME-}}" = {shlex.quote(str(app.home))}\n' f"exec {shlex.quote(str(ROOT / 'apps/albedo/priv/bin/albedo-daemon'))} erl -pa {shlex.quote(str(snapshot))}/*/ebin -eval 'albedo@@main:run(albedo)' -noshell -extra \"$@\"\n" ) launcher.chmod(0o700) app.env.update(ALBEDO_DAEMON=str(launcher), ALBEDO_STANDBY="0") app.write_extensions({"quota": {"enabled": False}}) app.store_secrets( "accounts", { "google-antigravity": [ { "type": "oauth", "access": TOKEN, "refresh": "fixture-refresh", "expires": 9999999999999, "projectId": "fixture-project", "email": "fixture@example.invalid", "extension_metadata": {"keep": True}, } ] }, ) (app.home / "antigravity.json").write_text( json.dumps( { "version": "2.32.1", "models": [ { "id": name, "name": name, "context": 200000, "output": 8192, "images": True, "modelEnum": "FIXTURE_" + name.upper().replace("-", "_"), } for name in [GEMINI, CLAUDE + "-low", CLAUDE + "-high"] ], "renamed": {}, } ) )
def session_number(seed: str) -> str: value = 0xCBF29CE484222325 for byte in seed.encode(): value = ((value ^ byte) * 0x100000001B3) & ((1 << 64) - 1) return str(value if value < (1 << 63) else value - (1 << 64))
def limit_response(details: object) -> Reply: """A Google HTTP failure with structured details, rather than SSE events.""" return Reply( "error", status=429, error_body={ "error": {"code": 429, "status": "RESOURCE_EXHAUSTED", "details": details} }, )
# Google's suspension body as reported in oh-my-pi issue 18341# (https://github.com/can1357/oh-my-pi/issues/18341), whitespace aside.SUSPENSION = { "error": { "code": 403, "message": "This service has been disabled in this account for violation of Terms of Service. Please submit an appeal to continue using this product.", "status": "PERMISSION_DENIED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "TOS_VIOLATION", "domain": "cloudcode-pa.googleapis.com", "metadata": { "uiMessage": "true", "appeal_url": "https://forms.gle/hGzM9MEUv2azZsrb9", "appeal_url_link_text": "Submit Appeal", }, } ], }}
def suspension_response() -> Reply: """Google refusing a suspended account, rather than SSE events.""" return Reply("error", status=403, error_body=SUSPENSION)