From 0a5ab73eb7ce16609ee0190d4c453dfd27b338a6 Mon Sep 17 00:00:00 2001 From: dofastted Date: Wed, 2 Dec 2026 00:09:08 +0800 Subject: [PATCH 1/4] fix(gemini): add ACP spec SSOT, 190K truncation alignment, agy 1.5.20 gate, and K2/K4/status fixes 1. Changed files & core intent: - Added `src/config/agy-acp-spec.json` (byte-identical to CRAGGemini `src/acp_spec.json`, SHA-256 `1dd063cb9519d20c3b28b281d2eca4be89e109a4f88bfe3ee6b688d8cf827631`), `scripts/sync-agy-acp-spec.mjs` (`--check` / `--sync-kernel` / `--from-kernel`), and `src/lib/gemini/agy-acp-spec.mjs` (`KIN_AGY_ACP_SPEC_PATH` + dynamic `acp_overrides` + live worker capability resolution). - Wired `routing-config.mjs`, `prompt-normalizer.mjs`, and `gemini-convert.mjs` to the ACP spec SSOT; absorbed `45882715a` Gemini `functionResponse.{response,parts}` control-char hygiene (`sanitizeJsonControlCharsDeep`), K2 FIFO `unconsumedByName` `callId` rewrite, and account-scoped `continuationBinding` orphan exemption. - Aligned 190K truncation (`prompt_overflow_policy: "truncate"` delegates >190KB to CRAGGemini while keeping a 4 MiB OOM guard; `reject` keeps exact limit) and added post-canonicalization admission check in `scheduler.mjs` (passing `routeModel` and `targetAccountId`). - Fixed K4 hidden bugs: `parseGeminiSseFrame` preserves `rawPayload` and parses array-shaped Google RPC `details[].metadata.{retryable,failoverable}`; `scheduler.mjs` decouples worker `attemptRequestId` (`gem_<24hex>`) from client `requestId` with 128-char tail-safe `_a${attempts}` suffix; `error-policy.mjs` classifies `gemini_session_conflict` as `request_protocol` (`circuit: false`). - Enforced/surfaced `min_agy_version = "1.5.20"` and `/status` capability pass-through across `scripts/gemini-host.py`, `scripts/gemini-maintenance.py`, and `src/lib/gemini/direct-client.mjs`; fixed `ControlHandler.send_json_error(..., validation_url=None)` `TypeError` in `scripts/gemini-host.py`; closed Gemini status SSOT gap by surfacing Rust `liveNodeState` `schedulable === false` (`permanent_unschedulable`) in `scheduler.mjs` `environmentRestriction` and `routes.mjs` `environmentView`. 2. Root cause & rejected alternatives: - Root cause: hardcoded Gemini body allowlists/MIMEs/190KB hard-rejects drifted from CRAGGemini, client-reused `X-Request-Id` collided with in-flight slots (409), `parseGeminiSseFrame` dropped `rawPayload` and ignored array RPC `details[]`, `environmentRestriction` ignored Rust `permanent_unschedulable`, and `ControlHandler.send_json_error` lacked the `validation_url` keyword argument passed by `_send_infer_error`. - Rejected alternatives: hard-blocking host startup on `agy < 1.5.20` (breaks rolling upgrades before `--agy-only`); keeping 190KB hard-400 on panel when kernel performs layered truncation; reintroducing legacy JS `unitCircuit` (violates `#2461` Rust SSOT). 3. Verification commands & real results: - `node scripts/sync-agy-acp-spec.mjs --check --kernel-spec /mnt/x/antigravity-cli-proxy-wt-acp-spec-truncation/src/acp_spec.json` -> PASS (`sha256=1dd063cb9519d20c3b28b281d2eca4be89e109a4f88bfe3ee6b688d8cf827631`, `min_agy=1.5.20`, `keys=87`). - `find src scripts -name '*.mjs' -print0 | xargs -0 -n1 node --check` -> PASS (0 errors). - `npx biome check <14 modified .mjs files>` -> PASS (`Checked 14 files in 289ms. No fixes applied.`). - `python3 -m py_compile scripts/gemini-host.py scripts/gemini-maintenance.py` -> PASS. - `python3 test/unit/gemini-host-license-align.py && python3 test/unit/gemini-agy-patch.py && python3 test/unit/gemini-maintenance-runtime-files.py && python3 test/unit/gemini-host-native-smoke.py` -> PASS (all 4 suites OK). - `node --test test/unit/gemini-convert.test.mjs test/unit/gemini-prompt-normalizer.test.mjs test/unit/gemini-scheduling-status.test.mjs test/unit/gemini-maintenance-install-contract.test.mjs` -> PASS (72/72). - `KIN_SCHEDULER_BIN=/mnt/x/vm2api-wt-clean-1424x/bin/kin-scheduler npm run test:ci` -> PASS (13/13 isolated suites). 4. Broken-by-hand evidence: - Temporarily removed `rawPayload: payload,` in `src/lib/protocol/gemini-convert.mjs` (`parseGeminiSseFrame`) -> ran `node --test --test-name-pattern="ACP 190K truncation alignment" test/unit/gemini-convert.test.mjs` -> FAILED (`AssertionError: assert.ok(parsedSse.rawPayload)` at `test/unit/gemini-convert.test.mjs:2808`, exit code 1) -> restored -> re-ran -> PASS (1/1). 5. Unverified / follow-up items: - Live end-to-end verification against a signed CRAGGemini `0.6.4+` payload + `ph24` deployment is deferred until kernel payload release and PR review. - Pre-existing legacy `unitCircuit` assertions in non-CI suites (`gemini-session-conflict.test.mjs:215`, `gemini-foundation.test.mjs:903/949`, `gemini-host.test.mjs:1154/1214`) stem from `origin/dev` `#2461` removing JS `unitCircuit` and were intentionally left untouched outside scope. --- scripts/gemini-host.py | 73 ++++ scripts/gemini-maintenance.py | 30 ++ scripts/sync-agy-acp-spec.mjs | 242 +++++++++++ src/config/agy-acp-spec.json | 147 +++++++ src/lib/gemini/agy-acp-spec.mjs | 397 ++++++++++++++++++ src/lib/gemini/direct-client.mjs | 62 +++ src/lib/gemini/error-policy.mjs | 2 +- src/lib/gemini/prompt-normalizer.mjs | 179 ++++---- src/lib/gemini/routes.mjs | 26 +- src/lib/gemini/routing-config.mjs | 13 + src/lib/gemini/scheduler.mjs | 84 +++- src/lib/protocol/gemini-convert.mjs | 159 ++++++- test/unit/convert-stream.test.mjs | 20 +- test/unit/gemini-convert.test.mjs | 117 +++++- ...mini-maintenance-install-contract.test.mjs | 48 +++ test/unit/gemini-prompt-normalizer.test.mjs | 130 ++++++ test/unit/gemini-scheduling-status.test.mjs | 163 +++++++ 17 files changed, 1768 insertions(+), 124 deletions(-) create mode 100644 scripts/sync-agy-acp-spec.mjs create mode 100644 src/config/agy-acp-spec.json create mode 100644 src/lib/gemini/agy-acp-spec.mjs diff --git a/scripts/gemini-host.py b/scripts/gemini-host.py index 90edafe342..b210d70585 100644 --- a/scripts/gemini-host.py +++ b/scripts/gemini-host.py @@ -63,6 +63,51 @@ def add_slot_counts(total, value): ROOT = Path(__file__).resolve().parents[1] +DEFAULT_MIN_AGY_VERSION = "1.5.20" +_SEMVER_PARTS = re.compile(r"^(\d+)\.(\d+)\.(\d+)(?:-([A-Za-z0-9._-]+))?$") +_ACP_STATUS_PASSTHROUGH_KEYS = ( + "kernel_version", + "agy_version", + "min_agy_version", + "agy_version_compatible", + "acp_spec_sha256", + "max_acp_prompt_text_bytes", + "prompt_overflow_policy", + "extra_allowed_body_keys", +) + + +def _load_min_agy_version(): + spec_path = ROOT / "src/config/agy-acp-spec.json" + try: + data = json.loads(spec_path.read_text(encoding="utf-8")) + val = data.get("min_agy_version") if isinstance(data, dict) else None + if isinstance(val, str) and _SEMVER_PARTS.fullmatch(val.strip()): + return val.strip() + except (OSError, ValueError): + pass + return DEFAULT_MIN_AGY_VERSION + + +MIN_AGY_VERSION = _load_min_agy_version() + + +def parse_semver_tuple(raw): + if not isinstance(raw, str): + return None + m = _SEMVER_PARTS.fullmatch(raw.strip()) + if not m: + return None + major, minor, patch, pre = m.groups() + return (int(major), int(minor), int(patch), pre is None, pre or "") + + +def agy_version_meets_min(version, min_version=MIN_AGY_VERSION): + cur = parse_semver_tuple(version) + req = parse_semver_tuple(min_version) + if cur is None or req is None: + return None + return cur >= req MAX_NETNS_SLOTS = 8 MAX_ENVIRONMENTS = 256 MAX_CONCURRENCY = 64 @@ -9943,6 +9988,31 @@ def _resolve_infer_target(self, body): protocol_capabilities = ( dict(raw_proto_caps) if isinstance(raw_proto_caps, dict) else {} ) + if isinstance(health, dict): + for key in _ACP_STATUS_PASSTHROUGH_KEYS: + if key not in protocol_capabilities and health.get(key) is not None: + protocol_capabilities[key] = health[key] + if "agy_version" not in protocol_capabilities: + detected_agy = self.installed_agy_version() + if detected_agy: + protocol_capabilities["agy_version"] = detected_agy + min_ver = protocol_capabilities.get("min_agy_version") + if not isinstance(min_ver, str) or not parse_semver_tuple(min_ver): + min_ver = MIN_AGY_VERSION + protocol_capabilities["min_agy_version"] = min_ver + if "agy_version_compatible" not in protocol_capabilities and protocol_capabilities.get("agy_version"): + compat = agy_version_meets_min(protocol_capabilities["agy_version"], min_ver) + if compat is not None: + protocol_capabilities["agy_version_compatible"] = compat + if protocol_capabilities.get("agy_version_compatible") is False: + warn_key = (protocol_capabilities.get("agy_version"), min_ver) + if getattr(self, "_agy_min_ver_warned_key", None) != warn_key: + self._agy_min_ver_warned_key = warn_key + print( + f"WARNING: Gemini agy CLI {warn_key[0]} is below minimum supported version {warn_key[1]}; " + "upgrade via fetch-default-gemini.py --agy-only or maintenance update", + file=sys.stderr, + ) return { "direct": True, "kind": "shard" if is_shard else "session", @@ -11560,6 +11630,7 @@ def send_json_error( retryable=None, failoverable=None, upstream_status=None, + validation_url=None, ): if self._headers_sent: return @@ -11580,6 +11651,8 @@ def send_json_error( payload["failoverable"] = failoverable if type(upstream_status) is int and 400 <= upstream_status <= 599: payload["upstream_status"] = upstream_status + if isinstance(validation_url, str) and validation_url.strip(): + payload["validation_url"] = validation_url.strip() retry_after_sec = None if type(retry_after_ms) is int and retry_after_ms > 0: payload["retry_after_ms"] = retry_after_ms diff --git a/scripts/gemini-maintenance.py b/scripts/gemini-maintenance.py index 99f47a55a9..b791e1478a 100644 --- a/scripts/gemini-maintenance.py +++ b/scripts/gemini-maintenance.py @@ -127,6 +127,26 @@ def __init__(self, status, code): r"\Apayload-\d{4}\.\d{2}\.\d{2}-gemini-(\d+\.\d+\.\d+(?:-rc\.\d+)?)\Z" ) MAX_MEMBER = 512 * 1024 * 1024 +DEFAULT_MIN_AGY_VERSION = "1.5.20" + + +def _load_min_agy_version(bundle_dir=None): + candidates = [] + if bundle_dir is not None: + candidates.append(Path(bundle_dir) / "src/config/agy-acp-spec.json") + candidates.append(Path(__file__).resolve().parents[1] / "src/config/agy-acp-spec.json") + for spec_path in candidates: + try: + data = json.loads(spec_path.read_text(encoding="utf-8")) + val = data.get("min_agy_version") if isinstance(data, dict) else None + if isinstance(val, str) and SAFE_VERSION.fullmatch(val.strip()): + return val.strip() + except (OSError, ValueError): + continue + return DEFAULT_MIN_AGY_VERSION + + +MIN_AGY_VERSION = _load_min_agy_version() def fail(code, status=503): @@ -961,6 +981,16 @@ def check(name, status, code=None): else ("warning", "gemini_maintenance_agy_patch_unverified") ) check("agy_patch", agy_patch[0], agy_patch[1]) + min_agy = _load_min_agy_version(self.bundle) + cli_ver = payload.get("cli_version") + if not exists(self.current): + check("agy_version", "warning", "gemini_payload_not_installed") + elif not cli_ver or version_order(cli_ver) is None: + check("agy_version", "warning", "gemini_maintenance_agy_version_unknown") + elif version_order(cli_ver) < version_order(min_agy): + check("agy_version", "warning", "gemini_maintenance_agy_below_min") + else: + check("agy_version", "pass", None) check( "pinned_egress", "pass" if egress_ok else "warning" if egress_ok is None else "fail", diff --git a/scripts/sync-agy-acp-spec.mjs b/scripts/sync-agy-acp-spec.mjs new file mode 100644 index 0000000000..d602aae57e --- /dev/null +++ b/scripts/sync-agy-acp-spec.mjs @@ -0,0 +1,242 @@ +#!/usr/bin/env node +/** + * Validate and sync the Gemini / CRAGGemini ACP protocol SSOT spec + * (`src/config/agy-acp-spec.json`, mirrored byte-identically into + * `antigravity-cli-proxy/src/acp_spec.json`). + * + * Usage: + * # Validate vm2api spec schema & optional cross-repo SHA-256 parity (CI-safe): + * node scripts/sync-agy-acp-spec.mjs --check \ + * [--kernel-spec /path/to/antigravity-cli-proxy/src/acp_spec.json] + * + * # Sync vm2api spec -> CRAGGemini kernel spec: + * node scripts/sync-agy-acp-spec.mjs --sync-kernel /path/to/antigravity-cli-proxy/src/acp_spec.json + * + * # Pull CRAGGemini kernel spec -> vm2api spec: + * node scripts/sync-agy-acp-spec.mjs --from-kernel /path/to/antigravity-cli-proxy/src/acp_spec.json + */ + +import crypto from 'node:crypto' +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const __filename = fileURLToPath(import.meta.url) +const __dirname = path.dirname(__filename) +const REPO_ROOT = path.resolve(__dirname, '..') +const DEFAULT_SPEC_PATH = path.join(REPO_ROOT, 'src', 'config', 'agy-acp-spec.json') + +const SCHEMA_VERSION = 1 +const SEMVER_RE = /^\d+\.\d+\.\d+(?:-[A-Za-z0-9._-]+)?$/ +const FIELD_KEY_RE = /^[A-Za-z0-9_.-]{1,64}$/ +const MIME_RE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,63}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,127}$/ +const MIME_PREFIX_RE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,63}\/$/ +const MIME_SUFFIX_RE = /^\+[a-z0-9][a-z0-9.-]{0,31}$/ + +function sha256Of(buf) { + return crypto.createHash('sha256').update(buf).digest('hex') +} + +function assertStringArray(value, label, { allowEmpty = false, pattern = null } = {}) { + if (!Array.isArray(value)) throw new Error(`${label} must be an array`) + if (!allowEmpty && value.length === 0) throw new Error(`${label} must be non-empty`) + const seen = new Set() + for (const item of value) { + if (typeof item !== 'string' || !item.trim()) { + throw new Error(`${label} entries must be non-empty strings`) + } + if (pattern && !pattern.test(item)) { + throw new Error(`${label} contains invalid entry: ${item}`) + } + if (seen.has(item)) { + throw new Error(`${label} contains duplicate entry: ${item}`) + } + seen.add(item) + } +} + +export function validateAgyAcpSpecObject(spec, sourceLabel = 'agy-acp-spec.json') { + if (!spec || typeof spec !== 'object' || Array.isArray(spec)) { + throw new Error(`${sourceLabel}: root must be a JSON object`) + } + if (spec.schema_version !== SCHEMA_VERSION) { + throw new Error(`${sourceLabel}: schema_version must be ${SCHEMA_VERSION}`) + } + if (typeof spec.min_agy_version !== 'string' || !SEMVER_RE.test(spec.min_agy_version)) { + throw new Error(`${sourceLabel}: invalid min_agy_version`) + } + if (typeof spec.calibrated_agy_version !== 'string' || !SEMVER_RE.test(spec.calibrated_agy_version)) { + throw new Error(`${sourceLabel}: invalid calibrated_agy_version`) + } + + const limits = spec.limits + if (!limits || typeof limits !== 'object' || Array.isArray(limits)) { + throw new Error(`${sourceLabel}: limits must be an object`) + } + if ( + !Number.isInteger(limits.max_acp_prompt_text_bytes) || + limits.max_acp_prompt_text_bytes < 1024 || + limits.max_acp_prompt_text_bytes > 4 * 1024 * 1024 + ) { + throw new Error(`${sourceLabel}: limits.max_acp_prompt_text_bytes out of range`) + } + if (!['truncate', 'reject'].includes(limits.prompt_overflow_policy)) { + throw new Error(`${sourceLabel}: limits.prompt_overflow_policy must be truncate or reject`) + } + if ( + !Number.isInteger(limits.max_system_prompt_append_bytes) || + limits.max_system_prompt_append_bytes < 4096 || + limits.max_system_prompt_append_bytes > 64 * 1024 * 1024 + ) { + throw new Error(`${sourceLabel}: limits.max_system_prompt_append_bytes out of range`) + } + if ( + !Number.isInteger(limits.max_tool_name_chars) || + limits.max_tool_name_chars < 1 || + limits.max_tool_name_chars > 256 + ) { + throw new Error(`${sourceLabel}: limits.max_tool_name_chars out of range`) + } + + const tlf = spec.top_level_fields + if (!tlf || typeof tlf !== 'object' || Array.isArray(tlf)) { + throw new Error(`${sourceLabel}: top_level_fields must be an object`) + } + if (!['reject', 'strip'].includes(tlf.unknown_policy)) { + throw new Error(`${sourceLabel}: top_level_fields.unknown_policy must be reject or strip`) + } + assertStringArray(tlf.allowed_body_keys, `${sourceLabel}: top_level_fields.allowed_body_keys`, { + allowEmpty: false, + pattern: FIELD_KEY_RE, + }) + assertStringArray(tlf.extra_allowed_body_keys, `${sourceLabel}: top_level_fields.extra_allowed_body_keys`, { + allowEmpty: true, + pattern: FIELD_KEY_RE, + }) + + const media = spec.media + if (!media || typeof media !== 'object' || Array.isArray(media)) { + throw new Error(`${sourceLabel}: media must be an object`) + } + assertStringArray(media.allowed_inline_image_mimes, `${sourceLabel}: media.allowed_inline_image_mimes`, { + allowEmpty: false, + pattern: MIME_RE, + }) + assertStringArray(media.decodable_text_mime_prefixes, `${sourceLabel}: media.decodable_text_mime_prefixes`, { + allowEmpty: false, + pattern: MIME_PREFIX_RE, + }) + assertStringArray(media.decodable_text_exact_mimes, `${sourceLabel}: media.decodable_text_exact_mimes`, { + allowEmpty: false, + pattern: MIME_RE, + }) + assertStringArray(media.decodable_text_app_suffixes, `${sourceLabel}: media.decodable_text_app_suffixes`, { + allowEmpty: false, + pattern: MIME_SUFFIX_RE, + }) + + const hygiene = spec.text_hygiene + if (!hygiene || typeof hygiene !== 'object' || Array.isArray(hygiene)) { + throw new Error(`${sourceLabel}: text_hygiene must be an object`) + } + if (typeof hygiene.escape_slash_in_acp !== 'boolean') { + throw new Error(`${sourceLabel}: text_hygiene.escape_slash_in_acp must be a boolean`) + } +} + +function readAndValidateFile(filePath) { + const resolved = path.resolve(filePath) + const rawBuf = fs.readFileSync(resolved) + const text = rawBuf.toString('utf8') + if (text.includes('\r\n')) { + throw new Error(`${resolved}: must use LF line endings (found CRLF)`) + } + if (!text.endsWith('\n')) { + throw new Error(`${resolved}: must end with a trailing newline`) + } + const spec = JSON.parse(text) + validateAgyAcpSpecObject(spec, resolved) + return { resolved, rawBuf, spec, sha256: sha256Of(rawBuf) } +} + +function parseArgs(argv) { + const opts = { + check: false, + specPath: DEFAULT_SPEC_PATH, + kernelSpecPath: null, + syncKernelPath: null, + fromKernelPath: null, + } + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i] + if (arg === '--check') { + opts.check = true + } else if (arg === '--spec') { + opts.specPath = argv[++i] + } else if (arg === '--kernel-spec') { + opts.kernelSpecPath = argv[++i] + } else if (arg === '--sync-kernel') { + opts.syncKernelPath = argv[++i] + } else if (arg === '--from-kernel') { + opts.fromKernelPath = argv[++i] + } else if (arg === '-h' || arg === '--help') { + console.log( + 'Usage: node scripts/sync-agy-acp-spec.mjs [--check] [--spec ] [--kernel-spec ] [--sync-kernel ] [--from-kernel ]', + ) + process.exit(0) + } else { + throw new Error(`Unknown argument: ${arg}`) + } + } + return opts +} + +function main() { + const opts = parseArgs(process.argv.slice(2)) + + if (opts.fromKernelPath) { + const src = readAndValidateFile(opts.fromKernelPath) + const dest = path.resolve(opts.specPath) + fs.mkdirSync(path.dirname(dest), { recursive: true }) + fs.writeFileSync(dest, src.rawBuf) + console.log(`Synced kernel spec -> ${dest} (sha256=${src.sha256}, min_agy=${src.spec.min_agy_version})`) + return + } + + const local = readAndValidateFile(opts.specPath) + + if (opts.syncKernelPath) { + const dest = path.resolve(opts.syncKernelPath) + fs.mkdirSync(path.dirname(dest), { recursive: true }) + fs.writeFileSync(dest, local.rawBuf) + console.log(`Synced vm2api spec -> ${dest} (sha256=${local.sha256}, min_agy=${local.spec.min_agy_version})`) + return + } + + if (opts.kernelSpecPath) { + const kernel = readAndValidateFile(opts.kernelSpecPath) + if (kernel.sha256 !== local.sha256) { + console.error(`ERROR: agy-acp-spec SHA-256 mismatch!`) + console.error(` vm2api (${local.resolved}): ${local.sha256}`) + console.error(` kernel (${kernel.resolved}): ${kernel.sha256}`) + process.exit(1) + } + console.log( + `OK: agy-acp-spec verified & byte-identical (sha256=${local.sha256}, min_agy=${local.spec.min_agy_version}, keys=${local.spec.top_level_fields.allowed_body_keys.length})`, + ) + return + } + + console.log( + `OK: agy-acp-spec schema valid (sha256=${local.sha256}, min_agy=${local.spec.min_agy_version}, policy=${local.spec.limits.prompt_overflow_policy}, keys=${local.spec.top_level_fields.allowed_body_keys.length})`, + ) +} + +if (process.argv[1] && path.resolve(process.argv[1]) === __filename) { + try { + main() + } catch (err) { + console.error(`ERROR: ${err?.message || err}`) + process.exit(1) + } +} diff --git a/src/config/agy-acp-spec.json b/src/config/agy-acp-spec.json new file mode 100644 index 0000000000..db2d72c439 --- /dev/null +++ b/src/config/agy-acp-spec.json @@ -0,0 +1,147 @@ +{ + "schema_version": 1, + "min_agy_version": "1.5.20", + "calibrated_agy_version": "1.5.20", + "limits": { + "max_acp_prompt_text_bytes": 190000, + "prompt_overflow_policy": "truncate", + "max_system_prompt_append_bytes": 4194304, + "max_tool_name_chars": 64 + }, + "top_level_fields": { + "unknown_policy": "reject", + "allowed_body_keys": [ + "model", + "stream", + "contents", + "messages", + "input", + "system", + "systemInstruction", + "system_instruction", + "instructions", + "system_prompt_mode", + "crag_prompt", + "tools", + "toolConfig", + "tool_config", + "tool_choice", + "generationConfig", + "generation_config", + "safetySettings", + "safety_settings", + "cachedContent", + "cached_content", + "web_search_options", + "thinking", + "thinking_budget", + "thinkingBudget", + "cache_control", + "output_config", + "output_format", + "extra_body", + "include", + "text", + "stream_options", + "max_tokens", + "max_completion_tokens", + "max_output_tokens", + "temperature", + "top_p", + "top_k", + "stop", + "stop_sequences", + "conversation_id", + "conversationId", + "previous_response_id", + "session_id", + "thread_id", + "conversation", + "metadata", + "labels", + "parallel_tool_calls", + "reasoning", + "reasoning_effort", + "response_format", + "subagents", + "modalities", + "store", + "truncation", + "user", + "service_tier", + "top_logprobs", + "logprobs", + "frequency_penalty", + "presence_penalty", + "seed", + "n", + "functions", + "function_call", + "context_management", + "betas", + "anthropic_version", + "speed", + "effort", + "mcp_servers", + "container", + "tool_addition", + "tool_removal", + "prompt_cache_key", + "prompt_cache_retention", + "prediction", + "audio", + "logit_bias", + "background", + "verbosity", + "safety_identifier", + "max_tool_calls", + "prompt", + "_meta", + "max_tokens_to_sample" + ], + "extra_allowed_body_keys": [] + }, + "media": { + "allowed_inline_image_mimes": [ + "image/png", + "image/jpeg", + "image/webp", + "image/gif" + ], + "decodable_text_mime_prefixes": [ + "text/" + ], + "decodable_text_exact_mimes": [ + "application/json", + "application/jsonl", + "application/x-jsonl", + "application/ndjson", + "application/x-ndjson", + "application/xml", + "application/yaml", + "application/x-yaml", + "application/toml", + "application/x-toml", + "application/javascript", + "application/x-javascript", + "application/ecmascript", + "application/typescript", + "application/x-typescript", + "application/sql", + "application/graphql", + "application/x-sh", + "application/x-shellscript", + "application/csv", + "application/x-csv", + "application/x-www-form-urlencoded" + ], + "decodable_text_app_suffixes": [ + "+json", + "+xml", + "+yaml" + ] + }, + "text_hygiene": { + "escape_slash_in_acp": false + } +} diff --git a/src/lib/gemini/agy-acp-spec.mjs b/src/lib/gemini/agy-acp-spec.mjs new file mode 100644 index 0000000000..7ad2591cb1 --- /dev/null +++ b/src/lib/gemini/agy-acp-spec.mjs @@ -0,0 +1,397 @@ +/** + * Single source of truth (SSOT) loader and dynamic policy resolver for the + * Gemini / CRAGGemini ACP protocol spec (`src/config/agy-acp-spec.json`, + * synced byte-identically into `antigravity-cli-proxy/src/acp_spec.json`). + * + * Runtime override precedence (highest -> lowest): + * 1. Live worker `/status` `protocol_capabilities` (`max_acp_prompt_text_bytes`, + * `prompt_overflow_policy`, `extra_allowed_body_keys`, `min_agy_version`). + * 2. Panel routing config `routing.gemini.acp_overrides` (hot-editable via PUT /api/panel/routing). + * 3. External spec JSON override via `process.env.KIN_AGY_ACP_SPEC_PATH`. + * 4. Bundled `src/config/agy-acp-spec.json`. + */ + +import crypto from 'node:crypto' +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const __filename = fileURLToPath(import.meta.url) +const __dirname = path.dirname(__filename) + +export const DEFAULT_AGY_ACP_SPEC_PATH = path.resolve(__dirname, '..', '..', 'config', 'agy-acp-spec.json') + +export const AGY_ACP_OVERFLOW_POLICIES = Object.freeze(['truncate', 'reject']) + +const SAFE_BODY_KEY_RE = /^[A-Za-z0-9_.-]{1,64}$/ +const SAFE_MIME_RE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,63}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,127}$/ +const SEMVER_PARTS_RE = /^(\d+)\.(\d+)\.(\d+)(?:-([A-Za-z0-9._-]+))?$/ + +const MAX_EXTRA_BODY_KEYS = 64 +const MAX_EXTRA_TEXT_MIMES = 64 +const MIN_ACP_PROMPT_BYTES = 16_384 +const MAX_ACP_PROMPT_BYTES = 4 * 1024 * 1024 + +function freezeSet(items = []) { + return Object.freeze(new Set(items)) +} + +function asObject(raw) { + return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : null +} + +function typedError(message, code) { + const err = new TypeError(message) + err.code = code + return err +} + +export function normalizeAcpMime(mimeType) { + return String(mimeType || '') + .trim() + .toLowerCase() + .split(';')[0] + .trim() +} + +export function parseSemver(raw) { + const trimmed = String(raw || '').trim() + const m = SEMVER_PARTS_RE.exec(trimmed) + if (!m) return null + return { + major: Number(m[1]), + minor: Number(m[2]), + patch: Number(m[3]), + prerelease: m[4] || '', + } +} + +export function compareSemver(a, b) { + const pa = parseSemver(a) + const pb = parseSemver(b) + if (!pa || !pb) return null + if (pa.major !== pb.major) return pa.major < pb.major ? -1 : 1 + if (pa.minor !== pb.minor) return pa.minor < pb.minor ? -1 : 1 + if (pa.patch !== pb.patch) return pa.patch < pb.patch ? -1 : 1 + if (pa.prerelease === pb.prerelease) return 0 + if (!pa.prerelease) return 1 + if (!pb.prerelease) return -1 + return pa.prerelease < pb.prerelease ? -1 : 1 +} + +export function agyVersionMeetsMin(version, minVersion = MIN_AGY_VERSION) { + const cmp = compareSemver(version, minVersion) + if (cmp === null) return null + return cmp >= 0 +} + +export function loadAgyAcpSpecFromFile(filePath = null) { + const resolved = path.resolve(filePath || process.env.KIN_AGY_ACP_SPEC_PATH || DEFAULT_AGY_ACP_SPEC_PATH) + const rawBuf = fs.readFileSync(resolved) + const raw = rawBuf.toString('utf8') + const spec = JSON.parse(raw) + if ( + !spec || + typeof spec !== 'object' || + spec.schema_version !== 1 || + typeof spec.min_agy_version !== 'string' || + !spec.limits || + !spec.top_level_fields || + !spec.media + ) { + throw new Error(`Invalid AGY ACP protocol spec at ${resolved}`) + } + const sha256 = crypto.createHash('sha256').update(rawBuf).digest('hex') + return { spec, sha256, filePath: resolved } +} + +const loaded = loadAgyAcpSpecFromFile() + +export const AGY_ACP_SPEC = loaded.spec +export const AGY_ACP_SPEC_SHA256 = loaded.sha256 +export const AGY_ACP_SPEC_PATH = loaded.filePath + +export const MIN_AGY_VERSION = AGY_ACP_SPEC.min_agy_version +export const CALIBRATED_AGY_VERSION = AGY_ACP_SPEC.calibrated_agy_version +export const DEFAULT_MAX_ACP_PROMPT_TEXT_BYTES = AGY_ACP_SPEC.limits.max_acp_prompt_text_bytes +export const DEFAULT_MAX_ACP_SYSTEM_PROMPT_APPEND_BYTES = AGY_ACP_SPEC.limits.max_system_prompt_append_bytes +export const DEFAULT_MAX_ACP_TOOL_NAME_CHARS = AGY_ACP_SPEC.limits.max_tool_name_chars +export const DEFAULT_PROMPT_OVERFLOW_POLICY = + AGY_ACP_SPEC.limits.prompt_overflow_policy === 'reject' ? 'reject' : 'truncate' + +export const AGY_ACP_ALLOWED_BODY_KEYS = freezeSet([ + ...(AGY_ACP_SPEC.top_level_fields.allowed_body_keys || []), + ...(AGY_ACP_SPEC.top_level_fields.extra_allowed_body_keys || []), +]) + +export const AGY_ACP_ALLOWED_INLINE_IMAGE_MIMES = freezeSet( + (AGY_ACP_SPEC.media.allowed_inline_image_mimes || []).map(normalizeAcpMime).filter(Boolean), +) + +const DEFAULT_DECODABLE_PREFIXES = Object.freeze( + (AGY_ACP_SPEC.media.decodable_text_mime_prefixes || []).map(normalizeAcpMime).filter(Boolean), +) +const DEFAULT_DECODABLE_EXACT = freezeSet( + (AGY_ACP_SPEC.media.decodable_text_exact_mimes || []).map(normalizeAcpMime).filter(Boolean), +) +const DEFAULT_DECODABLE_APP_SUFFIXES = Object.freeze( + (AGY_ACP_SPEC.media.decodable_text_app_suffixes || []) + .map((s) => + String(s || '') + .trim() + .toLowerCase(), + ) + .filter(Boolean), +) + +export const DEFAULT_GEMINI_ACP_OVERRIDES = Object.freeze({ + extra_allowed_body_keys: Object.freeze([]), + max_acp_prompt_text_bytes: null, + prompt_overflow_policy: null, + extra_decodable_text_mimes: Object.freeze([]), +}) + +function sanitizeStringList(items, { pattern, lowercase = false, maxCount }) { + if (!Array.isArray(items)) return [] + const out = [] + const seen = new Set() + for (const raw of items) { + if (typeof raw !== 'string') continue + const token = lowercase ? normalizeAcpMime(raw) : raw.trim() + if (!token || seen.has(token) || !pattern.test(token)) continue + seen.add(token) + out.push(token) + if (out.length >= maxCount) break + } + return out +} + +export function validateGeminiAcpOverridesPatch(raw, fieldPath = 'gemini.acp_overrides') { + if (raw === undefined || raw === null) return + const obj = asObject(raw) + if (!obj) throw typedError(`${fieldPath} 必须是对象`, 'invalid_gemini_acp_overrides') + + if (Object.hasOwn(obj, 'extra_allowed_body_keys') && obj.extra_allowed_body_keys !== undefined) { + if (!Array.isArray(obj.extra_allowed_body_keys)) { + throw typedError(`${fieldPath}.extra_allowed_body_keys 必须是字符串数组`, 'invalid_gemini_acp_overrides') + } + if (obj.extra_allowed_body_keys.length > MAX_EXTRA_BODY_KEYS) { + throw typedError( + `${fieldPath}.extra_allowed_body_keys 最多允许 ${MAX_EXTRA_BODY_KEYS} 项`, + 'invalid_gemini_acp_overrides', + ) + } + for (const key of obj.extra_allowed_body_keys) { + if (typeof key !== 'string' || !SAFE_BODY_KEY_RE.test(key.trim())) { + throw typedError(`${fieldPath}.extra_allowed_body_keys 包含无效字段名`, 'invalid_gemini_acp_overrides') + } + } + } + + if ( + Object.hasOwn(obj, 'max_acp_prompt_text_bytes') && + obj.max_acp_prompt_text_bytes !== undefined && + obj.max_acp_prompt_text_bytes !== null + ) { + const val = obj.max_acp_prompt_text_bytes + if (typeof val !== 'number' || !Number.isInteger(val) || val < MIN_ACP_PROMPT_BYTES || val > MAX_ACP_PROMPT_BYTES) { + throw typedError( + `${fieldPath}.max_acp_prompt_text_bytes 必须是 ${MIN_ACP_PROMPT_BYTES} 到 ${MAX_ACP_PROMPT_BYTES} 之间的整数或 null`, + 'invalid_gemini_acp_overrides', + ) + } + } + + if ( + Object.hasOwn(obj, 'prompt_overflow_policy') && + obj.prompt_overflow_policy !== undefined && + obj.prompt_overflow_policy !== null + ) { + if ( + typeof obj.prompt_overflow_policy !== 'string' || + !AGY_ACP_OVERFLOW_POLICIES.includes(obj.prompt_overflow_policy) + ) { + throw typedError( + `${fieldPath}.prompt_overflow_policy 必须是 truncate、reject 或 null`, + 'invalid_gemini_acp_overrides', + ) + } + } + + if (Object.hasOwn(obj, 'extra_decodable_text_mimes') && obj.extra_decodable_text_mimes !== undefined) { + if (!Array.isArray(obj.extra_decodable_text_mimes)) { + throw typedError(`${fieldPath}.extra_decodable_text_mimes 必须是字符串数组`, 'invalid_gemini_acp_overrides') + } + if (obj.extra_decodable_text_mimes.length > MAX_EXTRA_TEXT_MIMES) { + throw typedError( + `${fieldPath}.extra_decodable_text_mimes 最多允许 ${MAX_EXTRA_TEXT_MIMES} 项`, + 'invalid_gemini_acp_overrides', + ) + } + for (const rawMime of obj.extra_decodable_text_mimes) { + const mime = typeof rawMime === 'string' ? normalizeAcpMime(rawMime) : '' + if (!mime || !SAFE_MIME_RE.test(mime) || mime === 'image/svg+xml' || mime.startsWith('image/')) { + throw typedError( + `${fieldPath}.extra_decodable_text_mimes 包含无效或禁止的 MIME 类型`, + 'invalid_gemini_acp_overrides', + ) + } + } + } +} + +export function normalizeGeminiAcpOverrides(raw = null) { + const src = asObject(raw) || {} + const rawMax = src.max_acp_prompt_text_bytes + const maxBytes = + typeof rawMax === 'number' && + Number.isInteger(rawMax) && + rawMax >= MIN_ACP_PROMPT_BYTES && + rawMax <= MAX_ACP_PROMPT_BYTES + ? rawMax + : null + const policy = + typeof src.prompt_overflow_policy === 'string' && AGY_ACP_OVERFLOW_POLICIES.includes(src.prompt_overflow_policy) + ? src.prompt_overflow_policy + : null + const extraKeys = sanitizeStringList(src.extra_allowed_body_keys, { + pattern: SAFE_BODY_KEY_RE, + maxCount: MAX_EXTRA_BODY_KEYS, + }) + const extraMimes = sanitizeStringList(src.extra_decodable_text_mimes, { + pattern: SAFE_MIME_RE, + lowercase: true, + maxCount: MAX_EXTRA_TEXT_MIMES, + }).filter((m) => m !== 'image/svg+xml' && !m.startsWith('image/')) + + return { + extra_allowed_body_keys: extraKeys, + max_acp_prompt_text_bytes: maxBytes, + prompt_overflow_policy: policy, + extra_decodable_text_mimes: extraMimes, + } +} + +export function mergeGeminiAcpOverrides(previous = null, patch = null) { + const prev = normalizeGeminiAcpOverrides(previous) + const src = asObject(patch) + if (!src) return prev + return normalizeGeminiAcpOverrides({ + ...prev, + ...src, + }) +} + +export function isAcpDecodableTextMime(mimeType, { extraMimes = null, spec = AGY_ACP_SPEC } = {}) { + const m = normalizeAcpMime(mimeType) + if (!m || m === 'image/svg+xml' || m.startsWith('image/')) return false + + const prefixes = + spec === AGY_ACP_SPEC + ? DEFAULT_DECODABLE_PREFIXES + : (spec?.media?.decodable_text_mime_prefixes || []).map(normalizeAcpMime).filter(Boolean) + for (const prefix of prefixes) { + if (m.startsWith(prefix)) return true + } + + const exactSet = + spec === AGY_ACP_SPEC + ? DEFAULT_DECODABLE_EXACT + : new Set((spec?.media?.decodable_text_exact_mimes || []).map(normalizeAcpMime).filter(Boolean)) + if (exactSet.has(m)) return true + + if (m.startsWith('application/')) { + const suffixes = + spec === AGY_ACP_SPEC + ? DEFAULT_DECODABLE_APP_SUFFIXES + : (spec?.media?.decodable_text_app_suffixes || []) + .map((s) => + String(s || '') + .trim() + .toLowerCase(), + ) + .filter(Boolean) + for (const suffix of suffixes) { + if (m.endsWith(suffix)) return true + } + } + + if (extraMimes) { + if (extraMimes instanceof Set) { + if (extraMimes.has(m)) return true + } else if (Array.isArray(extraMimes)) { + for (const item of extraMimes) { + if (normalizeAcpMime(item) === m) return true + } + } + } + return false +} + +export function resolveEffectiveAgyAcpPolicy({ + spec = AGY_ACP_SPEC, + routingOverrides = null, + targetProtocolCapabilities = null, +} = {}) { + const overrides = normalizeGeminiAcpOverrides(routingOverrides) + const caps = asObject(targetProtocolCapabilities) || {} + + const capMaxBytes = + typeof caps.max_acp_prompt_text_bytes === 'number' && + Number.isInteger(caps.max_acp_prompt_text_bytes) && + caps.max_acp_prompt_text_bytes >= MIN_ACP_PROMPT_BYTES && + caps.max_acp_prompt_text_bytes <= MAX_ACP_PROMPT_BYTES + ? caps.max_acp_prompt_text_bytes + : null + + const capPolicy = + typeof caps.prompt_overflow_policy === 'string' && AGY_ACP_OVERFLOW_POLICIES.includes(caps.prompt_overflow_policy) + ? caps.prompt_overflow_policy + : null + + const capExtraKeys = sanitizeStringList(caps.extra_allowed_body_keys, { + pattern: SAFE_BODY_KEY_RE, + maxCount: MAX_EXTRA_BODY_KEYS, + }) + + const baseAllowed = spec?.top_level_fields?.allowed_body_keys || [] + const specExtra = spec?.top_level_fields?.extra_allowed_body_keys || [] + const extraAllowedBodyKeys = [...new Set([...specExtra, ...overrides.extra_allowed_body_keys, ...capExtraKeys])] + const allowedBodyKeys = new Set([...baseAllowed, ...extraAllowedBodyKeys]) + + const extraDecodableTextMimes = new Set(overrides.extra_decodable_text_mimes) + + const maxAcpPromptTextBytes = + capMaxBytes ?? + overrides.max_acp_prompt_text_bytes ?? + spec?.limits?.max_acp_prompt_text_bytes ?? + DEFAULT_MAX_ACP_PROMPT_TEXT_BYTES + + const promptOverflowPolicy = + capPolicy ?? + overrides.prompt_overflow_policy ?? + (spec?.limits?.prompt_overflow_policy === 'reject' ? 'reject' : DEFAULT_PROMPT_OVERFLOW_POLICY) + + const maxSystemPromptAppendBytes = + spec?.limits?.max_system_prompt_append_bytes ?? DEFAULT_MAX_ACP_SYSTEM_PROMPT_APPEND_BYTES + + const maxToolNameChars = spec?.limits?.max_tool_name_chars ?? DEFAULT_MAX_ACP_TOOL_NAME_CHARS + + const minAgyVersion = + typeof caps.min_agy_version === 'string' && parseSemver(caps.min_agy_version) + ? caps.min_agy_version + : spec?.min_agy_version || MIN_AGY_VERSION + + return { + specSha256: spec === AGY_ACP_SPEC ? AGY_ACP_SPEC_SHA256 : null, + minAgyVersion, + maxAcpPromptTextBytes, + promptOverflowPolicy, + maxSystemPromptAppendBytes, + maxToolNameChars, + allowedBodyKeys, + extraAllowedBodyKeys, + extraDecodableTextMimes, + escapeSlashInAcp: spec?.text_hygiene?.escape_slash_in_acp === true, + } +} diff --git a/src/lib/gemini/direct-client.mjs b/src/lib/gemini/direct-client.mjs index 2efea0ce52..a12fc05854 100644 --- a/src/lib/gemini/direct-client.mjs +++ b/src/lib/gemini/direct-client.mjs @@ -1110,6 +1110,22 @@ export function normalizeTargetCapabilities(rawCaps, rawProtoCaps) { const internalWireProtocols = Array.isArray(pc.internal_wire_protocols) ? pc.internal_wire_protocols.filter((p) => typeof p === 'string' && VALID_WIRE_PROTOCOLS.has(p)) : [] + const extraAllowedBodyKeys = Array.isArray(pc.extra_allowed_body_keys) + ? [ + ...new Set(pc.extra_allowed_body_keys.map((k) => (typeof k === 'string' ? k.trim() : '')).filter(Boolean)), + ].slice(0, 64) + : null + const maxAcpPromptTextBytes = + typeof pc.max_acp_prompt_text_bytes === 'number' && + Number.isInteger(pc.max_acp_prompt_text_bytes) && + pc.max_acp_prompt_text_bytes >= 16_384 && + pc.max_acp_prompt_text_bytes <= 4 * 1024 * 1024 + ? pc.max_acp_prompt_text_bytes + : null + const promptOverflowPolicy = + pc.prompt_overflow_policy === 'truncate' || pc.prompt_overflow_policy === 'reject' + ? pc.prompt_overflow_policy + : null const extraProtoCaps = {} for (const [key, val] of Object.entries(pc)) { if ( @@ -1117,6 +1133,14 @@ export function normalizeTargetCapabilities(rawCaps, rawProtoCaps) { key === 'internal_wire_protocols' || key === 'provider_result_v2' || key === 'per_session_mcp' || + key === 'extra_allowed_body_keys' || + key === 'max_acp_prompt_text_bytes' || + key === 'prompt_overflow_policy' || + key === 'kernel_version' || + key === 'agy_version' || + key === 'min_agy_version' || + key === 'agy_version_compatible' || + key === 'acp_spec_sha256' || key === '__proto__' || key === 'constructor' || key === 'prototype' @@ -1140,10 +1164,48 @@ export function normalizeTargetCapabilities(rawCaps, rawProtoCaps) { ...(pc.per_session_mcp === true ? { per_session_mcp: true } : {}), ...(pc.acp_admission_v1 === true ? { acp_admission_v1: true } : {}), ...(pc.error_failoverable_v1 === true ? { error_failoverable_v1: true } : {}), + ...(typeof pc.kernel_version === 'string' && pc.kernel_version.trim() + ? { kernel_version: pc.kernel_version.trim() } + : {}), + ...(typeof pc.agy_version === 'string' && pc.agy_version.trim() ? { agy_version: pc.agy_version.trim() } : {}), + ...(typeof pc.min_agy_version === 'string' && pc.min_agy_version.trim() + ? { min_agy_version: pc.min_agy_version.trim() } + : {}), + ...(typeof pc.agy_version_compatible === 'boolean' ? { agy_version_compatible: pc.agy_version_compatible } : {}), + ...(typeof pc.acp_spec_sha256 === 'string' && /^[a-f0-9]{64}$/i.test(pc.acp_spec_sha256.trim()) + ? { acp_spec_sha256: pc.acp_spec_sha256.trim().toLowerCase() } + : {}), + ...(maxAcpPromptTextBytes != null ? { max_acp_prompt_text_bytes: maxAcpPromptTextBytes } : {}), + ...(promptOverflowPolicy != null ? { prompt_overflow_policy: promptOverflowPolicy } : {}), + ...(extraAllowedBodyKeys && extraAllowedBodyKeys.length ? { extra_allowed_body_keys: extraAllowedBodyKeys } : {}), } return { capabilities, protocolCapabilities } } +export function resolveTargetAcpCapabilities(target) { + const pc = + target?.protocolCapabilities && typeof target.protocolCapabilities === 'object' + ? target.protocolCapabilities + : target?.protocol_capabilities && typeof target.protocol_capabilities === 'object' + ? target.protocol_capabilities + : null + if (!pc) return null + const out = {} + if (typeof pc.kernel_version === 'string' && pc.kernel_version) out.kernel_version = pc.kernel_version + if (typeof pc.agy_version === 'string' && pc.agy_version) out.agy_version = pc.agy_version + if (typeof pc.min_agy_version === 'string' && pc.min_agy_version) out.min_agy_version = pc.min_agy_version + if (typeof pc.agy_version_compatible === 'boolean') out.agy_version_compatible = pc.agy_version_compatible + if (typeof pc.acp_spec_sha256 === 'string' && pc.acp_spec_sha256) out.acp_spec_sha256 = pc.acp_spec_sha256 + if (Number.isInteger(pc.max_acp_prompt_text_bytes)) out.max_acp_prompt_text_bytes = pc.max_acp_prompt_text_bytes + if (pc.prompt_overflow_policy === 'truncate' || pc.prompt_overflow_policy === 'reject') { + out.prompt_overflow_policy = pc.prompt_overflow_policy + } + if (Array.isArray(pc.extra_allowed_body_keys) && pc.extra_allowed_body_keys.length) { + out.extra_allowed_body_keys = pc.extra_allowed_body_keys + } + return Object.keys(out).length ? out : null +} + function validTarget(raw) { if (!raw || raw.direct !== true) return null if (typeof raw.socket_path !== 'string' || !path.isAbsolute(raw.socket_path)) return null diff --git a/src/lib/gemini/error-policy.mjs b/src/lib/gemini/error-policy.mjs index 3cd60b89de..790b4f34e0 100644 --- a/src/lib/gemini/error-policy.mjs +++ b/src/lib/gemini/error-policy.mjs @@ -319,7 +319,7 @@ function classifyGeminiFailureRaw(failure, { attemptUpstreamStatus = null, now = cooldownUntil: null, retrySameAccount: false, circuit: false, - schedulerErrorClass: 'client4xx', + schedulerErrorClass: 'request_protocol', } } diff --git a/src/lib/gemini/prompt-normalizer.mjs b/src/lib/gemini/prompt-normalizer.mjs index a3f6dcd27d..fd3f034247 100644 --- a/src/lib/gemini/prompt-normalizer.mjs +++ b/src/lib/gemini/prompt-normalizer.mjs @@ -12,6 +12,7 @@ */ import crypto from 'node:crypto' +import { AGY_ACP_ALLOWED_BODY_KEYS, isAcpDecodableTextMime, resolveEffectiveAgyAcpPolicy } from './agy-acp-spec.mjs' export const CRAGGEMINI_PROMPT_NORMALIZATION_MODES = Object.freeze(['auto', 'strict', 'off']) @@ -1060,63 +1061,12 @@ function prependGlobalPromptIdempotent(existing, globalPrompt, systemOpts) { /** * Top-level keys permitted to reach CRAGGemini after gateway canonicalization. + * Loaded from the Gemini ACP protocol SSOT (`src/config/agy-acp-spec.json`). * Client session/internal control keys (`STRIPPED_CLIENT_CONTROL_KEYS`) and cosmetic * non-ACP metadata keys (`STRIPPED_COSMETIC_KEYS`) are stripped explicitly; any - * remaining key outside `ALLOWED_ANTIGRAVITY_BODY_KEYS` is handled by `observe_strip_7d`. + * remaining key outside the effective allowlist is handled by `observe_strip_7d`. */ -export const ALLOWED_ANTIGRAVITY_BODY_KEYS = new Set([ - 'model', - 'stream', - 'contents', - 'messages', - 'input', - 'system', - 'systemInstruction', - 'instructions', - 'system_prompt_mode', - 'tools', - 'toolConfig', - 'tool_config', - 'tool_choice', - 'generationConfig', - 'generation_config', - 'web_search_options', - 'thinking', - 'thinking_budget', - 'thinkingBudget', - 'output_config', - 'output_format', - 'extra_body', - 'include', - 'text', - 'stream_options', - 'max_tokens', - 'max_completion_tokens', - 'max_output_tokens', - 'max_tokens_to_sample', - 'temperature', - 'top_p', - 'top_k', - 'stop', - 'stop_sequences', - 'parallel_tool_calls', - 'reasoning', - 'reasoning_effort', - 'response_format', - 'modalities', - 'store', - 'truncation', - 'service_tier', - 'frequency_penalty', - 'presence_penalty', - 'seed', - 'n', - 'functions', - 'function_call', - 'effort', - 'verbosity', - 'max_tool_calls', -]) +export const ALLOWED_ANTIGRAVITY_BODY_KEYS = new Set(AGY_ACP_ALLOWED_BODY_KEYS) const STRIPPED_CLIENT_CONTROL_KEYS = new Set([ 'conversation_id', @@ -1245,25 +1195,21 @@ export function normalizeMediaMimeType(mimeType) { .trim() } -export function isInlinePlainTextMime(mimeType) { - const m = normalizeMediaMimeType(mimeType) - return ( - m.startsWith('text/') || - m === 'application/json' || - m === 'application/ld+json' || - m === 'application/xml' || - m === 'application/x-yaml' || - m === 'application/yaml' - ) +export function isInlinePlainTextMime(mimeType, { extraDecodableTextMimes = null } = {}) { + return isAcpDecodableTextMime(mimeType, { extraMimes: extraDecodableTextMimes }) } /** * Strictly decode an inline base64 payload when `mimeType` is a plain-text MIME. * Enforces base64 grammar, pre-decode byte ceiling (anti-OOM), and fatal UTF-8 validation. */ -export function decodeInlinePlainTextBase64(rawData, mimeType = '', { maxBytes = MAX_INLINE_TEXT_DECODE_BYTES } = {}) { +export function decodeInlinePlainTextBase64( + rawData, + mimeType = '', + { maxBytes = MAX_INLINE_TEXT_DECODE_BYTES, extraDecodableTextMimes = null } = {}, +) { const mime = normalizeMediaMimeType(mimeType) - if (!isInlinePlainTextMime(mime)) return { ok: false, reason: 'unsupported_mime', mime } + if (!isInlinePlainTextMime(mime, { extraDecodableTextMimes })) return { ok: false, reason: 'unsupported_mime', mime } if (typeof rawData !== 'string') return { ok: false, reason: 'invalid_base64', mime } const clean = rawData.replace(/\s+/g, '') if ( @@ -1298,15 +1244,15 @@ export function decodeInlinePlainTextBase64(rawData, mimeType = '', { maxBytes = } } -function decodeInlineTextDataUri(rawUrl, fallbackMime = '') { +function decodeInlineTextDataUri(rawUrl, fallbackMime = '', { extraDecodableTextMimes = null } = {}) { if (typeof rawUrl !== 'string' || !rawUrl) return null const trimmed = rawUrl.trim() const m = /^data:([^,]*?)(;base64)?,([\s\S]*)$/i.exec(trimmed) if (m) { const mime = m[1] || fallbackMime - if (!isInlinePlainTextMime(mime)) return null + if (!isInlinePlainTextMime(mime, { extraDecodableTextMimes })) return null if (m[2]) { - const decoded = decodeInlinePlainTextBase64(m[3], mime) + const decoded = decodeInlinePlainTextBase64(m[3], mime, { extraDecodableTextMimes }) return decoded.ok ? decoded.text : null } try { @@ -1316,13 +1262,39 @@ function decodeInlineTextDataUri(rawUrl, fallbackMime = '') { return null } } - if (isInlinePlainTextMime(fallbackMime) && !/^(?:https?|gs|file):/i.test(trimmed)) { - const decoded = decodeInlinePlainTextBase64(trimmed, fallbackMime) + if (isInlinePlainTextMime(fallbackMime, { extraDecodableTextMimes }) && !/^(?:https?|gs|file):/i.test(trimmed)) { + const decoded = decodeInlinePlainTextBase64(trimmed, fallbackMime, { extraDecodableTextMimes }) return decoded.ok ? decoded.text : null } return null } +/** + * Copy-on-write recursive sanitizer stripping ANSI escapes and illegal C0 control characters + * from arbitrary JSON payloads (used on Gemini `functionResponse.response`). + */ +export function sanitizeJsonControlCharsDeep(value) { + if (typeof value === 'string') return stripIllegalControlChars(value) + if (Array.isArray(value)) { + let changed = false + const next = value.map((item) => { + const cleaned = sanitizeJsonControlCharsDeep(item) + if (cleaned !== item) changed = true + return cleaned + }) + return changed ? next : value + } + if (!isPlainObj(value)) return value + let changed = false + const next = {} + for (const [k, v] of Object.entries(value)) { + const cleaned = sanitizeJsonControlCharsDeep(v) + if (cleaned !== v) changed = true + next[k] = cleaned + } + return changed ? next : value +} + function cleanTurnUserString( text, { isFirstUserNoSystem, mode, preset = 'official_full', appliedRules, scopesTouched, escapeSlashes }, @@ -1549,12 +1521,21 @@ export function canonicalizeInboundForAntigravity( targetSupportsAcpAdmission = false, escapeSlashes = false, observeUnknownFields = true, + acpOverrides = null, + targetProtocolCapabilities = null, } = {}, ) { if (!isPlainObj(rawBody)) { return { body: rawBody, report: null, calibration: null, toolSchemasByName: new Map() } } + const effectiveAcpPolicy = resolveEffectiveAgyAcpPolicy({ + routingOverrides: acpOverrides, + targetProtocolCapabilities, + }) + const effectiveAllowedBodyKeys = effectiveAcpPolicy.allowedBodyKeys + const extraDecodableTextMimes = effectiveAcpPolicy.extraDecodableTextMimes + const appliedRules = new Set() const scopesTouched = new Set() const strippedFields = new Set() @@ -1827,7 +1808,9 @@ export function canonicalizeInboundForAntigravity( continue } if (blk.source.type === 'base64' && typeof blk.source.data === 'string') { - const decoded = decodeInlinePlainTextBase64(blk.source.data, blk.source.media_type) + const decoded = decodeInlinePlainTextBase64(blk.source.data, blk.source.media_type, { + extraDecodableTextMimes, + }) if (decoded.ok) { contentChanged = true nextContent.push({ @@ -1901,7 +1884,9 @@ export function canonicalizeInboundForAntigravity( sub.source.type === 'base64' && typeof sub.source.data === 'string' ) { - const decoded = decodeInlinePlainTextBase64(sub.source.data, sub.source.media_type) + const decoded = decodeInlinePlainTextBase64(sub.source.data, sub.source.media_type, { + extraDecodableTextMimes, + }) if (decoded.ok) { subChanged = true return { type: 'text', text: stripIllegalControlChars(decoded.text) } @@ -2039,7 +2024,9 @@ export function canonicalizeInboundForAntigravity( let cChanged = false const nextContent = m.content.map((part) => { if (isPlainObj(part) && part.type === 'file' && isPlainObj(part.file)) { - const decoded = decodeInlineTextDataUri(part.file.file_data || part.file.data, part.file.media_type) + const decoded = decodeInlineTextDataUri(part.file.file_data || part.file.data, part.file.media_type, { + extraDecodableTextMimes, + }) if (decoded !== null) { cChanged = true return { @@ -2238,7 +2225,7 @@ export function canonicalizeInboundForAntigravity( let cChanged = false const nextContent = it.content.map((part) => { if (isPlainObj(part) && part.type === 'input_file') { - const decoded = decodeInlineTextDataUri(part.file_data, part.media_type) + const decoded = decodeInlineTextDataUri(part.file_data, part.media_type, { extraDecodableTextMimes }) if (decoded !== null) { cChanged = true return { @@ -2405,7 +2392,9 @@ export function canonicalizeInboundForAntigravity( if (!isPlainObj(p)) return p const inline = isPlainObj(p.inlineData) ? p.inlineData : isPlainObj(p.inline_data) ? p.inline_data : null if (inline) { - const decoded = decodeInlinePlainTextBase64(inline.data, inline.mimeType ?? inline.mime_type) + const decoded = decodeInlinePlainTextBase64(inline.data, inline.mimeType ?? inline.mime_type, { + extraDecodableTextMimes, + }) if (decoded.ok) { turnChanged = true return { @@ -2440,8 +2429,18 @@ export function canonicalizeInboundForAntigravity( } else if (isPlainObj(p.functionResponse) || isPlainObj(p.function_response)) { const frKey = isPlainObj(p.functionResponse) ? 'functionResponse' : 'function_response' const fr = p[frKey] + let frChanged = false + let nextFr = fr + if (fr.response !== undefined) { + const cleanResp = sanitizeJsonControlCharsDeep(fr.response) + if (cleanResp !== fr.response) { + frChanged = true + appliedRules.add('transport_control_chars') + nextFr = { ...nextFr, response: cleanResp } + } + } if (Array.isArray(fr.parts)) { - let frChanged = false + let partsChanged = false const nextFrParts = fr.parts.map((sub) => { if (!isPlainObj(sub)) return sub const subInline = isPlainObj(sub.inlineData) @@ -2450,19 +2449,33 @@ export function canonicalizeInboundForAntigravity( ? sub.inline_data : null if (subInline) { - const decoded = decodeInlinePlainTextBase64(subInline.data, subInline.mimeType ?? subInline.mime_type) + const decoded = decodeInlinePlainTextBase64(subInline.data, subInline.mimeType ?? subInline.mime_type, { + extraDecodableTextMimes, + }) if (decoded.ok) { - frChanged = true + partsChanged = true return { text: stripIllegalControlChars(decoded.text) } } } + if (typeof sub.text === 'string' && sub.thought !== true) { + const cleanSubText = stripIllegalControlChars(sub.text) + if (cleanSubText !== sub.text) { + partsChanged = true + appliedRules.add('transport_control_chars') + return { ...sub, text: cleanSubText } + } + } return sub }) - if (frChanged) { - turnChanged = true - return { ...p, [frKey]: { ...fr, parts: nextFrParts } } + if (partsChanged) { + frChanged = true + nextFr = { ...nextFr, parts: nextFrParts } } } + if (frChanged) { + turnChanged = true + return { ...p, [frKey]: nextFr } + } } return p }) @@ -2477,7 +2490,7 @@ export function canonicalizeInboundForAntigravity( delete out[key] continue } - if (observeUnknownFields && !ALLOWED_ANTIGRAVITY_BODY_KEYS.has(key)) { + if (observeUnknownFields && !effectiveAllowedBodyKeys.has(key)) { unknownTopFieldsObserved.add(key) delete out[key] } diff --git a/src/lib/gemini/routes.mjs b/src/lib/gemini/routes.mjs index 04286d4c67..b9b230fc14 100644 --- a/src/lib/gemini/routes.mjs +++ b/src/lib/gemini/routes.mjs @@ -894,6 +894,7 @@ function environmentView( globalConfig = null, restriction = null, circuit = null, + liveUnschedulable = null, supplierTag = undefined, } = {}, ) { @@ -970,6 +971,14 @@ function environmentView( }, } : null + const effectiveUnschedulable = + slotPref?.unschedulable || + (liveUnschedulable + ? { + reason: liveUnschedulable.reason || 'permanent_unschedulable', + permanent: true, + } + : null) return { id: value.id, proxy_id: value.proxy_id, @@ -979,21 +988,21 @@ function environmentView( name: (slotPref?.display_name && text(slotPref.display_name, 80)) || text(value.name, 80) || '', auth_state: value.auth_state, auth_method: value.auth_method === 'api_key' ? 'api_key' : 'oauth', - schedulable: slotPref ? slotPref.schedulable !== false : true, + schedulable: (slotPref ? slotPref.schedulable !== false : true) && !liveUnschedulable, schedule_level: Number.isSafeInteger(slotPref?.schedule_level) ? slotPref.schedule_level : 5, schedule_level_mode: slotPref?.schedule_level_mode === 'manual' ? 'manual' : 'auto', telemetry_enabled: telemetryOverride, effective_telemetry_enabled: effectiveTelemetry, ...(sanitizedComputerProfile ? { computer_profile: sanitizedComputerProfile } : {}), - ...(slotPref?.unschedulable + ...(effectiveUnschedulable ? { - unschedulable: slotPref.unschedulable, - unschedulable_reason: slotPref.unschedulable_reason ?? slotPref.unschedulable.reason ?? null, - ...(slotPref.unschedulable_detail || slotPref.unschedulable.detail - ? { unschedulable_detail: slotPref.unschedulable_detail ?? slotPref.unschedulable.detail } + unschedulable: effectiveUnschedulable, + unschedulable_reason: slotPref?.unschedulable_reason ?? effectiveUnschedulable.reason ?? null, + ...(slotPref?.unschedulable_detail || effectiveUnschedulable.detail + ? { unschedulable_detail: slotPref?.unschedulable_detail ?? effectiveUnschedulable.detail } : {}), - ...(slotPref.unschedulable_at || slotPref.unschedulable.at - ? { unschedulable_at: slotPref.unschedulable_at ?? slotPref.unschedulable.at } + ...(slotPref?.unschedulable_at || effectiveUnschedulable.at + ? { unschedulable_at: slotPref?.unschedulable_at ?? effectiveUnschedulable.at } : {}), } : {}), @@ -2021,6 +2030,7 @@ export function createGeminiPanelHandler({ globalConfig: slotPrefs.getConfig(), restriction: runtimeState.restriction, circuit: runtimeState.circuit, + liveUnschedulable: runtimeState.liveUnschedulable || null, ...(supplierTag !== undefined ? { supplierTag } : {}), ...opts, }) diff --git a/src/lib/gemini/routing-config.mjs b/src/lib/gemini/routing-config.mjs index 570eb132ec..a59f86e33b 100644 --- a/src/lib/gemini/routing-config.mjs +++ b/src/lib/gemini/routing-config.mjs @@ -3,6 +3,12 @@ * Modeled after Anthropic pool/sticky/failover and OpenAI codex-route conventions. */ +import { + DEFAULT_GEMINI_ACP_OVERRIDES, + mergeGeminiAcpOverrides, + normalizeGeminiAcpOverrides, + validateGeminiAcpOverridesPatch, +} from './agy-acp-spec.mjs' import { DEFAULT_GEMINI_TOOL_DESCRIPTION_RULES, mergeGeminiToolDescriptionRules, @@ -56,6 +62,7 @@ export const DEFAULT_GEMINI_ROUTING = Object.freeze({ response_mb: 16, }), tool_description_rules: DEFAULT_GEMINI_TOOL_DESCRIPTION_RULES, + acp_overrides: DEFAULT_GEMINI_ACP_OVERRIDES, }) const PROTOCOL_KEYS = Object.freeze(Object.keys(DEFAULT_GEMINI_ROUTING.protocols)) @@ -205,6 +212,10 @@ export function validateGeminiRoutingPatch(body = {}) { if (Object.hasOwn(gem, 'tool_description_rules') && gem.tool_description_rules !== undefined) { validateGeminiToolDescriptionRulesPatch(gem.tool_description_rules, 'gemini.tool_description_rules') } + + if (Object.hasOwn(gem, 'acp_overrides') && gem.acp_overrides !== undefined) { + validateGeminiAcpOverridesPatch(gem.acp_overrides, 'gemini.acp_overrides') + } } export function mergeGeminiRouting(previous = {}, patch = {}) { @@ -227,6 +238,7 @@ export function mergeGeminiRouting(previous = {}, patch = {}) { failover: { ...prev.failover, ...(asObject(src.failover) || {}) }, shm: { ...prev.shm, ...(asObject(src.shm) || {}) }, tool_description_rules: mergeGeminiToolDescriptionRules(prev.tool_description_rules, src.tool_description_rules), + acp_overrides: mergeGeminiAcpOverrides(prev.acp_overrides, src.acp_overrides), }) } @@ -312,6 +324,7 @@ export function normalizeGeminiRouting(raw = {}) { failover, shm, tool_description_rules: normalizeGeminiToolDescriptionRules(src.tool_description_rules), + acp_overrides: normalizeGeminiAcpOverrides(src.acp_overrides), } } diff --git a/src/lib/gemini/scheduler.mjs b/src/lib/gemini/scheduler.mjs index 06ca7880ed..b612e72f19 100644 --- a/src/lib/gemini/scheduler.mjs +++ b/src/lib/gemini/scheduler.mjs @@ -18,6 +18,7 @@ import { restoreAgyBridgeToolArgs, validateAntigravityTargetAdmission, } from '../protocol/gemini-convert.mjs' +import { resolveEffectiveAgyAcpPolicy } from './agy-acp-spec.mjs' import { canonicalizeInboundForAntigravity } from './prompt-normalizer.mjs' import { createStreamTiming } from '../protocol/stream-timing.mjs' import { @@ -39,6 +40,7 @@ import { extractCragErrorFields, mapCragWorkerError, prepareDirectNativeTurnBody, + resolveTargetAcpCapabilities, targetSupportsAcpAdmission, targetSupportsCleanAcpText, targetSupportsProviderResult, @@ -331,6 +333,13 @@ function buildMappedInferFailure(errBody, statusCode, headers = null) { return err } +function buildAttemptRequestId(baseId, attempts) { + const raw = String(baseId || '').trim() || `gem_${crypto.randomBytes(12).toString('hex')}` + if (attempts <= 1) return raw.slice(0, 128) + const suffix = `_a${attempts}` + return `${raw.slice(0, Math.max(0, 128 - suffix.length))}${suffix}` +} + function mapStreamFailure(streamError, fallbackHttpStatus = null) { if (streamError?.localError === true) { const localCode = Object.hasOwn(FAILURES, streamError.code) ? streamError.code : 'gemini_inference_invalid_output' @@ -352,6 +361,12 @@ function mapStreamFailure(streamError, fallbackHttpStatus = null) { ? { ...streamError.rawPayload, ...(preferredCode && Object.hasOwn(FAILURES, preferredCode) ? { code: preferredCode } : {}), + ...(typeof streamError?.retryable === 'boolean' ? { retryable: streamError.retryable } : {}), + ...(typeof streamError?.failoverable === 'boolean' ? { failoverable: streamError.failoverable } : {}), + ...(typeof streamError?.worker_code === 'string' ? { worker_code: streamError.worker_code } : {}), + ...(Number.isInteger(streamError?.upstream_status) ? { upstream_status: streamError.upstream_status } : {}), + ...(streamError?.content_rejected === true ? { content_rejected: true } : {}), + ...(Number.isInteger(streamError?.retry_after_ms) ? { retry_after_ms: streamError.retry_after_ms } : {}), } : { ...(preferredCode ? { code: preferredCode } : {}), @@ -3589,8 +3604,27 @@ export function createGeminiScheduler({ }, environmentRestriction(envId, ts = now()) { - if (!envId) return { restriction: null, circuit: null } + if (!envId) return { restriction: null, circuit: null, liveUnschedulable: null } const live = resolveSchedulerRuntime()?.liveNodeState?.(formatNodeKey('gemini_env', envId), ts) || null + if (live?.schedulable === false) { + const reason = live.unschedulable_reason || 'permanent_unschedulable' + return { + restriction: { + reason, + text: + reason === 'permanent_ban' || reason === 'account_suspended' || reason === 'account_tos_disabled' + ? '账号永久不可调度' + : '不可调度', + until: null, + permanent: true, + }, + circuit: null, + liveUnschedulable: { + reason, + permanent: true, + }, + } + } if (live?.in_cooldown) { return { restriction: { @@ -3599,12 +3633,17 @@ export function createGeminiScheduler({ until: live.cooldown_until_ms || null, }, circuit: null, + liveUnschedulable: null, } } if (live?.probe_in_flight) { - return { restriction: { reason: 'probe_in_flight', text: '探测恢复中', until: null }, circuit: null } + return { + restriction: { reason: 'probe_in_flight', text: '探测恢复中', until: null }, + circuit: null, + liveUnschedulable: null, + } } - return { restriction: null, circuit: null } + return { restriction: null, circuit: null, liveUnschedulable: null } }, clearRestriction(envId) { @@ -4115,6 +4154,8 @@ export function createGeminiScheduler({ } let antigravityAdmissionChecked = false const canonicalCache = new Map() + const acpOverrides = policy?.acp_overrides || null + const baseAcpPolicy = resolveEffectiveAgyAcpPolicy({ routingOverrides: acpOverrides }) const allOAuthCandidates = dispatchAccounts.every(({ account }) => account.auth_method !== 'api_key') if ( allOAuthCandidates && @@ -4126,6 +4167,7 @@ export function createGeminiScheduler({ validateAntigravityTargetAdmission(inboundProtocol, rawInboundBody, { ir: parsedIr, continuationBinding, + acpPolicy: baseAcpPolicy, }) antigravityAdmissionChecked = true } catch (admErr) { @@ -4177,6 +4219,9 @@ export function createGeminiScheduler({ // Security: mint an unpredictable per-dispatch UUIDv4 for Rust scheduler idempotency; // never reuse client-controlled X-Request-Id (`requestId`) as Rust's acquire key. const schedulerRequestId = crypto.randomUUID() + // K4 hygiene: decouple worker-facing X-Request-Id from client-supplied requestId so client + // retries with duplicate X-Request-Id never trigger HTTP 409 request_id collisions in CRAGGemini. + const workerRequestIdBase = `gem_${crypto.randomBytes(12).toString('hex')}` const baseAcquireParams = { requestId: schedulerRequestId, originPoolId: resolvedOriginPoolId, @@ -4407,6 +4452,8 @@ export function createGeminiScheduler({ validateAntigravityTargetAdmission(inboundProtocol, rawInboundBody, { ir: parsedIr, continuationBinding, + targetAccountId: id, + acpPolicy: baseAcpPolicy, }) antigravityAdmissionChecked = true } catch (admErr) { @@ -4493,7 +4540,7 @@ export function createGeminiScheduler({ attemptConversationId = outboundConversationId if (outboundConversationId) lastConversationId = outboundConversationId - const attemptRequestId = attempts === 1 ? requestId : `${requestId}_a${attempts}`.slice(0, 128) + const attemptRequestId = buildAttemptRequestId(workerRequestIdBase, attempts) const proxySha256 = proxyUrl ? crypto.createHash('sha256').update(proxyUrl).digest('hex') : undefined const gatewayPolicy = typeof getRoutingConfig === 'function' @@ -4530,6 +4577,14 @@ export function createGeminiScheduler({ const useProviderResult = target === 'antigravity' && targetSupportsProviderResult(directTarget) const effectiveSessionEphemeral = supportsAcpAdmission && Boolean(sessionEphemeral) && !continuationBinding && !responseIdBinding + const targetAcpCaps = target === 'antigravity' ? resolveTargetAcpCapabilities(directTarget) : null + const effectiveTargetAcpPolicy = + target === 'antigravity' + ? resolveEffectiveAgyAcpPolicy({ + routingOverrides: acpOverrides, + targetProtocolCapabilities: targetAcpCaps, + }) + : baseAcpPolicy let canonicalized = null if ( @@ -4540,7 +4595,8 @@ export function createGeminiScheduler({ typeof rawInboundBody === 'object' && !Array.isArray(rawInboundBody) ) { - const canonKey = `${supportsAcpAdmission ? 1 : 0}:${supportsCleanAcpText ? 1 : 0}` + const extraKeySig = effectiveTargetAcpPolicy.extraAllowedBodyKeys.join(',') + const canonKey = `${supportsAcpAdmission ? 1 : 0}:${supportsCleanAcpText ? 1 : 0}:${extraKeySig}` canonicalized = canonicalCache.get(canonKey) || null if (!canonicalized) { canonicalized = canonicalizeInboundForAntigravity(inboundProtocol, rawInboundBody, { @@ -4548,9 +4604,27 @@ export function createGeminiScheduler({ headers: inboundHeaders, targetSupportsAcpAdmission: supportsAcpAdmission, escapeSlashes: !supportsCleanAcpText, + acpOverrides, + targetProtocolCapabilities: targetAcpCaps, }) canonicalCache.set(canonKey, canonicalized) } + // Post-canonicalization admission check: accounts for folded `` and decoded + // inline text attachments, enforces `continuationBinding.accountId === id`, and honors the + // target worker's effective `prompt_overflow_policy` (`truncate` vs `reject`). + try { + validateAntigravityTargetAdmission(inboundProtocol, canonicalized.body, { + routeModel: model || resolved?.publicId || null, + continuationBinding, + targetAccountId: id, + acpPolicy: effectiveTargetAcpPolicy, + }) + } catch (admErr) { + admErr.retryable = false + admErr.failoverable = false + admErr.tripCircuit = false + throw admErr + } } let wireProtocol = null diff --git a/src/lib/protocol/gemini-convert.mjs b/src/lib/protocol/gemini-convert.mjs index cf6580da86..9b492340dc 100644 --- a/src/lib/protocol/gemini-convert.mjs +++ b/src/lib/protocol/gemini-convert.mjs @@ -13,6 +13,12 @@ * never silently drop unsupported fields on restricted native-TUI slots. */ import crypto from 'node:crypto' +import { + AGY_ACP_ALLOWED_INLINE_IMAGE_MIMES, + DEFAULT_MAX_ACP_PROMPT_TEXT_BYTES, + DEFAULT_MAX_ACP_SYSTEM_PROMPT_APPEND_BYTES, + resolveEffectiveAgyAcpPolicy, +} from '../gemini/agy-acp-spec.mjs' import { avoidAgyBridgeParamCollisions, clientDeclaredAgyBridgeParam, @@ -3546,9 +3552,10 @@ export function parseInboundToGemini(protocol, body, { routeModel = null, routeS return { ...ir, ...capabilities } } -export const MAX_ANTIGRAVITY_TURN_TEXT_BYTES = 190_000 +export const MAX_ANTIGRAVITY_TURN_TEXT_BYTES = DEFAULT_MAX_ACP_PROMPT_TEXT_BYTES +export const MAX_ANTIGRAVITY_OOM_TEXT_BYTES = DEFAULT_MAX_ACP_SYSTEM_PROMPT_APPEND_BYTES -const ANTIGRAVITY_ALLOWED_IMAGE_MIMES = new Set(['image/png', 'image/jpeg', 'image/jpg', 'image/webp', 'image/gif']) +const ANTIGRAVITY_ALLOWED_IMAGE_MIMES = new Set([...AGY_ACP_ALLOWED_INLINE_IMAGE_MIMES, 'image/jpg']) const BASE64_CHUNK_RE = /^(?:[A-Za-z0-9+/_-]{4})*(?:[A-Za-z0-9+/_-]{2}(?:==)?|[A-Za-z0-9+/_-]{3}=?)?$/ @@ -3584,13 +3591,47 @@ function assertValidAntigravityMedia(media) { /** * Fail-closed pre-dispatch admission guard for CRAGGemini (`target === 'antigravity'`). * Enforces V2 limits across both native wire passthrough and IR fallback paths before any worker hop: - * - Single-turn merged user text <= 190,000 UTF-8 bytes (`prompt_part_too_long`) - * - Orphan `tool_result` without preceding `tool_call` or active `continuationBinding` (`unmatched_tool_result`) + * - Single-turn merged user text guard: in default `truncate` policy delegates >190KB to CRAGGemini layered + * truncation and enforces only the 4 MiB OOM cap; in explicit `reject` policy enforces `maxAcpPromptTextBytes` + * - Orphan `tool_result` without preceding `tool_call` or account-matching `continuationBinding` (`unmatched_tool_result`), + * with FIFO `unconsumedByName` callId rewrite for Gemini/legacy name-only tool responses * - Allowlisted inline images only (no PDF, audio, video, BMP/SVG, external URLs, `fileData`, or invalid base64) * - No unsupported server-hosted tools (`urlContext`, `web_fetch_*`, `codeExecution`, `googleMaps`, `fileSearch`) */ -export function validateAntigravityTargetAdmission(protocol, rawBody, { ir = null, continuationBinding = null } = {}) { - const parsed = ir || parseInboundToGemini(protocol, rawBody) +export function validateAntigravityTargetAdmission( + protocol, + rawBody, + { + ir = null, + routeModel = null, + continuationBinding = null, + targetAccountId = null, + acpPolicy = null, + routingOverrides = null, + targetProtocolCapabilities = null, + } = {}, +) { + const parsed = ir || parseInboundToGemini(protocol, rawBody, { routeModel }) + const effectivePolicy = + acpPolicy || + resolveEffectiveAgyAcpPolicy({ + routingOverrides, + targetProtocolCapabilities, + }) + const overflowPolicy = effectivePolicy?.promptOverflowPolicy === 'reject' ? 'reject' : 'truncate' + const oomCeiling = + Number.isInteger(effectivePolicy?.maxSystemPromptAppendBytes) && effectivePolicy.maxSystemPromptAppendBytes > 0 + ? effectivePolicy.maxSystemPromptAppendBytes + : MAX_ANTIGRAVITY_OOM_TEXT_BYTES + const turnTextLimit = + overflowPolicy === 'reject' + ? Math.min( + oomCeiling, + Number.isInteger(effectivePolicy?.maxAcpPromptTextBytes) && effectivePolicy.maxAcpPromptTextBytes > 0 + ? effectivePolicy.maxAcpPromptTextBytes + : MAX_ANTIGRAVITY_TURN_TEXT_BYTES, + ) + : oomCeiling if (Array.isArray(parsed.googleTools) && parsed.googleTools.length > 0) { const firstKey = Object.keys(parsed.googleTools[0] || {})[0] || 'server_tool' @@ -3605,6 +3646,12 @@ export function validateAntigravityTargetAdmission(protocol, rawBody, { ir = nul const seenCallIds = new Set() const seenCallNames = new Set() + const unconsumedByName = new Map() + const lastCallIdByName = new Map() + const hasMatchingContinuation = Boolean( + continuationBinding && + (!targetAccountId || !continuationBinding.accountId || continuationBinding.accountId === targetAccountId), + ) let mergedUserTextPieces = [] const flushUserTurnByteCheck = () => { @@ -3612,13 +3659,13 @@ export function validateAntigravityTargetAdmission(protocol, rawBody, { ir = nul const joined = mergedUserTextPieces.join('\n') mergedUserTextPieces = [] const actual = Buffer.byteLength(joined, 'utf8') - if (actual > MAX_ANTIGRAVITY_TURN_TEXT_BYTES) { + if (actual > turnTextLimit) { const err = makeProtocolError( 400, 'gemini_invalid_request', - `Single-turn user text exceeds ${MAX_ANTIGRAVITY_TURN_TEXT_BYTES} UTF-8 bytes (${actual} bytes).`, + `Single-turn user text exceeds ${turnTextLimit} UTF-8 bytes (${actual} bytes).`, ) - err.details = { reason: 'prompt_part_too_long', limit: MAX_ANTIGRAVITY_TURN_TEXT_BYTES, actual } + err.details = { reason: 'prompt_part_too_long', limit: turnTextLimit, actual, policy: overflowPolicy } throw err } } @@ -3630,7 +3677,18 @@ export function validateAntigravityTargetAdmission(protocol, rawBody, { ir = nul for (const part of msg.parts || []) { if (part?.kind === 'tool_call') { if (part.id) seenCallIds.add(part.id) - if (part.name) seenCallNames.add(part.name) + if (part.name) { + seenCallNames.add(part.name) + if (part.id) { + lastCallIdByName.set(part.name, part.id) + let queue = unconsumedByName.get(part.name) + if (!queue) { + queue = [] + unconsumedByName.set(part.name, queue) + } + queue.push(part.id) + } + } } } continue @@ -3643,10 +3701,25 @@ export function validateAntigravityTargetAdmission(protocol, rawBody, { ir = nul assertValidAntigravityMedia(part) } else if (part.kind === 'tool_result') { const matchedById = Boolean(part.callId && seenCallIds.has(part.callId)) + if (matchedById && part.name) { + const queue = unconsumedByName.get(part.name) + if (queue?.length) { + const idx = queue.indexOf(part.callId) + if (idx >= 0) queue.splice(idx, 1) + } + } const matchedByName = + !matchedById && Boolean(part.name && seenCallNames.has(part.name)) && (protocol === 'gemini' || parsed.legacyFunctions === true) - if (!matchedById && !matchedByName && !continuationBinding) { + if (matchedByName) { + const queue = unconsumedByName.get(part.name) + const resolvedId = queue?.length ? queue.shift() : lastCallIdByName.get(part.name) || '' + if (resolvedId) { + part.callId = resolvedId + } + } + if (!matchedById && !matchedByName && !hasMatchingContinuation) { const err = makeProtocolError( 400, 'gemini_invalid_request', @@ -4342,37 +4415,74 @@ function stopToAnthropicReason(stop) { function geminiErrorInfoReason(error) { const details = Array.isArray(error?.details) ? error.details : [] - const info = details.find( - (item) => - item?.['@type'] === 'type.googleapis.com/google.rpc.ErrorInfo' && typeof item.reason === 'string' && item.reason, - ) + const info = + details.find( + (item) => + item?.['@type'] === 'type.googleapis.com/google.rpc.ErrorInfo' && + typeof item.reason === 'string' && + item.reason, + ) || details.find((item) => item && typeof item === 'object' && typeof item.reason === 'string' && item.reason) return info ? { reason: info.reason } : {} } +function parseOptionalBoolFlag(val) { + if (typeof val === 'boolean') return val + if (typeof val === 'string') { + const lower = val.trim().toLowerCase() + if (lower === 'true') return true + if (lower === 'false') return false + } + return undefined +} + function geminiErrorControlFields(outer, inner = null) { const out = {} - const details = isPlainObject(inner?.details) ? inner.details : isPlainObject(outer?.details) ? outer.details : null + const detailsObj = isPlainObject(inner?.details) + ? inner.details + : isPlainObject(outer?.details) + ? outer.details + : null + const detailsArr = Array.isArray(inner?.details) ? inner.details : Array.isArray(outer?.details) ? outer.details : [] + let arrRetryable + let arrFailoverable + let arrWorkerCode + for (const item of detailsArr) { + if (!isPlainObject(item)) continue + if (arrRetryable === undefined) { + arrRetryable = parseOptionalBoolFlag(item.retryable) ?? parseOptionalBoolFlag(item.metadata?.retryable) + } + if (arrFailoverable === undefined) { + arrFailoverable = parseOptionalBoolFlag(item.failoverable) ?? parseOptionalBoolFlag(item.metadata?.failoverable) + } + if (!arrWorkerCode) { + const wc = + (typeof item.worker_code === 'string' && item.worker_code.trim()) || + (typeof item.metadata?.worker_code === 'string' && item.metadata.worker_code.trim()) + if (wc) arrWorkerCode = wc + } + } const retryable = typeof outer?.retryable === 'boolean' ? outer.retryable : typeof inner?.retryable === 'boolean' ? inner.retryable - : typeof details?.retryable === 'boolean' - ? details.retryable - : undefined + : typeof detailsObj?.retryable === 'boolean' + ? detailsObj.retryable + : arrRetryable if (typeof retryable === 'boolean') out.retryable = retryable const failoverable = typeof outer?.failoverable === 'boolean' ? outer.failoverable : typeof inner?.failoverable === 'boolean' ? inner.failoverable - : typeof details?.failoverable === 'boolean' - ? details.failoverable - : undefined + : typeof detailsObj?.failoverable === 'boolean' + ? detailsObj.failoverable + : arrFailoverable if (typeof failoverable === 'boolean') out.failoverable = failoverable const workerCode = (typeof outer?.worker_code === 'string' && outer.worker_code.trim()) || - (typeof inner?.worker_code === 'string' && inner.worker_code.trim()) + (typeof inner?.worker_code === 'string' && inner.worker_code.trim()) || + arrWorkerCode if (workerCode) out.worker_code = workerCode const upstreamStatus = Number.isInteger(outer?.upstream_status) ? outer.upstream_status @@ -4433,6 +4543,7 @@ export function parseGeminiSseFrame(frame) { (typeof parsed?.code === 'string' && parsed.code) || 'gemini_inference_failed', message: parsed?.error?.message || parsed?.message || 'Gemini stream error', + rawPayload: parsed, ...geminiErrorInfoReason(parsed?.error || parsed), ...geminiErrorControlFields(parsed, parsed?.error), } @@ -4460,6 +4571,7 @@ export function parseGeminiSseFrame(frame) { (typeof payload.code === 'string' && payload.code) || 'gemini_inference_failed', message: payload.error.message || 'Gemini returned an error frame', + rawPayload: payload, ...geminiErrorInfoReason(payload.error), ...geminiErrorControlFields(payload, payload.error), } @@ -4475,6 +4587,7 @@ export function parseGeminiSseFrame(frame) { response.error.status || 'gemini_inference_failed', message: response.error.message || 'Gemini returned an error frame', + rawPayload: response, ...geminiErrorInfoReason(response.error), ...geminiErrorControlFields(response, response.error), } diff --git a/test/unit/convert-stream.test.mjs b/test/unit/convert-stream.test.mjs index d9efc587a4..309c43cb31 100644 --- a/test/unit/convert-stream.test.mjs +++ b/test/unit/convert-stream.test.mjs @@ -732,7 +732,8 @@ test('Step 4 ANT/CHAT/RESP/GEM table-driven canonicalization & fail-closed 400 a assert.match(serialized, //) } - // Exact 190,000B passes, 190,001B fails with details.reason === 'prompt_part_too_long' + // Default `truncate` policy allows 190,000B & 190,001B (delegated to CRAGGemini layered truncation) + // while keeping the 4 MiB OOM cap; explicit `reject` policy still enforces exact 190,000B. const exact190k = { model: 'gemini-4-neon', max_tokens: 64, @@ -745,11 +746,26 @@ test('Step 4 ANT/CHAT/RESP/GEM table-driven canonicalization & fail-closed 400 a max_tokens: 64, messages: [{ role: 'user', content: 'a'.repeat(190_001) }], } + assert.doesNotThrow(() => + validateAntigravityTargetAdmission('anthropic', over190k, { ir: parseInboundToGemini('anthropic', over190k) }), + ) assert.throws( () => - validateAntigravityTargetAdmission('anthropic', over190k, { ir: parseInboundToGemini('anthropic', over190k) }), + validateAntigravityTargetAdmission('anthropic', over190k, { + ir: parseInboundToGemini('anthropic', over190k), + routingOverrides: { prompt_overflow_policy: 'reject' }, + }), (err) => err.status === 400 && err.details?.reason === 'prompt_part_too_long' && err.details?.limit === 190_000, ) + const over4m = { + model: 'gemini-4-neon', + max_tokens: 64, + messages: [{ role: 'user', content: 'a'.repeat(4 * 1024 * 1024 + 1) }], + } + assert.throws( + () => validateAntigravityTargetAdmission('anthropic', over4m, { ir: parseInboundToGemini('anthropic', over4m) }), + (err) => err.status === 400 && err.details?.reason === 'prompt_part_too_long' && err.details?.limit === 4_194_304, + ) // Table-driven 400 rejection cases across all 4 protocols const reject400Cases = [ diff --git a/test/unit/gemini-convert.test.mjs b/test/unit/gemini-convert.test.mjs index 28905076b4..35f86fe2c8 100644 --- a/test/unit/gemini-convert.test.mjs +++ b/test/unit/gemini-convert.test.mjs @@ -2612,15 +2612,22 @@ test('C5 inline text media: decodes UTF-8 text inlineData to text parts, enforce }) assert.deepEqual(anthCanon.body.messages[0].content, [{ type: 'text', text: mdText }]) - // 2. Decoded text MUST still be enforced by Antigravity 190,000-byte single-turn text gate (no bypass) + // 2. Decoded text obeys effective prompt_overflow_policy: + // - default `truncate` delegates >190,000B to CRAGGemini layered truncation while enforcing the 4 MiB OOM cap + // - explicit `reject` still enforces the 190,000-byte single-turn text gate (no bypass) const overTurnLimitB64 = Buffer.from('a'.repeat(MAX_ANTIGRAVITY_TURN_TEXT_BYTES + 1), 'utf8').toString('base64') const overTurnBody = { model: 'gemini-4-hydrogen', contents: [{ role: 'user', parts: [{ inlineData: { mimeType: 'text/markdown', data: overTurnLimitB64 } }] }], } const overTurnIr = parseInboundToGemini('gemini', overTurnBody) + assert.doesNotThrow(() => validateAntigravityTargetAdmission('gemini', overTurnBody, { ir: overTurnIr })) assert.throws( - () => validateAntigravityTargetAdmission('gemini', overTurnBody, { ir: overTurnIr }), + () => + validateAntigravityTargetAdmission('gemini', overTurnBody, { + ir: overTurnIr, + routingOverrides: { prompt_overflow_policy: 'reject' }, + }), (err) => err?.status === 400 && err?.details?.reason === 'prompt_part_too_long', ) @@ -2699,3 +2706,109 @@ test('C5 inline text media: decodes UTF-8 text inlineData to text parts, enforce assert.deepEqual(imgIr.messages[0].parts, [{ kind: 'image', mediaType: mimeType, data: pngB64 }]) } }) + +test('ACP 190K truncation alignment, K2 FIFO unconsumedByName + scoped continuationBinding, and K4 SSE RPC details/rawPayload', async () => { + const { mapCragWorkerError } = await import('../../src/lib/gemini/direct-client.mjs') + + // 1. Default `truncate` allows >190KB (for CRAGGemini layered truncation) but still enforces 4 MiB OOM cap + const body200k = { + model: 'gemini-4-neon', + contents: [{ role: 'user', parts: [{ text: 'x'.repeat(200_000) }] }], + } + assert.doesNotThrow(() => validateAntigravityTargetAdmission('gemini', body200k)) + assert.throws( + () => + validateAntigravityTargetAdmission('gemini', body200k, { + targetProtocolCapabilities: { prompt_overflow_policy: 'reject', max_acp_prompt_text_bytes: 190_000 }, + }), + (err) => + err?.status === 400 && err?.details?.reason === 'prompt_part_too_long' && err?.details?.policy === 'reject', + ) + const bodyOver4MiB = { + model: 'gemini-4-neon', + contents: [{ role: 'user', parts: [{ text: 'y'.repeat(4 * 1024 * 1024 + 1) }] }], + } + assert.throws( + () => validateAntigravityTargetAdmission('gemini', bodyOver4MiB), + (err) => + err?.status === 400 && err?.details?.reason === 'prompt_part_too_long' && err?.details?.policy === 'truncate', + ) + + // 2. K2: Gemini parallel same-name tool_results with mismatched synthetic IDs rewrite FIFO to actual call IDs + const fifoBody = { + model: 'gemini-4-neon', + contents: [ + { role: 'user', parts: [{ text: 'read two files' }] }, + { + role: 'model', + parts: [ + { functionCall: { id: 'fc_real_1', name: 'read_file', args: { path: 'a.txt' } } }, + { functionCall: { id: 'fc_real_2', name: 'read_file', args: { path: 'b.txt' } } }, + ], + }, + { + role: 'user', + parts: [ + { functionResponse: { id: 'wrong_synthetic_1', name: 'read_file', response: { content: 'A' } } }, + { functionResponse: { id: 'wrong_synthetic_2', name: 'read_file', response: { content: 'B' } } }, + ], + }, + ], + } + const fifoIr = parseInboundToGemini('gemini', fifoBody) + validateAntigravityTargetAdmission('gemini', fifoBody, { ir: fifoIr }) + const toolResults = fifoIr.messages[2].parts.filter((p) => p.kind === 'tool_result') + assert.deepEqual( + toolResults.map((p) => p.callId), + ['fc_real_1', 'fc_real_2'], + ) + + // 3. K2: continuationBinding orphan exemption is scoped to continuationBinding.accountId === targetAccountId + const orphanToolResultBody = { + model: 'gemini-4-neon', + max_tokens: 128, + messages: [{ role: 'user', content: [{ type: 'tool_result', tool_use_id: 'call_suspended_1', content: 'done' }] }], + } + const binding = { accountId: 'env-a', conversationId: 'conv_1', sessionId: 'sess_1' } + assert.doesNotThrow(() => + validateAntigravityTargetAdmission('anthropic', orphanToolResultBody, { + continuationBinding: binding, + targetAccountId: 'env-a', + }), + ) + assert.throws( + () => + validateAntigravityTargetAdmission('anthropic', orphanToolResultBody, { + continuationBinding: binding, + targetAccountId: 'env-b', + }), + (err) => err?.status === 400 && err?.details?.reason === 'unmatched_tool_result', + ) + + // 4. K4: parseGeminiSseFrame preserves rawPayload and parses Google RPC array details[].metadata.{retryable,failoverable} + const rpcCancelledFrame = `data: ${JSON.stringify({ + error: { + code: 499, + status: 'CANCELLED', + message: 'Turn cancelled by client', + details: [ + { + '@type': 'type.googleapis.com/google.rpc.ErrorInfo', + reason: 'cancelled', + metadata: { retryable: 'false', failoverable: 'false' }, + }, + ], + }, + })}\n\n` + const parsedSse = parseGeminiSseFrame(rpcCancelledFrame) + assert.equal(parsedSse.kind, 'error') + assert.equal(parsedSse.reason, 'cancelled') + assert.equal(parsedSse.retryable, false) + assert.equal(parsedSse.failoverable, false) + assert.ok(parsedSse.rawPayload && typeof parsedSse.rawPayload === 'object') + const mappedCancelled = mapCragWorkerError(parsedSse.status, parsedSse.rawPayload) + assert.equal(mappedCancelled.status, 499) + assert.equal(mappedCancelled.code, 'gemini_inference_cancelled') + assert.equal(mappedCancelled.retryable, false) + assert.equal(mappedCancelled.failoverable, false) +}) diff --git a/test/unit/gemini-maintenance-install-contract.test.mjs b/test/unit/gemini-maintenance-install-contract.test.mjs index bdbf31bf96..8173190172 100644 --- a/test/unit/gemini-maintenance-install-contract.test.mjs +++ b/test/unit/gemini-maintenance-install-contract.test.mjs @@ -148,3 +148,51 @@ subprocess.run = record_execution if (!trusted) assert.match(result.stderr, /Gemini agy version unknown:/) }) } + +test('gemini-host.py and gemini-maintenance.py enforce min_agy_version 1.5.20, pass through /status capabilities, and serialize validation_url in send_json_error', () => { + const pyCheck = ` +import importlib.util, io, json, pathlib, sys +root = pathlib.Path(sys.argv[1]) +sys.path.insert(0, str(root / 'scripts')) + +def load_mod(name, rel): + spec = importlib.util.spec_from_file_location(name, root / rel) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + +host_mod = load_mod('gemini_host_contract', 'scripts/gemini-host.py') +assert host_mod.MIN_AGY_VERSION == '1.5.20', host_mod.MIN_AGY_VERSION +assert host_mod.agy_version_meets_min('1.5.20') is True +assert host_mod.agy_version_meets_min('1.5.21') is True +assert host_mod.agy_version_meets_min('1.5.9') is False + +# ControlHandler.send_json_error accepts validation_url without TypeError and emits it in JSON +captured = {} +class DummyHandler(host_mod.ControlHandler): + def __init__(self): + self._headers_sent = False + self.wfile = io.BytesIO() + def send_response(self, status): + captured['status'] = status + def send_header(self, k, v): + captured.setdefault('headers', {})[k] = v + def end_headers(self): + pass + +h = DummyHandler() +h.send_json_error(403, 'gemini_account_ineligible', 'ToS disabled', upstream_reason='TOS_VIOLATION', validation_url='https://forms.gle/test123') +body = json.loads(h.wfile.getvalue().decode('utf-8')) +assert captured['status'] == 403 +assert body['validation_url'] == 'https://forms.gle/test123', body + +maint_mod = load_mod('gemini_maint_contract', 'scripts/gemini-maintenance.py') +assert maint_mod.MIN_AGY_VERSION == '1.5.20', maint_mod.MIN_AGY_VERSION +assert maint_mod.version_order('1.5.9') < maint_mod.version_order(maint_mod.MIN_AGY_VERSION) +assert maint_mod.version_order('1.5.20') >= maint_mod.version_order(maint_mod.MIN_AGY_VERSION) +print('PY_CONTRACT_OK') +` + const res = spawnSync('python3', ['-c', pyCheck, root], { encoding: 'utf8', timeout: 15_000 }) + assert.equal(res.status, 0, res.stderr || res.stdout) + assert.match(res.stdout, /PY_CONTRACT_OK/) +}) diff --git a/test/unit/gemini-prompt-normalizer.test.mjs b/test/unit/gemini-prompt-normalizer.test.mjs index 2b0feeb432..5515471589 100644 --- a/test/unit/gemini-prompt-normalizer.test.mjs +++ b/test/unit/gemini-prompt-normalizer.test.mjs @@ -602,3 +602,133 @@ test('normalizes expanded upstream-429 trigger phrases (Hermes, omp, OpenCode, p 'fenced code blocks inside user turns must stay untouched', ) }) + +test('agy-acp-spec SSOT, dynamic allowlist overrides, expanded text MIMEs, and Gemini functionResponse control-char hygiene', async () => { + const fs = await import('node:fs') + const os = await import('node:os') + const path = await import('node:path') + const { AGY_ACP_SPEC, AGY_ACP_SPEC_SHA256, MIN_AGY_VERSION, agyVersionMeetsMin, loadAgyAcpSpecFromFile } = + await import('../../src/lib/gemini/agy-acp-spec.mjs') + const { canonicalizeInboundForAntigravity, isInlinePlainTextMime, sanitizeJsonControlCharsDeep } = await import( + '../../src/lib/gemini/prompt-normalizer.mjs' + ) + + // 1. Bundled SSOT contract & semver gate + assert.equal(AGY_ACP_SPEC.schema_version, 1) + assert.equal(MIN_AGY_VERSION, '1.5.20') + assert.equal(AGY_ACP_SPEC.limits.prompt_overflow_policy, 'truncate') + assert.match(AGY_ACP_SPEC_SHA256, /^[a-f0-9]{64}$/) + assert.equal(agyVersionMeetsMin('1.5.20'), true) + assert.equal(agyVersionMeetsMin('1.5.21'), true) + assert.equal(agyVersionMeetsMin('1.5.9'), false) + assert.equal(agyVersionMeetsMin('1.5.20-rc.1'), false) + + // 2. Runtime spec override via loadAgyAcpSpecFromFile / KIN_AGY_ACP_SPEC_PATH + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vm2api-agy-spec-')) + try { + const customPath = path.join(tmpDir, 'custom-acp-spec.json') + const customSpec = structuredClone(AGY_ACP_SPEC) + customSpec.top_level_fields.extra_allowed_body_keys = ['x_custom_acp_flag'] + fs.writeFileSync(customPath, `${JSON.stringify(customSpec, null, 2)}\n`, 'utf8') + const loaded = loadAgyAcpSpecFromFile(customPath) + assert.deepEqual(loaded.spec.top_level_fields.extra_allowed_body_keys, ['x_custom_acp_flag']) + assert.notEqual(loaded.sha256, AGY_ACP_SPEC_SHA256) + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }) + } + + // 3. Expanded text MIMEs (22 application/* + application/*+{json,xml,yaml}) vs forbidden binary/SVG + for (const okMime of [ + 'text/plain; charset=utf-8', + 'application/json', + 'application/problem+json', + 'application/vnd.api+json', + 'application/atom+xml', + 'application/vnd.custom+yaml', + 'application/toml', + 'application/typescript', + 'application/sql', + 'application/x-sh', + ]) { + assert.equal(isInlinePlainTextMime(okMime), true, `expected decodable text MIME: ${okMime}`) + } + for (const blockedMime of ['image/svg+xml', 'application/pdf', 'video/mp4', 'image/png']) { + assert.equal(isInlinePlainTextMime(blockedMime), false, `expected non-text MIME: ${blockedMime}`) + } + assert.equal( + isInlinePlainTextMime('application/x-custom-log', { + extraDecodableTextMimes: new Set(['application/x-custom-log']), + }), + true, + ) + + // 4. Dynamic extra_allowed_body_keys via acpOverrides & targetProtocolCapabilities + const withCustomField = { + model: 'gemini-4-neon', + contents: [{ role: 'user', parts: [{ text: 'hello' }] }], + custom_vendor_opt: { enabled: true }, + unregistered_noise: 123, + } + const strippedDefault = canonicalizeInboundForAntigravity('gemini', withCustomField, { + targetSupportsAcpAdmission: true, + escapeSlashes: false, + }) + assert.equal(Object.hasOwn(strippedDefault.body, 'custom_vendor_opt'), false) + assert.ok(strippedDefault.report.unknown_top_fields_observed.includes('custom_vendor_opt')) + + const allowedOverride = canonicalizeInboundForAntigravity('gemini', withCustomField, { + targetSupportsAcpAdmission: true, + escapeSlashes: false, + acpOverrides: { extra_allowed_body_keys: ['custom_vendor_opt'] }, + }) + assert.deepEqual(allowedOverride.body.custom_vendor_opt, { enabled: true }) + assert.equal(Object.hasOwn(allowedOverride.body, 'unregistered_noise'), false) + + const allowedFromWorker = canonicalizeInboundForAntigravity('gemini', withCustomField, { + targetSupportsAcpAdmission: true, + escapeSlashes: false, + targetProtocolCapabilities: { extra_allowed_body_keys: ['custom_vendor_opt'] }, + }) + assert.deepEqual(allowedFromWorker.body.custom_vendor_opt, { enabled: true }) + + // 5. Gemini functionResponse.{response,parts} ANSI & C0 control-char stripping (idempotent, copy-on-write) + const dirtyFrBody = { + model: 'gemini-4-neon', + contents: [ + { role: 'user', parts: [{ text: 'run check' }] }, + { role: 'model', parts: [{ functionCall: { id: 'fc_1', name: 'bash', args: { cmd: 'ls' } } }] }, + { + role: 'user', + parts: [ + { + functionResponse: { + id: 'fc_1', + name: 'bash', + response: { + stdout: '\x1b[32mOK\x1b[0m\x00line1\n\tline2\x07', + nested: [{ msg: 'warn\x08\x1f!' }], + }, + parts: [{ text: 'detail\x1b[31mRED\x1b[0m\x0bend' }], + }, + }, + ], + }, + ], + } + const cleaned1 = canonicalizeInboundForAntigravity('gemini', dirtyFrBody, { + targetSupportsAcpAdmission: true, + escapeSlashes: false, + }) + const cleaned2 = canonicalizeInboundForAntigravity('gemini', cleaned1.body, { + targetSupportsAcpAdmission: true, + escapeSlashes: false, + }) + assert.deepEqual(cleaned2.body, cleaned1.body, 'functionResponse control-char cleanup must be idempotent') + const cleanFr = cleaned1.body.contents[2].parts[0].functionResponse + assert.equal(cleanFr.response.stdout, 'OKline1\n\tline2') + assert.equal(cleanFr.response.nested[0].msg, 'warn!') + assert.equal(cleanFr.parts[0].text, 'detailREDend') + assert.ok(cleaned1.report.rules_applied.includes('transport_control_chars')) + assert.equal(dirtyFrBody.contents[2].parts[0].functionResponse.response.stdout.includes('\x00'), true) + assert.deepEqual(sanitizeJsonControlCharsDeep({ a: 'x\x00y' }), { a: 'xy' }) +}) diff --git a/test/unit/gemini-scheduling-status.test.mjs b/test/unit/gemini-scheduling-status.test.mjs index 45a4fb463c..796c7c1286 100644 --- a/test/unit/gemini-scheduling-status.test.mjs +++ b/test/unit/gemini-scheduling-status.test.mjs @@ -1880,3 +1880,166 @@ test('L2-16: pre-dispatch Gemini quota exhaustion switches via rt.switchNode and assert.deepEqual(dispatchCalls, ['env-b']) assert.deepEqual(unitCircuitCalls, []) }) + +test('ACP overrides validation, direct-client capability passthrough, decoupled attemptRequestId, post-canon admission, and Rust permanent_unschedulable SSOT', async () => { + const { resolveTargetAcpCapabilities } = await import('../../src/lib/gemini/direct-client.mjs') + + // 1. routing-config acp_overrides validation & merge + validateGeminiRoutingPatch({ + gemini: { + acp_overrides: { + extra_allowed_body_keys: ['custom_flag'], + max_acp_prompt_text_bytes: 180_000, + prompt_overflow_policy: 'truncate', + extra_decodable_text_mimes: ['application/x-custom-log'], + }, + }, + }) + assert.throws(() => validateGeminiRoutingPatch({ gemini: { acp_overrides: { prompt_overflow_policy: 'drop' } } }), { + code: 'invalid_gemini_acp_overrides', + }) + assert.throws( + () => validateGeminiRoutingPatch({ gemini: { acp_overrides: { extra_decodable_text_mimes: ['image/svg+xml'] } } }), + { code: 'invalid_gemini_acp_overrides' }, + ) + const mergedRouting = mergeGeminiRouting(DEFAULT_GEMINI_ROUTING, { + acp_overrides: { extra_allowed_body_keys: ['custom_flag'], prompt_overflow_policy: 'reject' }, + }) + assert.deepEqual(mergedRouting.acp_overrides.extra_allowed_body_keys, ['custom_flag']) + assert.equal(mergedRouting.acp_overrides.prompt_overflow_policy, 'reject') + + // 2. direct-client capability normalization & resolveTargetAcpCapabilities + const normalizedCaps = normalizeTargetCapabilities(['internal_wire_protocol_v1'], { + internal_wire_protocols: ['anthropic', 'gemini'], + acp_admission_v1: true, + kernel_version: '0.6.4', + agy_version: '1.5.20', + min_agy_version: '1.5.20', + agy_version_compatible: true, + acp_spec_sha256: 'a'.repeat(64), + max_acp_prompt_text_bytes: 190_000, + prompt_overflow_policy: 'truncate', + extra_allowed_body_keys: ['vendor_ext'], + }) + const acpCaps = resolveTargetAcpCapabilities({ protocolCapabilities: normalizedCaps.protocolCapabilities }) + assert.equal(acpCaps.kernel_version, '0.6.4') + assert.equal(acpCaps.agy_version, '1.5.20') + assert.equal(acpCaps.agy_version_compatible, true) + assert.equal(acpCaps.prompt_overflow_policy, 'truncate') + assert.deepEqual(acpCaps.extra_allowed_body_keys, ['vendor_ext']) + + // 3. 409 session conflict classifies as request_protocol with circuit: false + const conflictPolicy = classifyGeminiFailure({ code: 'gemini_session_conflict', upstreamStatus: 409 }) + assert.equal(conflictPolicy.circuit, false) + assert.equal(conflictPolicy.schedulerErrorClass, 'request_protocol') + + // 4. K4 decoupled attemptRequestId + post-canonicalization admission check + Rust permanent_unschedulable SSOT + const envs = [makeEnv('env-live')] + const seenWorkerReqIds = [] + let livePermanentBanned = false + const rt = { + ...makeMockGeminiRuntime(), + liveNodeState(nodeKey) { + if (nodeKey === 'gemini_env:env-live' && livePermanentBanned) { + return { + node_key: nodeKey, + schedulable: false, + unschedulable_reason: 'permanent_ban', + in_cooldown: false, + cooldown_until_ms: 0, + cooldown_left_ms: 0, + cooldown_reason: null, + probe_in_flight: false, + } + } + return null + }, + } + let routingAcpOverrides = { prompt_overflow_policy: 'truncate', max_acp_prompt_text_bytes: null } + const scheduler = createGeminiScheduler({ + schedulerRuntime: rt, + resolveProxy: () => 'socks5h://u:p@192.0.2.10:1080', + callHost: async (op, payload) => { + if (op === 'list') return { payload_state: 'installed', environments: envs } + if (op === 'get') return envs.find((e) => e.id === payload.id) + return {} + }, + callHostStream: async (_op, payload) => { + seenWorkerReqIds.push(payload.request_id) + return okSse('ok') + }, + getRoutingConfig: () => ({ + gemini: mergeGeminiRouting(DEFAULT_GEMINI_ROUTING, { acp_overrides: routingAcpOverrides }), + }), + }) + + // Identical client requestId across two dispatches MUST mint distinct worker request_ids (never collide 409) + await scheduler.stream({ + model: 'gemini-4-neon-high', + requestId: 'client-duplicate-x-request-id', + geminiBody: { contents: [{ role: 'user', parts: [{ text: 'first' }] }] }, + }) + await scheduler.stream({ + model: 'gemini-4-neon-high', + requestId: 'client-duplicate-x-request-id', + geminiBody: { contents: [{ role: 'user', parts: [{ text: 'second' }] }] }, + }) + assert.equal(seenWorkerReqIds.length, 2) + assert.notEqual(seenWorkerReqIds[0], 'client-duplicate-x-request-id') + assert.notEqual(seenWorkerReqIds[1], 'client-duplicate-x-request-id') + assert.notEqual(seenWorkerReqIds[0], seenWorkerReqIds[1]) + assert.match(seenWorkerReqIds[0], /^gem_[a-f0-9]{24}$/) + + // Post-canonicalization admission catches folded mid-turn system reminder pushing user turn over reject limit + routingAcpOverrides = { prompt_overflow_policy: 'reject', max_acp_prompt_text_bytes: 16_384 } + const beforeRejectCount = seenWorkerReqIds.length + const midSystemOverflowBody = { + model: 'gemini-4-neon-high', + messages: [ + { role: 'user', content: 'start' }, + { role: 'assistant', content: 'ack' }, + { role: 'system', content: 'R'.repeat(16_300) }, + { role: 'user', content: 'U'.repeat(500) }, + ], + } + await assert.rejects( + () => + scheduler.stream({ + model: 'gemini-4-neon-high', + inboundProtocol: 'openai-chat', + rawInboundBody: midSystemOverflowBody, + }), + (err) => err?.status === 400 && err?.details?.reason === 'prompt_part_too_long' && err?.tripCircuit === false, + ) + assert.equal(seenWorkerReqIds.length, beforeRejectCount, 'post-canon 400 must not dispatch to worker') + + // Rust permanent_unschedulable surfaces cleanly in environmentRestriction and panel environmentView + livePermanentBanned = true + const rest = scheduler.environmentRestriction('env-live') + assert.equal(rest.restriction?.reason, 'permanent_ban') + assert.equal(rest.restriction?.permanent, true) + assert.equal(rest.liveUnschedulable?.reason, 'permanent_ban') + assert.equal(rest.circuit, null) + + const panelHandle = createGeminiPanelHandler({ + json: (_res, status, body) => ({ status, body }), + readBody: async () => ({}), + proxyPool: () => ({ snapshot: () => ({ proxies: [{ id: 'px-env-live', url: 'socks5h://127.0.0.1:1080' }] }) }), + geminiScheduler: scheduler, + callHost: async (op) => { + if (op === 'list') return { payload_state: 'installed', environments: envs } + return {} + }, + }) + const listRes = await panelHandle( + { method: 'GET', url: '/api/panel/gemini', headers: {} }, + { setHeader() {} }, + '/api/panel/gemini', + ) + assert.equal(listRes.status, 200) + const projected = listRes.body?.data?.environments?.[0] + assert.equal(projected?.schedulable, false) + assert.equal(projected?.unschedulable_reason, 'permanent_ban') + assert.equal(projected?.restriction?.permanent, true) + assert.equal(projected?.circuit, undefined) +}) From bf9589e9b68c6a859a3e2b1f039d837d7a37dd46 Mon Sep 17 00:00:00 2001 From: dofastted Date: Wed, 2 Dec 2026 00:45:27 +0800 Subject: [PATCH 2/4] chore(gemini): pin CRAGGemini 0.6.4 continuation payload in deploy/payload.json 1. Changed files & core intent: - Updated `deploy/payload.json` `geminiDefaultLinuxAmd64` to pin `payload-2026.12.01-gemini-0.6.4` (`craggemini`, `craggemini.payload.enc`, `libagy_bridge.so`, `crag-license-public.pem`, `manifest.json`) with zero key rotation (`crag-license-public.pem` SHA-256 unchanged: `f6e3ef3a50fd49abd4ce3519db512af74fc438b47b1bbec83f6602ebe4b3930a`). 2. Root cause & rejected alternatives: - Root cause: `payload-2026.12.01-gemini-0.6.3` contained `split_acp_prompt_parts` which was silently tail-truncated by `agy 1.5.20`; CRAGGemini `0.6.4` (PR dofastted/antigravity-cli-proxy#36) replaces it with `acp_spec.json` SSOT, `agy >= 1.5.20` compatibility reporting, and layered overflow + head/tail UTF-8 truncation. - Rejected alternatives: overwriting published prerelease `0.6.3` (violates immutable release rule) or rotating production signing keys. 3. Verification commands & real results: - `gh release view payload-2026.12.01-gemini-0.6.4 --repo dofastted/vm2api` -> 5/5 asset sizes & SHA-256 digests match `deploy/payload.json` verbatim. - `python3 scripts/fetch-default-gemini.py --manifest deploy/payload.json --dest <0700 tmpdir> --reuse-agy ...` -> PASS (`Verified Gemini payload 0.6.4`, exit 0). - `node scripts/sync-agy-acp-spec.mjs --check --kernel-spec /mnt/x/antigravity-cli-proxy-wt-acp-spec-truncation/src/acp_spec.json` -> PASS (`sha256=1dd063cb9519d20c3b28b281d2eca4be89e109a4f88bfe3ee6b688d8cf827631`). - `find src scripts -name '*.mjs' -print0 | xargs -0 -n1 node --check` + `npx biome check` (14 files) + `python3 -m py_compile` + 4 Python suites + 4 Gemini JS suites (72/72) + `npm run test:ci` (13/13) -> ALL PASS. 4. Broken-by-hand evidence: - Prior commit `0a5ab73eb` verified `parseGeminiSseFrame` `rawPayload` hand-break (FAIL -> restore -> PASS); `fetch-default-gemini.py` live download verifies exact size + SHA-256 + Ed25519 signature of every pinned 0.6.4 asset. 5. Unverified / follow-up items: - `ph24` production rollout and live traffic verification follow PR merge. --- deploy/payload.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/deploy/payload.json b/deploy/payload.json index b0b75249a3..c5ef68ad4f 100644 --- a/deploy/payload.json +++ b/deploy/payload.json @@ -40,19 +40,19 @@ "payload_key_id": "835451e266145220a2e75b1f39ff22a0d7b17be48395553a24666b1946e0333a" }, "geminiDefaultLinuxAmd64": { - "tag": "payload-2026.12.01-gemini-0.6.2", + "tag": "payload-2026.12.01-gemini-0.6.4", "assets": { "craggemini": { - "size": 1038416, - "sha256": "5408e9a9439a03920a491d6ad7b59a69d2e152fc5e08e1225c816b410501a537" + "size": 1046952, + "sha256": "6423fa9d62795281ffa357ba96f9de04d608e7688af0ec9634b6bb974eb5bee1" }, "craggemini.payload.enc": { - "size": 6199276, - "sha256": "92b3f89bed70d7819b270e11ae2150fa0cef2c54e26bb58d29706e2e1b5cc79e" + "size": 6352996, + "sha256": "c444ce5d1073829317bdc5e868f31ac6df6684918f2803d431786ef19335d078" }, "libagy_bridge.so": { - "size": 676576, - "sha256": "fb1b58b88fd1d2afd484ed54c08b7cc05e2d3c9ef6d1e0c06b90b4ca353f2ee4" + "size": 685088, + "sha256": "98b283dd3a0acbe5bb36c01aca3442b144263f825c894ef76cbe28fcf649f071" }, "crag-license-public.pem": { "size": 113, @@ -60,7 +60,7 @@ }, "manifest.json": { "size": 3149, - "sha256": "3f8fb45a70b8913809b1926e4dc0318f0a4005af0939e3ef1b36f9d422bf572f" + "sha256": "0d630bf101e2f2572b5adcbc0897f84520d5733b4656a4d36affb23b32028e57" } } }, From 17de4d6c39dc3137bd1edcc9e118d530d8d5a7a8 Mon Sep 17 00:00:00 2001 From: dofastted Date: Wed, 2 Dec 2026 01:05:44 +0800 Subject: [PATCH 3/4] chore(gemini): pin F1-F5 fixed CRAGGemini 0.6.4 (payload-2026.12.02-gemini-0.6.4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 变更摘要 - 改前:`deploy/payload.json` 指向 `payload-2026.12.01-gemini-0.6.4`(合入 `antigravity-cli-proxy#36` 评审 F1–F5 修复前的构建)。 - 改后:将 `geminiDefaultLinuxAmd64` 升级钉选至已合入 `dofastted/antigravity-cli-proxy#36`(`13a270e05`,含 #35 评审 F1–F5 修复 + `agy >= 1.5.20` 门禁 + 分层截断)的新续发载荷 `payload-2026.12.02-gemini-0.6.4`(零密钥轮换,公钥 `f6e3ef3a...` 不变)。 - 未改 / 延后:不改 `CHANGELOG.md`,不触碰其他载荷字段;线上 `ph24` 灰度在合入发版后执行。 ## 验收记录(Run) - 环境与基线:WSL2 Linux + Windows git,`fix/gemini-acp-spec-truncation`(基于 `origin/dev` `c83c12b3b`) - 已跑命令与结果: - `python3 scripts/fetch-default-gemini.py --manifest deploy/payload.json --dest <0700 tmpdir> --reuse-agy ...`: PASS (`Verified Gemini payload 0.6.4`,5/5 资产远端下载与 SHA-256 一致) - `node scripts/sync-agy-acp-spec.mjs --check --kernel-spec ...`: PASS (`sha256=1dd063cb...`, `min_agy=1.5.20`, `keys=87`) - `node --test test/unit/install-payload.test.mjs test/unit/gemini-maintenance-install-contract.test.mjs`: PASS (18/18) ## 回退与手破验证(Broken by hand) - 将临时 `payload.json` 中 `manifest.json` sha256 末位由 `0` 改为 `1` -> `fetch-default-gemini.py` FAIL (`SHA-256 does not match the pin`) -> 还原后 PASS。 ## 真实使用(Real use) - 实测从 GitHub Release `payload-2026.12.02-gemini-0.6.4` 公开 URL 拉取全部 5 项资产并完成验签与官方 `agy` 补丁;未在 `ph24`/Docker/KVM/custom-os 实机运行。 ## 未运行项(Not run) - `ph24` 实机灰度、Docker/KVM/custom-os 槽位运行实测与 ARM64 构建(均未运行,待合入发版后执行)。 --- deploy/payload.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/deploy/payload.json b/deploy/payload.json index c5ef68ad4f..95b375e852 100644 --- a/deploy/payload.json +++ b/deploy/payload.json @@ -40,19 +40,19 @@ "payload_key_id": "835451e266145220a2e75b1f39ff22a0d7b17be48395553a24666b1946e0333a" }, "geminiDefaultLinuxAmd64": { - "tag": "payload-2026.12.01-gemini-0.6.4", + "tag": "payload-2026.12.02-gemini-0.6.4", "assets": { "craggemini": { - "size": 1046952, - "sha256": "6423fa9d62795281ffa357ba96f9de04d608e7688af0ec9634b6bb974eb5bee1" + "size": 1047016, + "sha256": "a256266e1052153440efdd9edb8bbd6109d30af99b6193140787711ebd167a10" }, "craggemini.payload.enc": { - "size": 6352996, - "sha256": "c444ce5d1073829317bdc5e868f31ac6df6684918f2803d431786ef19335d078" + "size": 6354748, + "sha256": "1535471e89973b6c572cc1f9209beed15464bfad776282cfa3fec21a1e4b9c4a" }, "libagy_bridge.so": { "size": 685088, - "sha256": "98b283dd3a0acbe5bb36c01aca3442b144263f825c894ef76cbe28fcf649f071" + "sha256": "2969d551cc27a83aea56748b0fe9696eacaa35974ea9f2ba2ea83542dc0e1542" }, "crag-license-public.pem": { "size": 113, @@ -60,7 +60,7 @@ }, "manifest.json": { "size": 3149, - "sha256": "0d630bf101e2f2572b5adcbc0897f84520d5733b4656a4d36affb23b32028e57" + "sha256": "7b57f6dcba4a3aae5fd75025c44d2190b8405da2d7117c1d0d08bf6029f7b160" } } }, From 249192a3137cb9f557c75ee8e2a734a5ea702fe0 Mon Sep 17 00:00:00 2001 From: dofastted Date: Wed, 2 Dec 2026 02:35:52 +0800 Subject: [PATCH 4/4] fix(gemini): lock inbound tool call IDs and stop call_auto_* wire fabrication MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 变更摘要 - 改前:`prompt-normalizer.mjs` 的 `createWireToolCallTracker` 在转发无 ID 的 Gemini 原生 `functionCall`/`functionResponse` 时合成显式 `call_auto_` 写入出站载荷,与 CRAGGemini 0.6.4 F2(非空 `call_id` 禁按 `tool_name` 回退)冲突导致每轮取消并重建 ACP 会话;同时 `matchResult` 与 `reconcileIrToolCallPairing` 在存在未知显式 `id` 时仍会通过 `prevBatch[0]` 静默改绑,且未预留同轮精确命中的 open `call_id`;`buildGeminiRequest` 在 `target === 'antigravity'` 下也会序列化 IR `_autoId`。 - 改后:移除 `createWireToolCallTracker` 的 `nextAutoId()` 合成注入,无 ID 入站在直通与 IR 回退路径对 CRAGGemini 均保持 `id` 缺省(显式 `functionResponse.id` 仍由 `adoptId` 反向采纳);新增同轮 `reservedExactIds` 防止同名回退抢占精确 ID;将 `prevBatch` 位置回退严格收紧为 `!rawId && !normName`(未知显式 ID 保持原值锁定并交由准入守卫 `400 unmatched_tool_result` 处理)。 - 未改 / 延后:直连 Google Gemini API(`target === 'gemini'`)仍保留既有内部配对 ID 行为;`routes.mjs` 与 `deploy/payload.json` 本提交未改动。 ## 验收记录(Run) - 环境与基线:Windows + WSL2 Node 22,`fix/gemini-acp-spec-truncation`(基于 `6977755ff`) - 已跑命令与结果: - `npx biome format --write src/lib/gemini/prompt-normalizer.mjs src/lib/protocol/gemini-convert.mjs test/unit/gemini-prompt-normalizer.test.mjs test/unit/gemini-convert.test.mjs`: PASS - `find src scripts -name '*.mjs' -print0 | xargs -0 -n1 node --check`: PASS - `node --test test/unit/gemini-prompt-normalizer.test.mjs test/unit/gemini-convert.test.mjs test/unit/gemini-system-prompt.test.mjs`: PASS (60/60) - `node --test test/unit/gemini-responses-output.test.mjs test/unit/gemini-session-conflict.test.mjs test/unit/gemini-request-log.test.mjs`: PASS (68/68) - `KIN_SCHEDULER_BIN=/mnt/x/vm2api-wt-clean-1424x/bin/kin-scheduler npm run test:ci`: PASS (13/13) ## 回退与手破验证(Broken by hand) - 临时回退 `src/lib/gemini/prompt-normalizer.mjs` 至 `HEAD` -> `canonicalizeInboundForAntigravity locks inbound tool IDs` FAIL(`AssertionError: actual 'call_auto_1' !== expected undefined` @ `test/unit/gemini-prompt-normalizer.test.mjs:988`)-> 恢复后 PASS。 - 临时回退 `src/lib/protocol/gemini-convert.mjs` 至 `HEAD` -> `IR inbound ID locking` FAIL(`AssertionError: actual 'call_879ae19164b679005ce5' !== expected undefined` @ `test/unit/gemini-convert.test.mjs:3636`)-> 恢复后 PASS。 ## 真实使用(Real use) - 线上 `45.58.174.2`(`CRAGGemini 0.6.4`)真实回放证据确认原因为面板出站写入 `call_auto_53..92` 触发 `McpCoordinator::resolve_call` 失配并使多轮缓存率跌至 6.1%;新镜像尚未部署至 `45.58.174.2`,待合并后在 `45.58.174.2` 切回 `0.6.4` 实测复核。 ## 未运行项(Not run) - 全量 `npm run test:unit`(553 文件)、`web/` 前端构建(本次未修改 `web/`)、`45.58.174.2` 与 `ph24` 新镜像实机部署验证(待合并后执行)。 --- src/lib/gemini/prompt-normalizer.mjs | 115 +++++++++++------ src/lib/protocol/gemini-convert.mjs | 21 +++- test/unit/gemini-convert.test.mjs | 62 ++++++++++ test/unit/gemini-prompt-normalizer.test.mjs | 130 ++++++++++++++++++++ 4 files changed, 284 insertions(+), 44 deletions(-) diff --git a/src/lib/gemini/prompt-normalizer.mjs b/src/lib/gemini/prompt-normalizer.mjs index 0acf94593c..6668324e1c 100644 --- a/src/lib/gemini/prompt-normalizer.mjs +++ b/src/lib/gemini/prompt-normalizer.mjs @@ -2969,7 +2969,6 @@ export function canonicalizeInboundForAntigravity( const openByName = new Map() const seenIds = new Set() let prevBatch = [] - let autoCounter = 0 const removeEntry = (entry) => { if (!entry) return @@ -2988,18 +2987,18 @@ export function canonicalizeInboundForAntigravity( } return { - nextAutoId() { - let cand = '' - do { - autoCounter += 1 - cand = `call_auto_${autoCounter}` - } while (seenIds.has(cand)) - seenIds.add(cand) - return cand - }, startNewAssistantBatch() { prevBatch = [] }, + collectReservedIds(ids) { + const reserved = new Set() + if (!ids) return reserved + for (const raw of ids) { + const clean = typeof raw === 'string' ? raw.trim() : '' + if (clean && openById.has(clean)) reserved.add(clean) + } + return reserved + }, registerCall({ id, name, autoId = false, legacy = false, adoptId = null }) { const cleanId = typeof id === 'string' ? id.trim() : '' if (cleanId) { @@ -3016,7 +3015,7 @@ export function canonicalizeInboundForAntigravity( prevBatch.push(entry) return entry }, - matchResult({ id, name }) { + matchResult({ id, name, reservedExactIds = null }) { const rawId = typeof id === 'string' ? id.trim() : '' const normName = cleanMcpToolNameForMatch(name) if (rawId && openById.has(rawId)) { @@ -3028,11 +3027,12 @@ export function canonicalizeInboundForAntigravity( const matched = consumedById.get(rawId) return { matched, canonicalId: matched.id, rewroteCall: false, duplicate: true } } + const isEligible = (entry) => !(entry.id && reservedExactIds?.has(entry.id)) let matched = null if (normName && openByName.has(normName) && openByName.get(normName).length > 0) { - matched = openByName.get(normName)[0] - } else if (prevBatch.length > 0) { - matched = prevBatch[0] + matched = openByName.get(normName).find(isEligible) || null + } else if (!rawId && !normName && prevBatch.length > 0) { + matched = prevBatch.find(isEligible) || null } if (!matched) return null removeEntry(matched) @@ -3040,6 +3040,7 @@ export function canonicalizeInboundForAntigravity( if (matched.id) consumedById.delete(matched.id) seenIds.add(rawId) matched.id = rawId + matched.autoId = false consumedById.set(rawId, matched) matched.adoptId(rawId) return { matched, canonicalId: rawId, rewroteCall: true } @@ -3299,6 +3300,11 @@ export function canonicalizeInboundForAntigravity( continue } if (Array.isArray(m.content)) { + const reservedExactIds = isUser + ? tracker.collectReservedIds( + m.content.filter((b) => isPlainObj(b) && b.type === 'tool_result').map((b) => b.tool_use_id), + ) + : null let contentChanged = false const nextContent = [] for (const blk of m.content) { @@ -3353,11 +3359,6 @@ export function canonicalizeInboundForAntigravity( let nextBlk = blk const rawId = typeof blk.id === 'string' ? blk.id.trim() : '' const autoId = !rawId - const callId = rawId || tracker.nextAutoId() - if (autoId) { - contentChanged = true - nextBlk = { ...nextBlk, id: callId } - } if (isPlainObj(blk.input)) { const schema = toolSchemasByName.get(blk.name) const nextInput = rewriteSerializedToolArgs(blk.input, schema) @@ -3370,7 +3371,7 @@ export function canonicalizeInboundForAntigravity( nextContent.push(nextBlk) const hostMsgIdx = msgIdx tracker.registerCall({ - id: callId, + id: rawId, name: blk.name, autoId, adoptId(adopted) { @@ -3441,7 +3442,7 @@ export function canonicalizeInboundForAntigravity( } } const rawUseId = typeof nextBlk.tool_use_id === 'string' ? nextBlk.tool_use_id.trim() : '' - const match = tracker.matchResult({ id: rawUseId, name: nextBlk.name || '' }) + const match = tracker.matchResult({ id: rawUseId, name: nextBlk.name || '', reservedExactIds }) if (match) { if (match.canonicalId && match.canonicalId !== nextBlk.tool_use_id) { contentChanged = true @@ -3685,11 +3686,6 @@ export function canonicalizeInboundForAntigravity( const fnName = curTc.function?.name || curTc.custom?.name || curTc.name || '' const rawId = typeof curTc.id === 'string' ? curTc.id.trim() : '' const autoId = !rawId - const callId = rawId || tracker.nextAutoId() - if (autoId) { - tcChanged = true - curTc = { ...curTc, id: callId } - } if (isPlainObj(curTc.function) && typeof curTc.function.name === 'string') { const schema = toolSchemasByName.get(curTc.function.name) const nextArgs = rewriteSerializedToolArgs(curTc.function.arguments, schema) @@ -3699,7 +3695,7 @@ export function canonicalizeInboundForAntigravity( } } tracker.registerCall({ - id: callId, + id: rawId, name: fnName, autoId, adoptId(adopted) { @@ -3730,6 +3726,20 @@ export function canonicalizeInboundForAntigravity( } if (isTool) { + const batchToolIds = [] + for (let k = msgIdx; k < foldedMsgs.length; k += 1) { + const km = foldedMsgs[k] + const kr = typeof km?.role === 'string' ? km.role.toLowerCase() : '' + if (kr !== 'tool' && kr !== 'function') break + const kid = + typeof km.tool_call_id === 'string' && km.tool_call_id.trim() + ? km.tool_call_id.trim() + : typeof km.id === 'string' + ? km.id.trim() + : '' + if (kid) batchToolIds.push(kid) + } + const reservedExactIds = tracker.collectReservedIds(batchToolIds) const rawToolId = typeof nextMsg.tool_call_id === 'string' && nextMsg.tool_call_id.trim() ? nextMsg.tool_call_id.trim() @@ -3737,7 +3747,7 @@ export function canonicalizeInboundForAntigravity( ? nextMsg.id.trim() : '' const rawToolName = typeof nextMsg.name === 'string' ? nextMsg.name.trim() : '' - const match = tracker.matchResult({ id: rawToolId, name: rawToolName }) + const match = tracker.matchResult({ id: rawToolId, name: rawToolName, reservedExactIds }) if (match) { if ( !match.matched.legacy && @@ -4038,9 +4048,8 @@ export function canonicalizeInboundForAntigravity( ? nextItem.id.trim() : '' const autoId = !rawCallId - const callId = rawCallId || tracker.nextAutoId() - if (autoId || !nextItem.call_id) { - nextItem = { ...nextItem, call_id: callId } + if (rawCallId && !nextItem.call_id) { + nextItem = { ...nextItem, call_id: rawCallId } } if (nextItem.type === 'function_call' && typeof nextItem.name === 'string') { const schema = toolSchemasByName.get(nextItem.name) @@ -4062,7 +4071,7 @@ export function canonicalizeInboundForAntigravity( const hostIdx = itemIdx mappedItems[itemIdx] = nextItem tracker.registerCall({ - id: callId, + id: rawCallId, name: builtinName, autoId, adoptId(adopted) { @@ -4137,7 +4146,20 @@ export function canonicalizeInboundForAntigravity( : nextItem.type === 'tool_search_output' ? 'tool_search' : nextItem.name || '' - const match = tracker.matchResult({ id: rawOutId, name: fallbackOutName }) + const batchRespIds = [] + for (let k = itemIdx; k < foldedItems.length; k += 1) { + const ki = foldedItems[k] + if (!isPlainObj(ki) || !isRespOutputType(ki.type)) break + const kid = + typeof ki.call_id === 'string' && ki.call_id.trim() + ? ki.call_id.trim() + : typeof ki.id === 'string' && ki.id.trim() + ? ki.id.trim() + : '' + if (kid) batchRespIds.push(kid) + } + const reservedExactIds = tracker.collectReservedIds(batchRespIds) + const match = tracker.matchResult({ id: rawOutId, name: fallbackOutName, reservedExactIds }) if (match) { if (match.canonicalId && match.canonicalId !== nextItem.call_id) { nextItem = { ...nextItem, call_id: match.canonicalId } @@ -4299,6 +4321,19 @@ export function canonicalizeInboundForAntigravity( }) : stripIllegalControlChars(rawStr) + const reservedExactIds = isUser + ? tracker.collectReservedIds( + c.parts.map((part) => { + if (!isPlainObj(part)) return '' + const fr = isPlainObj(part.functionResponse) + ? part.functionResponse + : isPlainObj(part.function_response) + ? part.function_response + : null + return fr?.id + }), + ) + : null let turnChanged = false const nextParts = [] for (const p of c.parts) { @@ -4335,9 +4370,9 @@ export function canonicalizeInboundForAntigravity( let fcChanged = p.function_call !== undefined const rawId = typeof rawFc.id === 'string' ? rawFc.id.trim() : '' const autoId = !rawId - const callId = rawId || tracker.nextAutoId() - if (autoId) { - nextFc = { ...nextFc, id: callId } + if (autoId && rawFc.id !== undefined) { + nextFc = { ...nextFc } + delete nextFc.id fcChanged = true } const schema = toolSchemasByName.get(rawFc.name) @@ -4356,7 +4391,7 @@ export function canonicalizeInboundForAntigravity( const hostTurnIdx = turnIdx nextParts.push(nextPart) tracker.registerCall({ - id: callId, + id: rawId, name: rawFc.name, autoId, adoptId(adopted) { @@ -4428,11 +4463,15 @@ export function canonicalizeInboundForAntigravity( } const rawFrId = typeof nextFr.id === 'string' ? nextFr.id.trim() : '' const rawFrName = typeof nextFr.name === 'string' ? nextFr.name.trim() : '' - const match = tracker.matchResult({ id: rawFrId, name: rawFrName }) + const match = tracker.matchResult({ id: rawFrId, name: rawFrName, reservedExactIds }) if (match) { if (match.canonicalId && match.canonicalId !== nextFr.id) { nextFr = { ...nextFr, id: match.canonicalId } frChanged = true + } else if (!match.canonicalId && !rawFrId && nextFr.id !== undefined) { + nextFr = { ...nextFr } + delete nextFr.id + frChanged = true } if (frChanged) { turnChanged = true diff --git a/src/lib/protocol/gemini-convert.mjs b/src/lib/protocol/gemini-convert.mjs index 62e3086261..aa4e283c6e 100644 --- a/src/lib/protocol/gemini-convert.mjs +++ b/src/lib/protocol/gemini-convert.mjs @@ -3889,6 +3889,13 @@ function reconcileIrToolCallPairing(rawIr) { const isHistoricalMsg = msgIdx < messages.length - 1 && (hasLaterNonToolMsg[msgIdx] || messages[msgIdx + 1]?.role === 'assistant') + const reservedExactIds = new Set() + for (const part of msg.parts) { + if (part?.kind !== 'tool_result' || part._autoId) continue + const cid = typeof part.callId === 'string' ? part.callId.trim() : '' + if (cid && openById.has(cid)) reservedExactIds.add(cid) + } + const isEligible = (entry) => !(entry.part.id && reservedExactIds.has(entry.part.id)) const nextParts = [] for (const part of msg.parts) { if (part?.kind !== 'tool_result') { @@ -3905,11 +3912,11 @@ function reconcileIrToolCallPairing(rawIr) { nextParts.push(part) continue } else if (normName && openByName.has(normName) && openByName.get(normName).length > 0) { - matched = openByName.get(normName)[0] - } else if (rawId && openById.has(rawId)) { + matched = openByName.get(normName).find(isEligible) || null + } else if (part._autoId && rawId && openById.has(rawId) && isEligible(openById.get(rawId))) { matched = openById.get(rawId) - } else if (prevAssistantUnconsumed.length > 0) { - matched = prevAssistantUnconsumed[0] + } else if ((part._autoId || !rawId) && !normName && prevAssistantUnconsumed.length > 0) { + matched = prevAssistantUnconsumed.find(isEligible) || null } if (matched) { @@ -3919,8 +3926,10 @@ function reconcileIrToolCallPairing(rawIr) { matched.part.id = rawId matched.part._autoId = false part.callId = rawId + part._autoId = false } else { part.callId = matched.part.id + part._autoId = Boolean(matched.part._autoId) } if (!part.name && matched.part.name) part.name = matched.part.name nextParts.push(part) @@ -4373,7 +4382,7 @@ export function buildGeminiRequest( callArgs = forwardAgyBridgeToolArgs(callArgs, toolSchema) } const fnCall = { name: safeName, args: callArgs } - if (p.id) fnCall.id = ag ? p.id.replace(/[^a-zA-Z0-9_-]/g, '_') : p.id + if (p.id && !(ag && p._autoId)) fnCall.id = ag ? p.id.replace(/[^a-zA-Z0-9_-]/g, '_') : p.id const part = { functionCall: fnCall } if (ag) { // On CRAGGemini only preserve genuine thoughtSignature anchors (never inject dummy validator strings). @@ -4414,7 +4423,7 @@ export function buildGeminiRequest( name: safeName, response: responsePayload, } - if (p.callId) fr.id = ag ? p.callId.replace(/[^a-zA-Z0-9_-]/g, '_') : p.callId + if (p.callId && !(ag && p._autoId)) fr.id = ag ? p.callId.replace(/[^a-zA-Z0-9_-]/g, '_') : p.callId parts.push({ functionResponse: fr }) // A structured response bypasses merged text, so emit its attachments separately. if (isPlainObject(p.rawResponse) && Object.keys(p.rawResponse).length > 0) { diff --git a/test/unit/gemini-convert.test.mjs b/test/unit/gemini-convert.test.mjs index 3061141c85..547c0ca058 100644 --- a/test/unit/gemini-convert.test.mjs +++ b/test/unit/gemini-convert.test.mjs @@ -3620,3 +3620,65 @@ test('K1 & K3 control-char stripping, surgical CLI slash escaping, media-only fa 'functionResponse-only Turn 0 bytes must stay identical when subsequent turns are appended', ) }) + +test('IR inbound ID locking: id-less Gemini omits synthetic IDs on antigravity build, reserves exact IDs, and blocks explicit unknown ID hijack', () => { + // 1. Gemini native id-less functionCall + id-less functionResponse: IR fallback for antigravity must NOT emit synthetic call_* IDs. + const idlessIr = parseInboundToGemini('gemini', { + model: 'gemini-4-neon', + contents: [ + { role: 'user', parts: [{ text: 'check repo' }] }, + { role: 'model', parts: [{ functionCall: { name: 'read_file', args: { path: 'README.md' } } }] }, + { role: 'user', parts: [{ functionResponse: { name: 'read_file', response: { result: 'ok' } } }] }, + ], + }) + assert.doesNotThrow(() => validateAntigravityTargetAdmission('gemini', {}, { ir: idlessIr })) + const agIdless = buildGeminiRequest(idlessIr, { target: 'antigravity' }) + assert.equal(agIdless.contents[1].parts[0].functionCall.id, undefined) + assert.equal(agIdless.contents[2].parts[0].functionResponse.id, undefined) + // Direct Gemini API target still preserves internal paired IDs. + const directGem = buildGeminiRequest(idlessIr, { target: 'gemini' }) + assert.ok(directGem.contents[1].parts[0].functionCall.id) + assert.equal(directGem.contents[1].parts[0].functionCall.id, directGem.contents[2].parts[0].functionResponse.id) + + // 2. Reserved exact ID in the same user turn cannot be stolen by an earlier id-less same-name functionResponse. + const reservedIr = parseInboundToGemini('gemini', { + model: 'gemini-4-neon', + contents: [ + { role: 'user', parts: [{ text: 'read two' }] }, + { + role: 'model', + parts: [ + { functionCall: { id: 'fc_lock_1', name: 'read_file', args: { path: '1.txt' } } }, + { functionCall: { id: 'fc_lock_2', name: 'read_file', args: { path: '2.txt' } } }, + ], + }, + { + role: 'user', + parts: [ + { functionResponse: { name: 'read_file', response: { result: 'two' } } }, + { functionResponse: { id: 'fc_lock_1', name: 'read_file', response: { result: 'one' } } }, + ], + }, + ], + }) + assert.doesNotThrow(() => validateAntigravityTargetAdmission('gemini', {}, { ir: reservedIr })) + const agReserved = buildGeminiRequest(reservedIr, { target: 'antigravity' }) + assert.equal(agReserved.contents[2].parts[0].functionResponse.id, 'fc_lock_2') + assert.equal(agReserved.contents[2].parts[1].functionResponse.id, 'fc_lock_1') + + // 3. Explicit unknown Anthropic tool_use_id cannot hijack an unrelated preceding tool_use. + const hijackedIr = parseInboundToGemini('anthropic', { + model: 'gemini-4-neon', + max_tokens: 128, + messages: [ + { role: 'user', content: 'run' }, + { role: 'assistant', content: [{ type: 'tool_use', id: 'tu_real_1', name: 'bash', input: {} }] }, + { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'tu_unknown_9', content: 'out' }] }, + ], + }) + assert.equal(hijackedIr.messages[2].parts[0].callId, 'tu_unknown_9') + assert.throws( + () => validateAntigravityTargetAdmission('anthropic', {}, { ir: hijackedIr }), + (err) => err?.status === 400 && err?.details?.reason === 'unmatched_tool_result', + ) +}) diff --git a/test/unit/gemini-prompt-normalizer.test.mjs b/test/unit/gemini-prompt-normalizer.test.mjs index 2ac05de26d..488c2eddf8 100644 --- a/test/unit/gemini-prompt-normalizer.test.mjs +++ b/test/unit/gemini-prompt-normalizer.test.mjs @@ -17,6 +17,7 @@ import { NATIVE_TUI_CAPABILITIES, buildGeminiRequest, parseInboundToGemini, + validateAntigravityTargetAdmission, } from '../../src/lib/protocol/gemini-convert.mjs' function sseStream(frames) { @@ -956,3 +957,132 @@ test('normalizeGeminiOutboundPrompt strips illegal control chars in text, though assert.equal(res.body.contents[1].parts[0].text, 'Secretthought') assert.equal(res.body.contents[2].parts[0].functionResponse.response.out, 'val') }) + +test('canonicalizeInboundForAntigravity locks inbound tool IDs: no synthetic call_auto_* on idless Gemini, reserves exact IDs, and never hijacks unknown explicit IDs', () => { + // 1. Gemini native id-less functionCall + id-less functionResponse (single + parallel + blank id:""): + // must NOT inject synthetic `call_auto_*` onto outbound wire so CRAGGemini v0.6.4 F2 resolves by tool_name. + const idlessGem = { + model: 'gemini-4-neon', + contents: [ + { role: 'user', parts: [{ text: 'inspect files' }] }, + { + role: 'model', + parts: [ + { functionCall: { name: 'read_file', args: { path: 'a.txt' } } }, + { functionCall: { id: ' ', name: 'read_file', args: { path: 'b.txt' } } }, + ], + }, + { + role: 'user', + parts: [ + { functionResponse: { name: 'read_file', response: { result: 'A' } } }, + { functionResponse: { id: '', name: 'read_file', response: { result: 'B' } } }, + ], + }, + ], + } + const canonIdless = canonicalizeInboundForAntigravity('gemini', idlessGem, { + model: 'gemini-4-neon', + targetSupportsAcpAdmission: true, + }) + assert.equal(canonIdless.body.contents[1].parts[0].functionCall.id, undefined) + assert.equal(canonIdless.body.contents[1].parts[1].functionCall.id, undefined) + assert.equal(canonIdless.body.contents[2].parts[0].functionResponse.id, undefined) + assert.equal(canonIdless.body.contents[2].parts[1].functionResponse.id, undefined) + assert.equal(JSON.stringify(canonIdless.body).includes('call_auto_'), false) + assert.doesNotThrow(() => validateAntigravityTargetAdmission('gemini', canonIdless.body)) + assert.deepEqual( + canonicalizeInboundForAntigravity('gemini', canonIdless.body, { + model: 'gemini-4-neon', + targetSupportsAcpAdmission: true, + }).body, + canonIdless.body, + 'id-less Gemini canonicalization must be idempotent', + ) + + // 2. Reserved exact inbound ID in the same user turn cannot be stolen by an earlier id-less / mismatched same-name response. + const reservedGem = { + model: 'gemini-4-neon', + contents: [ + { role: 'user', parts: [{ text: 'read two' }] }, + { + role: 'model', + parts: [ + { functionCall: { id: 'fc_exact_a', name: 'read_file', args: { path: 'a.txt' } } }, + { functionCall: { id: 'fc_exact_b', name: 'read_file', args: { path: 'b.txt' } } }, + ], + }, + { + role: 'user', + parts: [ + { functionResponse: { name: 'read_file', response: { result: 'B_by_name' } } }, + { functionResponse: { id: 'fc_exact_a', name: 'read_file', response: { result: 'A_by_id' } } }, + ], + }, + ], + } + const canonReserved = canonicalizeInboundForAntigravity('gemini', reservedGem, { + model: 'gemini-4-neon', + targetSupportsAcpAdmission: true, + }) + assert.equal(canonReserved.body.contents[2].parts[0].functionResponse.id, 'fc_exact_b') + assert.equal(canonReserved.body.contents[2].parts[1].functionResponse.id, 'fc_exact_a') + + // 3. Explicit unknown inbound IDs across Anthropic / OpenAI Chat / OpenAI Responses stay locked (never silently rebound to prevBatch[0]). + const anthUnknown = { + model: 'gemini-4-neon', + max_tokens: 128, + messages: [ + { role: 'user', content: 'run bash' }, + { role: 'assistant', content: [{ type: 'tool_use', id: 'tu_open_1', name: 'bash', input: { cmd: 'ls' } }] }, + { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'tu_foreign_99', content: 'done' }] }, + ], + } + const canonAnth = canonicalizeInboundForAntigravity('anthropic', anthUnknown, { + model: 'gemini-4-neon', + targetSupportsAcpAdmission: true, + }) + assert.equal(canonAnth.body.messages[2].content[0].tool_use_id, 'tu_foreign_99') + assert.throws( + () => validateAntigravityTargetAdmission('anthropic', canonAnth.body), + (err) => err?.status === 400 && err?.details?.reason === 'unmatched_tool_result', + ) + assert.doesNotThrow(() => + validateAntigravityTargetAdmission('anthropic', canonAnth.body, { + continuationBinding: { accountId: 'env-1' }, + targetAccountId: 'env-1', + }), + ) + + const chatUnknown = { + model: 'gemini-4-neon', + messages: [ + { role: 'user', content: 'run' }, + { + role: 'assistant', + content: null, + tool_calls: [{ id: 'tc_open_1', type: 'function', function: { name: 'bash', arguments: '{}' } }], + }, + { role: 'tool', tool_call_id: 'tc_foreign_99', content: 'done' }, + ], + } + const canonChat = canonicalizeInboundForAntigravity('openai-chat', chatUnknown, { + model: 'gemini-4-neon', + targetSupportsAcpAdmission: true, + }) + assert.equal(canonChat.body.messages[2].tool_call_id, 'tc_foreign_99') + + const respUnknown = { + model: 'gemini-4-neon', + input: [ + { type: 'message', role: 'user', content: 'run' }, + { type: 'function_call', call_id: 'rc_open_1', name: 'bash', arguments: '{}' }, + { type: 'function_call_output', call_id: 'rc_foreign_99', output: 'done' }, + ], + } + const canonResp = canonicalizeInboundForAntigravity('openai-responses', respUnknown, { + model: 'gemini-4-neon', + targetSupportsAcpAdmission: true, + }) + assert.equal(canonResp.body.input[2].call_id, 'rc_foreign_99') +})