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
2 changes: 2 additions & 0 deletions docs-site/src/content/docs/es/guides/api-key-catalog.md
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,8 @@ OpenCodex puede usar una suscripción de Google Antigravity a través de la prop

En un chat interactivo de Codex, Gemini puede solicitar las herramientas que ofrece ese chat, incluidas las del proyecto y las aplicaciones conectadas. Codex ejecuta la llamada con sus permisos habituales y devuelve el resultado en el mismo chat. Los adjuntos y las imágenes devueltas por herramientas como `view_image` requieren entrada de imágenes tanto en la configuración del modelo de Codex como en la sesión ACP.

Los argumentos de cada llamada a una herramienta pueden ocupar hasta 2 MiB una vez serializados en UTF-8, con un máximo de 64 niveles de profundidad y 10 000 valores JSON. Si se supera cualquiera de estos límites, el turno actual termina con el código `agy_acp_protocol`.

- **Requisitos:** Antigravity CLI 1.5.3 o posterior en `PATH` (o `OPENCODEX_AGY_BIN` con su ruta absoluta), con la sesión iniciada una vez en el host del proxy mediante `agy acp --login` o una sesión interactiva de `agy`. Si falla el inicio de sesión antes de comenzar la respuesta, la respuesta HTTP es 401 con el código `agy_login_required`. Si la respuesta ya se está transmitiendo, el flujo de eventos incluye `agy_login_required`.
- **Sin credenciales guardadas:** la CLI es dueña de su inicio de sesión de Google. OpenCodex nunca lo lee, lo guarda ni lo reenvía, y la fila rechaza una clave API, un grupo de claves, la conmutación de cuentas o un ajuste OAuth. Hay una sola cuenta, la de la CLI, y no hay rotación. Al seleccionar este preajuste en `ocx init`, se omite la pregunta sobre la clave API. `ocx login antigravity-acp` muestra el comando para iniciar sesión en el host.
- **Solo uso interactivo:** las respuestas del personal de Google en el foro de desarrolladores permiten que una aplicación personal inicie el binario oficial `agy acp` para la propia cuenta del usuario cuando el uso es interactivo y dirigido por el usuario, no un grupo de trabajadores desatendido ni un bucle de agente automatizado, y remiten las cargas programáticas a una clave API de Gemini o a Vertex AI ([respuesta del foro](https://discuss.ai.google.dev/t/tos-clarification-is-t3-code-official-antigravity-acp-agent-permitted-under-the-antigravity-terms-of-service/192027/2), [respuesta del foro](https://discuss.ai.google.dev/t/policy-question-omp-hosting-unmodified-antigravity-acp-for-one-user/199753)). OpenCodex aplica lo que puede saber con certeza: rechaza con HTTP 403 `agy_acp_interactive_only` un turno de subagente de Codex (`x-codex-parent-thread-id`), un turno que Codex marca como hilo generado o como su proceso de memoria, un miembro de combo, la llamada interna de decisión de un combo y una ruta elegida por la reserva de subagentes, y la configuración rechaza este proveedor como destino de combo, como `decisionModel` de un combo, como reserva de subagentes, como modelo predeterminado de subagentes administrados, como destino de compactación automática, como fase de `memoryModels` o como destino de `shadowCallIntercept`. La compactación manual sí admite ACP.
Expand Down
2 changes: 2 additions & 0 deletions docs-site/src/content/docs/guides/api-key-catalog.md
Original file line number Diff line number Diff line change
Expand Up @@ -915,6 +915,8 @@ once per turn and talks to it over the Agent Client Protocol on stdin and stdout

In an interactive Codex chat, Gemini can request tools advertised by that chat, including project tools and connected apps. Codex executes the call with its usual approvals and returns the result in the same chat. Inline attachments and images returned by tools such as `view_image` require image input in both the selected Codex model entry and the ACP session.

Each tool call accepts arguments up to 2 MiB of serialized UTF-8, 64 levels deep and 10,000 JSON values. A call that exceeds a limit ends the current turn with `agy_acp_protocol`.

- **Prerequisites:** Antigravity CLI 1.5.3 or newer on `PATH` (or `OPENCODEX_AGY_BIN` set to its absolute path),
signed in once on the proxy host with `agy acp --login` or an interactive `agy` session. A sign-in failure returns
HTTP 401 with code `agy_login_required` before the response starts. If the response is already streaming,
Expand Down
6 changes: 5 additions & 1 deletion src/adapters/agy-acp/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,11 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep
return;
}
sawFrame = true;
handle(parsedFrame);
try {
handle(parsedFrame);
} catch {
fail("agy_acp_protocol", "malformed frame");
}
}

incoming.abortSignal?.addEventListener("abort", onAbort, { once: true });
Expand Down
5 changes: 5 additions & 0 deletions src/adapters/agy-acp/client-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@ import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { randomUUID } from "node:crypto";
import type { AdapterEvent, OcxParsedRequest } from "../../types";
import { jsonUtf8Bytes } from "../../lib/json-byte-size";
import { TRANSLATOR_MAX_CALL_ARGUMENT_BYTES } from "../../lib/translator-budget";
import { buildCodeBuddyToolBridge, CODEBUDDY_MCP_TOOL_PREFIX, CODEBUDDY_MCP_SERVER_NAME } from "../codebuddy/tool-bridge";
import { codeBuddyMcpInvocation } from "../coding-agent/turn";

const TOOL_ARGUMENT_SHAPE = { maxDepth: 64, maxNodes: 10_000 };

// Adapt the capture-only MCP transport from OpenCodex PR 8776. The client
// executes the resulting structured call with its regular sandbox and approvals.
export async function stageClientTools(parsed: OcxParsedRequest, tmp: string) {
Expand All @@ -32,6 +36,7 @@ export async function stageClientTools(parsed: OcxParsedRequest, tmp: string) {
const args = { ...input } as Record<string, unknown>;
const props = tool.schema.properties;
if (!(props && typeof props === "object" && Object.hasOwn(props, "toolSummary"))) delete args.toolSummary;
jsonUtf8Bytes(args, TRANSLATOR_MAX_CALL_ARGUMENT_BYTES, TOOL_ARGUMENT_SHAPE);
// Each ACP session may number calls starting at one. Responses ids must be unique across sessions.
return { id: call.toolCallId, events: [
{ type: "tool_call_start", id: "call_" + randomUUID(), name: tool.wire },
Expand Down
15 changes: 11 additions & 4 deletions src/lib/json-byte-size.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,12 @@ export function jsonStringPartsUtf8Bytes(parts: readonly string[], limit = TRANS
return bytes;
}

/** Measure plain JSON data without allocating its serialized string or UTF-8 copy. */
export function jsonUtf8Bytes(value: unknown, limit = TRANSLATOR_MAX_TURN_BYTES): number {
/** Measure plain JSON data without allocating its serialized string or UTF-8 copy. The root is depth zero. */
export function jsonUtf8Bytes(
value: unknown,
limit = TRANSLATOR_MAX_TURN_BYTES,
shape?: { maxDepth: number; maxNodes: number },
): number {
let bytes = 0;
const add = (count: number) => {
if (count > limit - bytes) throw new TranslatorBudgetExceededError("request_copies", limit);
Expand Down Expand Up @@ -64,7 +68,11 @@ export function jsonUtf8Bytes(value: unknown, limit = TRANSLATOR_MAX_TURN_BYTES)
| { readonly array: readonly unknown[]; index: number }
| { readonly object: Record<string, unknown>; readonly keys: readonly string[]; index: number; first: boolean };
const stack: Frame[] = [];
let nodes = 0;
const visit = (item: unknown): void => {
if (shape && (++nodes > shape.maxNodes || stack.length > shape.maxDepth)) {
throw new RangeError("JSON data exceeds structural limits");
}
if (item === null) { add(4); return; }
if (typeof item === "string") { string(item); return; }
if (typeof item === "boolean") { add(item ? 4 : 5); return; }
Expand All @@ -85,8 +93,7 @@ export function jsonUtf8Bytes(value: unknown, limit = TRANSLATOR_MAX_TURN_BYTES)
const index = frame.index++;
if (index > 0) add(1);
const element = frame.array[index];
if (element === undefined) add(4);
else visit(element);
visit(element ?? null);
continue;
}
let field: unknown;
Expand Down
2 changes: 2 additions & 0 deletions structure/adapters/registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ The shared `src/adapters/coding-agent/turn.ts` calls the synchronous `IncomingMe
until it has a session ID and accepts updates only for that session. Permission requests are answered `cancelled`.
Caller-advertised tools use the capture-only CodeBuddy MCP helper. Each leg returns at most one
matching call to the host after child cleanup; the host executes it under its own tool permissions.
Both argument aliases are limited to depth 64, 10,000 JSON values, and 2 MiB of serialized UTF-8.
A frame handling error fails the current turn through the usual child cleanup.
Updates are tracked by call ID so a same-batch failure or non-permission cancellation drops a pending call.
Inline user and tool-result images require ACP image capability and enforce per-image and aggregate
encoded byte limits before sending `session/prompt`. Text replay under pressure keeps
Expand Down
3 changes: 3 additions & 0 deletions structure/transports/byte-accounting.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ Its raw leg, reconstruction and appended replay history use independent local co
charged to the request translator budget when supplied by delivery or empty-completion retry.
These charges do not borrow the bridge's WeakMap event leases or the parser's call leases.

ACP host-tool capture uses the iterative JSON byte counter with depth and value-count limits
before serializing arguments for the host. The [adapter contract](../adapters/registry.md) defines the limits.

Native Ollama late-output attribution uses `src/lib/json-byte-size.ts` to count the
parts as one JSON string before constructing its caption. The exact count includes
one pair of quotes, escaping, UTF-8 and surrogate pairs spanning parts, without a
Expand Down
31 changes: 29 additions & 2 deletions tests/adapters/agy-acp-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import * as fsPromises from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { PassThrough } from "node:stream";
import { TRANSLATOR_MAX_CALL_ARGUMENT_BYTES } from "../../src/lib/translator-budget";
import { createAgyAcpAdapter, AGY_ACP_ARGS, type AgyAcpDeps } from "../../src/adapters/agy-acp/adapter";
import { clearAgyVersionCacheForTests } from "../../src/adapters/agy-acp/binary";
import {
Expand Down Expand Up @@ -1147,18 +1148,44 @@ describe("host tools and multimodal replay", () => {
}
const call = { toolCallId: "local-1", name: "mcp_opencodex_read_fixture", rawInput: { toolSummary: "Read fixture" } };

test("enforces the host argument limits on both ACP call paths and cleans up the turn", async () => {
let nested: unknown = null;
for (let depth = 0; depth < 64; depth++) nested = [nested];
const cases = [
{ rawInput: { items: nested } },
{ rawInput: { items: Array(10_000).fill(null) } },
{ args: { text: "x".repeat(TRANSLATOR_MAX_CALL_ARGUMENT_BYTES) } },
];
for (const args of cases) {
const result = await run(script((frame, api) => {
if (frame.method !== "session/prompt") return;
const toolCall = { toolCallId: call.toolCallId, name: call.name, ...args };
if ("args" in args) api.request(101, "session/request_permission", { sessionId: "s1", toolCall });
else api.notify({ sessionUpdate: "tool_call", ...toolCall });
return true;
}), { parsed: withTool(), deps: { createWorkspace: () => createTurnWorkspace(tmpdir() + "/test-home") } });
expect(terminal(result)).toMatchObject([{ type: "error", code: "agy_acp_protocol" }]);
expect(result.events.some(event => event.type === "tool_call_start")).toBe(false);
expect(existsSync(result.cwd)).toBe(false);
}
});

test("returns a declared call to the host after cleanup and replays its image result alongside the attachment", async () => {
const request = withTool();
const first = await run(script((frame, api) => {
if (frame.method !== "session/prompt") return;
api.request(101, "session/request_permission", { sessionId: "s1", toolCall: call });
api.request(101, "session/request_permission", { sessionId: "s1", toolCall: {
...call, rawInput: { ...call.rawInput, rows: [{ text: "café", ready: false }, null] },
} });
return true;
}), { parsed: request, deps: { createWorkspace: () => createTurnWorkspace(tmpdir() + "/test-home") } });
expect(existsSync(first.cwd)).toBe(false);
expect(first.sent.find(frame => frame.id === 101)?.result).toEqual({ outcome: { outcome: "cancelled" } });
const start = first.events.find(event => event.type === "tool_call_start");
expect(start?.name).toBe(tool.name);
expect(first.events.find(event => event.type === "tool_call_delta")).toMatchObject({ arguments: "{}" });
expect(first.events.find(event => event.type === "tool_call_delta")).toMatchObject({
arguments: JSON.stringify({ rows: [{ text: "café", ready: false }, null] }),
});
expect(terminal(first)).toMatchObject([{ type: "done", stopReason: "tool_use" }]);

const image = (data: string) => ({ type: "image" as const, imageUrl: "data:image/png;base64," + data });
Expand Down
7 changes: 7 additions & 0 deletions tests/lib/json-byte-size.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ describe("jsonUtf8Bytes", () => {
expect(reads).toBeLessThan(16);
});

test("applies optional depth and node limits to the serialized values, including array holes", () => {
const value = { rows: [undefined, 7], omitted: undefined };
expect(jsonUtf8Bytes(value, 100, { maxDepth: 2, maxNodes: 4 })).toBe(serialized(value));
expect(() => jsonUtf8Bytes(value, 100, { maxDepth: 1, maxNodes: 4 })).toThrow(RangeError);
expect(() => jsonUtf8Bytes(value, 100, { maxDepth: 2, maxNodes: 3 })).toThrow(RangeError);
});

test("rejects non-JSON values, including a top-level undefined", () => {
expect(() => jsonUtf8Bytes(undefined)).toThrow(TypeError);
expect(() => jsonUtf8Bytes({ f: () => 1 })).toThrow(TypeError);
Expand Down
Loading