GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — vm2api/scripts/verify-craggemini-sessions.mjs at dev · dofastted/vm2api Expand file tree/ Copy pathverify-craggemini-sessions.mjsMore file actions 3029 lines (2891 loc) · 112 KB / Copy pathverify-craggemini-sessions.mjsFile metadata and controls3029 lines (2891 loc) · 112 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 #!/usr/bin/env node /** * Real-session & standards replay verifier for vm2api -> CRAGGemini ingress cleaning, * multi-protocol consistency, gemini-host.py whitelist, craggemini Rust parser acceptance, * and outbound native restoration. * * Inspired by `X:/crag-standalone/scripts/replay-standards.py`. * * Privacy invariant: * - Reads local CLI sessions (Claude Code, Codex, Gemini CLI) in memory only. * - Never writes or prints raw user prompts, assistant text, credentials, or secrets; * only structural diagnostics, counts, and anonymized failure reasons are emitted. */ import { spawnSync } from 'node:child_process' import crypto from 'node:crypto' import { EventEmitter } from 'node:events' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { Readable } from 'node:stream' import { fileURLToPath } from 'node:url' import { normalizeGeminiOutboundPrompt } from '../src/lib/gemini/prompt-normalizer.mjs' import { createGeminiPublicHandler } from '../src/lib/gemini/routes.mjs' import { createGeminiScheduler } from '../src/lib/gemini/scheduler.mjs' import { NATIVE_TUI_CAPABILITIES, SKIP_THOUGHT_SIGNATURE, buildGeminiRequest, parseInboundToGemini, } from '../src/lib/protocol/gemini-convert.mjs' const __dirname = path.dirname(fileURLToPath(import.meta.url)) const REPO_ROOT = path.resolve(__dirname, '..') const DEFAULT_MODEL = 'gemini-3-pro' const MINIMAL_CRAGGEMINI_KEYS = new Set([ 'model', 'contents', 'systemInstruction', 'system_prompt_mode', 'tools', 'toolConfig', 'generationConfig', 'conversation_id', ]) const CRAGGEMINI_ALLOWED_BODY_KEYS = new Set([ 'model', 'stream', 'contents', 'messages', 'input', 'system', 'systemInstruction', 'system_instruction', 'instructions', 'system_prompt_mode', 'crag_prompt', 'tools', 'toolConfig', 'tool_config', 'tool_choice', 'generationConfig', 'generation_config', 'web_search_options', 'thinking', 'max_tokens', 'temperature', 'top_p', 'top_k', 'stop', 'stop_sequences', 'conversation_id', 'previous_response_id', 'metadata', 'parallel_tool_calls', 'reasoning', 'response_format', 'subagents', ]) const CRAGGEMINI_SUPPORTED_ASPECT_RATIOS = new Set([ '1:1', '2:3', '3:2', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9', '1:4', '4:1', '1:8', '8:1', ]) const CRAGGEMINI_SCHEMA_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'array', 'object']) const CRAGGEMINI_MAX_REQUEST_BYTES = 12 * 1024 * 1024 const VALID_MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/ const VALID_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/ const UNICODE_CONTROL_RE = /[^\P{Cc}\n\r\t]/u const UNICODE_WS_RE = /\p{White_Space}+/u function isPlainObject(v) { return v != null && typeof v === 'object' && !Array.isArray(v) } function parseArgs(argv) { const home = os.homedir() const opts = { standardsDir: fs.existsSync('X:/crag-standalone/tests/fixtures/replay-standards') ? 'X:/crag-standalone/tests/fixtures/replay-standards' : fs.existsSync('/mnt/x/crag-standalone/tests/fixtures/replay-standards') ? '/mnt/x/crag-standalone/tests/fixtures/replay-standards' : '', claudeDir: path.join(home, '.claude', 'projects'), codexDir: path.join(home, '.codex', 'sessions'), geminiDir: path.join(home, '.gemini', 'tmp'), limitPerSource: 20, maxTurnsPerSession: 3, verbose: false, json: false, list: false, skipHostPython: false, only: null, } for (let i = 0; i < argv.length; i += 1) { const arg = argv[i] if (arg === '--help' || arg === '-h') { console.log(`Usage: node scripts/verify-craggemini-sessions.mjs [options] Options: --standards-dir <dir> Path to crag-standalone replay-standards corpus --claude-dir <dir> Path to local Claude Code projects dir (~/.claude/projects) --codex-dir <dir> Path to local Codex sessions dir (~/.codex/sessions) --gemini-dir <dir> Path to local Gemini CLI tmp dir (~/.gemini/tmp) --limit <n> Max session files per CLI source (default: 20, 0 = all) --turns <n> Max snapshot turns extracted per session (default: 3) --only <sources> Comma-separated subset: parity,standards,packets,claude,codex,gemini,resume --skip-host-python Skip invoking scripts/gemini-host.py via Python --list List discovered corpus & session samples without running --verbose Print detailed per-sample summary --json Output machine-readable JSON summary`) process.exit(0) } else if (arg === '--standards-dir') opts.standardsDir = argv[++i] || '' else if (arg === '--claude-dir') opts.claudeDir = argv[++i] || '' else if (arg === '--codex-dir') opts.codexDir = argv[++i] || '' else if (arg === '--gemini-dir') opts.geminiDir = argv[++i] || '' else if (arg === '--limit') opts.limitPerSource = Math.max(0, Number(argv[++i] ?? 20)) else if (arg === '--turns') opts.maxTurnsPerSession = Math.max(1, Number(argv[++i] ?? 3)) else if (arg === '--only') opts.only = new Set( String(argv[++i] || '') .split(',') .map((s) => s.trim()) .filter(Boolean), ) else if (arg === '--skip-host-python') opts.skipHostPython = true else if (arg === '--list') opts.list = true else if (arg === '--verbose') opts.verbose = true else if (arg === '--json') opts.json = true } return opts } function walkFiles(dir, re, out = []) { if (!dir || !fs.existsSync(dir)) return out let entries try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return out } for (const entry of entries) { const full = path.join(dir, entry.name) if (entry.isDirectory()) walkFiles(full, re, out) else if (entry.isFile() && re.test(entry.name)) out.push(full) } return out } function pickRepresentativeFiles(files, limit) { const sized = files .map((f) => { try { return { file: f, size: fs.statSync(f).size } } catch { return { file: f, size: 0 } } }) .filter((x) => x.size > 0) .sort((a, b) => b.size - a.size) if (!limit || sized.length <= limit) return sized.map((x) => x.file) // Pick a spread across largest, median, and recent small sessions for diversity. const picked = [] const topCount = Math.ceil(limit * 0.6) for (let i = 0; i < Math.min(topCount, sized.length); i += 1) picked.push(sized[i].file) const rest = sized.slice(topCount) const step = Math.max(1, Math.floor(rest.length / Math.max(1, limit - picked.length))) for (let i = 0; i < rest.length && picked.length < limit; i += step) picked.push(rest[i].file) return picked } // --------------------------------------------------------------------------- // 1. Faithful CRAGGemini Rust Validator (mirrors X:/antigravity-cli-proxy/src/) // --------------------------------------------------------------------------- function cragValidText(text) { if (typeof text !== 'string') return { ok: false, reason: 'text is not string' } if (!text.trim()) return { ok: false, reason: 'valid_text: empty or whitespace-only text' } if (Buffer.byteLength(text, 'utf8') > CRAGGEMINI_MAX_REQUEST_BYTES) { return { ok: false, reason: 'valid_text: exceeds MAX_REQUEST (12 MiB)' } } for (const token of text.trim().split(UNICODE_WS_RE)) { if (token.startsWith('/')) { return { ok: false, reason: `valid_text: whitespace-delimited token starts with '/': "${token.slice(0, 32)}"` } } } const ctrl = UNICODE_CONTROL_RE.exec(text) if (ctrl) { const cp = ctrl[0].codePointAt(0).toString(16).padStart(4, '0') return { ok: false, reason: `valid_text: illegal control char U+${cp}` } } return { ok: true } } function cragValidSystemPrompt(text) { if (typeof text !== 'string') return { ok: false, reason: 'system_prompt is not string' } if (Buffer.byteLength(text, 'utf8') > CRAGGEMINI_MAX_REQUEST_BYTES) { return { ok: false, reason: 'valid_system_prompt: exceeds MAX_REQUEST' } } const ctrl = UNICODE_CONTROL_RE.exec(text) if (ctrl) { const cp = ctrl[0].codePointAt(0).toString(16).padStart(4, '0') return { ok: false, reason: `valid_system_prompt: illegal control char U+${cp}` } } return { ok: true } } function cragSanitizePromptLine(text) { let out = '' let prevWs = true for (const ch of text) { if (ch === '/' && prevWs) { out += './' prevWs = false } else { out += ch prevWs = /\p{White_Space}/u.test(ch) } } return out } function cragProjectSchemaNode(node, depth = 0) { if (depth > 32) return { ok: false, reason: 'schema recursion depth > 32' } if (node === null || node === true) return { ok: true } if (node === false) return { ok: false, reason: 'schema false forbids all values' } if (!isPlainObject(node)) return { ok: false, reason: 'schema node must be JSON object or boolean' } if (node.not === true || (isPlainObject(node.not) && Object.keys(node.not).length === 0)) { return { ok: false, reason: 'schema.not forbids all values' } } if (node.type !== undefined) { if (Array.isArray(node.type)) { const nonNull = [] for (const item of node.type) { if (typeof item !== 'string') return { ok: false, reason: 'schema.type array must contain strings' } if (item.toLowerCase() !== 'null') nonNull.push(item.toLowerCase()) } if (!nonNull.length) return { ok: false, reason: 'schema.type array has no non-null type' } for (const t of nonNull) { if (!CRAGGEMINI_SCHEMA_TYPES.has(t)) return { ok: false, reason: `unsupported schema.type: ${t}` } } } else if (typeof node.type === 'string') { const lower = node.type.toLowerCase() if (lower !== 'type_unspecified' && lower !== 'null' && !CRAGGEMINI_SCHEMA_TYPES.has(lower)) { return { ok: false, reason: `unsupported schema.type: ${node.type}` } } } } if (isPlainObject(node.properties)) { for (const [k, v] of Object.entries(node.properties)) { const sub = cragProjectSchemaNode(v, depth + 1) if (!sub.ok) return { ok: false, reason: `properties.${k}: ${sub.reason}` } } } if (node.items !== undefined) { if (Array.isArray(node.items)) { for (const it of node.items) { const sub = cragProjectSchemaNode(it, depth + 1) if (!sub.ok) return sub } } else { const sub = cragProjectSchemaNode(node.items, depth + 1) if (!sub.ok) return sub } } for (const key of ['anyOf', 'oneOf', 'allOf']) { if (Array.isArray(node[key])) { for (const v of node[key]) { const sub = cragProjectSchemaNode(v, depth + 1) if (!sub.ok) return sub } } } return { ok: true } } /** * Validates that an outbound Gemini body produced by vm2api will be accepted by * `craggemini` (`X:/antigravity-cli-proxy/src/{server,tools,schema,protocol,resume}.rs`) * AND obeys our strict minimal-ingress cleanliness invariants. */ function validateCragGeminiContract(body, { expectedModel = DEFAULT_MODEL, strictMinimal = true } = {}) { const errors = [] if (!isPlainObject(body)) return { ok: false, errors: ['body must be a JSON object'] } // 1. Minimal & ALLOWED_BODY_KEYS check for (const key of Object.keys(body)) { if (!CRAGGEMINI_ALLOWED_BODY_KEYS.has(key)) { errors.push(`craggemini ALLOWED_BODY_KEYS rejects top-level key "${key}"`) } if (strictMinimal && !MINIMAL_CRAGGEMINI_KEYS.has(key)) { errors.push(`non-minimal top-level key leaked for antigravity: "${key}"`) } } // 2. model check if (typeof body.model !== 'string' || !VALID_MODEL_RE.test(body.model)) { errors.push(`invalid model: ${JSON.stringify(body.model)}`) } else if (expectedModel && body.model !== expectedModel) { errors.push(`model mismatch: got ${body.model}, expected ${expectedModel}`) } // 3. system_prompt_mode check if (body.system_prompt_mode !== undefined && !['official_full', 'zero'].includes(body.system_prompt_mode)) { errors.push(`invalid system_prompt_mode: ${JSON.stringify(body.system_prompt_mode)}`) } // 4. systemInstruction check (server.rs::parse_system_instruction + valid_system_prompt) let systemText = '' if (body.systemInstruction !== undefined) { const si = body.systemInstruction if (!isPlainObject(si) || !Array.isArray(si.parts) || si.parts.length === 0) { errors.push('systemInstruction must be { parts: [{ text }] }') } else { for (const p of si.parts) { if (!isPlainObject(p) || Object.keys(p).length !== 1 || typeof p.text !== 'string') { errors.push('systemInstruction.parts entries must each have exactly one key "text" (string)') } else { systemText += p.text } } if (!systemText.trim()) errors.push('systemInstruction text is empty/whitespace') else { const vs = cragValidSystemPrompt(systemText) if (!vs.ok) errors.push(vs.reason) } } } // 5. conversation_id check if (body.conversation_id !== undefined) { if (typeof body.conversation_id !== 'string' || !VALID_ID_RE.test(body.conversation_id)) { errors.push(`invalid conversation_id: ${JSON.stringify(body.conversation_id)}`) } } // 6. generationConfig check (must be image-only on strictMinimal) let hasImageGen = false if (body.generationConfig !== undefined) { const gc = body.generationConfig if (!isPlainObject(gc)) { errors.push('generationConfig must be an object') } else { const allowedGenKeys = new Set(['responseModalities', 'imageConfig', 'candidateCount']) for (const k of Object.keys(gc)) { if (strictMinimal && !allowedGenKeys.has(k)) { errors.push(`non-image generationConfig key leaked: "${k}"`) } } if (gc.responseModalities !== undefined) { if ( !Array.isArray(gc.responseModalities) || !gc.responseModalities.some((m) => String(m).toUpperCase() === 'IMAGE') ) { errors.push('generationConfig.responseModalities must include IMAGE when present') } else { hasImageGen = true } } if (gc.imageConfig !== undefined) { if (!isPlainObject(gc.imageConfig)) { errors.push('generationConfig.imageConfig must be an object') } else { hasImageGen = true if ( gc.imageConfig.aspectRatio !== undefined && !CRAGGEMINI_SUPPORTED_ASPECT_RATIOS.has(gc.imageConfig.aspectRatio) ) { errors.push(`unsupported imageConfig.aspectRatio: ${gc.imageConfig.aspectRatio}`) } if (gc.imageConfig.imageSize !== undefined && !['1K', '2K', '4K'].includes(gc.imageConfig.imageSize)) { errors.push(`unsupported imageConfig.imageSize: ${gc.imageConfig.imageSize}`) } } } if (strictMinimal && !hasImageGen) { errors.push('generationConfig present without image generation fields') } } } // 7. tools & toolConfig check (tools.rs::parse_tools_and_config + schema.rs::project_tool_schema) const declaredTools = [] let hasWebSearch = false let hasWebFetch = false if (body.tools !== undefined) { if (!Array.isArray(body.tools) || body.tools.length === 0) { errors.push('tools must be a non-empty array when present') } else { for (const entry of body.tools) { if (!isPlainObject(entry)) { errors.push('tools entry must be an object') continue } const keys = Object.keys(entry) let recognized = false if (entry.googleSearch !== undefined) { hasWebSearch = true recognized = true } if (entry.urlContext !== undefined) { hasWebFetch = true recognized = true } if (entry.functionDeclarations !== undefined) { recognized = true if (!Array.isArray(entry.functionDeclarations)) { errors.push('functionDeclarations must be an array') } else { for (const decl of entry.functionDeclarations) { if (!isPlainObject(decl) || typeof decl.name !== 'string' || !decl.name.trim()) { errors.push('functionDeclaration missing valid name') continue } if (decl.name.length > 64 || !/^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/.test(decl.name)) { errors.push(`invalid wire functionDeclaration.name: "${decl.name}"`) } if (decl.parameters !== undefined) { const sc = cragProjectSchemaNode(decl.parameters) if (!sc.ok) errors.push(`tool "${decl.name}" schema rejected by craggemini: ${sc.reason}`) } declaredTools.push(decl.name) } } } if (!recognized) { errors.push(`unrecognized/unsupported tool entry keys: [${keys.join(', ')}]`) } } } } if (body.toolConfig !== undefined) { const fcc = body.toolConfig?.functionCallingConfig if (!isPlainObject(fcc)) { errors.push('toolConfig.functionCallingConfig must be an object') } else { const mode = String(fcc.mode || 'AUTO').toUpperCase() if (!['AUTO', 'NONE', 'ANY'].includes(mode)) { errors.push(`craggemini rejects functionCallingConfig.mode="${mode}"`) } if ( strictMinimal && mode === 'AUTO' && (!Array.isArray(fcc.allowedFunctionNames) || !fcc.allowedFunctionNames.length) ) { errors.push('redundant AUTO toolConfig should be omitted') } } } // 8. contents check (server.rs::parse_gemini_content + resume.rs::build_delta + protocol.rs::valid_text) const canonicalMsgs = [] let inlineMediaCount = 0 if (!Array.isArray(body.contents) || body.contents.length === 0) { errors.push('contents must be a non-empty array') } else { for (let i = 0; i < body.contents.length; i += 1) { const entry = body.contents[i] if (!isPlainObject(entry)) { errors.push(`contents[${i}] must be an object`) continue } for (const k of Object.keys(entry)) { if (k !== 'role' && k !== 'parts') errors.push(`contents[${i}] has disallowed key "${k}"`) } const role = entry.role || 'user' if (!['user', 'model', 'assistant', 'tool', 'function'].includes(role)) { errors.push(`contents[${i}] invalid role "${role}"`) } if (!Array.isArray(entry.parts) || entry.parts.length === 0) { errors.push(`contents[${i}].parts must be a non-empty array`) continue } const cm = { role: role === 'model' ? 'assistant' : role, text: '', toolCalls: [], toolResults: [], } for (let j = 0; j < entry.parts.length; j += 1) { const p = entry.parts[j] if (!isPlainObject(p)) { errors.push(`contents[${i}].parts[${j}] must be an object`) continue } if (p.thought === true) { errors.push(`contents[${i}].parts[${j}] leaked thought:true into antigravity contents`) } if (p.thoughtSignature === SKIP_THOUGHT_SIGNATURE) { errors.push(`contents[${i}].parts[${j}] leaked dummy SKIP_THOUGHT_SIGNATURE`) } if ('fileData' in p || 'file_data' in p) { errors.push(`contents[${i}].parts[${j}] leaked unsupported fileData`) } let kindCount = 0 if (p.text !== undefined) { if (typeof p.text !== 'string') errors.push(`contents[${i}].parts[${j}].text must be string`) else if (p.thought !== true) cm.text += p.text kindCount += 1 } if (p.inlineData !== undefined) { const io = p.inlineData if (!isPlainObject(io) || !io.mimeType || !io.data) { errors.push(`contents[${i}].parts[${j}].inlineData missing mimeType or data`) } else { inlineMediaCount += 1 } kindCount += 1 } if (p.functionCall !== undefined) { const fc = p.functionCall if (!isPlainObject(fc) || typeof fc.name !== 'string' || !fc.name) { errors.push(`contents[${i}].parts[${j}].functionCall missing name`) } else { cm.toolCalls.push({ id: fc.id || null, name: fc.name }) } kindCount += 1 } if (p.functionResponse !== undefined) { const fr = p.functionResponse if (!isPlainObject(fr) || fr.response === undefined) { errors.push(`contents[${i}].parts[${j}].functionResponse missing response`) } else { cm.toolResults.push({ callId: fr.id || null, name: fr.name || null, content: fr.response, }) } kindCount += 1 } if (kindCount !== 1) { errors.push(`contents[${i}].parts[${j}] has kind_count=${kindCount} (craggemini requires exactly 1)`) } } canonicalMsgs.push(cm) } } // 9. Simulate craggemini `resume::build_delta` + `compile_native_prompt` + `valid_text` if (canonicalMsgs.length > 0 && errors.length === 0) { const last = canonicalMsgs[canonicalMsgs.length - 1] const prior = canonicalMsgs.slice(0, -1) let deltaText = last.text if (canonicalMsgs.length > 1 && !last.text.trim() && last.toolResults.length > 0) { deltaText = last.toolResults .map((tr) => `[Tool Result \`${tr.name || 'tool'}\`]: ${JSON.stringify(tr.content)}`) .join('\n') } const effectiveDelta = !deltaText.trim() && inlineMediaCount > 0 ? 'Inspect the attached media.' : deltaText const vd = cragValidText(effectiveDelta) if (!vd.ok) { errors.push(`craggemini effective_delta rejected: ${vd.reason}`) } else { const sections = [] if (prior.length > 0) { const preambleLines = [] for (const m of prior) { const r = m.role === 'assistant' ? 'Assistant' : m.role === 'tool' ? 'Tool' : 'User' if (m.text.trim()) preambleLines.push(`${r}: ${m.text.trim()}`) for (const tc of m.toolCalls) preambleLines.push(`${r} called tool \`${tc.name}\``) for (const tr of m.toolResults) { preambleLines.push(`Tool \`${tr.name || 'tool'}\` returned: ${JSON.stringify(tr.content)}`) } } if (preambleLines.length) { sections.push(`[Conversation Context]\n${cragSanitizePromptLine(preambleLines.join('\n'))}`) } } const hasAnyBridge = prior.length > 0 || declaredTools.length > 0 || hasWebSearch || hasWebFetch || hasImageGen || inlineMediaCount > 0 const compiled = hasAnyBridge ? [...sections, effectiveDelta].join('\n\n') : effectiveDelta const vc = cragValidText(compiled) if (!vc.ok) { errors.push(`craggemini compiled_prompt rejected: ${vc.reason}`) } } } return { ok: errors.length === 0, errors, declaredTools } } // --------------------------------------------------------------------------- // 2. Python Host `_extract_native_turn_body` Batch Validator // --------------------------------------------------------------------------- function runHostPythonValidator(cases) { const hostPyPath = path.join(REPO_ROOT, 'scripts', 'gemini-host.py') const pyCode = ` import json, sys, types, socketserver, importlib.util if not hasattr(socketserver, 'UnixStreamServer'): socketserver.UnixStreamServer = socketserver.TCPServer for mod in ('fcntl', 'grp', 'pwd', 'pty', 'termios', 'resource'): sys.modules.setdefault(mod, types.ModuleType(mod)) spec = importlib.util.spec_from_file_location('gemini_host_verify', sys.argv[1]) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) extract = mod.Host._extract_native_turn_body payload = json.loads(sys.stdin.read()) results = [] for item in payload: cleaned = extract(item['model'], item['body']) if cleaned is None: results.append({'id': item['id'], 'ok': False, 'reason': '_extract_native_turn_body returned None'}) else: same_keys = sorted(cleaned.keys()) == sorted(item['body'].keys()) results.append({ 'id': item['id'], 'ok': True, 'sameKeys': same_keys, 'droppedKeys': sorted(set(item['body'].keys()) - set(cleaned.keys())), 'addedKeys': sorted(set(cleaned.keys()) - set(item['body'].keys())), }) print(json.dumps(results)) ` const input = JSON.stringify(cases) for (const bin of ['python3', 'python']) { const res = spawnSync(bin, ['-B', '-c', pyCode, hostPyPath], { input, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, }) if (res.status === 0 && res.stdout.trim()) { return { ok: true, bin, results: JSON.parse(res.stdout) } } } return { ok: false, bin: null, results: [], error: 'No working python3/python executable found' } } // --------------------------------------------------------------------------- // 3. Synthetic Tool Schemas for Reconstructed Real CLI Sessions // --------------------------------------------------------------------------- function schemaForObservedTool(name, observedArgs = []) { const props = {} for (const args of observedArgs) { if (!isPlainObject(args)) continue for (const [k, v] of Object.entries(args)) { if (props[k]) continue if (typeof v === 'string') props[k] = { type: 'string' } else if (typeof v === 'number') props[k] = { type: Number.isInteger(v) ? 'integer' : 'number' } else if (typeof v === 'boolean') props[k] = { type: 'boolean' } else if (Array.isArray(v)) props[k] = { type: 'array', items: { type: 'string' } } else if (isPlainObject(v)) props[k] = { type: 'object', properties: {} } else props[k] = { type: 'string' } } } return { type: 'object', properties: props } } // --------------------------------------------------------------------------- // 4. Corpus Loaders: Standards, Packets, Claude Code, Codex, Gemini CLI // --------------------------------------------------------------------------- function loadStandardsCorpus(standardsDir) { if (!standardsDir || !fs.existsSync(standardsDir)) return [] const samples = [] const files = [ 'chat.json', 'gemini.json', 'messages.json', 'boundaries.json', 'persona/inputs.json', 'admission/inputs.json', ] for (const rel of files) { const full = path.join(standardsDir, rel) if (!fs.existsSync(full)) continue let arr try { arr = JSON.parse(fs.readFileSync(full, 'utf8')) } catch { continue } if (!Array.isArray(arr)) continue for (const item of arr) { if (!item?.id || !item.input) continue // Skip pure wrapper-reference items in admission/inputs.json that only declare `base` without `path`/`input`. const rawPath = item.path || '' let protocol = '' let url = rawPath let body = item.input if (rawPath === '/v1/chat/completions') { protocol = 'openai-chat' } else if (rawPath.startsWith('/v1beta/')) { protocol = 'gemini' url = rawPath.replace(/claude-haiku-4-5/g, DEFAULT_MODEL) } else if (rawPath === '/v1/messages') { protocol = 'anthropic' } else if (rawPath === '/internal/v1/messages' && isPlainObject(item.input?.body)) { protocol = 'anthropic' url = '/v1/messages' body = item.input.body } else { continue } // Clone and rewrite model to DEFAULT_MODEL so vm2api routes cleanly onto our test CRAGGemini model. const cloned = structuredClone(body) if (protocol !== 'gemini') cloned.model = DEFAULT_MODEL // `chat-bad-schema` has non-object json_schema.schema and must fail closed with 400. // `gemini-multiple-candidates` (non-image candidateCount) is intentionally stripped on CRAGGemini // while preserved for direct Gemini API Key; `tool-orphan` is hardened by ensureGeminiContentsValid. const expectBadRequest = item.id === 'chat-bad-schema' samples.push({ source: 'standards', id: `std:${rel.replace(/\.json$/, '')}:${item.id}`, protocol, url, body: cloned, expectStatus: expectBadRequest ? 400 : 200, stream: Boolean(cloned.stream) || url.includes('streamGenerateContent'), originNote: `${rel}#${item.id}`, extraAssert: item.id === 'gemini-multiple-candidates' ? (outboundBody) => outboundBody && 'generationConfig' in outboundBody ? 'non-image candidateCount should be stripped from antigravity generationConfig' : null : null, }) } } return samples } function loadPacketFixtures() { const dir = path.join(REPO_ROOT, 'test', 'fixtures') if (!fs.existsSync(dir)) return [] const samples = [] for (const name of [ 'pkt-001-openai.chat.completions.json', 'pkt-002-anthropic.messages.json', 'pkt-003-openai.responses.json', 'synth-tools-metadata.anthropic.json', ]) { const full = path.join(dir, name) if (!fs.existsSync(full)) continue const doc = JSON.parse(fs.readFileSync(full, 'utf8')) const protoMap = { 'openai.chat.completions': ['openai-chat', '/v1/chat/completions'], 'anthropic.messages': ['anthropic', '/v1/messages'], 'openai.responses': ['openai-responses', '/v1/responses'], } const mapped = protoMap[doc.inbound_protocol] if (!mapped || !isPlainObject(doc.inbound_body)) continue const body = structuredClone(doc.inbound_body) body.model = DEFAULT_MODEL samples.push({ source: 'packets', id: `pkt:${name.replace(/\.json$/, '')}`, protocol: mapped[0], url: mapped[1], body, expectStatus: 200, stream: Boolean(body.stream), originNote: name, }) } return samples } function loadClaudeSessions(claudeDir, { limit, maxTurns }) { const files = pickRepresentativeFiles(walkFiles(claudeDir, /\.jsonl$/), limit) const samples = [] for (const file of files) { const rawLines = fs.readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean) const messages = [] const toolArgsMap = new Map() for (const line of rawLines) { let row try { row = JSON.parse(line) } catch { continue } const msg = row?.message if (!isPlainObject(msg) || !['user', 'assistant'].includes(msg.role)) continue const content = msg.content if (typeof content === 'string') { if (!content.trim()) continue messages.push({ role: msg.role, content }) } else if (Array.isArray(content) && content.length > 0) { const cleanBlocks = [] for (const b of content) { if (!isPlainObject(b) || !b.type) continue if (b.type === 'tool_use' && b.name) { const list = toolArgsMap.get(b.name) || [] if (list.length < 3) list.push(b.input) toolArgsMap.set(b.name, list) // Keep exact real block structure (including caller metadata if present) cleanBlocks.push(b) } else { cleanBlocks.push(b) } } if (cleanBlocks.length) messages.push({ role: msg.role, content: cleanBlocks }) } } if (!messages.length) continue // Build snapshots ending on real user turns (both plain text turns and tool_result continuation turns) const userTurnEndIndices = [] for (let i = 0; i < messages.length; i += 1) { if (messages[i].role === 'user') userTurnEndIndices.push(i) } if (!userTurnEndIndices.length) continue const chosen = selectTurnIndices(userTurnEndIndices, maxTurns) const tools = [...toolArgsMap.entries()].map(([name, argList]) => ({ name, description: `Claude CLI tool ${name}`, input_schema: schemaForObservedTool(name, argList), })) const shortId = path.basename(file, '.jsonl').slice(0, 12) for (const endIdx of chosen) { // Slice a realistic window (up to 24 messages ending at endIdx, starting on a user turn) let startIdx = Math.max(0, endIdx - 23) while (startIdx < endIdx && messages[startIdx].role !== 'user') startIdx += 1 const slice = messages.slice(startIdx, endIdx + 1) if (!slice.length) continue const hasToolResult = Array.isArray(slice[slice.length - 1].content) && slice[slice.length - 1].content.some((b) => b?.type === 'tool_result') const body = { model: DEFAULT_MODEL, max_tokens: 4096, stream: true, system: [ { type: 'text', text: 'x-anthropic-billing-header: cc_version=2.1.321; cch=deadbeef; cc_entrypoint=cli' }, { type: 'text', text: 'You are Claude Code, an interactive CLI agent.', cache_control: { type: 'ephemeral', ttl: '1h' }, }, ], thinking: { type: 'enabled', budget_tokens: 4096 }, ...(tools.length ? { tools } : {}), messages: slice, } samples.push({ source: 'claude', id: `claude:${shortId}:t${endIdx}${hasToolResult ? ':toolres' : ''}`, protocol: 'anthropic', url: '/v1/messages', body, expectStatus: 200, stream: true, originNote: `${shortId} (${slice.length} msgs, ${tools.length} tools)`, }) } } return samples } function loadCodexSessions(codexDir, { limit, maxTurns }) { const files = pickRepresentativeFiles(walkFiles(codexDir, /\.jsonl$/), limit) const samples = [] for (const file of files) { const rawLines = fs.readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean) let instructions = '' const items = [] const toolArgsMap = new Map() const builtinTypes = new Set() for (const line of rawLines) { let row try { row = JSON.parse(line) } catch { continue } if (row?.type === 'session_meta' && typeof row.payload?.base_instructions?.text === 'string') { instructions = row.payload.base_instructions.text.slice(0, 8000) } else if (row?.type === 'session_meta' && typeof row.payload?.base_instructions === 'string') { instructions = row.payload.base_instructions.slice(0, 8000) } if (row?.type !== 'response_item' || !isPlainObject(row.payload)) continue const pl = row.payload const t = pl.type if ( t === 'message' || t === 'reasoning' || t === 'function_call' || t === 'function_call_output' || t === 'custom_tool_call' || t === 'custom_tool_call_output' || t === 'local_shell_call' || t === 'local_shell_call_output' || t === 'shell_call' || t === 'shell_call_output' || t === 'apply_patch_call' || t === 'apply_patch_call_output' ) { if (t === 'function_call' && pl.name) { const list = toolArgsMap.get(pl.name) || [] if (list.length < 3) { try { list.push(typeof pl.arguments === 'string' ? JSON.parse(pl.arguments) : pl.arguments) } catch {} } toolArgsMap.set(pl.name, list) } else if (t === 'custom_tool_call' && pl.name) { builtinTypes.add(`custom:${pl.name}`) } else if (t === 'local_shell_call') { builtinTypes.add('local_shell') } else if (t === 'shell_call') { builtinTypes.add('shell') } else if (t === 'apply_patch_call') { builtinTypes.add('apply_patch') } items.push(pl) } } if (!items.length) continue // Pick snapshots ending on a user message or *_output item const endIndices = [] for (let i = 0; i < items.length; i += 1) { const it = items[i] if ( (it.type === 'message' && it.role === 'user') || it.type === 'function_call_output' || it.type === 'custom_tool_call_output' || it.type === 'local_shell_call_output' || it.type === 'shell_call_output' || it.type === 'apply_patch_call_output' ) { endIndices.push(i) } } if (!endIndices.length) continue const chosen = selectTurnIndices(endIndices, maxTurns) const tools = [] for (const [name, argList] of toolArgsMap.entries()) { tools.push({ type: 'function', name, description: `Codex CLI tool ${name}`, parameters: schemaForObservedTool(name, argList), }) } for (const bt of builtinTypes) { if (bt.startsWith('custom:')) tools.push({ type: 'custom', name: bt.slice(7), description: 'Codex custom tool' }) else tools.push({ type: bt }) } const shortId = path.basename(file, '.jsonl').slice(-12) for (const endIdx of chosen) { const startIdx = Math.max(0, endIdx - 29) const slice = items.slice(startIdx, endIdx + 1) if (!slice.length) continue const isOutput = slice[slice.length - 1].type?.endsWith('_output') const body = { model: DEFAULT_MODEL, stream: true, ...(instructions ? { instructions } : {}), reasoning: { effort: 'high', summary: 'auto' }, parallel_tool_calls: true, ...(tools.length ? { tools } : {}), input: slice, } samples.push({ source: 'codex', id: `codex:${shortId}:i${endIdx}${isOutput ? ':toolout' : ''}`, protocol: 'openai-responses', url: '/v1/responses', |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |