diff --git a/deploy/payload.json b/deploy/payload.json index 7b01ce018d..558509f612 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.02-gemini-0.6.4", "assets": { "craggemini": { - "size": 1038416, - "sha256": "5408e9a9439a03920a491d6ad7b59a69d2e152fc5e08e1225c816b410501a537" + "size": 1047016, + "sha256": "a256266e1052153440efdd9edb8bbd6109d30af99b6193140787711ebd167a10" }, "craggemini.payload.enc": { - "size": 6199276, - "sha256": "92b3f89bed70d7819b270e11ae2150fa0cef2c54e26bb58d29706e2e1b5cc79e" + "size": 6354748, + "sha256": "1535471e89973b6c572cc1f9209beed15464bfad776282cfa3fec21a1e4b9c4a" }, "libagy_bridge.so": { - "size": 676576, - "sha256": "fb1b58b88fd1d2afd484ed54c08b7cc05e2d3c9ef6d1e0c06b90b4ca353f2ee4" + "size": 685088, + "sha256": "2969d551cc27a83aea56748b0fe9696eacaa35974ea9f2ba2ea83542dc0e1542" }, "crag-license-public.pem": { "size": 113, @@ -60,7 +60,7 @@ }, "manifest.json": { "size": 3149, - "sha256": "3f8fb45a70b8913809b1926e4dc0318f0a4005af0939e3ef1b36f9d422bf572f" + "sha256": "7b57f6dcba4a3aae5fd75025c44d2190b8405da2d7117c1d0d08bf6029f7b160" } } }, diff --git a/scripts/gemini-host.py b/scripts/gemini-host.py index 90edafe342..ce460c7e67 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 @@ -6477,7 +6522,10 @@ def installed_agy_sha256(self): return AGY_SHA256 def installed_agy_version(self): - agy_path = self.payload / "agy" + payload = getattr(self, "payload", None) + if payload is None: + return None + agy_path = payload / "agy" try: info = os.stat(agy_path, follow_symlinks=False) except OSError: @@ -9943,6 +9991,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 +11633,7 @@ def send_json_error( retryable=None, failoverable=None, upstream_status=None, + validation_url=None, ): if self._headers_sent: return @@ -11580,6 +11654,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..5ef812b088 --- /dev/null +++ b/src/lib/gemini/agy-acp-spec.mjs @@ -0,0 +1,404 @@ +/** + * 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' || + !parseSemver(spec.min_agy_version) || + !spec.limits || + !Number.isInteger(spec.limits.max_acp_prompt_text_bytes) || + spec.limits.max_acp_prompt_text_bytes < MIN_ACP_PROMPT_BYTES || + !Number.isInteger(spec.limits.max_system_prompt_append_bytes) || + spec.limits.max_system_prompt_append_bytes < MIN_ACP_PROMPT_BYTES || + !spec.top_level_fields || + !Array.isArray(spec.top_level_fields.allowed_body_keys) || + spec.top_level_fields.allowed_body_keys.length === 0 || + !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 0b59bef60c..a7378b5c76 100644 --- a/src/lib/gemini/direct-client.mjs +++ b/src/lib/gemini/direct-client.mjs @@ -1119,6 +1119,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 ( @@ -1126,6 +1142,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' @@ -1149,10 +1173,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/prompt-normalizer.mjs b/src/lib/gemini/prompt-normalizer.mjs index 38db9e89a8..6668324e1c 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' import { clampEffortToSupported, effortFromThinkingBudget, @@ -1163,63 +1164,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', @@ -1424,7 +1374,7 @@ export function normalizeMediaMimeType(rawMime) { return normalizeGeminiMediaMime(rawMime) } -export function isInlinePlainTextMime(rawMime) { +export function isInlinePlainTextMime(rawMime, { extraDecodableTextMimes = null } = {}) { const clean = normalizeMediaMimeType(rawMime) if (!clean) return false if (clean.startsWith('image/') || clean.startsWith('audio/') || clean.startsWith('video/')) return false @@ -1439,7 +1389,11 @@ export function isInlinePlainTextMime(rawMime) { ) { return false } - return isDecodableInlineTextMime(clean) || EXTRA_INLINE_TEXT_APP_MIMES.has(clean) + return ( + isAcpDecodableTextMime(clean, { extraMimes: extraDecodableTextMimes }) || + isDecodableInlineTextMime(clean) || + EXTRA_INLINE_TEXT_APP_MIMES.has(clean) + ) } export function inferPlainTextMimeFromFilename(filename) { @@ -1459,10 +1413,10 @@ export function inferPlainTextMimeFromFilename(filename) { export function decodeInlinePlainTextBase64( rawData, mimeType = undefined, - { maxBytes = MAX_INLINE_TEXT_DECODE_BYTES } = {}, + { maxBytes = MAX_INLINE_TEXT_DECODE_BYTES, extraDecodableTextMimes = null } = {}, ) { const mime = mimeType === undefined ? '' : normalizeMediaMimeType(mimeType) - if (mimeType !== undefined && !isInlinePlainTextMime(mime)) { + if (mimeType !== undefined && !isInlinePlainTextMime(mime, { extraDecodableTextMimes })) { return { ok: false, reason: 'unsupported_mime', mime } } if (typeof rawData !== 'string') { @@ -1506,15 +1460,20 @@ export function decodeInlinePlainTextBase64( } } -export function decodeInlineTextDataUri(rawUrl, fallbackMime = '', filename = '') { +export function decodeInlineTextDataUri( + rawUrl, + fallbackMime = '', + filename = '', + { 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 || inferPlainTextMimeFromFilename(filename) - 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 { @@ -1525,8 +1484,8 @@ export function decodeInlineTextDataUri(rawUrl, fallbackMime = '', filename = '' } } const effectiveMime = fallbackMime || inferPlainTextMimeFromFilename(filename) - if (isInlinePlainTextMime(effectiveMime) && !/^(?:https?|gs|file|s3):/i.test(trimmed)) { - const decoded = decodeInlinePlainTextBase64(trimmed, effectiveMime) + if (isInlinePlainTextMime(effectiveMime, { extraDecodableTextMimes }) && !/^(?:https?|gs|file|s3):/i.test(trimmed)) { + const decoded = decodeInlinePlainTextBase64(trimmed, effectiveMime, { extraDecodableTextMimes }) return decoded.ok ? decoded.text : null } return null @@ -2914,6 +2873,8 @@ export function canonicalizeInboundForAntigravity( targetSupportsAcpAdmission = false, escapeSlashes = false, observeUnknownFields = true, + acpOverrides = null, + targetProtocolCapabilities = null, model = null, publicModel = null, resolvedModel = null, @@ -2923,6 +2884,13 @@ export function canonicalizeInboundForAntigravity( 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() @@ -3001,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 @@ -3020,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) { @@ -3048,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)) { @@ -3060,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) @@ -3072,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 } @@ -3281,12 +3250,16 @@ export function canonicalizeInboundForAntigravity( const decodeAnthropicDocText = (source) => { if (!isPlainObj(source)) return null if (source.type === 'text' && typeof source.data === 'string') return source.data - if (source.type === 'base64' && typeof source.data === 'string' && isInlinePlainTextMime(source.media_type)) { - const res = decodeInlinePlainTextBase64(source.data) + if ( + source.type === 'base64' && + typeof source.data === 'string' && + isInlinePlainTextMime(source.media_type, { extraDecodableTextMimes }) + ) { + const res = decodeInlinePlainTextBase64(source.data, undefined, { extraDecodableTextMimes }) return res.ok ? res.text : null } if (source.type === 'url' && typeof source.url === 'string' && source.url.trim().startsWith('data:')) { - return decodeInlineTextDataUri(source.url, source.media_type) + return decodeInlineTextDataUri(source.url, source.media_type, '', { extraDecodableTextMimes }) } return null } @@ -3327,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) { @@ -3381,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) @@ -3398,7 +3371,7 @@ export function canonicalizeInboundForAntigravity( nextContent.push(nextBlk) const hostMsgIdx = msgIdx tracker.registerCall({ - id: callId, + id: rawId, name: blk.name, autoId, adoptId(adopted) { @@ -3469,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 @@ -3664,6 +3637,7 @@ export function canonicalizeInboundForAntigravity( part.file.file_data || part.file.data, part.file.media_type || part.file.mime_type, part.file.filename, + { extraDecodableTextMimes }, ) if (decoded !== null) { cChanged = true @@ -3712,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) @@ -3726,7 +3695,7 @@ export function canonicalizeInboundForAntigravity( } } tracker.registerCall({ - id: callId, + id: rawId, name: fnName, autoId, adoptId(adopted) { @@ -3757,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() @@ -3764,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 && @@ -4009,6 +3992,7 @@ export function canonicalizeInboundForAntigravity( part.file_data || part.file_url, part.media_type || part.mime_type, part.filename, + { extraDecodableTextMimes }, ) if (decoded !== null) { cChanged = true @@ -4064,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) @@ -4088,7 +4071,7 @@ export function canonicalizeInboundForAntigravity( const hostIdx = itemIdx mappedItems[itemIdx] = nextItem tracker.registerCall({ - id: callId, + id: rawCallId, name: builtinName, autoId, adoptId(adopted) { @@ -4163,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 } @@ -4325,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) { @@ -4336,8 +4345,8 @@ export function canonicalizeInboundForAntigravity( if (rawInline) { const mime = rawInline.mimeType ?? rawInline.mime_type ?? '' const b64 = rawInline.data - if (typeof b64 === 'string' && isInlinePlainTextMime(mime)) { - const dec = decodeInlinePlainTextBase64(b64, mime) + if (typeof b64 === 'string' && isInlinePlainTextMime(mime, { extraDecodableTextMimes })) { + const dec = decodeInlinePlainTextBase64(b64, mime, { extraDecodableTextMimes }) if (dec.ok) { turnChanged = true nextParts.push({ text: formatTurnText(dec.text || '.') }) @@ -4361,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) @@ -4382,7 +4391,7 @@ export function canonicalizeInboundForAntigravity( const hostTurnIdx = turnIdx nextParts.push(nextPart) tracker.registerCall({ - id: callId, + id: rawId, name: rawFc.name, autoId, adoptId(adopted) { @@ -4411,6 +4420,7 @@ export function canonicalizeInboundForAntigravity( const cleanResp = sanitizeJsonControlCharsDeep(nextFr.response) if (cleanResp !== nextFr.response) { nextFr = { ...nextFr, response: cleanResp } + appliedRules.add('transport_control_chars') frChanged = true } } @@ -4426,8 +4436,8 @@ export function canonicalizeInboundForAntigravity( : null if (nInline) { const nMime = nInline.mimeType ?? nInline.mime_type ?? '' - if (typeof nInline.data === 'string' && isInlinePlainTextMime(nMime)) { - const dec = decodeInlinePlainTextBase64(nInline.data) + if (typeof nInline.data === 'string' && isInlinePlainTextMime(nMime, { extraDecodableTextMimes })) { + const dec = decodeInlinePlainTextBase64(nInline.data, undefined, { extraDecodableTextMimes }) if (dec.ok) { nestedChanged = true return { text: stripIllegalControlChars(dec.text) || '.' } @@ -4440,6 +4450,7 @@ export function canonicalizeInboundForAntigravity( const cleanN = stripIllegalControlChars(np.text) if (cleanN !== np.text) { nestedChanged = true + appliedRules.add('transport_control_chars') return { ...np, text: cleanN } } } @@ -4452,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 @@ -4524,7 +4539,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 17b1805eca..6e3412cba9 100644 --- a/src/lib/gemini/routes.mjs +++ b/src/lib/gemini/routes.mjs @@ -906,6 +906,7 @@ function environmentView( globalConfig = null, restriction = null, circuit = null, + liveUnschedulable = null, supplierTag = undefined, } = {}, ) { @@ -1037,6 +1038,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, @@ -1046,21 +1055,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 } : {}), } : {}), @@ -2119,6 +2128,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 1a3034f810..c98d705a6e 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 { @@ -49,6 +50,7 @@ import { extractCragErrorFields, mapCragWorkerError, prepareDirectNativeTurnBody, + resolveTargetAcpCapabilities, targetSupportsAcpAdmission, targetSupportsCleanAcpText, targetSupportsProviderResult, @@ -535,6 +537,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' @@ -556,6 +565,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 } : {}), @@ -3797,8 +3812,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?.permanent_unschedulable === true) { + const reason = live.permanent_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: { @@ -3807,12 +3841,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) { @@ -4390,6 +4429,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 && @@ -4401,6 +4442,7 @@ export function createGeminiScheduler({ validateAntigravityTargetAdmission(inboundProtocol, rawInboundBody, { ir: parsedIr, continuationBinding, + acpPolicy: baseAcpPolicy, }) antigravityAdmissionChecked = true } catch (admErr) { @@ -4452,6 +4494,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, @@ -4682,6 +4727,8 @@ export function createGeminiScheduler({ validateAntigravityTargetAdmission(inboundProtocol, rawInboundBody, { ir: parsedIr, continuationBinding, + targetAccountId: id, + acpPolicy: baseAcpPolicy, }) antigravityAdmissionChecked = true } catch (admErr) { @@ -4768,10 +4815,7 @@ export function createGeminiScheduler({ attemptConversationId = outboundConversationId if (outboundConversationId) lastConversationId = outboundConversationId - const attemptSuffix = attempts === 1 ? '' : `_a${attempts}` - const attemptRequestId = attemptSuffix - ? `${String(requestId || '').slice(0, Math.max(1, 128 - attemptSuffix.length))}${attemptSuffix}` - : String(requestId || '').slice(0, 128) + const attemptRequestId = buildAttemptRequestId(workerRequestIdBase, attempts) const proxySha256 = proxyUrl ? crypto.createHash('sha256').update(proxyUrl).digest('hex') : undefined const gatewayPolicy = typeof getRoutingConfig === 'function' @@ -4808,6 +4852,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 ( @@ -4818,7 +4870,8 @@ export function createGeminiScheduler({ typeof rawInboundBody === 'object' && !Array.isArray(rawInboundBody) ) { - const canonKey = `${supportsAcpAdmission ? 1 : 0}:${supportsCleanAcpText ? 1 : 0}:${resolved.upstreamModel || ''}` + const extraKeySig = effectiveTargetAcpPolicy.extraAllowedBodyKeys.join(',') + const canonKey = `${supportsAcpAdmission ? 1 : 0}:${supportsCleanAcpText ? 1 : 0}:${resolved.upstreamModel || ''}:${extraKeySig}` canonicalized = canonicalCache.get(canonKey) || null if (!canonicalized) { canonicalized = canonicalizeInboundForAntigravity(inboundProtocol, rawInboundBody, { @@ -4826,12 +4879,30 @@ export function createGeminiScheduler({ headers: inboundHeaders, targetSupportsAcpAdmission: supportsAcpAdmission, escapeSlashes: !supportsCleanAcpText, + acpOverrides, + targetProtocolCapabilities: targetAcpCaps, model: resolved.upstreamModel, publicModel: resolved.publicId, resolvedModel: resolved, }) 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 7529d2b766..aa4e283c6e 100644 --- a/src/lib/protocol/gemini-convert.mjs +++ b/src/lib/protocol/gemini-convert.mjs @@ -13,6 +13,11 @@ * never silently drop unsupported fields on restricted native-TUI slots. */ import crypto from 'node:crypto' +import { + DEFAULT_MAX_ACP_PROMPT_TEXT_BYTES, + DEFAULT_MAX_ACP_SYSTEM_PROMPT_APPEND_BYTES, + resolveEffectiveAgyAcpPolicy, +} from '../gemini/agy-acp-spec.mjs' import { MAX_INLINE_TEXT_DECODE_BYTES, avoidAgyBridgeParamCollisions, @@ -3884,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') { @@ -3900,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) { @@ -3914,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) @@ -3966,7 +3980,8 @@ export function parseInboundToGemini(protocol, body, { routeModel = null, routeS return { ...ir, ...capabilities, thinkingDisabled } } -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 BASE64_CHUNK_RE = /^(?:[A-Za-z0-9+/_-]{4})*(?:[A-Za-z0-9+/_-]{2}(?:==)?|[A-Za-z0-9+/_-]{3}=?)?$/ @@ -4003,13 +4018,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' @@ -4025,6 +4074,10 @@ export function validateAntigravityTargetAdmission(protocol, rawBody, { ir = nul const seenCallIds = new Set() const unconsumedByName = new Map() const lastCallIdByName = new Map() + const hasMatchingContinuation = Boolean( + continuationBinding && + (!targetAccountId || !continuationBinding.accountId || continuationBinding.accountId === targetAccountId), + ) let mergedUserTextPieces = [] const flushUserTurnByteCheck = () => { @@ -4032,13 +4085,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 } } @@ -4085,7 +4138,7 @@ export function validateAntigravityTargetAdmission(protocol, rawBody, { ir = nul matchedByName = true } } - if (!matchedById && !matchedByName && !continuationBinding) { + if (!matchedById && !matchedByName && !hasMatchingContinuation) { const err = makeProtocolError( 400, 'gemini_invalid_request', @@ -4329,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). @@ -4370,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) { @@ -4754,37 +4807,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 @@ -4845,6 +4935,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), } @@ -4872,6 +4963,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), } @@ -4887,6 +4979,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/src/lib/scheduler/scheduler-runtime.mjs b/src/lib/scheduler/scheduler-runtime.mjs index 4c42b7ad3f..38f1f3df76 100644 --- a/src/lib/scheduler/scheduler-runtime.mjs +++ b/src/lib/scheduler/scheduler-runtime.mjs @@ -1353,6 +1353,8 @@ export class SchedulerRuntime { return { node_key: key, schedulable: node.schedulable !== false && !node.permanent_unschedulable, + permanent_unschedulable: Boolean(node.permanent_unschedulable), + permanent_reason: node.permanent_reason || null, unschedulable_reason: node.permanent_reason || node.unschedulable_reason || null, in_cooldown: inCooldown, cooldown_until_ms: nodeUntil > now ? nodeUntil : cooldownLeftMs > 0 ? now + cooldownLeftMs : 0, 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 512410ec38..547c0ca058 100644 --- a/test/unit/gemini-convert.test.mjs +++ b/test/unit/gemini-convert.test.mjs @@ -2650,15 +2650,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', ) @@ -2738,6 +2745,112 @@ test('C5 inline text media: decodes UTF-8 text inlineData to text parts, enforce } }) +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) +}) + test('adaptive thinking omits hardcoded medium effort and respects injected defaultEffort & thinkingDisabled across protocols', () => { assert.equal(DEFAULT_GEMINI_EFFORT, 'low') @@ -3133,7 +3246,7 @@ test('inline plain-text media decodes to UTF-8 across all 4 protocols while sing model: 'gemini-4-neon', contents: [{ role: 'user', parts: [{ inlineData: { mimeType: 'text/markdown', data: over190KbBase64 } }] }], }) - validateAntigravityTargetAdmission('gemini', {}, { ir }) + validateAntigravityTargetAdmission('gemini', {}, { ir, routingOverrides: { prompt_overflow_policy: 'reject' } }) }, (err) => err?.status === 400 && err?.details?.reason === 'prompt_part_too_long', ) @@ -3148,7 +3261,7 @@ test('inline plain-text media decodes to UTF-8 across all 4 protocols while sing }, ], }) - validateAntigravityTargetAdmission('gemini', {}, { ir }) + validateAntigravityTargetAdmission('gemini', {}, { ir, routingOverrides: { prompt_overflow_policy: 'reject' } }) }, (err) => err?.status === 400 && err?.details?.reason === 'unsupported_media_type', ) @@ -3507,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-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 3603644bf5..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) { @@ -605,6 +606,136 @@ test('normalizes expanded upstream-429 trigger phrases (Hermes, omp, OpenCode, p ) }) +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' }) +}) + test('canonicalizeInboundForAntigravity converts thinking/effort, tool schemas/choice, inline text media, K2 IDs, and K3 media-only turns across all 4 wire formats', () => { // 1. Haiku 4.5 (`enabled_only`): degrades `adaptive` -> `enabled` + `budget_tokens` (< max_tokens) and strips `output_config.effort` const haikuRes = canonicalizeInboundForAntigravity( @@ -826,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') +}) diff --git a/test/unit/gemini-request-log.test.mjs b/test/unit/gemini-request-log.test.mjs index 140e89a591..e8aa1b86ff 100644 --- a/test/unit/gemini-request-log.test.mjs +++ b/test/unit/gemini-request-log.test.mjs @@ -85,13 +85,19 @@ function makeReq({ method = 'POST', url, body, headers = {}, groupType = 'gemini test('#2436 Responses context overflow uses a failed SSE terminal only before streaming output', async (t) => { const model = 'gemini-4-neon' const overflowBody = { model, input: 'x'.repeat(190001), stream: true } + const rejectOpts = { routingOverrides: { prompt_overflow_policy: 'reject' } } const admissionError = () => { try { - validateAntigravityTargetAdmission('openai-responses', overflowBody) + validateAntigravityTargetAdmission('openai-responses', overflowBody, rejectOpts) assert.fail('expected real admission overflow') } catch (error) { assert.equal(error.code, 'gemini_invalid_request') - assert.deepEqual(error.details, { reason: 'prompt_part_too_long', limit: 190000, actual: 190001 }) + assert.deepEqual(error.details, { + reason: 'prompt_part_too_long', + limit: 190000, + actual: 190001, + policy: 'reject', + }) return error } } @@ -121,7 +127,8 @@ test('#2436 Responses context overflow uses a failed SSE terminal only before st readBody: async () => ({}), scheduler: { stream: async (options) => { - if (dispatchAdmission) validateAntigravityTargetAdmission(options.inboundProtocol, options.rawInboundBody) + if (dispatchAdmission) + validateAntigravityTargetAdmission(options.inboundProtocol, options.rawInboundBody, rejectOpts) if (emitted) options.onEvent({ kind: 'text', text: 'already written' }) throw error }, @@ -215,6 +222,7 @@ test('#2436 Responses context overflow uses a failed SSE terminal only before st reason: 'prompt_part_too_long', limit: '190000', actual: '190001', + policy: 'reject', retryable: 'false', }, }, diff --git a/test/unit/gemini-scheduling-status.test.mjs b/test/unit/gemini-scheduling-status.test.mjs index 1fbcdd1423..bee8d84802 100644 --- a/test/unit/gemini-scheduling-status.test.mjs +++ b/test/unit/gemini-scheduling-status.test.mjs @@ -2107,3 +2107,183 @@ 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 liveOverride = null + const rt = { + ...makeMockGeminiRuntime(), + liveNodeState(nodeKey) { + if (nodeKey === 'gemini_env:env-live' && liveOverride) { + return { + node_key: nodeKey, + in_cooldown: false, + cooldown_until_ms: 0, + cooldown_left_ms: 0, + cooldown_reason: null, + probe_in_flight: false, + ...liveOverride, + } + } + 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') + + // Non-permanent schedulable=false (e.g. env_not_ready, operator schedulable_false) must NOT be misclassified as permanent + for (const nonPermReason of ['env_not_ready', 'schedulable_false']) { + liveOverride = { + schedulable: false, + permanent_unschedulable: false, + permanent_reason: null, + unschedulable_reason: nonPermReason, + } + const nonPermRest = scheduler.environmentRestriction('env-live') + assert.equal(nonPermRest.restriction, null, `${nonPermReason} must not produce a permanent restriction`) + assert.equal(nonPermRest.liveUnschedulable, null, `${nonPermReason} must not set liveUnschedulable`) + } + + // Rust permanent_unschedulable surfaces cleanly in environmentRestriction and panel environmentView + liveOverride = { + schedulable: false, + permanent_unschedulable: true, + permanent_reason: 'permanent_ban', + unschedulable_reason: 'permanent_ban', + } + 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) +}) diff --git a/test/unit/gemini-session-conflict.test.mjs b/test/unit/gemini-session-conflict.test.mjs index 15c56f818b..675eb6921c 100644 --- a/test/unit/gemini-session-conflict.test.mjs +++ b/test/unit/gemini-session-conflict.test.mjs @@ -705,9 +705,11 @@ test('long 128-char requestId preserves distinct _a2 suffix on session_retry and }) assert.equal(okTurn.text, 'dedup-recovered') assert.equal(seenRequestIds.length, 2) - assert.equal(seenRequestIds[0].length, 128) - assert.equal(seenRequestIds[1].length, 128) + assert.ok(seenRequestIds[0].length <= 128) + assert.ok(seenRequestIds[1].length <= 128) + assert.notEqual(seenRequestIds[0], maxLenReqId) assert.ok(seenRequestIds[1].endsWith('_a2'), `expected _a2 suffix on retry request_id, got ${seenRequestIds[1]}`) + assert.equal(seenRequestIds[1], `${seenRequestIds[0]}_a2`) assert.notEqual(seenRequestIds[1], seenRequestIds[0]) // Even when a session_conflict is wrapped with HTTP 502 and retryable=false, lease release reports request_protocol (never server5xx).