From 93c85c3b10154d2d703e2003e9c0edb0cca73a11 Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:46:10 +0900 Subject: [PATCH 1/2] Bound host tool arguments received from Antigravity ACP --- .../content/docs/guides/api-key-catalog.md | 2 ++ src/adapters/agy-acp/adapter.ts | 6 +++- src/adapters/agy-acp/client-tools.ts | 5 +++ src/lib/json-byte-size.ts | 15 ++++++--- structure/adapters/registry.md | 2 ++ structure/transports/byte-accounting.md | 3 ++ tests/adapters/agy-acp-adapter.test.ts | 31 +++++++++++++++++-- tests/lib/json-byte-size.test.ts | 7 +++++ 8 files changed, 64 insertions(+), 7 deletions(-) diff --git a/docs-site/src/content/docs/guides/api-key-catalog.md b/docs-site/src/content/docs/guides/api-key-catalog.md index 3479e5bde6c..53034225151 100644 --- a/docs-site/src/content/docs/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/guides/api-key-catalog.md @@ -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, diff --git a/src/adapters/agy-acp/adapter.ts b/src/adapters/agy-acp/adapter.ts index ceebac6ed7e..4febbd8babf 100644 --- a/src/adapters/agy-acp/adapter.ts +++ b/src/adapters/agy-acp/adapter.ts @@ -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 }); diff --git a/src/adapters/agy-acp/client-tools.ts b/src/adapters/agy-acp/client-tools.ts index ceda4c24945..be77a3d21d4 100644 --- a/src/adapters/agy-acp/client-tools.ts +++ b/src/adapters/agy-acp/client-tools.ts @@ -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) { @@ -32,6 +36,7 @@ export async function stageClientTools(parsed: OcxParsedRequest, tmp: string) { const args = { ...input } as Record; 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 }, diff --git a/src/lib/json-byte-size.ts b/src/lib/json-byte-size.ts index f42c33acae7..8dc170114ef 100644 --- a/src/lib/json-byte-size.ts +++ b/src/lib/json-byte-size.ts @@ -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); @@ -64,7 +68,11 @@ export function jsonUtf8Bytes(value: unknown, limit = TRANSLATOR_MAX_TURN_BYTES) | { readonly array: readonly unknown[]; index: number } | { readonly object: Record; 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; } @@ -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; diff --git a/structure/adapters/registry.md b/structure/adapters/registry.md index 674fab8fbc8..ee49ba8c118 100644 --- a/structure/adapters/registry.md +++ b/structure/adapters/registry.md @@ -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 diff --git a/structure/transports/byte-accounting.md b/structure/transports/byte-accounting.md index 60cdcfb7d65..892662401fa 100644 --- a/structure/transports/byte-accounting.md +++ b/structure/transports/byte-accounting.md @@ -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 diff --git a/tests/adapters/agy-acp-adapter.test.ts b/tests/adapters/agy-acp-adapter.test.ts index 071b9f8cd2a..159bd3f7e7e 100644 --- a/tests/adapters/agy-acp-adapter.test.ts +++ b/tests/adapters/agy-acp-adapter.test.ts @@ -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 { @@ -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 }); diff --git a/tests/lib/json-byte-size.test.ts b/tests/lib/json-byte-size.test.ts index b6bf8a9f635..66627551d20 100644 --- a/tests/lib/json-byte-size.test.ts +++ b/tests/lib/json-byte-size.test.ts @@ -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); From 54c60256b932bb093e32c0cbe5c6b7b6b30bd86f Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:11:43 +0900 Subject: [PATCH 2/2] docs(agy-acp): align Spanish tool argument limits --- docs-site/src/content/docs/es/guides/api-key-catalog.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs-site/src/content/docs/es/guides/api-key-catalog.md b/docs-site/src/content/docs/es/guides/api-key-catalog.md index 8e8d21d43e7..e48007b2035 100644 --- a/docs-site/src/content/docs/es/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/es/guides/api-key-catalog.md @@ -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.