Files
PaperClipAI/packages/paperclip-runner/scripts/patch-antigravity-runtime.mjs
T
DottaandClaude Fable 5.2 78e4f4f130 feat(runner): Antigravity on ACP 1.5.2 with Linux, API-key auth and Gemini 4 Neon (still pending) (#22591)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The native Runner starts each agent harness and owns its lifecycle,
credentials and recovery
> - Google Antigravity is Google's only first-party coding harness, and
it is the harness for Gemini 4 Neon
> - The Runner had an Antigravity integration, but only as a pending
candidate: ACP server 1.4.3, macOS ARM64 only, Google sign-in only,
closed unless an operator opened it for one company and one model
> - Cloud sandboxes run Linux and use API keys, so the candidate could
not run there, and it had one attended test cell
> - This pull request moves the integration to ACP server 1.5.2, makes
it run on Linux and with a Gemini API key, adds the tests the other ACPX
harnesses have, and removes the code paths that would block recovery
after release
> - The benefit is that the release of Antigravity becomes a small
declaration change after the live suites pass. The profile stays
`pending` in this pull request.

## Linked Issues or Issue Description

Refs #98
Refs #6559
Refs #8523
Refs #21121 (a separate legacy-style `agy_local` adapter that uses the
CLI print protocol; this pull request does not replace or include it)

## What Changed

**Runtime**
- Pin Antigravity ACP server 1.5.2 (was 1.4.3). Owned admission patch is
`1.5.2-paperclip.2`.
- Verified patched closures for `darwin-arm64`, `linux-x64` and
`linux-arm64`. `darwin-x64` stays inventory-only.
- The patcher reads Mach-O and ELF builds. It signs macOS output only.
One admission source serves all platforms.
- Platform gates in TypeScript, Rust, the sidecar schema and the server
admit each host that has a verified closure.

**Auth and models**
- Gemini API-key auth reaches an exact-model session receipt. Admission
accepts a model only when the base model and the thinking level both
match the requested ID.
- API-key connections get a model list on local and cloud environments.
The list is generated at build time from the pinned runtime. The server
starts no process to read it.
- Gemini 4 Neon, Carbon, Argon and Hydrogen are selectable. The picker
marks them "needs a paid Gemini API plan" for API-key connections.
- One shared module maps model ID to family and thinking level.
- `google/gemini-4-neon` is added to the OpenCode model list. A new
model audit is in `doc/adapter-model-audit-2026-11-22.md`.

**Lifecycle and failures**
- A provider error no longer completes the turn. The driver classifies
it: overloaded, rate limit, quota, auth rejected, model unavailable.
- Overload retries are bounded (3 attempts, about 14 seconds).
- A refused session reload maps to incompatible saved state, so the
automatic replacement conversation applies.
- Server gates that refused restart recovery, remote targets and shared
state for Antigravity now apply only while the profile is pending.
- A Google sign-in connection with a cloud environment is refused at
save and at Test, with a plain message.
- A released profile rejects candidate grants in TypeScript and in Rust.

**Launch cost and integrity (all native ACPX providers)**
- Each closure is verified one time into a sealed read-only store. Later
launches check file identities and hash the exact executable they start.
- Remote provider-pack verification is recorded per sandbox lease. Later
runs check kernel identity and fall back to the full hash on any
difference.
- Superseded stores are removed in the background after a launch.

**Provider pack and image**
- The provider pack carries Antigravity for `linux-x64` as a candidate
provider. It becomes an ordinary provider from the profile status alone.
- The Daytona image build accepts the candidate. A credential-free smoke
runs in the build.

**Tests and CI**
- New `antigravity-qualification` suite: 24 cells, local and Daytona.
- New model lineup suites: 14 API-key cells and 14 Gemini 4 cells. Each
cell requires the exact model in the Runner receipt.
- Antigravity can run the `chat-features` cases with `--profile
runner-acpx-antigravity`.
- `runner-full-stack-e2e.yml` passes `GEMINI_API_KEY` for the new
profile and derives candidate providers from the selected Daytona cells.

**Docs**
- `doc/plans/2026-11-22-antigravity-qualification.md` is the current
release contract, acceptance ledger and operator recipe.

## Verification

Commands that passed on the final revision:

- `pnpm build`
- Typecheck for all packages, including the runner-e2e test projects
- `pnpm test:e2e:runner:unit`: 11,665 Vitest tests passed, 25 skipped;
386 node tests passed
- `cargo test -p paperclip-runner-core -- --test-threads=4`: 1,199
passed, 2 failed. The 2 failures are Codex transport timing tests that
pass alone and on `master`.
- `cargo fmt --check`, `check:acpx-profiles`, `check:protocol-types`,
`node scripts/check-maps.mjs`
- Native patch tests: 9 of 9 on `darwin-arm64` and 9 of 9 on `linux-x64`
- UI picker tests: 397 of 397

Known failures that also fail on `master`:

- 11 runner package script tests (browser, Pi and package-boundary
checks)
- 6 `runtime-selection` tests that read an untracked local skill file

Live evidence, without a prompt:

- Clean provisioning on `darwin-arm64` and on `linux-x64` in a Daytona
sandbox. The closure digests reproduce. A changed or missing file is
rejected.
- `initialize` reports 1.5.2. An API-key session returns a receipt for
exactly `gemini-3.8-flash-low` and the exact instruction bytes, on both
platforms.
- All 28 model IDs (14 Gemini 3, 14 Gemini 4) return an exact receipt
under an API key.
- A session survives a process kill and resumes in a new process with
exact receipts, on both platforms.
- The server's remote path verifies the provider pack in a Daytona
sandbox.
- Run start to native `initialize`: 3.45 s to 1.46 s on macOS, 3.65 s to
1.74 s on Linux x64, before the per-launch executable hash was restored
(about 60 ms on macOS; not measured on Linux).
- Remote pack verification on a reused sandbox lease: about 4.3 s to
about 0.25 s.

Live evidence, with a prompt, on an already-released harness:

- Pi native, `pi-native.runner-acpx-pi.local.agent-files-fresh-run`, on
`darwin-arm64` at `427e9b088b`: 1 of 1 passed, 14 of 14 checks, both
native runs succeeded (25.5 s and 25.7 s). The process started from the
new launch store with no fallback warning.
- The same cell and `native-pending-controller-restart` failed in the
paid workflow on this branch and on `master` in the same way, before any
native start. The workflow does not install the Pi runtime for local
cells, so the agent setup check fails. That is a workflow gap, not part
of this change.

**Not run.** No Antigravity prompt completed on 1.5.2 on any platform.
The only Gemini key available is on the free tier, and Google returned
503 or 429 for each attempt on two days. These gates are open:

- All 24 `antigravity-qualification` cells
- Both model lineup suites, including inference on Gemini 4 Neon
- The attended Google sign-in journey on 1.5.2
- The chat cases under Antigravity
- Image pull time and startup time on a published image
- A native start on `linux-arm64`
- A live provider-death cell for Kimi, Pi or Copilot on the new launch
store (one ordinary Pi cell passed live; see above)

## Risks

- **The launch store changes how every native ACPX provider starts**
(Kimi, Copilot, Cursor, Pi), not only Antigravity. A review found two
defects in the first version (an executable swap was possible, and Pi
launches broke). Both are fixed with tests. One live Pi cell passed on
this branch on macOS. No live provider-death cell and no Linux cell ran
for those providers.
- The profile digest changes. Saved Antigravity candidate sessions and
existing candidate grants stop working. The new release refuses old
state by name and starts a replacement conversation.
- The Linux provider pack and the Daytona image grow by about 834 MB
(about 274 MB compressed) when Antigravity is included.
- The pack verification record is in server memory. The first run after
a server restart pays the full hash again.
- Antigravity 1.5.2 reads the workspace `GEMINI.md` and `AGENTS.md` as
user rules. This is deliberate and matches Codex. Any other rule file is
refused.
- Orchestrator mode is not available. ACP server 1.5.2 does not expose
it.
- Antigravity stays `pending`. Normal users cannot run it until a later
change removes the pending status.

## Model Used

- Claude Fable 5.2 (`claude-fable-5-2`) planned, briefed and integrated
the work, with tool use.
- Claude Opus 5.5 (`claude-opus-5-5`) subagents wrote the code and ran
the tests, with tool use and code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 08:21:11 -06:00

369 lines
22 KiB
JavaScript

import { createHash } from "node:crypto";
import { execFileSync } from "node:child_process";
import { chmod, lstat, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { inflateRawSync } from "node:zlib";
export const ANTIGRAVITY_PATCH_SCHEMA = "paperclip.antigravity.native_patch.v1";
export const ANTIGRAVITY_PATCH_VERSION = "1.5.2-paperclip.2";
const ACP_ROOT = "google3/cloud/developer_experience/antigravity_extensions/acp_server/";
const SDK_ROOT = "google3/third_party/py/google/antigravity/connections/local/";
const SERVER_SOURCE = ACP_ROOT + "server.py";
const SDK_SOURCE = SDK_ROOT + "local_connection.py";
const EVENT_PROCESSOR_SOURCE = SDK_ROOT + "event_processor.py";
const ADMISSION_SOURCE = ACP_ROOT + "paperclip_admission.py";
const IDENTITY_SOURCE = ACP_ROOT + "paperclip_native_identity.py";
const REMOVED_BYTECODE = new Set([
ACP_ROOT + "__pycache__/server.cpython-314.pyc",
SDK_ROOT + "__pycache__/local_connection.cpython-314.pyc",
SDK_ROOT + "__pycache__/event_processor.cpython-314.pyc",
]);
const RUNTIME_FILES = ["agy_acp_server.par", "localharness_external"];
/** Each patchable vendor build and how its Python archive is embedded. The
* Linux builds are ELF launchers with the archive appended; macOS embeds it in
* a Mach-O section and must be re-signed after patching. */
export const ANTIGRAVITY_PATCH_TARGETS = Object.freeze({
"darwin-arm64": Object.freeze({ format: "macho", cpuType: 0x0100000c, signed: true }),
"linux-x64": Object.freeze({ format: "elf", machine: 62, signed: false }),
"linux-arm64": Object.freeze({ format: "elf", machine: 183, signed: false }),
});
const SHA256 = /^[a-f0-9]{64}$/;
const digest = value => createHash("sha256").update(value).digest("hex");
const fail = message => { throw new Error(`Antigravity native patch: ${message}`); };
/** Exact vendor identity for one target, taken from the verified closure declaration. */
export function antigravityPatchTarget(target, vendorEntries) {
if (typeof target !== "string" || !Object.hasOwn(ANTIGRAVITY_PATCH_TARGETS, target)) fail("unsupported native target");
if (!Array.isArray(vendorEntries) || vendorEntries.length !== RUNTIME_FILES.length || vendorEntries.some((entry, index) => entry?.path !== RUNTIME_FILES[index] || !SHA256.test(entry.sha256))) fail("explicit verified vendor entries are required");
return { target, ...ANTIGRAVITY_PATCH_TARGETS[target], serverSha256: vendorEntries[0].sha256, harnessSha256: vendorEntries[1].sha256 };
}
/** Generated identity module: the helper digest comes from the verified closure
* manifest, so one owned admission source serves every platform. */
export function antigravityNativeIdentitySource(harnessSha256) {
if (!SHA256.test(harnessSha256)) fail("invalid native helper digest");
return Buffer.from(`"""Generated by Paperclip's native patch from the verified closure manifest."""\nHELPER_SHA256 = "${harnessSha256}"\n`);
}
export function antigravityParSection(bytes, cpuType = ANTIGRAVITY_PATCH_TARGETS["darwin-arm64"].cpuType) {
if (!Buffer.isBuffer(bytes) || bytes.length < 32 || bytes.readUInt32LE(0) !== 0xfeedfacf || bytes.readUInt32LE(4) !== cpuType) fail("expected the pinned ARM64 Mach-O executable");
const commandCount = bytes.readUInt32LE(16);
let cursor = 32;
const sections = [];
for (let index = 0; index < commandCount; index++) {
if (cursor + 8 > bytes.length) fail("truncated Mach-O command");
const command = bytes.readUInt32LE(cursor);
const size = bytes.readUInt32LE(cursor + 4);
if (size < 8 || cursor + size > bytes.length) fail("invalid Mach-O command bounds");
if (command === 0x19) {
if (size < 72) fail("truncated Mach-O segment");
const count = bytes.readUInt32LE(cursor + 64);
if (72 + count * 80 > size) fail("invalid Mach-O sections");
for (let section = 0; section < count; section++) {
const offset = cursor + 72 + section * 80;
if (bytes.subarray(offset, offset + 16).toString("utf8").split("\0")[0] !== ".par_data") continue;
const length = Number(bytes.readBigUInt64LE(offset + 40));
const start = bytes.readUInt32LE(offset + 48);
if (!Number.isSafeInteger(length) || length < 22 || start + length > bytes.length) fail("invalid embedded Python archive bounds");
sections.push({ start, length });
}
}
cursor += size;
}
if (sections.length !== 1) fail("expected exactly one embedded Python archive");
return sections[0];
}
/** The Linux launcher is a 64-bit little-endian ELF executable whose last
* file bytes are a `.par_data` section holding the Python ZIP. Its offsets are
* relative to the section start; every other byte stays unchanged. */
export function antigravityElfArchive(bytes, machine) {
if (!Buffer.isBuffer(bytes) || bytes.length < 64 || bytes.readUInt32BE(0) !== 0x7f454c46 || bytes[4] !== 2 || bytes[5] !== 1 || bytes[6] !== 1
|| ![2, 3].includes(bytes.readUInt16LE(16)) || bytes.readUInt16LE(18) !== machine) fail("expected the pinned 64-bit ELF executable");
const programOffset = Number(bytes.readBigUInt64LE(32));
const sectionOffset = Number(bytes.readBigUInt64LE(40));
const programSize = bytes.readUInt16LE(54), programCount = bytes.readUInt16LE(56);
const sectionSize = bytes.readUInt16LE(58), sectionCount = bytes.readUInt16LE(60), namesIndex = bytes.readUInt16LE(62);
if (programSize !== 56 || sectionSize !== 64 || !programCount || namesIndex >= sectionCount || !Number.isSafeInteger(programOffset) || !Number.isSafeInteger(sectionOffset)
|| programOffset + programCount * programSize > bytes.length || sectionOffset + sectionCount * sectionSize > bytes.length) fail("invalid ELF header bounds");
const range = header => {
const start = Number(bytes.readBigUInt64LE(header + 24)), length = Number(bytes.readBigUInt64LE(header + 32));
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(length) || start + length > bytes.length) fail("invalid ELF section bounds");
return { start, length };
};
const names = range(sectionOffset + namesIndex * sectionSize);
const sections = [];
let otherEnd = Math.max(64, programOffset + programCount * programSize, sectionOffset + sectionCount * sectionSize);
for (let index = 0; index < sectionCount; index++) {
const header = sectionOffset + index * sectionSize;
const nameOffset = bytes.readUInt32LE(header);
const nameEnd = bytes.indexOf(0, names.start + nameOffset);
if (nameOffset >= names.length || nameEnd < 0 || nameEnd > names.start + names.length) fail("invalid ELF section name");
const bounds = range(header);
if (bytes.subarray(names.start + nameOffset, nameEnd).toString("latin1") === ".par_data") {
if (bytes.readUInt32LE(header + 4) !== 1) fail("invalid embedded Python archive section");
sections.push(bounds);
} else if (bytes.readUInt32LE(header + 4) !== 8) otherEnd = Math.max(otherEnd, bounds.start + bounds.length); // SHT_NOBITS has no file bytes.
}
for (let index = 0; index < programCount; index++) {
const header = programOffset + index * programSize;
const end = Number(bytes.readBigUInt64LE(header + 8)) + Number(bytes.readBigUInt64LE(header + 32));
if (!Number.isSafeInteger(end) || end > bytes.length) fail("invalid ELF segment bounds");
otherEnd = Math.max(otherEnd, end);
}
if (sections.length !== 1) fail("expected exactly one embedded Python archive");
const [section] = sections;
if (section.length < 22 || section.start < otherEnd || section.start + section.length !== bytes.length) fail("invalid embedded Python archive bounds");
return section;
}
export function antigravityEmbeddedArchive(bytes, target) {
return target.format === "macho" ? antigravityParSection(bytes, target.cpuType) : antigravityElfArchive(bytes, target.machine);
}
const crcTable = Array.from({ length: 256 }, (_, index) => {
let value = index;
for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ ((value & 1) ? 0xedb88320 : 0);
return value >>> 0;
});
function crc32(bytes) {
let value = 0xffffffff;
for (const byte of bytes) value = (value >>> 8) ^ crcTable[(value ^ byte) & 0xff];
return (value ^ 0xffffffff) >>> 0;
}
/** Operates only after the complete vendor executable's SHA-256 is verified. */
export function antigravityEmbeddedZip(bytes) {
const end = bytes.length - 22;
if (end < 0 || bytes.readUInt32LE(end) !== 0x06054b50 || bytes.readUInt16LE(end + 4) || bytes.readUInt16LE(end + 6) || bytes.readUInt16LE(end + 20)) fail("unsupported embedded ZIP ending");
const count = bytes.readUInt16LE(end + 10);
const centralOffset = bytes.readUInt32LE(end + 16);
if (bytes.readUInt16LE(end + 8) !== count || centralOffset + bytes.readUInt32LE(end + 12) !== end) fail("invalid embedded ZIP index");
const entries = [];
const names = new Set();
let cursor = centralOffset;
for (let index = 0; index < count; index++) {
if (cursor + 46 > end || bytes.readUInt32LE(cursor) !== 0x02014b50) fail("invalid embedded ZIP entry");
const flags = bytes.readUInt16LE(cursor + 8);
const method = bytes.readUInt16LE(cursor + 10);
const compressedLength = bytes.readUInt32LE(cursor + 20);
const length = bytes.readUInt32LE(cursor + 24);
const nameLength = bytes.readUInt16LE(cursor + 28);
const extraLength = bytes.readUInt16LE(cursor + 30);
const commentLength = bytes.readUInt16LE(cursor + 32);
const local = bytes.readUInt32LE(cursor + 42);
const next = cursor + 46 + nameLength + extraLength + commentLength;
if (next > end || (flags & ~0x800) || ![0, 8].includes(method) || local + 30 > centralOffset || bytes.readUInt32LE(local) !== 0x04034b50) fail("unsupported embedded ZIP entry");
const name = bytes.subarray(cursor + 46, cursor + 46 + nameLength).toString("utf8");
if (names.has(name) || !Buffer.from(name).equals(bytes.subarray(cursor + 46, cursor + 46 + nameLength))) fail("duplicate or invalid embedded ZIP name");
names.add(name);
const dataStart = local + 30 + bytes.readUInt16LE(local + 26) + bytes.readUInt16LE(local + 28);
if (dataStart + compressedLength > centralOffset) fail("invalid embedded ZIP payload bounds");
entries.push({ name, method, length, checksum: bytes.readUInt32LE(cursor + 16), localHeader: bytes.subarray(local, dataStart), payload: bytes.subarray(dataStart, dataStart + compressedLength), central: bytes.subarray(cursor, next) });
cursor = next;
}
if (cursor !== end) fail("invalid embedded ZIP index length");
return entries;
}
function content(entry) {
const value = entry.method === 8 ? inflateRawSync(entry.payload, { maxOutputLength: entry.length }) : entry.payload;
if (value.length !== entry.length || crc32(value) !== entry.checksum) fail("embedded source integrity mismatch");
return value;
}
function storedEntry(name, value) {
const filename = Buffer.from(name);
const checksum = crc32(value);
const localHeader = Buffer.alloc(30 + filename.length);
localHeader.writeUInt32LE(0x04034b50);
localHeader.writeUInt16LE(20, 4);
localHeader.writeUInt16LE(33, 12); // 1980-01-01, stable ZIP date.
localHeader.writeUInt32LE(checksum, 14);
localHeader.writeUInt32LE(value.length, 18);
localHeader.writeUInt32LE(value.length, 22);
localHeader.writeUInt16LE(filename.length, 26);
filename.copy(localHeader, 30);
const central = Buffer.alloc(46 + filename.length);
central.writeUInt32LE(0x02014b50);
central.writeUInt16LE(0x314, 4);
central.writeUInt16LE(20, 6);
central.writeUInt16LE(33, 14);
central.writeUInt32LE(checksum, 16);
central.writeUInt32LE(value.length, 20);
central.writeUInt32LE(value.length, 24);
central.writeUInt16LE(filename.length, 28);
central.writeUInt32LE((0o100644 << 16) >>> 0, 38);
filename.copy(central, 46);
return { name, method: 0, length: value.length, checksum, localHeader, payload: value, central };
}
export function replaceAntigravitySource(source, needle, replacement) {
if (source.split(needle).length !== 2) fail("pinned native source anchor changed");
return source.replace(needle, replacement);
}
export function antigravityPatchedSources(server, sdk, eventProcessor) {
replaceAntigravitySource(server, "class AgyAdapter(Agent):", "class AgyAdapter(Agent):");
server = replaceAntigravitySource(server,
` # Immediately flush open tool calls on error step (validation/execution
# failure).
if step.status == sdk_types_module.StepStatus.ERROR:
if open_tool_calls:
logging.warning(
"Step error encountered; flushing open tool calls: %s. Error: %s",
open_tool_calls,
step.error,
)
for tc_id in list(open_tool_calls):
open_tool_calls.pop(tc_id, None)
await self._client.session_update(
session_id=session_id,
update=schema.ToolCallProgress(
session_update="tool_call_update",
tool_call_id=tc_id,
raw_output=step.error or "Tool execution failed",
status="failed",
),
)
`,
` # A step error belongs only to that step's tool calls. The terminal block
# below resolves their execution/permission identities. Unattributed errors
# remain diagnostics; turn cleanup still settles unfinished work.
if step.status == sdk_types_module.StepStatus.ERROR:
logging.warning(
"Step error encountered for %s. Error: %s", step.id, step.error
)
from google3.cloud.developer_experience.antigravity_extensions.acp_server import paperclip_admission as paperclip_turn
paperclip_turn.observe_step(step)
`,
);
server += "\n\n# Paperclip's owned admission patch, applied to this pinned release only.\nfrom google3.cloud.developer_experience.antigravity_extensions.acp_server import paperclip_admission\npaperclip_admission.install(AgyAdapter)\n";
sdk = replaceAntigravitySource(sdk,
" harness_config = self._build_harness_config()\n process, ws, ws_url = await self._spawn_harness_and_connect_ws()",
" harness_config = self._build_harness_config()\n from google3.cloud.developer_experience.antigravity_extensions.acp_server import paperclip_admission\n paperclip_prepared = paperclip_admission.prepare_native_config(harness_config, self)\n process, ws, ws_url = await self._spawn_harness_and_connect_ws()",
);
sdk = replaceAntigravitySource(sdk,
" init_resp = init_resp_event.initialize_conversation_response\n parsed = event_processor.parse_initialize_response(init_resp)",
" self._paperclip_native_admission = paperclip_admission.acknowledge_native_config(paperclip_prepared, init_resp_event, harness_config)\n init_resp = init_resp_event.initialize_conversation_response\n parsed = event_processor.parse_initialize_response(init_resp)",
);
eventProcessor = replaceAntigravitySource(eventProcessor,
` result = await self._execute_client_tool(tc)
if result is not None:
await self._send_tool_results([result])
`,
` result = await self._execute_client_tool(tc)
if result is not None:
# Native StepUpdate events suppress local custom-tool identities. Close
# ACP file callbacks from their actual result, preserving the same id.
client_file_result = tc.name in {
"client_view_file", "client_create_file", "client_edit_file"
}
if client_file_result and (
result.id != tc.id or result.step_id != tc.step_id
):
raise ValueError("Client file result identity differs from its call")
await self._send_tool_results([result])
if client_file_result:
await self.step_queue.put(tool_call_step.model_copy(update={
"status": types.StepStatus.ERROR
if result.error is not None else types.StepStatus.DONE,
"content": result.result if isinstance(result.result, str) else "",
"error": result.error or "",
"tool_calls": [tc],
}))
`,
);
return { server, sdk, eventProcessor };
}
function rebuildZip(entries, length) {
const paddingName = "paperclip_native_patch_padding";
const used = entries.reduce((total, entry) => total + entry.localHeader.length + entry.payload.length + entry.central.length, 0);
const paddingLength = length - used - 22 - 30 - 46 - Buffer.byteLength(paddingName) * 2;
if (paddingLength < 0 || entries.length + 1 > 0xffff) fail("patched source exceeds the pinned native section");
entries = [...entries, storedEntry(paddingName, Buffer.alloc(paddingLength))];
const locals = [];
const centrals = [];
let offset = 0;
for (const entry of entries) {
const central = Buffer.from(entry.central);
central.writeUInt32LE(offset, 42);
locals.push(entry.localHeader, entry.payload);
centrals.push(central);
offset += entry.localHeader.length + entry.payload.length;
}
const central = Buffer.concat(centrals);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50);
end.writeUInt16LE(entries.length, 8);
end.writeUInt16LE(entries.length, 10);
end.writeUInt32LE(central.length, 12);
end.writeUInt32LE(offset, 16);
const result = Buffer.concat([...locals, central, end]);
if (result.length !== length) fail("patched section size changed");
return result;
}
/** Verifies the complete vendor executable before decoding it. The buffer is
* patched in place, so large Linux builds need only one copy in memory. */
export function patchAntigravityServerBytes(server, admissionSource, target) {
if (!target || !Object.hasOwn(ANTIGRAVITY_PATCH_TARGETS, target.target ?? "") || !SHA256.test(target.serverSha256 ?? "") || !SHA256.test(target.harnessSha256 ?? "")) fail("explicit verified native target is required");
if (!Buffer.isBuffer(server) || digest(server) !== target.serverSha256) fail("official server SHA-256 mismatch");
const section = antigravityEmbeddedArchive(server, target);
const entries = antigravityEmbeddedZip(server.subarray(section.start, section.start + section.length));
const byName = new Map(entries.map(entry => [entry.name, entry]));
if (!byName.has(SERVER_SOURCE) || !byName.has(SDK_SOURCE) || !byName.has(EVENT_PROCESSOR_SOURCE) || byName.has(ADMISSION_SOURCE) || byName.has(IDENTITY_SOURCE) || [...REMOVED_BYTECODE].some(name => !byName.has(name))) fail("pinned Python runtime layout changed");
const patched = antigravityPatchedSources(content(byName.get(SERVER_SOURCE)).toString("utf8"), content(byName.get(SDK_SOURCE)).toString("utf8"), content(byName.get(EVENT_PROCESSOR_SOURCE)).toString("utf8"));
const replacements = new Map([[SERVER_SOURCE, Buffer.from(patched.server)], [SDK_SOURCE, Buffer.from(patched.sdk)], [EVENT_PROCESSOR_SOURCE, Buffer.from(patched.eventProcessor)]]);
const updated = entries.filter(entry => !REMOVED_BYTECODE.has(entry.name)).map(entry => replacements.has(entry.name) ? storedEntry(entry.name, replacements.get(entry.name)) : entry);
updated.push(storedEntry(ADMISSION_SOURCE, admissionSource), storedEntry(IDENTITY_SOURCE, antigravityNativeIdentitySource(target.harnessSha256)));
// rebuildZip copies every retained entry before the original bytes change.
const archive = rebuildZip(updated, section.length);
archive.copy(server, section.start);
return server;
}
/** Explicit install step; uses Node built-ins, plus the macOS signing tool for a macOS target. */
export async function patchAntigravityRuntime({ source, destination, target: targetName, vendorEntries } = {}) {
const target = antigravityPatchTarget(targetName, vendorEntries);
if (target.signed && process.platform !== "darwin") fail("a macOS target must be patched and signed on macOS");
if (!source || !destination) fail("explicit source and destination directories are required");
const original = resolve(source);
const destinationPath = resolve(destination);
const serverPath = join(original, "agy_acp_server.par");
const harnessPath = join(original, "localharness_external");
for (const file of [serverPath, harnessPath]) {
const stat = await lstat(file);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) fail("vendor closure contains links or special files");
}
const [harness, admission] = await Promise.all([readFile(harnessPath), readFile(new URL("./patch-antigravity-runtime.admission.py", import.meta.url))]);
if (digest(harness) !== target.harnessSha256) fail("official helper SHA-256 mismatch");
const patched = patchAntigravityServerBytes(await readFile(serverPath), admission, target);
const unsignedServerSha256 = digest(patched);
await mkdir(dirname(destinationPath), { recursive: true, mode: 0o700 });
try { await lstat(destinationPath); fail("destination exists; refusing to replace a runtime"); }
catch (error) { if (error.code !== "ENOENT") throw error; }
const temporary = await mkdtemp(join(dirname(destinationPath), ".antigravity-native-patch-"));
try {
const executable = join(temporary, "agy_acp_server.par");
await writeFile(executable, patched, { mode: 0o700 });
if (target.signed) {
execFileSync("/usr/bin/codesign", ["--force", "--sign", "-", "--timestamp=none", executable], { stdio: "pipe", timeout: 30_000 });
execFileSync("/usr/bin/codesign", ["--verify", "--strict", executable], { stdio: "pipe", timeout: 30_000 });
}
await writeFile(join(temporary, "localharness_external"), harness, { mode: 0o555 });
await chmod(executable, 0o555);
await chmod(join(temporary, "localharness_external"), 0o555);
const serverSha256 = target.signed ? digest(await readFile(executable)) : unsignedServerSha256;
const result = { schema: ANTIGRAVITY_PATCH_SCHEMA, version: ANTIGRAVITY_PATCH_VERSION, target: target.target, sourceServerSha256: target.serverSha256, sourceHarnessSha256: target.harnessSha256, admissionSourceSha256: digest(admission), unsignedServerSha256, serverSha256, harnessSha256: target.harnessSha256 };
await rename(temporary, destinationPath);
return result;
} catch (error) {
await rm(temporary, { recursive: true, force: true });
throw error;
}
}