koder 0.4.10__tar.gz → 0.4.13__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/child_outputs/1.md +1 -0
  2. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/child_outputs/1.result.md +245 -0
  3. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/child_outputs/2.md +0 -0
  4. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/child_outputs/3.md +1 -0
  5. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/child_outputs/3.result.md +208 -0
  6. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/final_report.md +51 -0
  7. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/prompts/1.md +12 -0
  8. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/prompts/2.md +12 -0
  9. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/prompts/3.md +10 -0
  10. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/raw/antigravity_claude_handler_retry.md +136 -0
  11. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/raw/antigravity_claude_request_thinking.md +287 -0
  12. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/raw/antigravity_claude_streaming_signature.md +151 -0
  13. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/raw/koder_antigravity_build_request.md +206 -0
  14. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/raw/koder_tool_utils_signature.md +386 -0
  15. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/run_children.sh +27 -0
  16. koder-0.4.13/.research/20260126-antigravity-claude-fix-7q1/tasks.txt +3 -0
  17. koder-0.4.13/.research/20260126-antigravity-signature-zise/final_report.md +57 -0
  18. {koder-0.4.10 → koder-0.4.13}/PKG-INFO +30 -14
  19. {koder-0.4.10 → koder-0.4.13}/README.md +22 -7
  20. {koder-0.4.10 → koder-0.4.13}/koder_agent/agentic/agent.py +48 -15
  21. {koder-0.4.10 → koder-0.4.13}/koder_agent/auth/client_integration.py +10 -20
  22. koder-0.4.13/koder_agent/auth/constants.py +245 -0
  23. koder-0.4.13/koder_agent/auth/litellm_oauth.py +28 -0
  24. koder-0.4.13/koder_agent/auth/providers/__init__.py +166 -0
  25. koder-0.4.13/koder_agent/auth/providers/antigravity.py +1358 -0
  26. koder-0.4.13/koder_agent/auth/providers/chatgpt.py +1024 -0
  27. koder-0.4.13/koder_agent/auth/providers/claude.py +697 -0
  28. koder-0.4.13/koder_agent/auth/providers/google.py +762 -0
  29. koder-0.4.13/koder_agent/auth/tool_utils.py +2544 -0
  30. {koder-0.4.10 → koder-0.4.13}/koder_agent/core/commands.py +4 -4
  31. {koder-0.4.10 → koder-0.4.13}/koder_agent/core/keyboard_listener.py +12 -2
  32. {koder-0.4.10 → koder-0.4.13}/koder_agent/core/scheduler.py +19 -30
  33. {koder-0.4.10 → koder-0.4.13}/koder_agent/core/streaming_display.py +5 -152
  34. {koder-0.4.10 → koder-0.4.13}/koder_agent/tools/search.py +1 -7
  35. {koder-0.4.10 → koder-0.4.13}/koder_agent/utils/client.py +31 -27
  36. {koder-0.4.10 → koder-0.4.13}/pyproject.toml +10 -9
  37. koder-0.4.10/koder_agent/auth/constants.py +0 -111
  38. koder-0.4.10/koder_agent/auth/litellm_oauth.py +0 -2687
  39. koder-0.4.10/koder_agent/auth/providers/__init__.py +0 -58
  40. koder-0.4.10/koder_agent/auth/providers/antigravity.py +0 -297
  41. koder-0.4.10/koder_agent/auth/providers/chatgpt.py +0 -199
  42. koder-0.4.10/koder_agent/auth/providers/claude.py +0 -261
  43. koder-0.4.10/koder_agent/auth/providers/google.py +0 -194
  44. koder-0.4.10/koder_agent/auth/tool_utils.py +0 -1274
  45. {koder-0.4.10 → koder-0.4.13}/.gitignore +0 -0
  46. {koder-0.4.10 → koder-0.4.13}/LICENSE +0 -0
  47. {koder-0.4.10 → koder-0.4.13}/koder_agent/__init__.py +0 -0
  48. {koder-0.4.10 → koder-0.4.13}/koder_agent/agentic/__init__.py +0 -0
  49. {koder-0.4.10 → koder-0.4.13}/koder_agent/agentic/approval_hooks.py +0 -0
  50. {koder-0.4.10 → koder-0.4.13}/koder_agent/agentic/hooks.py +0 -0
  51. {koder-0.4.10 → koder-0.4.13}/koder_agent/agentic/skill_guardrail.py +0 -0
  52. {koder-0.4.10 → koder-0.4.13}/koder_agent/auth/__init__.py +0 -0
  53. {koder-0.4.10 → koder-0.4.13}/koder_agent/auth/base.py +0 -0
  54. {koder-0.4.10 → koder-0.4.13}/koder_agent/auth/callback_server.py +0 -0
  55. {koder-0.4.10 → koder-0.4.13}/koder_agent/auth/cli_handler.py +0 -0
  56. {koder-0.4.10 → koder-0.4.13}/koder_agent/auth/codex_prompts.py +0 -0
  57. {koder-0.4.10 → koder-0.4.13}/koder_agent/auth/token_storage.py +0 -0
  58. {koder-0.4.10 → koder-0.4.13}/koder_agent/cli.py +0 -0
  59. {koder-0.4.10 → koder-0.4.13}/koder_agent/config/__init__.py +0 -0
  60. {koder-0.4.10 → koder-0.4.13}/koder_agent/config/cli_handler.py +0 -0
  61. {koder-0.4.10 → koder-0.4.13}/koder_agent/config/manager.py +0 -0
  62. {koder-0.4.10 → koder-0.4.13}/koder_agent/config/models.py +0 -0
  63. {koder-0.4.10 → koder-0.4.13}/koder_agent/core/__init__.py +0 -0
  64. {koder-0.4.10 → koder-0.4.13}/koder_agent/core/interactive.py +0 -0
  65. {koder-0.4.10 → koder-0.4.13}/koder_agent/core/security.py +0 -0
  66. {koder-0.4.10 → koder-0.4.13}/koder_agent/core/session.py +0 -0
  67. {koder-0.4.10 → koder-0.4.13}/koder_agent/core/status_line.py +0 -0
  68. {koder-0.4.10 → koder-0.4.13}/koder_agent/core/usage_tracker.py +0 -0
  69. {koder-0.4.10 → koder-0.4.13}/koder_agent/mcp/__init__.py +0 -0
  70. {koder-0.4.10 → koder-0.4.13}/koder_agent/mcp/cli_handler.py +0 -0
  71. {koder-0.4.10 → koder-0.4.13}/koder_agent/mcp/server_config.py +0 -0
  72. {koder-0.4.10 → koder-0.4.13}/koder_agent/mcp/server_factory.py +0 -0
  73. {koder-0.4.10 → koder-0.4.13}/koder_agent/mcp/server_manager.py +0 -0
  74. {koder-0.4.10 → koder-0.4.13}/koder_agent/tools/__init__.py +0 -0
  75. {koder-0.4.10 → koder-0.4.13}/koder_agent/tools/engine.py +0 -0
  76. {koder-0.4.10 → koder-0.4.13}/koder_agent/tools/file.py +0 -0
  77. {koder-0.4.10 → koder-0.4.13}/koder_agent/tools/shell.py +0 -0
  78. {koder-0.4.10 → koder-0.4.13}/koder_agent/tools/skill.py +0 -0
  79. {koder-0.4.10 → koder-0.4.13}/koder_agent/tools/skill_context.py +0 -0
  80. {koder-0.4.10 → koder-0.4.13}/koder_agent/tools/task.py +0 -0
  81. {koder-0.4.10 → koder-0.4.13}/koder_agent/tools/todo.py +0 -0
  82. {koder-0.4.10 → koder-0.4.13}/koder_agent/tools/web.py +0 -0
  83. {koder-0.4.10 → koder-0.4.13}/koder_agent/utils/__init__.py +0 -0
  84. {koder-0.4.10 → koder-0.4.13}/koder_agent/utils/model_info.py +0 -0
  85. {koder-0.4.10 → koder-0.4.13}/koder_agent/utils/prompts.py +0 -0
  86. {koder-0.4.10 → koder-0.4.13}/koder_agent/utils/queue.py +0 -0
  87. {koder-0.4.10 → koder-0.4.13}/koder_agent/utils/sessions.py +0 -0
  88. {koder-0.4.10 → koder-0.4.13}/koder_agent/utils/terminal_theme.py +0 -0
@@ -0,0 +1 @@
1
+ [{"type":"system","subtype":"hook_started","hook_id":"18202dc5-8fcd-4b26-aedd-b8ebcd247fc1","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"5760aae0-ae22-45a4-a617-9493c5400b24","session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8"},{"type":"system","subtype":"hook_started","hook_id":"45bde566-1541-418b-9066-f0ad4b148d49","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"a3561d12-a271-4a98-9560-0a33664560b7","session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8"},{"type":"system","subtype":"hook_response","hook_id":"18202dc5-8fcd-4b26-aedd-b8ebcd247fc1","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"{\n \"hookSpecificOutput\": {\n \"hookEventName\": \"SessionStart\",\n \"additionalContext\": \"You are in 'learning' output style mode, which combines interactive learning with educational explanations. This mode differs from the original unshipped Learning output style by also incorporating explanatory functionality.\\n\\n## Learning Mode Philosophy\\n\\nInstead of implementing everything yourself, identify opportunities where the user can write 5-10 lines of meaningful code that shapes the solution. Focus on business logic, design choices, and implementation strategies where their input truly matters.\\n\\n## When to Request User Contributions\\n\\nRequest code contributions for:\\n- Business logic with multiple valid approaches\\n- Error handling strategies\\n- Algorithm implementation choices\\n- Data structure decisions\\n- User experience decisions\\n- Design patterns and architecture choices\\n\\n## How to Request Contributions\\n\\nBefore requesting code:\\n1. Create the file with surrounding context\\n2. Add function signature with clear parameters/return type\\n3. Include comments explaining the purpose\\n4. Mark the location with TODO or clear placeholder\\n\\nWhen requesting:\\n- Explain what you've built and WHY this decision matters\\n- Reference the exact file and prepared location\\n- Describe trade-offs to consider, constraints, or approaches\\n- Frame it as valuable input that shapes the feature, not busy work\\n- Keep requests focused (5-10 lines of code)\\n\\n## Example Request Pattern\\n\\nContext: I've set up the authentication middleware. The session timeout behavior is a security vs. UX trade-off - should sessions auto-extend on activity, or have a hard timeout? This affects both security posture and user experience.\\n\\nRequest: In auth/middleware.ts, implement the handleSessionTimeout() function to define the timeout behavior.\\n\\nGuidance: Consider: auto-extending improves UX but may leave sessions open longer; hard timeouts are more secure but might frustrate active users.\\n\\n## Balance\\n\\nDon't request contributions for:\\n- Boilerplate or repetitive code\\n- Obvious implementations with no meaningful choices\\n- Configuration or setup code\\n- Simple CRUD operations\\n\\nDo request contributions when:\\n- There are meaningful trade-offs to consider\\n- The decision shapes the feature's behavior\\n- Multiple valid approaches exist\\n- The user's domain knowledge would improve the solution\\n\\n## Explanatory Mode\\n\\nAdditionally, provide educational insights about the codebase as you help with tasks. Be clear and educational, providing helpful explanations while remaining focused on the task. Balance educational content with task completion.\\n\\n### Insights\\nBefore and after writing code, provide brief educational explanations about implementation choices using:\\n\\n\\\"`★ Insight ─────────────────────────────────────`\\n[2-3 key educational points]\\n`─────────────────────────────────────────────────`\\\"\\n\\nThese insights should be included in the conversation, not in the codebase. Focus on interesting insights specific to the codebase or the code you just wrote, rather than general programming concepts. Provide insights as you write code, not just at the end.\"\n }\n}\n","stdout":"{\n \"hookSpecificOutput\": {\n \"hookEventName\": \"SessionStart\",\n \"additionalContext\": \"You are in 'learning' output style mode, which combines interactive learning with educational explanations. This mode differs from the original unshipped Learning output style by also incorporating explanatory functionality.\\n\\n## Learning Mode Philosophy\\n\\nInstead of implementing everything yourself, identify opportunities where the user can write 5-10 lines of meaningful code that shapes the solution. Focus on business logic, design choices, and implementation strategies where their input truly matters.\\n\\n## When to Request User Contributions\\n\\nRequest code contributions for:\\n- Business logic with multiple valid approaches\\n- Error handling strategies\\n- Algorithm implementation choices\\n- Data structure decisions\\n- User experience decisions\\n- Design patterns and architecture choices\\n\\n## How to Request Contributions\\n\\nBefore requesting code:\\n1. Create the file with surrounding context\\n2. Add function signature with clear parameters/return type\\n3. Include comments explaining the purpose\\n4. Mark the location with TODO or clear placeholder\\n\\nWhen requesting:\\n- Explain what you've built and WHY this decision matters\\n- Reference the exact file and prepared location\\n- Describe trade-offs to consider, constraints, or approaches\\n- Frame it as valuable input that shapes the feature, not busy work\\n- Keep requests focused (5-10 lines of code)\\n\\n## Example Request Pattern\\n\\nContext: I've set up the authentication middleware. The session timeout behavior is a security vs. UX trade-off - should sessions auto-extend on activity, or have a hard timeout? This affects both security posture and user experience.\\n\\nRequest: In auth/middleware.ts, implement the handleSessionTimeout() function to define the timeout behavior.\\n\\nGuidance: Consider: auto-extending improves UX but may leave sessions open longer; hard timeouts are more secure but might frustrate active users.\\n\\n## Balance\\n\\nDon't request contributions for:\\n- Boilerplate or repetitive code\\n- Obvious implementations with no meaningful choices\\n- Configuration or setup code\\n- Simple CRUD operations\\n\\nDo request contributions when:\\n- There are meaningful trade-offs to consider\\n- The decision shapes the feature's behavior\\n- Multiple valid approaches exist\\n- The user's domain knowledge would improve the solution\\n\\n## Explanatory Mode\\n\\nAdditionally, provide educational insights about the codebase as you help with tasks. Be clear and educational, providing helpful explanations while remaining focused on the task. Balance educational content with task completion.\\n\\n### Insights\\nBefore and after writing code, provide brief educational explanations about implementation choices using:\\n\\n\\\"`★ Insight ─────────────────────────────────────`\\n[2-3 key educational points]\\n`─────────────────────────────────────────────────`\\\"\\n\\nThese insights should be included in the conversation, not in the codebase. Focus on interesting insights specific to the codebase or the code you just wrote, rather than general programming concepts. Provide insights as you write code, not just at the end.\"\n }\n}\n","stderr":"","exit_code":0,"outcome":"success","uuid":"3125b1de-62ea-477f-aa73-c89b7ed135d9","session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8"},{"type":"system","subtype":"hook_response","hook_id":"45bde566-1541-418b-9066-f0ad4b148d49","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"{\n \"hookSpecificOutput\": {\n \"hookEventName\": \"SessionStart\",\n \"additionalContext\": \"<EXTREMELY_IMPORTANT>\\nYou have superpowers.\\n\\n**Below is the full content of your 'superpowers:using-superpowers' skill - your introduction to using skills. For all other skills, use the 'Skill' tool:**\\n\\n---\\nname: using-superpowers\\ndescription: Use when starting any conversation - establishes how to find and use skills, requiring Skill tool invocation before ANY response including clarifying questions\\n---\\n\\n<EXTREMELY-IMPORTANT>\\nIf you think there is even a 1% chance a skill might apply to what you are doing, you ABSOLUTELY MUST invoke the skill.\\n\\nIF A SKILL APPLIES TO YOUR TASK, YOU DO NOT HAVE A CHOICE. YOU MUST USE IT.\\n\\nThis is not negotiable. This is not optional. You cannot rationalize your way out of this.\\n</EXTREMELY-IMPORTANT>\\n\\n## How to Access Skills\\n\\n**In Claude Code:** Use the `Skill` tool. When you invoke a skill, its content is loaded and presented to you—follow it directly. Never use the Read tool on skill files.\\n\\n**In other environments:** Check your platform's documentation for how skills are loaded.\\n\\n# Using Skills\\n\\n## The Rule\\n\\n**Invoke relevant or requested skills BEFORE any response or action.** Even a 1% chance a skill might apply means that you should invoke the skill to check. If an invoked skill turns out to be wrong for the situation, you don't need to use it.\\n\\n```dot\\ndigraph skill_flow {\\n \\\"User message received\\\" [shape=doublecircle];\\n \\\"Might any skill apply?\\\" [shape=diamond];\\n \\\"Invoke Skill tool\\\" [shape=box];\\n \\\"Announce: 'Using [skill] to [purpose]'\\\" [shape=box];\\n \\\"Has checklist?\\\" [shape=diamond];\\n \\\"Create TodoWrite todo per item\\\" [shape=box];\\n \\\"Follow skill exactly\\\" [shape=box];\\n \\\"Respond (including clarifications)\\\" [shape=doublecircle];\\n\\n \\\"User message received\\\" -> \\\"Might any skill apply?\\\";\\n \\\"Might any skill apply?\\\" -> \\\"Invoke Skill tool\\\" [label=\\\"yes, even 1%\\\"];\\n \\\"Might any skill apply?\\\" -> \\\"Respond (including clarifications)\\\" [label=\\\"definitely not\\\"];\\n \\\"Invoke Skill tool\\\" -> \\\"Announce: 'Using [skill] to [purpose]'\\\";\\n \\\"Announce: 'Using [skill] to [purpose]'\\\" -> \\\"Has checklist?\\\";\\n \\\"Has checklist?\\\" -> \\\"Create TodoWrite todo per item\\\" [label=\\\"yes\\\"];\\n \\\"Has checklist?\\\" -> \\\"Follow skill exactly\\\" [label=\\\"no\\\"];\\n \\\"Create TodoWrite todo per item\\\" -> \\\"Follow skill exactly\\\";\\n}\\n```\\n\\n## Red Flags\\n\\nThese thoughts mean STOP—you're rationalizing:\\n\\n| Thought | Reality |\\n|---------|---------|\\n| \\\"This is just a simple question\\\" | Questions are tasks. Check for skills. |\\n| \\\"I need more context first\\\" | Skill check comes BEFORE clarifying questions. |\\n| \\\"Let me explore the codebase first\\\" | Skills tell you HOW to explore. Check first. |\\n| \\\"I can check git/files quickly\\\" | Files lack conversation context. Check for skills. |\\n| \\\"Let me gather information first\\\" | Skills tell you HOW to gather information. |\\n| \\\"This doesn't need a formal skill\\\" | If a skill exists, use it. |\\n| \\\"I remember this skill\\\" | Skills evolve. Read current version. |\\n| \\\"This doesn't count as a task\\\" | Action = task. Check for skills. |\\n| \\\"The skill is overkill\\\" | Simple things become complex. Use it. |\\n| \\\"I'll just do this one thing first\\\" | Check BEFORE doing anything. |\\n| \\\"This feels productive\\\" | Undisciplined action wastes time. Skills prevent this. |\\n| \\\"I know what that means\\\" | Knowing the concept ≠ using the skill. Invoke it. |\\n\\n## Skill Priority\\n\\nWhen multiple skills could apply, use this order:\\n\\n1. **Process skills first** (brainstorming, debugging) - these determine HOW to approach the task\\n2. **Implementation skills second** (frontend-design, mcp-builder) - these guide execution\\n\\n\\\"Let's build X\\\" → brainstorming first, then implementation skills.\\n\\\"Fix this bug\\\" → debugging first, then domain-specific skills.\\n\\n## Skill Types\\n\\n**Rigid** (TDD, debugging): Follow exactly. Don't adapt away discipline.\\n\\n**Flexible** (patterns): Adapt principles to context.\\n\\nThe skill itself tells you which.\\n\\n## User Instructions\\n\\nInstructions say WHAT, not HOW. \\\"Add X\\\" or \\\"Fix Y\\\" doesn't mean skip workflows.\\n\\n\\n</EXTREMELY_IMPORTANT>\"\n }\n}\n","stdout":"{\n \"hookSpecificOutput\": {\n \"hookEventName\": \"SessionStart\",\n \"additionalContext\": \"<EXTREMELY_IMPORTANT>\\nYou have superpowers.\\n\\n**Below is the full content of your 'superpowers:using-superpowers' skill - your introduction to using skills. For all other skills, use the 'Skill' tool:**\\n\\n---\\nname: using-superpowers\\ndescription: Use when starting any conversation - establishes how to find and use skills, requiring Skill tool invocation before ANY response including clarifying questions\\n---\\n\\n<EXTREMELY-IMPORTANT>\\nIf you think there is even a 1% chance a skill might apply to what you are doing, you ABSOLUTELY MUST invoke the skill.\\n\\nIF A SKILL APPLIES TO YOUR TASK, YOU DO NOT HAVE A CHOICE. YOU MUST USE IT.\\n\\nThis is not negotiable. This is not optional. You cannot rationalize your way out of this.\\n</EXTREMELY-IMPORTANT>\\n\\n## How to Access Skills\\n\\n**In Claude Code:** Use the `Skill` tool. When you invoke a skill, its content is loaded and presented to you—follow it directly. Never use the Read tool on skill files.\\n\\n**In other environments:** Check your platform's documentation for how skills are loaded.\\n\\n# Using Skills\\n\\n## The Rule\\n\\n**Invoke relevant or requested skills BEFORE any response or action.** Even a 1% chance a skill might apply means that you should invoke the skill to check. If an invoked skill turns out to be wrong for the situation, you don't need to use it.\\n\\n```dot\\ndigraph skill_flow {\\n \\\"User message received\\\" [shape=doublecircle];\\n \\\"Might any skill apply?\\\" [shape=diamond];\\n \\\"Invoke Skill tool\\\" [shape=box];\\n \\\"Announce: 'Using [skill] to [purpose]'\\\" [shape=box];\\n \\\"Has checklist?\\\" [shape=diamond];\\n \\\"Create TodoWrite todo per item\\\" [shape=box];\\n \\\"Follow skill exactly\\\" [shape=box];\\n \\\"Respond (including clarifications)\\\" [shape=doublecircle];\\n\\n \\\"User message received\\\" -> \\\"Might any skill apply?\\\";\\n \\\"Might any skill apply?\\\" -> \\\"Invoke Skill tool\\\" [label=\\\"yes, even 1%\\\"];\\n \\\"Might any skill apply?\\\" -> \\\"Respond (including clarifications)\\\" [label=\\\"definitely not\\\"];\\n \\\"Invoke Skill tool\\\" -> \\\"Announce: 'Using [skill] to [purpose]'\\\";\\n \\\"Announce: 'Using [skill] to [purpose]'\\\" -> \\\"Has checklist?\\\";\\n \\\"Has checklist?\\\" -> \\\"Create TodoWrite todo per item\\\" [label=\\\"yes\\\"];\\n \\\"Has checklist?\\\" -> \\\"Follow skill exactly\\\" [label=\\\"no\\\"];\\n \\\"Create TodoWrite todo per item\\\" -> \\\"Follow skill exactly\\\";\\n}\\n```\\n\\n## Red Flags\\n\\nThese thoughts mean STOP—you're rationalizing:\\n\\n| Thought | Reality |\\n|---------|---------|\\n| \\\"This is just a simple question\\\" | Questions are tasks. Check for skills. |\\n| \\\"I need more context first\\\" | Skill check comes BEFORE clarifying questions. |\\n| \\\"Let me explore the codebase first\\\" | Skills tell you HOW to explore. Check first. |\\n| \\\"I can check git/files quickly\\\" | Files lack conversation context. Check for skills. |\\n| \\\"Let me gather information first\\\" | Skills tell you HOW to gather information. |\\n| \\\"This doesn't need a formal skill\\\" | If a skill exists, use it. |\\n| \\\"I remember this skill\\\" | Skills evolve. Read current version. |\\n| \\\"This doesn't count as a task\\\" | Action = task. Check for skills. |\\n| \\\"The skill is overkill\\\" | Simple things become complex. Use it. |\\n| \\\"I'll just do this one thing first\\\" | Check BEFORE doing anything. |\\n| \\\"This feels productive\\\" | Undisciplined action wastes time. Skills prevent this. |\\n| \\\"I know what that means\\\" | Knowing the concept ≠ using the skill. Invoke it. |\\n\\n## Skill Priority\\n\\nWhen multiple skills could apply, use this order:\\n\\n1. **Process skills first** (brainstorming, debugging) - these determine HOW to approach the task\\n2. **Implementation skills second** (frontend-design, mcp-builder) - these guide execution\\n\\n\\\"Let's build X\\\" → brainstorming first, then implementation skills.\\n\\\"Fix this bug\\\" → debugging first, then domain-specific skills.\\n\\n## Skill Types\\n\\n**Rigid** (TDD, debugging): Follow exactly. Don't adapt away discipline.\\n\\n**Flexible** (patterns): Adapt principles to context.\\n\\nThe skill itself tells you which.\\n\\n## User Instructions\\n\\nInstructions say WHAT, not HOW. \\\"Add X\\\" or \\\"Fix Y\\\" doesn't mean skip workflows.\\n\\n\\n</EXTREMELY_IMPORTANT>\"\n }\n}\n","stderr":"","exit_code":0,"outcome":"success","uuid":"f95e07a9-068e-4684-8d64-a62d7fe3d99c","session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8"},{"type":"system","subtype":"init","cwd":"/Users/fei/coding-agent/koder","session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","tools":["Task","TaskOutput","Bash","Glob","Grep","ExitPlanMode","Read","Edit","Write","NotebookEdit","WebFetch","TodoWrite","WebSearch","TaskStop","AskUserQuestion","Skill","EnterPlanMode","ToolSearch","mcp__ai-hub__chat","mcp__ai-hub__list_models","mcp__ai-hub__get_model_info","ListMcpResourcesTool","ReadMcpResourceTool","mcp__firecrawl__firecrawl_scrape","mcp__firecrawl__firecrawl_map","mcp__firecrawl__firecrawl_search","mcp__firecrawl__firecrawl_crawl","mcp__firecrawl__firecrawl_check_crawl_status","mcp__firecrawl__firecrawl_extract","mcp__firecrawl__firecrawl_agent","mcp__firecrawl__firecrawl_agent_status","mcp__plugin_claude-code-settings_chrome__click","mcp__plugin_claude-code-settings_chrome__close_page","mcp__plugin_claude-code-settings_chrome__drag","mcp__plugin_claude-code-settings_chrome__emulate","mcp__plugin_claude-code-settings_chrome__evaluate_script","mcp__plugin_claude-code-settings_chrome__fill","mcp__plugin_claude-code-settings_chrome__fill_form","mcp__plugin_claude-code-settings_chrome__get_console_message","mcp__plugin_claude-code-settings_chrome__get_network_request","mcp__plugin_claude-code-settings_chrome__handle_dialog","mcp__plugin_claude-code-settings_chrome__hover","mcp__plugin_claude-code-settings_chrome__list_console_messages","mcp__plugin_claude-code-settings_chrome__list_network_requests","mcp__plugin_claude-code-settings_chrome__list_pages","mcp__plugin_claude-code-settings_chrome__navigate_page","mcp__plugin_claude-code-settings_chrome__new_page","mcp__plugin_claude-code-settings_chrome__performance_analyze_insight","mcp__plugin_claude-code-settings_chrome__performance_start_trace","mcp__plugin_claude-code-settings_chrome__performance_stop_trace","mcp__plugin_claude-code-settings_chrome__press_key","mcp__plugin_claude-code-settings_chrome__resize_page","mcp__plugin_claude-code-settings_chrome__select_page","mcp__plugin_claude-code-settings_chrome__take_screenshot","mcp__plugin_claude-code-settings_chrome__take_snapshot","mcp__plugin_claude-code-settings_chrome__upload_file","mcp__plugin_claude-code-settings_chrome__wait_for"],"mcp_servers":[{"name":"ai-hub","status":"connected"},{"name":"firecrawl","status":"connected"},{"name":"plugin:claude-code-settings:chrome","status":"connected"}],"model":"claude-opus-4-5-20251101","permissionMode":"acceptEdits","slash_commands":["kiro-skill","agent-browser","interview-campus","remotion-best-practices","stop-slop","video-downloader","baoyu-xhs-images","codex-skill","youtube-transcribe-skill","humanizer-zh","qiaomu-paper-interpreter","rednote-reconstruct-work","baoyu-infographic","spec-kit-skill","web-design-guidelines","prompt-optimizer","baoyu-cover-image","rednote-discovery","deep-research","baoyu-post-to-wechat","baoyu-danger-gemini-web","rednote-reconstruct-biz","humanizer-en","rednote-topic-analyzer","peers-advisory-group","rednote-reconstruct-tech","baoyu-danger-x-to-markdown","baoyu-compress-image","notebooklm","mp-imitator","interview-social-questions","magazine-layout","baoyu-comic","autonomous-skill","multi-lens-thinking","rednote-title-generator","baoyu-post-to-x","rednote-writer","baoyu-image-gen","rednote-seo-imitator","interview-social","baoyu-slide-deck","baoyu-article-illustrator","ui-skills","rednote-batch-writer","vercel-react-best-practices","nanobanana-skill","daily-topic-selector","rednote-imitate","baoyu-url-to-markdown","virtual-product","json-canvas","mp-dna-imitator","rednote-seo","interview-me-planmd","debug","codex-delegate","transfer-context","update-claudemd","refactor","ensemble-opinion","commit-smart","setup-repo","gemini-delegate","feature-dev:feature-dev","claude-code-settings:gh:review-pr","claude-code-settings:gh:fix-issue","claude-code-settings:eureka","claude-code-settings:reflection-harder","claude-code-settings:think-harder","claude-code-settings:translate","claude-code-settings:reflection","claude-code-settings:think-ultra","claude-code-settings:cc:create-command","agent-sdk-dev:new-sdk-app","pr-review-toolkit:review-pr","commit-commands:commit-push-pr","commit-commands:clean_gone","commit-commands:commit","code-review:code-review","ralph-wiggum:help","ralph-wiggum:cancel-ralph","ralph-wiggum:ralph-loop","hookify:help","hookify:list","hookify:configure","hookify:hookify","plugin-dev:create-plugin","kiro-skill:kiro:vibe","kiro-skill:kiro:task","kiro-skill:kiro:spec","kiro-skill:kiro:design","kiro-skill:kiro:execute","agent-sdk-dev:new-sdk-app","pr-review-toolkit:review-pr","commit-commands:commit-push-pr","commit-commands:clean_gone","commit-commands:commit","feature-dev:feature-dev","code-review:code-review","plugin-dev:create-plugin","superpowers:execute-plan","superpowers:write-plan","superpowers:brainstorm","claude-code-settings:kiro-skill","claude-code-settings:codex-skill","claude-code-settings:youtube-transcribe-skill","claude-code-settings:spec-kit-skill","claude-code-settings:deep-research","claude-code-settings:autonomous-skill","claude-code-settings:nanobanana-skill","example-skills:theme-factory","example-skills:doc-coauthoring","example-skills:xlsx","example-skills:pdf","example-skills:algorithmic-art","example-skills:internal-comms","example-skills:skill-creator","example-skills:canvas-design","example-skills:pptx","example-skills:slack-gif-creator","example-skills:webapp-testing","example-skills:frontend-design","example-skills:mcp-builder","example-skills:brand-guidelines","example-skills:docx","example-skills:web-artifacts-builder","document-skills:theme-factory","document-skills:doc-coauthoring","document-skills:xlsx","document-skills:pdf","document-skills:algorithmic-art","document-skills:internal-comms","document-skills:skill-creator","document-skills:canvas-design","document-skills:pptx","document-skills:slack-gif-creator","document-skills:webapp-testing","document-skills:frontend-design","document-skills:mcp-builder","document-skills:brand-guidelines","document-skills:docx","document-skills:web-artifacts-builder","frontend-design:frontend-design","hookify:writing-rules","plugin-dev:command-development","plugin-dev:skill-development","plugin-dev:plugin-settings","plugin-dev:plugin-structure","plugin-dev:hook-development","plugin-dev:mcp-integration","plugin-dev:agent-development","kiro-skill:kiro-skill","spec-kit-skill:spec-kit-skill","codex-skill:codex-skill","nanobanana-skill:nanobanana-skill","youtube-transcribe-skill:youtube-transcribe-skill","autonomous-skill:autonomous-skill","frontend-design:frontend-design","plugin-dev:command-development","plugin-dev:skill-development","plugin-dev:plugin-settings","plugin-dev:plugin-structure","plugin-dev:hook-development","plugin-dev:mcp-integration","plugin-dev:agent-development","superpowers:using-git-worktrees","superpowers:test-driven-development","superpowers:systematic-debugging","superpowers:using-superpowers","superpowers:dispatching-parallel-agents","superpowers:executing-plans","superpowers:finishing-a-development-branch","superpowers:brainstorming","superpowers:writing-plans","superpowers:requesting-code-review","superpowers:receiving-code-review","superpowers:writing-skills","superpowers:verification-before-completion","superpowers:subagent-driven-development","compact","context","cost","init","pr-comments","release-notes","review","security-review"],"apiKeySource":"none","claude_code_version":"2.1.19","output_style":"default","agents":["Bash","general-purpose","statusline-setup","Explore","Plan","feature-dev:code-reviewer","feature-dev:code-explorer","feature-dev:code-architect","claude-code-settings:insight-documenter","claude-code-settings:ui-engineer","claude-code-settings:instruction-reflector","claude-code-settings:command-creator","claude-code-settings:github-issue-fixer","claude-code-settings:deep-reflector","claude-code-settings:pr-reviewer","agent-sdk-dev:agent-sdk-verifier-ts","agent-sdk-dev:agent-sdk-verifier-py","pr-review-toolkit:code-reviewer","pr-review-toolkit:silent-failure-hunter","pr-review-toolkit:code-simplifier","pr-review-toolkit:comment-analyzer","pr-review-toolkit:pr-test-analyzer","pr-review-toolkit:type-design-analyzer","hookify:conversation-analyzer","plugin-dev:agent-creator","plugin-dev:skill-reviewer","plugin-dev:plugin-validator","code-simplifier:code-simplifier","superpowers:code-reviewer","claude_critic"],"skills":["kiro-skill","agent-browser","interview-campus","remotion-best-practices","stop-slop","video-downloader","baoyu-xhs-images","codex-skill","youtube-transcribe-skill","humanizer-zh","qiaomu-paper-interpreter","rednote-reconstruct-work","baoyu-infographic","spec-kit-skill","web-design-guidelines","prompt-optimizer","baoyu-cover-image","rednote-discovery","deep-research","baoyu-post-to-wechat","baoyu-danger-gemini-web","rednote-reconstruct-biz","humanizer-en","rednote-topic-analyzer","peers-advisory-group","rednote-reconstruct-tech","baoyu-danger-x-to-markdown","baoyu-compress-image","notebooklm","mp-imitator","interview-social-questions","magazine-layout","baoyu-comic","autonomous-skill","multi-lens-thinking","rednote-title-generator","baoyu-post-to-x","rednote-writer","baoyu-image-gen","rednote-seo-imitator","interview-social","baoyu-slide-deck","baoyu-article-illustrator","ui-skills","rednote-batch-writer","vercel-react-best-practices","nanobanana-skill","daily-topic-selector","rednote-imitate","baoyu-url-to-markdown","virtual-product","json-canvas","mp-dna-imitator","rednote-seo","superpowers:execute-plan","superpowers:write-plan","superpowers:brainstorm","claude-code-settings:kiro-skill","claude-code-settings:codex-skill","claude-code-settings:youtube-transcribe-skill","claude-code-settings:spec-kit-skill","claude-code-settings:deep-research","claude-code-settings:autonomous-skill","claude-code-settings:nanobanana-skill","example-skills:theme-factory","example-skills:doc-coauthoring","example-skills:xlsx","example-skills:pdf","example-skills:algorithmic-art","example-skills:internal-comms","example-skills:skill-creator","example-skills:canvas-design","example-skills:pptx","example-skills:slack-gif-creator","example-skills:webapp-testing","example-skills:frontend-design","example-skills:mcp-builder","example-skills:brand-guidelines","example-skills:docx","example-skills:web-artifacts-builder","document-skills:theme-factory","document-skills:doc-coauthoring","document-skills:xlsx","document-skills:pdf","document-skills:algorithmic-art","document-skills:internal-comms","document-skills:skill-creator","document-skills:canvas-design","document-skills:pptx","document-skills:slack-gif-creator","document-skills:webapp-testing","document-skills:frontend-design","document-skills:mcp-builder","document-skills:brand-guidelines","document-skills:docx","document-skills:web-artifacts-builder","frontend-design:frontend-design","hookify:writing-rules","plugin-dev:command-development","plugin-dev:skill-development","plugin-dev:plugin-settings","plugin-dev:plugin-structure","plugin-dev:hook-development","plugin-dev:mcp-integration","plugin-dev:agent-development","kiro-skill:kiro-skill","spec-kit-skill:spec-kit-skill","codex-skill:codex-skill","nanobanana-skill:nanobanana-skill","youtube-transcribe-skill:youtube-transcribe-skill","autonomous-skill:autonomous-skill","frontend-design:frontend-design","plugin-dev:command-development","plugin-dev:skill-development","plugin-dev:plugin-settings","plugin-dev:plugin-structure","plugin-dev:hook-development","plugin-dev:mcp-integration","plugin-dev:agent-development","superpowers:using-git-worktrees","superpowers:test-driven-development","superpowers:systematic-debugging","superpowers:using-superpowers","superpowers:dispatching-parallel-agents","superpowers:executing-plans","superpowers:finishing-a-development-branch","superpowers:brainstorming","superpowers:writing-plans","superpowers:requesting-code-review","superpowers:receiving-code-review","superpowers:writing-skills","superpowers:verification-before-completion","superpowers:subagent-driven-development"],"plugins":[{"name":"feature-dev","path":"/Users/fei/.claude/plugins/cache/claude-code-plugins/feature-dev/1.0.0"},{"name":"claude-code-settings","path":"/Users/fei/.claude/plugins/cache/claude-code-settings/claude-code-settings/2.1.4"},{"name":"example-skills","path":"/Users/fei/.claude/plugins/cache/anthropic-agent-skills/example-skills/69c0b1a06741"},{"name":"agent-sdk-dev","path":"/Users/fei/.claude/plugins/cache/claude-code-plugins/agent-sdk-dev/1.0.0"},{"name":"pr-review-toolkit","path":"/Users/fei/.claude/plugins/cache/claude-code-plugins/pr-review-toolkit/1.0.0"},{"name":"commit-commands","path":"/Users/fei/.claude/plugins/cache/claude-code-plugins/commit-commands/1.0.0"},{"name":"security-guidance","path":"/Users/fei/.claude/plugins/cache/claude-code-plugins/security-guidance/1.0.0"},{"name":"document-skills","path":"/Users/fei/.claude/plugins/cache/anthropic-agent-skills/document-skills/69c0b1a06741"},{"name":"code-review","path":"/Users/fei/.claude/plugins/cache/claude-code-plugins/code-review/1.0.0"},{"name":"explanatory-output-style","path":"/Users/fei/.claude/plugins/cache/claude-code-plugins/explanatory-output-style/1.0.0"},{"name":"learning-output-style","path":"/Users/fei/.claude/plugins/cache/claude-code-plugins/learning-output-style/1.0.0"},{"name":"frontend-design","path":"/Users/fei/.claude/plugins/cache/claude-code-plugins/frontend-design/1.0.0"},{"name":"ralph-wiggum","path":"/Users/fei/.claude/plugins/cache/claude-code-plugins/ralph-wiggum/1.0.0"},{"name":"hookify","path":"/Users/fei/.claude/plugins/cache/claude-code-plugins/hookify/0.1.0"},{"name":"plugin-dev","path":"/Users/fei/.claude/plugins/cache/claude-code-plugins/plugin-dev/0.1.0"},{"name":"kiro-skill","path":"/Users/fei/.claude/plugins/cache/claude-code-settings/kiro-skill/1.0.1"},{"name":"spec-kit-skill","path":"/Users/fei/.claude/plugins/cache/claude-code-settings/spec-kit-skill/1.0.1"},{"name":"codex-skill","path":"/Users/fei/.claude/plugins/cache/claude-code-settings/codex-skill/1.0.1"},{"name":"nanobanana-skill","path":"/Users/fei/.claude/plugins/cache/claude-code-settings/nanobanana-skill/1.0.1"},{"name":"youtube-transcribe-skill","path":"/Users/fei/.claude/plugins/cache/claude-code-settings/youtube-transcribe-skill/1.0.1"},{"name":"autonomous-skill","path":"/Users/fei/.claude/plugins/cache/claude-code-settings/autonomous-skill/1.0.1"},{"name":"agent-sdk-dev","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/agent-sdk-dev/e30768372b41"},{"name":"pr-review-toolkit","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/pr-review-toolkit/e30768372b41"},{"name":"commit-commands","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/commit-commands/e30768372b41"},{"name":"feature-dev","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/feature-dev/e30768372b41"},{"name":"security-guidance","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/security-guidance/e30768372b41"},{"name":"code-review","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/code-review/e30768372b41"},{"name":"explanatory-output-style","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/explanatory-output-style/e30768372b41"},{"name":"learning-output-style","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/learning-output-style/e30768372b41"},{"name":"frontend-design","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/frontend-design/e30768372b41"},{"name":"plugin-dev","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/plugin-dev/e30768372b41"},{"name":"typescript-lsp","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/typescript-lsp/1.0.0"},{"name":"pyright-lsp","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/pyright-lsp/1.0.0"},{"name":"gopls-lsp","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/gopls-lsp/1.0.0"},{"name":"code-simplifier","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/code-simplifier/1.0.0"},{"name":"superpowers","path":"/Users/fei/.claude/plugins/cache/claude-plugins-official/superpowers/4.1.1"}],"uuid":"88cf49df-c07f-42ae-ab01-c3155af59691"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_012NnixA7aMpg3krfy4UyqdX","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to compare signature validation and thinking handling logic between two codebases:\n1. Antigravity-Manager (Rust) - the reference implementation\n2. Koder (Python) - needs to be checked for issues\n\nThey want me to:\n1. Summarize the Antigravity-Manager logic\n2. Identify mismatches in Koder\n3. Provide porting recommendations\n\nLet me start by reading the source files to understand both implementations.","signature":"EscECkYICxgCKkDh3PhJKXmhflYBujw2UURfen+O9ag46V/249bYm3jQHTxD1KICszh2asK20MdSi3YpB/oA6ZdoRXoyW0yTDUjdEgzQ2TUgyVnJqaXzX2MaDOFG9OvxtiLYQiwwqiIwLKIF2ehlbVBsbGe5JO3H73h07+X3u9R6nfptdrTxYE2xoU1o9pFTGwSErtqG9VqiKq4DHQ9m9vplYdZ2IixNNiTLtL2fl9CBdIhwhzVDPRREz8QpHsskJkkm+vbOUmJKcgBFYnR++KI8noFJuTRFVRFBwO1Aco+kTCc0wQqeXmr/ii/BlaiFVlMuQKMrzcttqmCdlE1P0yz17BIziy9m+F0vnZg8ffDHs3LGiVOEdeEv4RVI8MFZD9pNI1Pk63apxerSW/HBhqAjjPzzDA9qynzwikHScJoeL1OZY1YahvdSWouuhQZZVU7lJQEhCjS150kd2q3d6i3I9FQH7zKyDS5ivIshiGwWyaV9QDZJWmZjZjXuYnvgTsqAmYWj0grVZnDQ8C4RbegKnJcbPNGz1sK8JuB934LRke80eS/ogXopsChKOAK+uwCDLmLZHGXkbStN6SM/fh59tdMf1EgaWaC71+77T9N+Q9hLeg3dWOzaNDnMqOsK4rhxJAGxsEDgY7Y3y/g2Y18b46uGQht52klE7Qe20qzOx/3PW8c1oQQM5puAqUpIfgnSMe1ON/D58FkMNhUgTbH+Ylz5i+DD4tx5TcWpL2H7T1kxcTSYwh1Akwcz1HxQV/CCeqtBpn5L7RgB"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"cache_creation_input_tokens":37343,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":37343,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"f7492042-749a-4ca7-946b-4073e3738f72"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_012NnixA7aMpg3krfy4UyqdX","type":"message","role":"assistant","content":[{"type":"text","text":"I'll analyze both codebases to compare the signature validation and thinking handling logic. Let me read the relevant files."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"cache_creation_input_tokens":37343,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":37343,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"decd3668-13e0-46f5-a548-8bc7ca787c86"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_012NnixA7aMpg3krfy4UyqdX","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01MbhXqYVtKTceNRnXQgoenT","name":"Read","input":{"file_path":"/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs"},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"cache_creation_input_tokens":37343,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":37343,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"a36ace1c-3288-473e-9af8-c23a5a303d66"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_012NnixA7aMpg3krfy4UyqdX","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_011Ua1nF3qgs2y4W5mxc9UTD","name":"Read","input":{"file_path":"/Users/fei/coding-agent/koder/koder_agent/auth/litellm_oauth.py"},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"cache_creation_input_tokens":37343,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":37343,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"78e776db-c130-4279-a4d7-e20632c2ec70"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_012NnixA7aMpg3krfy4UyqdX","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01H6LW4Aw7MJFu4PKTDL82pH","name":"Read","input":{"file_path":"/Users/fei/coding-agent/koder/koder_agent/auth/tool_utils.py"},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"cache_creation_input_tokens":37343,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":37343,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"1c352044-f328-406c-b206-17ab560bc811"},{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01H6LW4Aw7MJFu4PKTDL82pH","type":"tool_result","content":" 1→\"\"\"Tool calling utilities for OAuth providers.\n 2→\n 3→Shared utilities for converting, cleaning, and managing tool calls across\n 4→different OAuth providers (Google, Claude, ChatGPT, Antigravity).\n 5→\n 6→Reference implementations:\n 7→- /tmp/oauth-providers/antigravity-auth/src/plugin/request-helpers.ts\n 8→- /tmp/oauth-providers/antigravity-auth/src/plugin/transform/claude.ts\n 9→- /tmp/oauth-providers/chatgpt-auth/lib/request/request-transformer.ts\n 10→\"\"\"\n 11→\n 12→import json\n 13→import logging\n 14→import threading\n 15→import time\n 16→import uuid\n 17→from collections import defaultdict\n 18→from typing import Any, Dict, List, Optional, Tuple\n 19→\n 20→logger = logging.getLogger(__name__)\n 21→\n 22→# =============================================================================\n 23→# THOUGHT SIGNATURE CACHE (Gemini 3)\n 24→# Stores thoughtSignature values to survive LiteLLM's streaming handler\n 25→# Thread-safe via threading.Lock for concurrent access\n 26→# =============================================================================\n 27→\n 28→# Cache: {(call_id, function_name): (thought_signature, timestamp)}\n 29→_thought_signature_cache: Dict[Tuple[str, str], Tuple[str, float]] = {}\n 30→# Most recent thought_signature for parallel calls fallback (per function name)\n 31→_last_thought_signature_by_name: Dict[str, Tuple[str, float]] = {}\n 32→# Global last signature for cross-function parallel calls (legacy fallback)\n 33→_last_thought_signature: Optional[Tuple[str, float]] = None\n 34→# Session-based signature cache: session_id -> (signature, message_count, timestamp)\n 35→_session_signature_cache: Dict[str, Tuple[str, int, float]] = {}\n 36→_CACHE_TTL_SECONDS = 300 # 5 minutes TTL\n 37→_SESSION_CACHE_TTL_SECONDS = 2 * 60 * 60 # 2 hours TTL (match Antigravity-Manager)\n 38→_BATCH_WINDOW_SECONDS = 2 # Window for parallel call batch (used for fallback)\n 39→# Lock for thread-safe cache access (required for multi-step operations)\n 40→_cache_lock = threading.Lock()\n 41→_MAX_CACHE_SIZE = 1000 # Prevent unbounded growth\n 42→\n 43→\n 44→def _normalize_function_name(name: str) -> str:\n 45→ \"\"\"Normalize function name by stripping known prefixes.\n 46→\n 47→ Handles prefixes like: default_api:, tools:, functions:, etc.\n 48→ \"\"\"\n 49→ known_prefixes = (\"default_api:\", \"tools:\", \"functions:\", \"tool:\")\n 50→ for prefix in known_prefixes:\n 51→ if name.startswith(prefix):\n 52→ return name[len(prefix) :]\n 53→ return name\n 54→\n 55→\n 56→def cache_thought_signature(call_id: str, function_name: str, thought_signature: str) -> None:\n 57→ \"\"\"Cache a thoughtSignature for later retrieval.\n 58→\n 59→ Also stores as \"last signature\" for parallel calls that don't have their own.\n 60→ Thread-safe via _cache_lock.\n 61→\n 62→ Args:\n 63→ call_id: Tool call ID\n 64→ function_name: Function name\n 65→ thought_signature: The thoughtSignature to cache\n 66→ \"\"\"\n 67→ global _last_thought_signature\n 68→\n 69→ key = (call_id, function_name)\n 70→ now = time.time()\n 71→ normalized_name = _normalize_function_name(function_name)\n 72→\n 73→ with _cache_lock:\n 74→ # Store in main cache\n 75→ _thought_signature_cache[key] = (thought_signature, now)\n 76→\n 77→ # Also store normalized version for prefix-agnostic lookup\n 78→ if normalized_name != function_name:\n 79→ _thought_signature_cache[(call_id, normalized_name)] = (thought_signature, now)\n 80→\n 81→ # Store per-function-name fallback for parallel calls\n 82→ _last_thought_signature_by_name[normalized_name] = (thought_signature, now)\n 83→\n 84→ # Clean up old entries and enforce size limit\n 85→ _cleanup_thought_signature_cache_unlocked()\n 86→\n 87→\n 88→def cache_thinking_signature(thought_signature: str) -> None:\n 89→ \"\"\"Cache a thoughtSignature from a thinking block.\n 90→\n 91→ Gemini 3 may emit thoughtSignature only on thinking parts (not functionCall).\n 92→ Store it as the global fallback so tool calls without explicit signatures can reuse it.\n 93→ \"\"\"\n 94→ global _last_thought_signature\n 95→\n 96→ if not thought_signature or not isinstance(thought_signature, str):\n 97→ return\n 98→\n 99→ now = time.time()\n 100→ with _cache_lock:\n 101→ _last_thought_signature = (thought_signature, now)\n 102→ _cleanup_thought_signature_cache_unlocked()\n 103→\n 104→\n 105→def cache_session_signature(session_id: str, thought_signature: str, message_count: int) -> None:\n 106→ \"\"\"Cache the latest thinking signature for a session (Gemini 3 tool loops).\n 107→\n 108→ Mirrors Antigravity-Manager's session cache: prefer most recent signatures,\n 109→ detect rewind (message_count decreases), and only store sufficiently long signatures.\n 110→ \"\"\"\n 111→ if not session_id or not thought_signature or not isinstance(thought_signature, str):\n 112→ return\n 113→ if len(thought_signature) < MIN_SIGNATURE_LENGTH:\n 114→ return\n 115→\n 116→ now = time.time()\n 117→ with _cache_lock:\n 118→ existing = _session_signature_cache.get(session_id)\n 119→ should_store = False\n 120→ if existing is None:\n 121→ should_store = True\n 122→ else:\n 123→ _, existing_count, ts = existing\n 124→ # Expired entry\n 125→ if now - ts >= _SESSION_CACHE_TTL_SECONDS:\n 126→ should_store = True\n 127→ # Rewind detected\n 128→ elif message_count < existing_count:\n 129→ should_store = True\n 130→ # Same message count: prefer longer signature\n 131→ elif message_count == existing_count:\n 132→ should_store = len(thought_signature) > len(existing[0])\n 133→ else:\n 134→ should_store = True\n 135→\n 136→ if should_store:\n 137→ _session_signature_cache[session_id] = (\n 138→ thought_signature,\n 139→ message_count,\n 140→ now,\n 141→ )\n 142→\n 143→ _cleanup_thought_signature_cache_unlocked()\n 144→\n 145→\n 146→def get_session_signature(session_id: str) -> Optional[str]:\n 147→ \"\"\"Retrieve cached session signature if valid and not expired.\"\"\"\n 148→ if not session_id:\n 149→ return None\n 150→\n 151→ now = time.time()\n 152→ with _cache_lock:\n 153→ entry = _session_signature_cache.get(session_id)\n 154→ if not entry:\n 155→ return None\n 156→ sig, _count, ts = entry\n 157→ if now - ts >= _SESSION_CACHE_TTL_SECONDS:\n 158→ return None\n 159→ return sig\n 160→\n 161→\n 162→def _extract_part_thought_signature(part: Dict[str, Any]) -> Optional[str]:\n 163→ \"\"\"Extract thoughtSignature from a Gemini part (direct or metadata.google).\"\"\"\n 164→ sig = part.get(\"thoughtSignature\")\n 165→ if isinstance(sig, str) and sig:\n 166→ return sig\n 167→\n 168→ func_call = part.get(\"functionCall\")\n 169→ if isinstance(func_call, dict):\n 170→ sig = func_call.get(\"thoughtSignature\") or func_call.get(\"thought_signature\")\n 171→ if isinstance(sig, str) and sig:\n 172→ return sig\n 173→\n 174→ func_meta = func_call.get(\"metadata\")\n 175→ if isinstance(func_meta, dict):\n 176→ google_meta = func_meta.get(\"google\")\n 177→ if isinstance(google_meta, dict):\n 178→ sig = google_meta.get(\"thoughtSignature\")\n 179→ if isinstance(sig, str) and sig:\n 180→ return sig\n 181→\n 182→ metadata = part.get(\"metadata\")\n 183→ if isinstance(metadata, dict):\n 184→ google_meta = metadata.get(\"google\")\n 185→ if isinstance(google_meta, dict):\n 186→ sig = google_meta.get(\"thoughtSignature\")\n 187→ if isinstance(sig, str) and sig:\n 188→ return sig\n 189→\n 190→ return None\n 191→\n 192→\n 193→def inject_thought_signature_for_function_calls(\n 194→ contents: List[Dict[str, Any]], session_id: str\n 195→) -> List[Dict[str, Any]]:\n 196→ \"\"\"Inject thoughtSignature into functionCall parts when missing.\n 197→\n 198→ Uses session-scoped cached signatures (no fake signatures).\n 199→ Mirrors Antigravity-Manager's wrap_request behavior.\n 200→ \"\"\"\n 201→ if not contents or not session_id:\n 202→ return contents\n 203→\n 204→ sig = get_session_signature(session_id)\n 205→ if not sig:\n 206→ return contents\n 207→\n 208→ updated_contents = []\n 209→ for content in contents:\n 210→ if not isinstance(content, dict) or not isinstance(content.get(\"parts\"), list):\n 211→ updated_contents.append(content)\n 212→ continue\n 213→\n 214→ parts = []\n 215→ for part in content[\"parts\"]:\n 216→ if not isinstance(part, dict):\n 217→ parts.append(part)\n 218→ continue\n 219→\n 220→ if \"functionCall\" in part and not _extract_part_thought_signature(part):\n 221→ new_part = dict(part)\n 222→ new_part[\"thoughtSignature\"] = sig\n 223→ parts.append(new_part)\n 224→ else:\n 225→ parts.append(part)\n 226→\n 227→ updated_contents.append({**content, \"parts\": parts})\n 228→\n 229→ return updated_contents\n 230→\n 231→\n 232→def get_cached_thought_signature(call_id: str, function_name: str) -> Optional[str]:\n 233→ \"\"\"Retrieve a cached thoughtSignature.\n 234→\n 235→ Handles various function name formats via normalization:\n 236→ - Direct name: \"grep_search\"\n 237→ - With API prefix: \"default_api:grep_search\", \"tools:grep_search\", etc.\n 238→\n 239→ For parallel function calls, Gemini only provides thoughtSignature for the\n 240→ first call. This function falls back to the most recent signature if no\n 241→ exact match is found (within the batch window).\n 242→\n 243→ Thread-safe via _cache_lock.\n 244→\n 245→ Args:\n 246→ call_id: Tool call ID\n 247→ function_name: Function name (may include prefix)\n 248→\n 249→ Returns:\n 250→ The cached thoughtSignature, or None if not found or expired\n 251→ \"\"\"\n 252→ now = time.time()\n 253→ normalized_name = _normalize_function_name(function_name)\n 254→\n 255→ with _cache_lock:\n 256→ # Strategy 1: Try exact match first\n 257→ key = (call_id, function_name)\n 258→ if key in _thought_signature_cache:\n 259→ sig, timestamp = _thought_signature_cache[key]\n 260→ if now - timestamp < _CACHE_TTL_SECONDS:\n 261→ return sig\n 262→\n 263→ # Strategy 2: Try normalized name (handles all prefixes)\n 264→ if normalized_name != function_name:\n 265→ key = (call_id, normalized_name)\n 266→ if key in _thought_signature_cache:\n 267→ sig, timestamp = _thought_signature_cache[key]\n 268→ if now - timestamp < _CACHE_TTL_SECONDS:\n 269→ return sig\n 270→\n 271→ # NOTE: Do not use per-function/global fallbacks for Gemini 3 tool calls.\n 272→ # Thought signatures must match the specific functionCall in the response.\n 273→\n 274→ # No valid signature found - log warning for debugging (only for Gemini 3 models)\n 275→ # This is outside the lock since logging doesn't need synchronization\n 276→ logger.debug(\n 277→ f\"No thoughtSignature found for call_id={call_id}, function={function_name}. \"\n 278→ \"This is expected for non-Gemini-3 models.\"\n 279→ )\n 280→ return None\n 281→\n 282→\n 283→def _cleanup_thought_signature_cache_unlocked() -> None:\n 284→ \"\"\"Remove expired entries from the cache and enforce size limits.\n 285→\n 286→ MUST be called while holding _cache_lock.\n 287→ Also cleans up the per-function-name fallback cache.\n 288→ \"\"\"\n 289→ global _last_thought_signature\n 290→\n 291→ now = time.time()\n 292→\n 293→ # Clean main cache - remove expired entries\n 294→ expired_keys = [\n 295→ key for key, (_, ts) in _thought_signature_cache.items() if now - ts >= _CACHE_TTL_SECONDS\n 296→ ]\n 297→ for key in expired_keys:\n 298→ del _thought_signature_cache[key]\n 299→\n 300→ # Clean per-function-name fallback cache\n 301→ expired_names = [\n 302→ name\n 303→ for name, (_, ts) in _last_thought_signature_by_name.items()\n 304→ if now - ts >= _CACHE_TTL_SECONDS\n 305→ ]\n 306→ for name in expired_names:\n 307→ del _last_thought_signature_by_name[name]\n 308→\n 309→ # Clear global fallback if expired\n 310→ if _last_thought_signature:\n 311→ _, timestamp = _last_thought_signature\n 312→ if now - timestamp >= _CACHE_TTL_SECONDS:\n 313→ _last_thought_signature = None\n 314→\n 315→ # Enforce size limit on main cache (LRU-style: remove oldest)\n 316→ if len(_thought_signature_cache) > _MAX_CACHE_SIZE:\n 317→ # Sort by timestamp and remove oldest entries\n 318→ sorted_entries = sorted(_thought_signature_cache.items(), key=lambda x: x[1][1])\n 319→ entries_to_remove = len(_thought_signature_cache) - _MAX_CACHE_SIZE\n 320→ for key, _ in sorted_entries[:entries_to_remove]:\n 321→ del _thought_signature_cache[key]\n 322→\n 323→ # Clean session cache - remove expired entries\n 324→ expired_sessions = [\n 325→ key\n 326→ for key, (_, _, ts) in _session_signature_cache.items()\n 327→ if now - ts >= _SESSION_CACHE_TTL_SECONDS\n 328→ ]\n 329→ for key in expired_sessions:\n 330→ del _session_signature_cache[key]\n 331→\n 332→\n 333→def clear_thought_signature_cache() -> None:\n 334→ \"\"\"Clear all cached thought signatures.\n 335→\n 336→ Useful for testing and when switching between providers.\n 337→ Thread-safe.\n 338→ \"\"\"\n 339→ global _last_thought_signature\n 340→\n 341→ with _cache_lock:\n 342→ _thought_signature_cache.clear()\n 343→ _last_thought_signature_by_name.clear()\n 344→ _last_thought_signature = None\n 345→ _session_signature_cache.clear()\n 346→\n 347→\n 348→# Placeholder for tools with empty schemas (Claude VALIDATED mode requires at least one property)\n 349→EMPTY_SCHEMA_PLACEHOLDER_NAME = \"_placeholder\"\n 350→EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION = \"Placeholder. Always pass true.\"\n 351→\n 352→# =============================================================================\n 353→# CLAUDE TOOL HARDENING CONSTANTS (Ported from antigravity-auth)\n 354→# =============================================================================\n 355→\n 356→# Sentinel value to bypass thought signature validation\n 357→# When a thinking block has an invalid/missing signature, use this to skip validation\n 358→# Reference: antigravity-auth/src/constants.ts SKIP_THOUGHT_SIGNATURE\n 359→SKIP_THOUGHT_SIGNATURE = \"skip_thought_signature_validator\"\n 360→\n 361→# System instruction for Claude tool usage hardening\n 362→# Prevents hallucinated parameters by explicitly stating the rules\n 363→# Reference: antigravity-auth/src/constants.ts CLAUDE_TOOL_SYSTEM_INSTRUCTION\n 364→CLAUDE_TOOL_SYSTEM_INSTRUCTION = \"\"\"CRITICAL TOOL USAGE INSTRUCTIONS:\n 365→You are operating in a custom environment where tool definitions differ from your training data.\n 366→You MUST follow these rules strictly:\n 367→\n 368→1. DO NOT use your internal training data to guess tool parameters\n 369→2. ONLY use the exact parameter structure defined in the tool schema\n 370→3. Parameter names in schemas are EXACT - do not substitute with similar names from your training\n 371→4. Array parameters have specific item types - check the schema's 'items' field for the exact structure\n 372→5. When you see \"STRICT PARAMETERS\" in a tool description, those type definitions override any assumptions\n 373→6. Tool use in agentic workflows is REQUIRED - you must call tools with the exact parameters specified\n 374→\n 375→If you are unsure about a tool's parameters, YOU MUST read the schema definition carefully.\"\"\"\n 376→\n 377→# Template for parameter signature injection into tool descriptions\n 378→# Reference: antigravity-auth/src/constants.ts CLAUDE_DESCRIPTION_PROMPT\n 379→CLAUDE_DESCRIPTION_PROMPT = \"\\n\\n⚠️ STRICT PARAMETERS: {params}.\"\n 380→\n 381→# Minimum signature length to be considered valid (from TypeScript MIN_SIGNATURE_LENGTH)\n 382→MIN_SIGNATURE_LENGTH = 50\n 383→\n 384→# Unsupported constraint keywords that should be moved to description hints\n 385→# Claude/Gemini reject these in VALIDATED mode\n 386→UNSUPPORTED_CONSTRAINTS = [\n 387→ \"minLength\",\n 388→ \"maxLength\",\n 389→ \"exclusiveMinimum\",\n 390→ \"exclusiveMaximum\",\n 391→ \"pattern\",\n 392→ \"minItems\",\n 393→ \"maxItems\",\n 394→ \"format\",\n 395→ \"default\",\n 396→ \"examples\",\n 397→]\n 398→\n 399→# Keywords that should be removed after hint extraction\n 400→UNSUPPORTED_KEYWORDS = [\n 401→ *UNSUPPORTED_CONSTRAINTS,\n 402→ \"$schema\",\n 403→ \"$defs\",\n 404→ \"definitions\",\n 405→ \"const\",\n 406→ \"$ref\",\n 407→ \"additionalProperties\",\n 408→ \"propertyNames\",\n 409→ \"title\",\n 410→ \"$id\",\n 411→ \"$comment\",\n 412→]\n 413→\n 414→\n 415→# =============================================================================\n 416→# JSON SCHEMA CLEANING FOR LLM TOOL CALLS\n 417→# Cleans JSON schemas for providers that don't support advanced features\n 418→# like $ref/$defs (GitHub Copilot, Antigravity, etc.)\n 419→# =============================================================================\n 420→\n 421→\n 422→def _append_description_hint(schema: Dict[str, Any], hint: str) -> Dict[str, Any]:\n 423→ \"\"\"Append a hint to a schema's description field.\"\"\"\n 424→ if not schema or not isinstance(schema, dict):\n 425→ return schema\n 426→\n 427→ existing = schema.get(\"description\", \"\")\n 428→ if isinstance(existing, str) and existing:\n 429→ new_description = f\"{existing} ({hint})\"\n 430→ else:\n 431→ new_description = hint\n 432→\n 433→ return {**schema, \"description\": new_description}\n 434→\n 435→\n 436→def _convert_refs_to_hints(schema: Any) -> Any:\n 437→ \"\"\"Phase 1a: Convert $ref to description hints.\n 438→\n 439→ $ref: \"#/$defs/Foo\" → { type: \"object\", description: \"See: Foo\" }\n 440→ \"\"\"\n 441→ if not schema or not isinstance(schema, dict):\n 442→ return schema\n 443→\n 444→ if isinstance(schema, list):\n 445→ return [_convert_refs_to_hints(item) for item in schema]\n 446→\n 447→ # If this object has $ref, replace it with a hint\n 448→ if isinstance(schema.get(\"$ref\"), str):\n 449→ ref_val = schema[\"$ref\"]\n 450→ def_name = ref_val.split(\"/\")[-1] if \"/\" in ref_val else ref_val\n 451→ hint = f\"See: {def_name}\"\n 452→ existing_desc = schema.get(\"description\", \"\")\n 453→ new_description = f\"{existing_desc} ({hint})\" if existing_desc else hint\n 454→ return {\"type\": \"object\", \"description\": new_description}\n 455→\n 456→ # Recursively process all properties\n 457→ result = {}\n 458→ for key, value in schema.items():\n 459→ result[key] = _convert_refs_to_hints(value)\n 460→ return result\n 461→\n 462→\n 463→def _convert_const_to_enum(schema: Any) -> Any:\n 464→ \"\"\"Phase 1b: Convert const to enum.\n 465→\n 466→ { const: \"foo\" } → { enum: [\"foo\"] }\n 467→ \"\"\"\n 468→ if not schema or not isinstance(schema, dict):\n 469→ return schema\n 470→\n 471→ if isinstance(schema, list):\n 472→ return [_convert_const_to_enum(item) for item in schema]\n 473→\n 474→ result = {}\n 475→ for key, value in schema.items():\n 476→ if key == \"const\" and \"enum\" not in schema:\n 477→ result[\"enum\"] = [value]\n 478→ else:\n 479→ result[key] = _convert_const_to_enum(value)\n 480→ return result\n 481→\n 482→\n 483→def _add_enum_hints(schema: Any) -> Any:\n 484→ \"\"\"Phase 1c: Add enum hints to description.\n 485→\n 486→ { enum: [\"a\", \"b\", \"c\"] } → adds \"(Allowed: a, b, c)\" to description\n 487→ \"\"\"\n 488→ if not schema or not isinstance(schema, dict):\n 489→ return schema\n 490→\n 491→ if isinstance(schema, list):\n 492→ return [_add_enum_hints(item) for item in schema]\n 493→\n 494→ result = dict(schema)\n 495→\n 496→ # Add enum hint if enum has 2-10 items\n 497→ if isinstance(result.get(\"enum\"), list) and 1 < len(result[\"enum\"]) <= 10:\n 498→ vals = \", \".join(str(v) for v in result[\"enum\"])\n 499→ result = _append_description_hint(result, f\"Allowed: {vals}\")\n 500→\n 501→ # Recursively process nested objects\n 502→ for key, value in list(result.items()):\n 503→ if key != \"enum\" and isinstance(value, dict):\n 504→ result[key] = _add_enum_hints(value)\n 505→ elif key != \"enum\" and isinstance(value, list):\n 506→ result[key] = [_add_enum_hints(item) for item in value]\n 507→\n 508→ return result\n 509→\n 510→\n 511→def _add_additional_properties_hints(schema: Any) -> Any:\n 512→ \"\"\"Phase 1d: Add additionalProperties hints.\n 513→\n 514→ { additionalProperties: false } → adds \"(No extra properties allowed)\" to description\n 515→ \"\"\"\n 516→ if not schema or not isinstance(schema, dict):\n 517→ return schema\n 518→\n 519→ if isinstance(schema, list):\n 520→ return [_add_additional_properties_hints(item) for item in schema]\n 521→\n 522→ result = dict(schema)\n 523→\n 524→ if result.get(\"additionalProperties\") is False:\n 525→ result = _append_description_hint(result, \"No extra properties allowed\")\n 526→\n 527→ # Recursively process nested objects\n 528→ for key, value in list(result.items()):\n 529→ if key != \"additionalProperties\" and isinstance(value, dict):\n 530→ result[key] = _add_additional_properties_hints(value)\n 531→ elif key != \"additionalProperties\" and isinstance(value, list):\n 532→ result[key] = [_add_additional_properties_hints(item) for item in value]\n 533→\n 534→ return result\n 535→\n 536→\n 537→def _move_constraints_to_description(schema: Any) -> Any:\n 538→ \"\"\"Phase 1e: Move unsupported constraints to description hints.\n 539→\n 540→ { minLength: 1, maxLength: 100 } → adds \"(minLength: 1) (maxLength: 100)\" to description\n 541→ \"\"\"\n 542→ if not schema or not isinstance(schema, dict):\n 543→ return schema\n 544→\n 545→ if isinstance(schema, list):\n 546→ return [_move_constraints_to_description(item) for item in schema]\n 547→\n 548→ result = dict(schema)\n 549→\n 550→ # Move constraint values to description\n 551→ for constraint in UNSUPPORTED_CONSTRAINTS:\n 552→ if constraint in result and not isinstance(result[constraint], dict):\n 553→ result = _append_description_hint(result, f\"{constraint}: {result[constraint]}\")\n 554→\n 555→ # Recursively process nested objects\n 556→ for key, value in list(result.items()):\n 557→ if isinstance(value, dict):\n 558→ result[key] = _move_constraints_to_description(value)\n 559→ elif isinstance(value, list):\n 560→ result[key] = [_move_constraints_to_description(item) for item in value]\n 561→\n 562→ return result\n 563→\n 564→\n 565→def _merge_all_of(schema: Any) -> Any:\n 566→ \"\"\"Phase 2a: Merge allOf schemas into a single object.\"\"\"\n 567→ if not schema or not isinstance(schema, dict):\n 568→ return schema\n 569→\n 570→ if isinstance(schema, list):\n 571→ return [_merge_all_of(item) for item in schema]\n 572→\n 573→ result = dict(schema)\n 574→\n 575→ if isinstance(result.get(\"allOf\"), list):\n 576→ all_of = result.pop(\"allOf\")\n 577→ merged_properties = {}\n 578→ merged_required = []\n 579→\n 580→ for sub_schema in all_of:\n 581→ if isinstance(sub_schema, dict):\n 582→ if isinstance(sub_schema.get(\"properties\"), dict):\n 583→ merged_properties.update(sub_schema[\"properties\"])\n 584→ if isinstance(sub_schema.get(\"required\"), list):\n 585→ merged_required.extend(sub_schema[\"required\"])\n 586→\n 587→ if merged_properties:\n 588→ existing_props = result.get(\"properties\", {})\n 589→ result[\"properties\"] = {**existing_props, **merged_properties}\n 590→\n 591→ if merged_required:\n 592→ existing_req = result.get(\"required\", [])\n 593→ result[\"required\"] = list(set(existing_req + merged_required))\n 594→\n 595→ # Recursively process nested objects\n 596→ for key, value in list(result.items()):\n 597→ if isinstance(value, dict):\n 598→ result[key] = _merge_all_of(value)\n 599→ elif isinstance(value, list):\n 600→ result[key] = [_merge_all_of(item) for item in value]\n 601→\n 602→ return result\n 603→\n 604→\n 605→def _remove_unsupported_keywords(schema: Any) -> Any:\n 606→ \"\"\"Phase 3: Remove unsupported keywords from schema.\"\"\"\n 607→ if not schema or not isinstance(schema, dict):\n 608→ return schema\n 609→\n 610→ if isinstance(schema, list):\n 611→ return [_remove_unsupported_keywords(item) for item in schema]\n 612→\n 613→ result = {}\n 614→ for key, value in schema.items():\n 615→ if key in UNSUPPORTED_KEYWORDS:\n 616→ continue\n 617→ if isinstance(value, dict):\n 618→ result[key] = _remove_unsupported_keywords(value)\n 619→ elif isinstance(value, list):\n 620→ result[key] = [_remove_unsupported_keywords(item) for item in value]\n 621→ else:\n 622→ result[key] = value\n 623→\n 624→ return result\n 625→\n 626→\n 627→def _fix_required_fields(schema: Any) -> Any:\n 628→ \"\"\"Fix required fields that reference non-existent properties.\n 629→\n 630→ Gemini API validates that all entries in 'required' array have\n 631→ corresponding properties defined. This removes invalid entries.\n 632→ \"\"\"\n 633→ if not schema or not isinstance(schema, dict):\n 634→ return schema\n 635→\n 636→ result = dict(schema)\n 637→\n 638→ # Fix required at this level\n 639→ if isinstance(result.get(\"required\"), list) and isinstance(result.get(\"properties\"), dict):\n 640→ valid_props = set(result[\"properties\"].keys())\n 641→ result[\"required\"] = [r for r in result[\"required\"] if r in valid_props]\n 642→ # Remove empty required array\n 643→ if not result[\"required\"]:\n 644→ del result[\"required\"]\n 645→\n 646→ # Recursively fix nested schemas\n 647→ for key, value in list(result.items()):\n 648→ if isinstance(value, dict):\n 649→ result[key] = _fix_required_fields(value)\n 650→ elif isinstance(value, list):\n 651→ result[key] = [\n 652→ _fix_required_fields(item) if isinstance(item, dict) else item for item in value\n 653→ ]\n 654→\n 655→ return result\n 656→\n 657→\n 658→def clean_json_schema(schema: Any) -> Dict[str, Any]:\n 659→ \"\"\"Clean JSON schema for LLM providers that don't support advanced features.\n 660→\n 661→ Some providers (GitHub Copilot, Antigravity, etc.) don't support $ref/$defs\n 662→ or other advanced JSON Schema features. This function cleans the schema\n 663→ by converting unsupported features to description hints.\n 664→\n 665→ Applies the following transformations:\n 666→ 1a. Convert $ref to description hints\n 667→ 1b. Convert const to enum\n 668→ 1c. Add enum hints to descriptions\n 669→ 1d. Add additionalProperties hints\n 670→ 1e. Move unsupported constraints to description\n 671→ 2a. Merge allOf schemas\n 672→ 3. Remove unsupported keywords ($ref, $defs, additionalProperties, etc.)\n 673→ 4. Fix required fields referencing non-existent properties\n 674→\n 675→ Args:\n 676→ schema: JSON schema to clean\n 677→\n 678→ Returns:\n 679→ Cleaned schema compatible with all LLM providers\n 680→ \"\"\"\n 681→ if not schema or not isinstance(schema, dict):\n 682→ return {\"type\": \"object\", \"properties\": {}}\n 683→\n 684→ # Phase 1: Convert and hint\n 685→ result = _convert_refs_to_hints(schema)\n 686→ result = _convert_const_to_enum(result)\n 687→ result = _add_enum_hints(result)\n 688→ result = _add_additional_properties_hints(result)\n 689→ result = _move_constraints_to_description(result)\n 690→\n 691→ # Phase 2: Merge\n 692→ result = _merge_all_of(result)\n 693→\n 694→ # Phase 3: Remove unsupported keywords\n 695→ result = _remove_unsupported_keywords(result)\n 696→\n 697→ # Phase 4: Fix required fields referencing non-existent properties\n 698→ result = _fix_required_fields(result)\n 699→\n 700→ # Ensure type is object\n 701→ if \"type\" not in result:\n 702→ result[\"type\"] = \"object\"\n 703→\n 704→ return result\n 705→\n 706→\n 707→# =============================================================================\n 708→# CLAUDE SCHEMA CLEANING (Ported from Antigravity-Manager's json_schema.rs)\n 709→# =============================================================================\n 710→\n 711→# Whitelist of allowed fields for Claude VALIDATED mode\n 712→# Any field not in this list will be removed\n 713→CLAUDE_ALLOWED_SCHEMA_FIELDS = {\n 714→ \"type\",\n 715→ \"description\",\n 716→ \"properties\",\n 717→ \"required\",\n 718→ \"items\",\n 719→ \"enum\",\n 720→ \"title\",\n 721→}\n 722→\n 723→# Constraints to move to description hints\n 724→CLAUDE_CONSTRAINT_FIELDS = [\n 725→ (\"minLength\", \"minLen\"),\n 726→ (\"maxLength\", \"maxLen\"),\n 727→ (\"pattern\", \"pattern\"),\n 728→ (\"minimum\", \"min\"),\n 729→ (\"maximum\", \"max\"),\n 730→ (\"multipleOf\", \"multipleOf\"),\n 731→ (\"exclusiveMinimum\", \"exclMin\"),\n 732→ (\"exclusiveMaximum\", \"exclMax\"),\n 733→ (\"minItems\", \"minItems\"),\n 734→ (\"maxItems\", \"maxItems\"),\n 735→ (\"propertyNames\", \"propertyNames\"),\n 736→ (\"format\", \"format\"),\n 737→]\n 738→\n 739→\n 740→def _score_schema_option(schema: Any) -> int:\n 741→ \"\"\"Score a schema option for anyOf/oneOf selection.\n 742→\n 743→ Higher scores are preferred:\n 744→ - Object with properties: 3\n 745→ - Array: 2\n 746→ - Scalar type (non-null): 1\n 747→ - Null or invalid: 0\n 748→ \"\"\"\n 749→ if not schema or not isinstance(schema, dict):\n 750→ return 0\n 751→\n 752→ # Object with properties scores highest\n 753→ if schema.get(\"properties\") or schema.get(\"type\") == \"object\":\n 754→ return 3\n 755→\n 756→ # Array scores medium\n 757→ if schema.get(\"items\") or schema.get(\"type\") == \"array\":\n 758→ return 2\n 759→\n 760→ # Non-null scalar types score low\n 761→ type_val = schema.get(\"type\")\n 762→ if type_val and type_val != \"null\":\n 763→ return 1\n 764→\n 765→ return 0\n 766→\n 767→\n 768→def _extract_best_schema_from_union(union_array: List[Any]) -> Optional[Dict[str, Any]]:\n 769→ \"\"\"Extract the best schema option from anyOf/oneOf array.\n 770→\n 771→ Selects the schema with the highest complexity score.\n 772→ \"\"\"\n 773→ best_option = None\n 774→ best_score = -1\n 775→\n 776→ for item in union_array:\n 777→ score = _score_schema_option(item)\n 778→ if score > best_score:\n 779→ best_score = score\n 780→ best_option = item\n 781→\n 782→ return dict(best_option) if isinstance(best_option, dict) else None\n 783→\n 784→\n 785→def _flatten_anyof_oneof_for_claude(schema: Dict[str, Any]) -> Dict[str, Any]:\n 786→ \"\"\"Flatten anyOf/oneOf by selecting the best option and merging properties.\n 787→\n 788→ Based on Antigravity-Manager's extract_best_schema_from_union logic.\n 789→ \"\"\"\n 790→ result = dict(schema)\n 791→\n 792→ # Check for anyOf or oneOf\n 793→ for union_key in (\"anyOf\", \"oneOf\"):\n 794→ union_array = result.get(union_key)\n 795→ if not isinstance(union_array, list) or not union_array:\n 796→ continue\n 797→\n 798→ # Only process if type is not already set or is \"object\"\n 799→ current_type = result.get(\"type\")\n 800→ if current_type and current_type not in (\"object\", \"null\"):\n 801→ # Type already set, just remove anyOf/oneOf\n 802→ result.pop(union_key, None)\n 803→ continue\n 804→\n 805→ # Find best option\n 806→ best_branch = _extract_best_schema_from_union(union_array)\n 807→ if not best_branch:\n 808→ result.pop(union_key, None)\n 809→ continue\n 810→\n 811→ # Merge properties from best branch\n 812→ if best_branch.get(\"properties\"):\n 813→ target_props = result.setdefault(\"properties\", {})\n 814→ for prop_key, prop_val in best_branch.get(\"properties\", {}).items():\n 815→ if prop_key not in target_props:\n 816→ target_props[prop_key] = prop_val\n 817→\n 818→ # Merge required\n 819→ if best_branch.get(\"required\"):\n 820→ target_req = result.setdefault(\"required\", [])\n 821→ for req_item in best_branch.get(\"required\", []):\n 822→ if req_item not in target_req:\n 823→ target_req.append(req_item)\n 824→\n 825→ # Copy type if not set\n 826→ if not result.get(\"type\") and best_branch.get(\"type\"):\n 827→ result[\"type\"] = best_branch[\"type\"]\n 828→\n 829→ # Remove the union key\n 830→ result.pop(union_key, None)\n 831→\n 832→ return result\n 833→\n 834→\n 835→def _flatten_type_array_for_claude(schema: Dict[str, Any]) -> Tuple[Dict[str, Any], bool]:\n 836→ \"\"\"Flatten type array to single type with nullable hint.\n 837→\n 838→ E.g., [\"string\", \"null\"] -> \"string\" (returns is_nullable=True)\n 839→\n 840→ Returns:\n 841→ Tuple of (modified schema, is_nullable)\n 842→ \"\"\"\n 843→ result = dict(schema)\n 844→ is_nullable = False\n 845→\n 846→ type_val = result.get(\"type\")\n 847→ if isinstance(type_val, list):\n 848→ has_null = \"null\" in type_val\n 849→ non_null_types = [t for t in type_val if t != \"null\" and t]\n 850→\n 851→ # Select first non-null type, or \"string\" as fallback\n 852→ first_type = non_null_types[0] if non_null_types else \"string\"\n 853→ result[\"type\"] = first_type.lower() # Keep lowercase for Claude\n 854→\n 855→ # Track nullable for description hint\n 856→ if has_null:\n 857→ is_nullable = True\n 858→ elif isinstance(type_val, str):\n 859→ # Ensure lowercase\n 860→ result[\"type\"] = type_val.lower()\n 861→ if type_val.lower() == \"null\":\n 862→ is_nullable = True\n 863→ result[\"type\"] = \"string\" # Fallback\n 864→\n 865→ return result, is_nullable\n 866→\n 867→\n 868→def _add_constraint_hints_for_claude(schema: Dict[str, Any]) -> Dict[str, Any]:\n 869→ \"\"\"Move constraint fields to description hints.\n 870→\n 871→ Based on Antigravity-Manager's constraint migration logic.\n 872→ \"\"\"\n 873→ result = dict(schema)\n 874→ hints = []\n 875→\n 876→ for field, label in CLAUDE_CONSTRAINT_FIELDS:\n 877→ val = result.get(field)\n 878→ if val is not None:\n 879→ val_str = str(val) if not isinstance(val, str) else val\n 880→ hints.append(f\"{label}: {val_str}\")\n 881→\n 882→ if hints:\n 883→ suffix = f\" [Constraint: {', '.join(hints)}]\"\n 884→ desc = result.get(\"description\", \"\")\n 885→ if suffix not in desc:\n 886→ result[\"description\"] = desc + suffix if desc else suffix.strip()\n 887→\n 888→ return result\n 889→\n 890→\n 891→def _apply_whitelist_for_claude(schema: Dict[str, Any]) -> Dict[str, Any]:\n 892→ \"\"\"Apply whitelist filtering - remove all fields not in CLAUDE_ALLOWED_SCHEMA_FIELDS.\"\"\"\n 893→ return {\n 894→ key: value\n 895→ for key, value in schema.items()\n 896→ if key in CLAUDE_ALLOWED_SCHEMA_FIELDS\n 897→ }\n 898→\n 899→\n 900→def _add_empty_object_placeholder_for_claude(schema: Dict[str, Any]) -> Dict[str, Any]:\n 901→ \"\"\"Add placeholder property for empty object schemas.\n 902→\n 903→ Claude VALIDATED mode requires at least one property in object schemas.\n 904→ \"\"\"\n 905→ result = dict(schema)\n 906→\n 907→ if result.get(\"type\") == \"object\":\n 908→ props = result.get(\"properties\")\n 909→ has_props = props and isinstance(props, dict) and len(props) > 0\n 910→\n 911→ if not has_props:\n 912→ result[\"properties\"] = {\n 913→ \"reason\": {\n 914→ \"type\": \"string\",\n 915→ \"description\": \"Reason for calling this tool\",\n 916→ }\n 917→ }\n 918→ result[\"required\"] = [\"reason\"]\n 919→\n 920→ return result\n 921→\n 922→\n 923→def _fix_required_for_claude(schema: Dict[str, Any]) -> Dict[str, Any]:\n 924→ \"\"\"Remove required entries that don't exist in properties.\"\"\"\n 925→ result = dict(schema)\n 926→\n 927→ if isinstance(result.get(\"required\"), list) and isinstance(result.get(\"properties\"), dict):\n 928→ valid_props = set(result[\"properties\"].keys())\n 929→ result[\"required\"] = [r for r in result[\"required\"] if r in valid_props]\n 930→ if not result[\"required\"]:\n 931→ del result[\"required\"]\n 932→\n 933→ return result\n 934→\n 935→\n 936→def clean_json_schema_for_claude(schema: Any) -> Dict[str, Any]:\n 937→ \"\"\"Clean JSON schema for Claude VALIDATED mode via Antigravity.\n 938→\n 939→ This is a comprehensive cleaning function based on Antigravity-Manager's\n 940→ json_schema.rs implementation. It ensures schemas are compatible with\n 941→ Claude's strict JSON Schema draft 2020-12 validation.\n 942→\n 943→ Key transformations:\n 944→ 1. Flatten $ref references\n 945→ 2. Merge allOf schemas\n 946→ 3. Flatten anyOf/oneOf to best option\n 947→ 4. Flatten type arrays ([\"string\", \"null\"] -> \"string\")\n 948→ 5. Move constraints to description hints\n 949→ 6. Apply whitelist filtering (only allowed fields kept)\n 950→ 7. Add placeholder for empty object schemas\n 951→ 8. Fix required fields\n 952→\n 953→ Args:\n 954→ schema: JSON schema to clean\n 955→\n 956→ Returns:\n 957→ Cleaned schema compatible with Claude VALIDATED mode\n 958→ \"\"\"\n 959→ if not schema or not isinstance(schema, dict):\n 960→ return {\n 961→ \"type\": \"object\",\n 962→ \"properties\": {\n 963→ \"reason\": {\n 964→ \"type\": \"string\",\n 965→ \"description\": \"Reason for calling this tool\",\n 966→ }\n 967→ },\n 968→ \"required\": [\"reason\"],\n 969→ }\n 970→\n 971→ result = dict(schema)\n 972→\n 973→ # Phase 1: Resolve $ref (reuse existing function)\n 974→ result = _resolve_refs(result)\n 975→\n 976→ # Phase 2: Merge allOf\n 977→ result = _merge_all_of(result)\n 978→\n 979→ # Phase 3: Flatten anyOf/oneOf\n 980→ result = _flatten_anyof_oneof_for_claude(result)\n 981→\n 982→ # Phase 4: Flatten type arrays and track nullable\n 983→ result, is_nullable = _flatten_type_array_for_claude(result)\n 984→\n 985→ # Phase 5: Add constraint hints\n 986→ result = _add_constraint_hints_for_claude(result)\n 987→\n 988→ # Phase 6: Apply whitelist\n 989→ result = _apply_whitelist_for_claude(result)\n 990→\n 991→ # Phase 7: Add placeholder for empty objects\n 992→ result = _add_empty_object_placeholder_for_claude(result)\n 993→\n 994→ # Phase 8: Fix required fields\n 995→ result = _fix_required_for_claude(result)\n 996→\n 997→ # Add nullable hint if needed\n 998→ if is_nullable:\n 999→ desc = result.get(\"description\", \"\")\n 1000→ if \"(nullable)\" not in desc:\n 1001→ result[\"description\"] = f\"{desc} (nullable)\" if desc else \"(nullable)\"\n 1002→\n 1003→ # Ensure type is set\n 1004→ if \"type\" not in result:\n 1005→ result[\"type\"] = \"object\"\n 1006→\n 1007→ # Recursively clean nested schemas\n 1008→ if isinstance(result.get(\"properties\"), dict):\n 1009→ cleaned_props = {}\n 1010→ nullable_keys = set()\n 1011→ for prop_key, prop_val in result[\"properties\"].items():\n 1012→ if isinstance(prop_val, dict):\n 1013→ cleaned = clean_json_schema_for_claude(prop_val)\n 1014→ cleaned_props[prop_key] = cleaned\n 1015→ # Track nullable properties\n 1016→ if \"(nullable)\" in cleaned.get(\"description\", \"\"):\n 1017→ nullable_keys.add(prop_key)\n 1018→ else:\n 1019→ cleaned_props[prop_key] = prop_val\n 1020→ result[\"properties\"] = cleaned_props\n 1021→\n 1022→ # Remove nullable fields from required\n 1023→ if nullable_keys and isinstance(result.get(\"required\"), list):\n 1024→ result[\"required\"] = [r for r in result[\"required\"] if r not in nullable_keys]\n 1025→ if not result[\"required\"]:\n 1026→ del result[\"required\"]\n 1027→\n 1028→ if isinstance(result.get(\"items\"), dict):\n 1029→ result[\"items\"] = clean_json_schema_for_claude(result[\"items\"])\n 1030→\n 1031→ return result\n 1032→\n 1033→\n 1034→# =============================================================================\n 1035→# GEMINI SCHEMA TRANSFORMATION (Ported from antigravity-auth)\n 1036→# =============================================================================\n 1037→\n 1038→# Fields that Gemini API rejects - must be removed from schemas\n 1039→# Antigravity uses strict protobuf-backed JSON validation\n 1040→GEMINI_UNSUPPORTED_SCHEMA_FIELDS = {\n 1041→ \"additionalProperties\",\n 1042→ \"$schema\",\n 1043→ \"$id\",\n 1044→ \"$comment\",\n 1045→ \"$ref\",\n 1046→ \"$defs\",\n 1047→ \"definitions\",\n 1048→ \"const\",\n 1049→ \"contentMediaType\",\n 1050→ \"contentEncoding\",\n 1051→ \"if\",\n 1052→ \"then\",\n 1053→ \"else\",\n 1054→ \"not\",\n 1055→ \"patternProperties\",\n 1056→ \"unevaluatedProperties\",\n 1057→ \"unevaluatedItems\",\n 1058→ \"dependentRequired\",\n 1059→ \"dependentSchemas\",\n 1060→ \"propertyNames\",\n 1061→ \"minContains\",\n 1062→ \"maxContains\",\n 1063→}\n 1064→\n 1065→\n 1066→def _resolve_refs(schema: Any, defs: Optional[Dict[str, Any]] = None) -> Any:\n 1067→ \"\"\"Resolve $ref references in JSON Schema.\n 1068→\n 1069→ Args:\n 1070→ schema: JSON Schema that may contain $ref\n 1071→ defs: Dictionary of definitions (from $defs or definitions)\n 1072→\n 1073→ Returns:\n 1074→ Schema with $ref replaced by actual definitions\n 1075→ \"\"\"\n 1076→ if not schema or not isinstance(schema, dict):\n 1077→ return schema\n 1078→\n 1079→ if isinstance(schema, list):\n 1080→ return [_resolve_refs(item, defs) for item in schema]\n 1081→\n 1082→ # Extract definitions from schema if present\n 1083→ local_defs = schema.get(\"$defs\") or schema.get(\"definitions\") or {}\n 1084→ if local_defs:\n 1085→ defs = {**defs, **local_defs} if defs else local_defs\n 1086→\n 1087→ # Check for $ref\n 1088→ ref = schema.get(\"$ref\")\n 1089→ if ref and isinstance(ref, str) and defs:\n 1090→ # Parse ref like \"#/$defs/TodoItem\" or \"#/definitions/TodoItem\"\n 1091→ if ref.startswith(\"#/$defs/\"):\n 1092→ ref_name = ref[8:] # Remove \"#/$defs/\"\n 1093→ if ref_name in defs:\n 1094→ # Return resolved definition (recursively resolve any nested refs)\n 1095→ return _resolve_refs(defs[ref_name], defs)\n 1096→ elif ref.startswith(\"#/definitions/\"):\n 1097→ ref_name = ref[14:] # Remove \"#/definitions/\"\n 1098→ if ref_name in defs:\n 1099→ return _resolve_refs(defs[ref_name], defs)\n 1100→\n 1101→ # Recursively resolve refs in nested structures\n 1102→ result: Dict[str, Any] = {}\n 1103→ for key, value in schema.items():\n 1104→ if key in (\"$defs\", \"definitions\"):\n 1105→ # Don't include definitions in output\n 1106→ continue\n 1107→ elif key == \"properties\" and isinstance(value, dict):\n 1108→ result[key] = {\n 1109→ prop_name: _resolve_refs(prop_schema, defs)\n 1110→ for prop_name, prop_schema in value.items()\n 1111→ }\n 1112→ elif key == \"items\":\n 1113→ result[key] = _resolve_refs(value, defs)\n 1114→ elif key in (\"anyOf\", \"oneOf\", \"allOf\") and isinstance(value, list):\n 1115→ result[key] = [_resolve_refs(item, defs) for item in value]\n 1116→ else:\n 1117→ result[key] = value\n 1118→\n 1119→ return result\n 1120→\n 1121→\n 1122→def _convert_anyof_to_nullable(anyof_items: List[Any]) -> Optional[Dict[str, Any]]:\n 1123→ \"\"\"Convert anyOf pattern with null to Gemini's nullable format.\n 1124→\n 1125→ Common JSON Schema patterns for nullable fields:\n 1126→ - anyOf: [{type: 'integer'}, {type: 'null'}]\n 1127→\n 1128→ Gemini expects:\n 1129→ - {type: 'INTEGER', nullable: true}\n 1130→\n 1131→ Args:\n 1132→ anyof_items: List of anyOf schema items\n 1133→\n 1134→ Returns:\n 1135→ Gemini-compatible schema with nullable, or None if not a nullable pattern\n 1136→ \"\"\"\n 1137→ if len(anyof_items) != 2:\n 1138→ return None\n 1139→\n 1140→ null_item = None\n 1141→ non_null_item = None\n 1142→\n 1143→ for item in anyof_items:\n 1144→ if isinstance(item, dict):\n 1145→ item_type = item.get(\"type\", \"\").lower()\n 1146→ if item_type == \"null\":\n 1147→ null_item = item\n 1148→ else:\n 1149→ non_null_item = item\n 1150→\n 1151→ if null_item is not None and non_null_item is not None:\n 1152→ # This is a nullable pattern: convert to Gemini format\n 1153→ result = to_gemini_schema(non_null_item)\n 1154→ if isinstance(result, dict):\n 1155→ result[\"nullable\"] = True\n 1156→ return result\n 1157→\n 1158→ return None\n 1159→\n 1160→\n 1161→def to_gemini_schema(schema: Any) -> Any:\n 1162→ \"\"\"Transform a JSON Schema to Gemini-compatible format.\n 1163→\n 1164→ Based on @google/genai SDK's processJsonSchema() function.\n 1165→ Reference: antigravity-auth/src/plugin/transform/gemini.ts toGeminiSchema()\n 1166→\n 1167→ Key transformations:\n 1168→ - Converts type values to uppercase (object -> OBJECT, string -> STRING)\n 1169→ - Removes unsupported fields ($schema, additionalProperties, etc.)\n 1170→ - Recursively processes nested schemas (properties, items, anyOf, etc.)\n 1171→ - Converts anyOf with null to nullable: true (Gemini format)\n 1172→ - Ensures arrays have 'items' field (Gemini API requires it)\n 1173→\n 1174→ Args:\n 1175→ schema: A JSON Schema object or primitive value\n 1176→\n 1177→ Returns:\n 1178→ Gemini-compatible schema with uppercase types\n 1179→ \"\"\"\n 1180→ # Return primitives and arrays as-is\n 1181→ if not schema or not isinstance(schema, dict):\n 1182→ return schema\n 1183→\n 1184→ if isinstance(schema, list):\n 1185→ return [to_gemini_schema(item) for item in schema]\n 1186→\n 1187→ result: Dict[str, Any] = {}\n 1188→\n 1189→ # First pass: collect all property names for required validation\n 1190→ property_names: set[str] = set()\n 1191→ if isinstance(schema.get(\"properties\"), dict):\n 1192→ property_names = set(schema[\"properties\"].keys())\n 1193→\n 1194→ # Check for anyOf pattern that represents nullable - convert early\n 1195→ anyof = schema.get(\"anyOf\")\n 1196→ if isinstance(anyof, list):\n 1197→ nullable_result = _convert_anyof_to_nullable(anyof)\n 1198→ if nullable_result is not None:\n 1199→ return nullable_result\n 1200→\n 1201→ for key, value in schema.items():\n 1202→ # Skip unsupported fields that Gemini API rejects\n 1203→ if key in GEMINI_UNSUPPORTED_SCHEMA_FIELDS:\n 1204→ continue\n 1205→\n 1206→ if key == \"type\" and isinstance(value, str):\n 1207→ # Convert type to uppercase for Gemini API\n 1208→ result[key] = value.upper()\n 1209→ elif key == \"properties\" and isinstance(value, dict):\n 1210→ # Recursively transform nested property schemas\n 1211→ props: Dict[str, Any] = {}\n 1212→ for prop_name, prop_schema in value.items():\n 1213→ props[prop_name] = to_gemini_schema(prop_schema)\n 1214→ result[key] = props\n 1215→ elif key == \"items\" and isinstance(value, dict):\n 1216→ # Transform array items schema\n 1217→ result[key] = to_gemini_schema(value)\n 1218→ elif key in (\"anyOf\", \"oneOf\", \"allOf\") and isinstance(value, list):\n 1219→ # For non-nullable anyOf/oneOf/allOf, skip them as Gemini doesn't support these\n 1220→ # We've already handled the nullable pattern above\n 1221→ # Just use the first non-null type as a fallback\n 1222→ for item in value:\n 1223→ if isinstance(item, dict) and item.get(\"type\", \"\").lower() != \"null\":\n 1224→ transformed = to_gemini_schema(item)\n 1225→ if isinstance(transformed, dict):\n 1226→ for k, v in transformed.items():\n 1227→ if k not in result:\n 1228→ result[k] = v\n 1229→ break\n 1230→ # Don't include anyOf/oneOf/allOf in result - Gemini doesn't support them\n 1231→ continue\n 1232→ elif key == \"enum\" and isinstance(value, list):\n 1233→ # Keep enum values as-is\n 1234→ result[key] = value\n 1235→ elif key in (\"default\", \"examples\"):\n 1236→ # Keep default and examples as-is\n 1237→ result[key] = value\n 1238→ elif key == \"required\" and isinstance(value, list):\n 1239→ # Filter required array to only include properties that exist\n 1240→ # This fixes: \"parameters.required[X]: property is not defined\"\n 1241→ if property_names:\n 1242→ valid_required = [prop for prop in value if isinstance(prop, str) and prop in property_names]\n 1243→ if valid_required:\n 1244→ result[key] = valid_required\n 1245→ # If no valid required properties, omit the required field entirely\n 1246→ else:\n 1247→ # If there are no properties, keep required as-is\n 1248→ result[key] = value\n 1249→ else:\n 1250→ result[key] = value\n 1251→\n 1252→ # Issue #80: Ensure array schemas have an 'items' field\n 1253→ # Gemini API requires: \"parameters.properties[X].items: missing field\"\n 1254→ if result.get(\"type\") == \"ARRAY\" and \"items\" not in result:\n 1255→ result[\"items\"] = {\"type\": \"STRING\"}\n 1256→\n 1257→ return result\n 1258→\n 1259→\n 1260→def ensure_tool_has_properties(schema: Dict[str, Any], uppercase_types: bool = True) -> Dict[str, Any]:\n 1261→ \"\"\"Ensure tool schema has at least one property for VALIDATED mode.\n 1262→\n 1263→ Claude/Antigravity VALIDATED mode requires tool parameters to be an object schema\n 1264→ with at least one property. This adds a placeholder if needed.\n 1265→\n 1266→ Args:\n 1267→ schema: Tool parameter schema\n 1268→ uppercase_types: If True, use uppercase types (OBJECT, BOOLEAN) for Gemini/Antigravity\n 1269→\n 1270→ Returns:\n 1271→ Schema with guaranteed properties\n 1272→ \"\"\"\n 1273→ obj_type = \"OBJECT\" if uppercase_types else \"object\"\n 1274→ bool_type = \"BOOLEAN\" if uppercase_types else \"boolean\"\n 1275→\n 1276→ if not schema or not isinstance(schema, dict):\n 1277→ return {\n 1278→ \"type\": obj_type,\n 1279→ \"properties\": {\n 1280→ EMPTY_SCHEMA_PLACEHOLDER_NAME: {\n 1281→ \"type\": bool_type,\n 1282→ \"description\": EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,\n 1283→ }\n 1284→ },\n 1285→ \"required\": [EMPTY_SCHEMA_PLACEHOLDER_NAME],\n 1286→ }\n 1287→\n 1288→ result = dict(schema)\n 1289→ # Ensure type is uppercase for Gemini/Antigravity\n 1290→ if uppercase_types:\n 1291→ result[\"type\"] = \"OBJECT\"\n 1292→ else:\n 1293→ result[\"type\"] = \"object\"\n 1294→\n 1295→ # Check if properties exist and are non-empty\n 1296→ has_properties = isinstance(result.get(\"properties\"), dict) and len(result[\"properties\"]) > 0\n 1297→\n 1298→ if not has_properties:\n 1299→ result[\"properties\"] = {\n 1300→ EMPTY_SCHEMA_PLACEHOLDER_NAME: {\n 1301→ \"type\": bool_type,\n 1302→ \"description\": EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,\n 1303→ }\n 1304→ }\n 1305→ required = result.get(\"required\", [])\n 1306→ if isinstance(required, list):\n 1307→ result[\"required\"] = list(set(required + [EMPTY_SCHEMA_PLACEHOLDER_NAME]))\n 1308→ else:\n 1309→ result[\"required\"] = [EMPTY_SCHEMA_PLACEHOLDER_NAME]\n 1310→\n 1311→ return result\n 1312→\n 1313→\n 1314→# =============================================================================\n 1315→# TOOL HARDENING FUNCTIONS (Ported from antigravity-auth)\n 1316→# =============================================================================\n 1317→\n 1318→\n 1319→def _format_type_hint(prop_data: Dict[str, Any]) -> str:\n 1320→ \"\"\"Format a type hint string from property schema.\n 1321→\n 1322→ Reference: antigravity-auth/src/plugin/request-helpers.ts formatTypeHint()\n 1323→ \"\"\"\n 1324→ prop_type = prop_data.get(\"type\", \"any\")\n 1325→\n 1326→ if prop_type == \"array\":\n 1327→ items = prop_data.get(\"items\", {})\n 1328→ if isinstance(items, dict):\n 1329→ items_type = items.get(\"type\", \"any\")\n 1330→ return f\"array of {items_type}\"\n 1331→ return \"array\"\n 1332→\n 1333→ if prop_type == \"object\":\n 1334→ return \"object\"\n 1335→\n 1336→ return str(prop_type)\n 1337→\n 1338→\n 1339→def inject_parameter_signatures(\n 1340→ tools: List[Dict[str, Any]],\n 1341→ prompt_template: str = CLAUDE_DESCRIPTION_PROMPT,\n 1342→) -> List[Dict[str, Any]]:\n 1343→ \"\"\"Inject parameter signatures into tool descriptions (tool hardening).\n 1344→\n 1345→ Appends a strict parameter signature to each tool description to prevent\n 1346→ Claude from hallucinating parameters from training data.\n 1347→\n 1348→ Reference: antigravity-auth/src/plugin/request-helpers.ts injectParameterSignatures()\n 1349→\n 1350→ Args:\n 1351→ tools: Gemini-style tools array (with functionDeclarations)\n 1352→ prompt_template: Template for the signature (default: CLAUDE_DESCRIPTION_PROMPT)\n 1353→\n 1354→ Returns:\n 1355→ Modified tools array with signatures injected\n 1356→ \"\"\"\n 1357→ if not tools or not isinstance(tools, list):\n 1358→ return tools\n 1359→\n 1360→ result = []\n 1361→ for tool in tools:\n 1362→ if not isinstance(tool, dict):\n 1363→ result.append(tool)\n 1364→ continue\n 1365→\n 1366→ declarations = tool.get(\"functionDeclarations\")\n 1367→ if not isinstance(declarations, list):\n 1368→ result.append(tool)\n 1369→ continue\n 1370→\n 1371→ new_declarations = []\n 1372→ for decl in declarations:\n 1373→ if not isinstance(decl, dict):\n 1374→ new_declarations.append(decl)\n 1375→ continue\n 1376→\n 1377→ # Skip if signature already injected\n 1378→ description = decl.get(\"description\", \"\")\n 1379→ if \"STRICT PARAMETERS:\" in description:\n 1380→ new_declarations.append(decl)\n 1381→ continue\n 1382→\n 1383→ schema = decl.get(\"parameters\") or decl.get(\"parametersJsonSchema\")\n 1384→ if not schema or not isinstance(schema, dict):\n 1385→ new_declarations.append(decl)\n 1386→ continue\n 1387→\n 1388→ required = schema.get(\"required\", [])\n 1389→ if not isinstance(required, list):\n 1390→ required = []\n 1391→\n 1392→ properties = schema.get(\"properties\", {})\n 1393→ if not isinstance(properties, dict) or not properties:\n 1394→ new_declarations.append(decl)\n 1395→ continue\n 1396→\n 1397→ # Build parameter list\n 1398→ param_list = []\n 1399→ for prop_name, prop_data in properties.items():\n 1400→ if prop_name == EMPTY_SCHEMA_PLACEHOLDER_NAME:\n 1401→ continue\n 1402→ if not isinstance(prop_data, dict):\n 1403→ continue\n 1404→ type_hint = _format_type_hint(prop_data)\n 1405→ is_required = prop_name in required\n 1406→ param_str = f\"{prop_name} ({type_hint}{', REQUIRED' if is_required else ''})\"\n 1407→ param_list.append(param_str)\n 1408→\n 1409→ if not param_list:\n 1410→ new_declarations.append(decl)\n 1411→ continue\n 1412→\n 1413→ # Inject signature\n 1414→ sig_str = prompt_template.replace(\"{params}\", \", \".join(param_list))\n 1415→ new_decl = dict(decl)\n 1416→ new_decl[\"description\"] = (description or \"\") + sig_str\n 1417→ new_declarations.append(new_decl)\n 1418→\n 1419→ result.append({**tool, \"functionDeclarations\": new_declarations})\n 1420→\n 1421→ return result\n 1422→\n 1423→\n 1424→def inject_tool_hardening_instruction(\n 1425→ payload: Dict[str, Any],\n 1426→ instruction_text: str = CLAUDE_TOOL_SYSTEM_INSTRUCTION,\n 1427→) -> None:\n 1428→ \"\"\"Inject a tool hardening system instruction into the request payload.\n 1429→\n 1430→ Prepends the instruction to the systemInstruction to prevent Claude from\n 1431→ hallucinating tool parameters.\n 1432→\n 1433→ Reference: antigravity-auth/src/plugin/request-helpers.ts injectToolHardeningInstruction()\n 1434→\n 1435→ Args:\n 1436→ payload: The Gemini request payload (modified in place)\n 1437→ instruction_text: The instruction text to inject\n 1438→ \"\"\"\n 1439→ if not instruction_text:\n 1440→ return\n 1441→\n 1442→ existing = payload.get(\"systemInstruction\")\n 1443→\n 1444→ # Skip if instruction already present\n 1445→ if existing and isinstance(existing, dict) and \"parts\" in existing:\n 1446→ parts = existing.get(\"parts\", [])\n 1447→ if isinstance(parts, list) and any(\n 1448→ isinstance(p, dict) and \"CRITICAL TOOL USAGE INSTRUCTIONS\" in (p.get(\"text\") or \"\")\n 1449→ for p in parts\n 1450→ ):\n 1451→ return\n 1452→\n 1453→ instruction_part = {\"text\": instruction_text}\n 1454→\n 1455→ if payload.get(\"systemInstruction\"):\n 1456→ if isinstance(existing, dict) and \"parts\" in existing:\n 1457→ parts = existing.get(\"parts\", [])\n 1458→ if isinstance(parts, list):\n 1459→ parts.insert(0, instruction_part)\n 1460→ elif isinstance(existing, str):\n 1461→ payload[\"systemInstruction\"] = {\n 1462→ \"role\": \"user\",\n 1463→ \"parts\": [instruction_part, {\"text\": existing}],\n 1464→ }\n 1465→ else:\n 1466→ payload[\"systemInstruction\"] = {\n 1467→ \"role\": \"user\",\n 1468→ \"parts\": [instruction_part],\n 1469→ }\n 1470→ else:\n 1471→ payload[\"systemInstruction\"] = {\n 1472→ \"role\": \"user\",\n 1473→ \"parts\": [instruction_part],\n 1474→ }\n 1475→\n 1476→\n 1477→# =============================================================================\n 1478→# THINKING SIGNATURE MANAGEMENT (Claude multi-turn conversations)\n 1479→# =============================================================================\n 1480→\n 1481→\n 1482→def has_signed_thinking_part(part: Dict[str, Any]) -> bool:\n 1483→ \"\"\"Check if a part has a valid signed thinking signature.\n 1484→\n 1485→ Reference: antigravity-auth/src/plugin/request.ts hasSignedThinkingPart()\n 1486→ \"\"\"\n 1487→ if not part or not isinstance(part, dict):\n 1488→ return False\n 1489→\n 1490→ # Gemini format: thought=true + thoughtSignature\n 1491→ if part.get(\"thought\") is True:\n 1492→ sig = part.get(\"thoughtSignature\", \"\")\n 1493→ return isinstance(sig, str) and len(sig) >= MIN_SIGNATURE_LENGTH\n 1494→\n 1495→ # Anthropic format: type=thinking/redacted_thinking + signature\n 1496→ part_type = part.get(\"type\", \"\")\n 1497→ if part_type in (\"thinking\", \"redacted_thinking\"):\n 1498→ sig = part.get(\"signature\", \"\")\n 1499→ return isinstance(sig, str) and len(sig) >= MIN_SIGNATURE_LENGTH\n 1500→\n 1501→ return False\n 1502→\n 1503→\n 1504→def ensure_thinking_signature_for_tool_use(\n 1505→ contents: List[Dict[str, Any]],\n 1506→ session_key: str,\n 1507→) -> List[Dict[str, Any]]:\n 1508→ \"\"\"Ensure thinking blocks have signatures before tool use parts.\n 1509→\n 1510→ For Claude thinking models, tool use requires signed thinking to precede it.\n 1511→ If no valid signed thinking is found, inject the SKIP_THOUGHT_SIGNATURE sentinel.\n 1512→\n 1513→ Reference: antigravity-auth/src/plugin/request.ts ensureThinkingBeforeToolUseInContents()\n 1514→\n 1515→ Args:\n 1516→ contents: Gemini-style contents array\n 1517→ session_key: Session key for signature caching\n 1518→\n 1519→ Returns:\n 1520→ Modified contents with thinking signatures ensured\n 1521→ \"\"\"\n 1522→ result = []\n 1523→\n 1524→ for content in contents:\n 1525→ if not isinstance(content, dict) or not isinstance(content.get(\"parts\"), list):\n 1526→ result.append(content)\n 1527→ continue\n 1528→\n 1529→ role = content.get(\"role\")\n 1530→ if role not in (\"model\", \"assistant\"):\n 1531→ result.append(content)\n 1532→ continue\n 1533→\n 1534→ parts = content[\"parts\"]\n 1535→\n 1536→ # Check if this content has tool use (functionCall)\n 1537→ has_tool_use = any(\n 1538→ isinstance(p, dict) and (\"functionCall\" in p or \"tool_use\" in p or \"toolUse\" in p)\n 1539→ for p in parts\n 1540→ )\n 1541→ if not has_tool_use:\n 1542→ result.append(content)\n 1543→ continue\n 1544→\n 1545→ # Separate thinking parts from other parts\n 1546→ thinking_parts = []\n 1547→ other_parts = []\n 1548→\n 1549→ for part in parts:\n 1550→ if not isinstance(part, dict):\n 1551→ other_parts.append(part)\n 1552→ continue\n 1553→\n 1554→ is_thinking = (\n 1555→ part.get(\"thought\") is True\n 1556→ or part.get(\"type\") in (\"thinking\", \"reasoning\", \"redacted_thinking\")\n 1557→ )\n 1558→ if is_thinking:\n 1559→ thinking_parts.append(part)\n 1560→ else:\n 1561→ other_parts.append(part)\n 1562→\n 1563→ # Check if we have a valid signed thinking\n 1564→ has_signed = any(has_signed_thinking_part(p) for p in thinking_parts)\n 1565→\n 1566→ if has_signed:\n 1567→ # Put thinking parts first, then other parts\n 1568→ result.append({**content, \"parts\": thinking_parts + other_parts})\n 1569→ else:\n 1570→ # No valid signed thinking - inject sentinel signature\n 1571→ # This allows Claude to proceed without blocking on signature validation\n 1572→ existing_thinking = thinking_parts[0] if thinking_parts else {}\n 1573→ thinking_text = existing_thinking.get(\"thinking\") or existing_thinking.get(\"text\") or \"\"\n 1574→\n 1575→ sentinel_block = {\n 1576→ \"type\": \"thinking\",\n 1577→ \"thinking\": thinking_text,\n 1578→ \"signature\": SKIP_THOUGHT_SIGNATURE,\n 1579→ }\n 1580→\n 1581→ logger.debug(\n 1582→ \"Injecting sentinel signature for tool use (session=%s)\", session_key\n 1583→ )\n 1584→ result.append({**content, \"parts\": [sentinel_block] + other_parts})\n 1585→\n 1586→ return result\n 1587→\n 1588→\n 1589→# =============================================================================\n 1590→# TOOL DEFINITION CONVERSION\n 1591→# =============================================================================\n 1592→\n 1593→\n 1594→def convert_tools_to_gemini_format(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n 1595→ \"\"\"Convert OpenAI-style tools to Gemini functionDeclarations format.\n 1596→\n 1597→ OpenAI format:\n 1598→ [{\"type\": \"function\", \"function\": {\"name\": \"...\", \"description\": \"...\", \"parameters\": {...}}}]\n 1599→\n 1600→ Gemini format:\n 1601→ [{\"functionDeclarations\": [{\"name\": \"...\", \"description\": \"...\", \"parameters\": {...}}]}]\n 1602→\n 1603→ Key transformations for Gemini compatibility:\n 1604→ - Types converted to uppercase (string -> STRING, object -> OBJECT)\n 1605→ - Unsupported fields removed ($schema, additionalProperties, etc.)\n 1606→ - Arrays ensured to have 'items' field\n 1607→ - Required fields validated against existing properties\n 1608→\n 1609→ Args:\n 1610→ tools: OpenAI-style tool definitions\n 1611→\n 1612→ Returns:\n 1613→ Gemini-style tool definitions with uppercase type schemas\n 1614→ \"\"\"\n 1615→ if not tools:\n 1616→ return []\n 1617→\n 1618→ function_declarations = []\n 1619→\n 1620→ for tool in tools:\n 1621→ if not isinstance(tool, dict):\n 1622→ continue\n 1623→\n 1624→ # Handle OpenAI function tool format\n 1625→ if tool.get(\"type\") == \"function\" and isinstance(tool.get(\"function\"), dict):\n 1626→ func = tool[\"function\"]\n 1627→ declaration: Dict[str, Any] = {\n 1628→ \"name\": func.get(\"name\", \"\"),\n 1629→ \"description\": func.get(\"description\", \"\"),\n 1630→ }\n 1631→ if \"parameters\" in func:\n 1632→ # Resolve $ref references first, then transform to Gemini format\n 1633→ resolved_params = _resolve_refs(func[\"parameters\"])\n 1634→ gemini_params = to_gemini_schema(resolved_params)\n 1635→ declaration[\"parameters\"] = gemini_params\n 1636→ else:\n 1637→ # Provide default placeholder schema for tools without parameters\n 1638→ declaration[\"parameters\"] = {\n 1639→ \"type\": \"OBJECT\",\n 1640→ \"properties\": {\n 1641→ \"_placeholder\": {\n 1642→ \"type\": \"BOOLEAN\",\n 1643→ \"description\": \"Placeholder. Always pass true.\",\n 1644→ }\n 1645→ },\n 1646→ \"required\": [\"_placeholder\"],\n 1647→ }\n 1648→ function_declarations.append(declaration)\n 1649→\n 1650→ # Handle direct function declaration\n 1651→ elif \"name\" in tool:\n 1652→ declaration = {\n 1653→ \"name\": tool.get(\"name\", \"\"),\n 1654→ \"description\": tool.get(\"description\", \"\"),\n 1655→ }\n 1656→ params = tool.get(\"parameters\") or tool.get(\"input_schema\") or tool.get(\"inputSchema\")\n 1657→ if params:\n 1658→ # Resolve $ref references first, then transform to Gemini format\n 1659→ resolved_params = _resolve_refs(params)\n 1660→ gemini_params = to_gemini_schema(resolved_params)\n 1661→ declaration[\"parameters\"] = gemini_params\n 1662→ else:\n 1663→ # Provide default placeholder schema\n 1664→ declaration[\"parameters\"] = {\n 1665→ \"type\": \"OBJECT\",\n 1666→ \"properties\": {\n 1667→ \"_placeholder\": {\n 1668→ \"type\": \"BOOLEAN\",\n 1669→ \"description\": \"Placeholder. Always pass true.\",\n 1670→ }\n 1671→ },\n 1672→ \"required\": [\"_placeholder\"],\n 1673→ }\n 1674→ function_declarations.append(declaration)\n 1675→\n 1676→ # Handle already wrapped functionDeclarations\n 1677→ elif \"functionDeclarations\" in tool:\n 1678→ # Transform schemas in existing declarations\n 1679→ for decl in tool[\"functionDeclarations\"]:\n 1680→ cleaned_decl = dict(decl)\n 1681→ if \"parameters\" in cleaned_decl:\n 1682→ # Resolve $ref references first, then transform to Gemini format\n 1683→ resolved_params = _resolve_refs(cleaned_decl[\"parameters\"])\n 1684→ cleaned_decl[\"parameters\"] = to_gemini_schema(resolved_params)\n 1685→ else:\n 1686→ cleaned_decl[\"parameters\"] = {\n 1687→ \"type\": \"OBJECT\",\n 1688→ \"properties\": {},\n 1689→ }\n 1690→ function_declarations.append(cleaned_decl)\n 1691→\n 1692→ if not function_declarations:\n 1693→ return []\n 1694→\n 1695→ return [{\"functionDeclarations\": function_declarations}]\n 1696→\n 1697→\n 1698→def convert_tools_to_claude_format(\n 1699→ tools: List[Dict[str, Any]],\n 1700→ inject_signatures: bool = True,\n 1701→) -> List[Dict[str, Any]]:\n 1702→ \"\"\"Convert OpenAI-style tools to Claude format with schema cleaning.\n 1703→\n 1704→ Applies:\n 1705→ - Conversion to functionDeclarations format\n 1706→ - JSON schema cleaning for VALIDATED mode\n 1707→ - Optional parameter signature injection (tool hardening)\n 1708→\n 1709→ Args:\n 1710→ tools: OpenAI-style tool definitions\n 1711→ inject_signatures: Whether to inject parameter signatures into descriptions\n 1712→\n 1713→ Returns:\n 1714→ Claude-style tool definitions with cleaned schemas\n 1715→ \"\"\"\n 1716→ if not tools:\n 1717→ return []\n 1718→\n 1719→ function_declarations = []\n 1720→\n 1721→ for tool in tools:\n 1722→ if not isinstance(tool, dict):\n 1723→ continue\n 1724→\n 1725→ # Extract function info\n 1726→ func = None\n 1727→ if tool.get(\"type\") == \"function\" and isinstance(tool.get(\"function\"), dict):\n 1728→ func = tool[\"function\"]\n 1729→ elif \"name\" in tool:\n 1730→ func = tool\n 1731→ elif \"functionDeclarations\" in tool:\n 1732→ # Already in Claude format, just clean schemas\n 1733→ for decl in tool[\"functionDeclarations\"]:\n 1734→ cleaned = dict(decl)\n 1735→ if \"parameters\" in cleaned:\n 1736→ # Use Claude-specific schema cleaning for VALIDATED mode\n 1737→ cleaned[\"parameters\"] = clean_json_schema_for_claude(cleaned[\"parameters\"])\n 1738→ function_declarations.append(cleaned)\n 1739→ continue\n 1740→\n 1741→ if not func:\n 1742→ continue\n 1743→\n 1744→ # Build declaration\n 1745→ name = str(func.get(\"name\", \"\")).replace(\" \", \"_\")[:64]\n 1746→ description = func.get(\"description\", \"\")\n 1747→\n 1748→ # Get parameters\n 1749→ params = (\n 1750→ func.get(\"parameters\")\n 1751→ or func.get(\"input_schema\")\n 1752→ or func.get(\"inputSchema\")\n 1753→ or {\"type\": \"object\", \"properties\": {}}\n 1754→ )\n 1755→\n 1756→ # Clean schema using Claude-specific cleaning for VALIDATED mode\n 1757→ cleaned_params = clean_json_schema_for_claude(params)\n 1758→\n 1759→ # Optionally inject parameter signatures into description (tool hardening)\n 1760→ if inject_signatures and cleaned_params.get(\"properties\"):\n 1761→ sig_parts = []\n 1762→ for param_name, param_schema in cleaned_params[\"properties\"].items():\n 1763→ if param_name == EMPTY_SCHEMA_PLACEHOLDER_NAME:\n 1764→ continue\n 1765→ param_type = param_schema.get(\"type\", \"any\")\n 1766→ sig_parts.append(f\"{param_name}: {param_type}\")\n 1767→ if sig_parts:\n 1768→ signature = f\"({', '.join(sig_parts)})\"\n 1769→ if description:\n 1770→ description = f\"{description} {signature}\"\n 1771→ else:\n 1772→ description = signature\n 1773→\n 1774→ declaration = {\n 1775→ \"name\": name,\n 1776→ \"description\": description,\n 1777→ \"parameters\": cleaned_params,\n 1778→ }\n 1779→ function_declarations.append(declaration)\n 1780→\n 1781→ if not function_declarations:\n 1782→ return []\n 1783→\n 1784→ return [{\"functionDeclarations\": function_declarations}]\n 1785→\n 1786→\n 1787→def convert_tools_to_codex_format(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n 1788→ \"\"\"Convert OpenAI-style tools to ChatGPT Codex (Responses API) format.\n 1789→\n 1790→ OpenAI Chat Completions format:\n 1791→ [{\"type\": \"function\", \"function\": {\"name\": \"...\", \"description\": \"...\", \"parameters\": {...}}}]\n 1792→\n 1793→ OpenAI Responses format (Codex API):\n 1794→ [{\"type\": \"function\", \"name\": \"...\", \"description\": \"...\", \"parameters\": {...}}]\n 1795→\n 1796→ The key difference is that Responses format has name/description at the top level\n 1797→ alongside type, not nested under a \"function\" key.\n 1798→\n 1799→ Args:\n 1800→ tools: OpenAI Chat Completions-style tool definitions\n 1801→\n 1802→ Returns:\n 1803→ OpenAI Responses-style tool definitions for Codex API\n 1804→ \"\"\"\n 1805→ if not tools:\n 1806→ return []\n 1807→\n 1808→ codex_tools = []\n 1809→\n 1810→ for tool in tools:\n 1811→ if not isinstance(tool, dict):\n 1812→ continue\n 1813→\n 1814→ # Handle OpenAI Chat Completions format (nested under \"function\")\n 1815→ if tool.get(\"type\") == \"function\" and isinstance(tool.get(\"function\"), dict):\n 1816→ func = tool[\"function\"]\n 1817→ codex_tool: Dict[str, Any] = {\n 1818→ \"type\": \"function\",\n 1819→ \"name\": func.get(\"name\", \"\"),\n 1820→ }\n 1821→ if \"description\" in func:\n 1822→ codex_tool[\"description\"] = func[\"description\"]\n 1823→ if \"parameters\" in func:\n 1824→ codex_tool[\"parameters\"] = func[\"parameters\"]\n 1825→ if \"strict\" in func:\n 1826→ codex_tool[\"strict\"] = func[\"strict\"]\n 1827→ codex_tools.append(codex_tool)\n 1828→\n 1829→ # Handle already-converted Responses format or direct format\n 1830→ elif \"type\" in tool and \"name\" in tool:\n 1831→ # Already in Responses format, pass through\n 1832→ codex_tools.append(tool)\n 1833→\n 1834→ # Handle direct function declaration (no type wrapper)\n 1835→ elif \"name\" in tool:\n 1836→ codex_tool = {\n 1837→ \"type\": \"function\",\n 1838→ \"name\": tool.get(\"name\", \"\"),\n 1839→ }\n 1840→ if \"description\" in tool:\n 1841→ codex_tool[\"description\"] = tool[\"description\"]\n 1842→ params = tool.get(\"parameters\") or tool.get(\"input_schema\")\n 1843→ if params:\n 1844→ codex_tool[\"parameters\"] = params\n 1845→ codex_tools.append(codex_tool)\n 1846→\n 1847→ return codex_tools\n 1848→\n 1849→\n 1850→# =============================================================================\n 1851→# TOOL MESSAGE CONVERSION (OpenAI → Gemini/Claude format)\n 1852→# =============================================================================\n 1853→\n 1854→\n 1855→def convert_tool_message_to_gemini_part(msg: Dict[str, Any]) -> Dict[str, Any]:\n 1856→ \"\"\"Convert an OpenAI tool result message to a Gemini functionResponse part.\n 1857→\n 1858→ OpenAI format:\n 1859→ {\"role\": \"tool\", \"tool_call_id\": \"...\", \"name\": \"...\", \"content\": \"...\"}\n 1860→\n 1861→ Gemini format:\n 1862→ {\"functionResponse\": {\"name\": \"...\", \"response\": {...}}}\n 1863→\n 1864→ Args:\n 1865→ msg: OpenAI-style tool result message\n 1866→\n 1867→ Returns:\n 1868→ Gemini-style functionResponse part\n 1869→ \"\"\"\n 1870→ name = msg.get(\"name\", msg.get(\"tool_name\", \"unknown_function\"))\n 1871→ content = msg.get(\"content\", \"\")\n 1872→\n 1873→ # Try to parse content as JSON\n 1874→ response_data: Any\n 1875→ if isinstance(content, str):\n 1876→ try:\n 1877→ response_data = json.loads(content)\n 1878→ except json.JSONDecodeError:\n 1879→ response_data = {\"result\": content}\n 1880→ elif isinstance(content, dict):\n 1881→ response_data = content\n 1882→ else:\n 1883→ response_data = {\"result\": str(content)}\n 1884→\n 1885→ return {\n 1886→ \"functionResponse\": {\n 1887→ \"name\": name,\n 1888→ \"response\": response_data,\n 1889→ }\n 1890→ }\n 1891→\n 1892→\n 1893→def convert_tool_calls_to_gemini_parts(tool_calls: List[Any]) -> List[Dict[str, Any]]:\n 1894→ \"\"\"Convert OpenAI tool_calls to Gemini functionCall parts.\n 1895→\n 1896→ OpenAI format:\n 1897→ [{\"id\": \"...\", \"function\": {\"name\": \"...\", \"arguments\": \"...\"}, \"thought_signature\": \"...\"}]\n 1898→\n 1899→ Gemini format:\n 1900→ [{\"functionCall\": {\"name\": \"...\", \"args\": {...}}, \"thoughtSignature\": \"...\"}]\n 1901→\n 1902→ Note: thoughtSignature is required for Gemini 3 models. It's preserved from the\n 1903→ original response and must be passed back exactly as received. If not found in\n 1904→ the tool call, attempts to retrieve from cache.\n 1905→\n 1906→ Args:\n 1907→ tool_calls: OpenAI-style tool calls (may be dicts or ChatCompletionMessageToolCall objects)\n 1908→\n 1909→ Returns:\n 1910→ Gemini-style functionCall parts (with thoughtSignature if present or cached)\n 1911→ \"\"\"\n 1912→ parts = []\n 1913→ for call in tool_calls:\n 1914→ # Handle both dict and ChatCompletionMessageToolCall objects\n 1915→ call_id = None\n 1916→ if isinstance(call, dict):\n 1917→ call_id = call.get(\"id\")\n 1918→ func = call.get(\"function\", {})\n 1919→ if isinstance(func, dict):\n 1920→ name = func.get(\"name\", call.get(\"name\", \"\"))\n 1921→ args_str = func.get(\"arguments\", call.get(\"arguments\", \"{}\"))\n 1922→ else:\n 1923→ # func might be a Function object\n 1924→ name = getattr(func, \"name\", call.get(\"name\", \"\"))\n 1925→ args_str = getattr(func, \"arguments\", call.get(\"arguments\", \"{}\"))\n 1926→ # Get thought_signature from dict\n 1927→ thought_sig = call.get(\"thought_signature\") or call.get(\"thoughtSignature\")\n 1928→ else:\n 1929→ # Handle ChatCompletionMessageToolCall objects (from LiteLLM)\n 1930→ call_id = getattr(call, \"id\", None)\n 1931→ func = getattr(call, \"function\", None)\n 1932→ if func:\n 1933→ name = getattr(func, \"name\", \"\")\n 1934→ args_str = getattr(func, \"arguments\", \"{}\")\n 1935→ else:\n 1936→ name = getattr(call, \"name\", \"\")\n 1937→ args_str = getattr(call, \"arguments\", \"{}\")\n 1938→ # Try to get thought_signature from object attributes\n 1939→ thought_sig = getattr(call, \"thought_signature\", None) or getattr(\n 1940→ call, \"thoughtSignature\", None\n 1941→ )\n 1942→\n 1943→ # If thought_signature not found, try to retrieve from cache (call_id required)\n 1944→ if not thought_sig and call_id and name:\n 1945→ thought_sig = get_cached_thought_signature(call_id, name)\n 1946→\n 1947→ # Parse arguments\n 1948→ if isinstance(args_str, str):\n 1949→ try:\n 1950→ args = json.loads(args_str)\n 1951→ except json.JSONDecodeError:\n 1952→ args = {}\n 1953→ else:\n 1954→ args = args_str or {}\n 1955→\n 1956→ part: Dict[str, Any] = {\n 1957→ \"functionCall\": {\n 1958→ \"name\": name,\n 1959→ \"args\": args,\n 1960→ }\n 1961→ }\n 1962→\n 1963→ # Preserve thoughtSignature for Gemini 3 models\n 1964→ if thought_sig:\n 1965→ part[\"thoughtSignature\"] = thought_sig\n 1966→\n 1967→ parts.append(part)\n 1968→\n 1969→ return parts\n 1970→\n 1971→\n 1972→# =============================================================================\n 1973→# TOOL ID MANAGEMENT (Claude/Antigravity)\n 1974→# =============================================================================\n 1975→\n 1976→\n 1977→def assign_tool_call_ids(\n 1978→ contents: List[Dict[str, Any]],\n 1979→) -> Tuple[List[Dict[str, Any]], Dict[str, List[str]]]:\n 1980→ \"\"\"Pass 1: Assign IDs to functionCall parts.\n 1981→\n 1982→ Generates unique IDs for functionCall parts that don't have them.\n 1983→ Returns the modified contents and a dict of pending call IDs by function name.\n 1984→\n 1985→ Args:\n 1986→ contents: Gemini-style contents array\n 1987→\n 1988→ Returns:\n 1989→ Tuple of (modified contents, pending IDs by function name)\n 1990→ \"\"\"\n 1991→ pending_by_name: Dict[str, List[str]] = defaultdict(list)\n 1992→ result = []\n 1993→\n 1994→ for content in contents:\n 1995→ if not isinstance(content, dict):\n 1996→ result.append(content)\n 1997→ continue\n 1998→\n 1999→ parts = content.get(\"parts\")\n 2000→ if not isinstance(parts, list):\n 2001→ result.append(content)\n 2002→ continue\n 2003→\n 2004→ new_parts = []\n 2005→ for part in parts:\n 2006→ if not isinstance(part, dict):\n 2007→ new_parts.append(part)\n 2008→ continue\n 2009→\n 2010→ if \"functionCall\" in part:\n 2011→ call = dict(part[\"functionCall\"])\n 2012→ if not call.get(\"id\"):\n 2013→ call[\"id\"] = f\"tool-call-{uuid.uuid4().hex[:8]}\"\n 2014→ name = call.get(\"name\", \"unknown\")\n 2015→ pending_by_name[name].append(call[\"id\"])\n 2016→ new_parts.append({**part, \"functionCall\": call})\n 2017→ else:\n 2018→ new_parts.append(part)\n 2019→\n 2020→ result.append({**content, \"parts\": new_parts})\n 2021→\n 2022→ return result, dict(pending_by_name)\n 2023→\n 2024→\n 2025→def match_tool_response_ids(\n 2026→ contents: List[Dict[str, Any]],\n 2027→ pending_by_name: Dict[str, List[str]],\n 2028→) -> List[Dict[str, Any]]:\n 2029→ \"\"\"Pass 2: Match functionResponse IDs using FIFO queue per function name.\n 2030→\n 2031→ Assigns IDs to functionResponse parts by matching them to pending\n 2032→ functionCall IDs in FIFO order.\n 2033→\n 2034→ Args:\n 2035→ contents: Gemini-style contents array (already processed by pass 1)\n 2036→ pending_by_name: Dict of pending call IDs by function name\n 2037→\n 2038→ Returns:\n 2039→ Modified contents with matched response IDs\n 2040→ \"\"\"\n 2041→ # Create a mutable copy of pending queues\n 2042→ queues = {name: list(ids) for name, ids in pending_by_name.items()}\n 2043→ result = []\n 2044→\n 2045→ for content in contents:\n 2046→ if not isinstance(content, dict):\n 2047→ result.append(content)\n 2048→ continue\n 2049→\n 2050→ parts = content.get(\"parts\")\n 2051→ if not isinstance(parts, list):\n 2052→ result.append(content)\n 2053→ continue\n 2054→\n 2055→ new_parts = []\n 2056→ for part in parts:\n 2057→ if not isinstance(part, dict):\n 2058→ new_parts.append(part)\n 2059→ continue\n 2060→\n 2061→ if \"functionResponse\" in part:\n 2062→ resp = dict(part[\"functionResponse\"])\n 2063→ name = resp.get(\"name\", \"unknown\")\n 2064→\n 2065→ # Try to match with pending call\n 2066→ if not resp.get(\"id\") and name in queues and queues[name]:\n 2067→ resp[\"id\"] = queues[name].pop(0) # FIFO\n 2068→\n 2069→ new_parts.append({**part, \"functionResponse\": resp})\n 2070→ else:\n 2071→ new_parts.append(part)\n 2072→\n 2073→ result.append({**content, \"parts\": new_parts})\n 2074→\n 2075→ return result\n 2076→\n 2077→\n 2078→def fix_tool_response_grouping(contents: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n 2079→ \"\"\"Pass 3: Orphan recovery - fix mismatched tool call/response pairs.\n 2080→\n 2081→ Handles cases where functionResponse parts don't have matching IDs\n 2082→ by attempting to pair them with unmatched functionCall parts.\n 2083→\n 2084→ Args:\n 2085→ contents: Gemini-style contents array\n 2086→\n 2087→ Returns:\n 2088→ Modified contents with orphan responses fixed\n 2089→ \"\"\"\n 2090→ # First, collect all call IDs and response IDs\n 2091→ all_call_ids: Dict[str, List[str]] = defaultdict(list) # name -> [ids]\n 2092→ all_response_ids: Dict[str, List[str]] = defaultdict(list) # name -> [ids]\n 2093→ call_names: Dict[str, str] = {} # id -> name\n 2094→\n 2095→ for content in contents:\n 2096→ if not isinstance(content, dict):\n 2097→ continue\n 2098→ parts = content.get(\"parts\", [])\n 2099→ if not isinstance(parts, list):\n 2100→ continue\n 2101→\n 2102→ for part in parts:\n 2103→ if not isinstance(part, dict):\n 2104→ continue\n 2105→ if \"functionCall\" in part:\n 2106→ call = part[\"functionCall\"]\n 2107→ call_id = call.get(\"id\")\n 2108→ name = call.get(\"name\", \"unknown\")\n 2109→ if call_id:\n 2110→ all_call_ids[name].append(call_id)\n 2111→ call_names[call_id] = name\n 2112→ elif \"functionResponse\" in part:\n 2113→ resp = part[\"functionResponse\"]\n 2114→ resp_id = resp.get(\"id\")\n 2115→ name = resp.get(\"name\", \"unknown\")\n 2116→ if resp_id:\n 2117→ all_response_ids[name].append(resp_id)\n 2118→\n 2119→ # Find orphaned responses (responses without matching calls)\n 2120→ result = []\n 2121→ for content in contents:\n 2122→ if not isinstance(content, dict):\n 2123→ result.append(content)\n 2124→ continue\n 2125→\n 2126→ parts = content.get(\"parts\", [])\n 2127→ if not isinstance(parts, list):\n 2128→ result.append(content)\n 2129→ continue\n 2130→\n 2131→ new_parts = []\n 2132→ for part in parts:\n 2133→ if not isinstance(part, dict):\n 2134→ new_parts.append(part)\n 2135→ continue\n 2136→\n 2137→ if \"functionResponse\" in part:\n 2138→ resp = dict(part[\"functionResponse\"])\n 2139→ resp_id = resp.get(\"id\")\n 2140→ name = resp.get(\"name\", \"unknown\")\n 2141→\n 2142→ # Check if this response's ID matches any call\n 2143→ if resp_id and resp_id not in call_names:\n 2144→ # Try to find an unmatched call with the same name\n 2145→ if name in all_call_ids and all_call_ids[name]:\n 2146→ unmatched = [\n 2147→ cid\n 2148→ for cid in all_call_ids[name]\n 2149→ if cid not in all_response_ids.get(name, [])\n 2150→ ]\n 2151→ if unmatched:\n 2152→ resp[\"id\"] = unmatched[0]\n 2153→ all_response_ids[name].append(unmatched[0])\n 2154→\n 2155→ new_parts.append({**part, \"functionResponse\": resp})\n 2156→ else:\n 2157→ new_parts.append(part)\n 2158→\n 2159→ result.append({**content, \"parts\": new_parts})\n 2160→\n 2161→ return result\n 2162→\n 2163→\n 2164→def apply_tool_pairing_fixes(\n 2165→ payload: Dict[str, Any],\n 2166→ is_claude: bool = False,\n 2167→) -> Dict[str, Any]:\n 2168→ \"\"\"Apply all tool pairing fixes to a request payload.\n 2169→\n 2170→ Runs the full 3-pass tool ID management pipeline:\n 2171→ 1. Assign IDs to functionCall parts\n 2172→ 2. Match functionResponse IDs using FIFO\n 2173→ 3. Orphan recovery\n 2174→\n 2175→ Args:\n 2176→ payload: Request payload with 'contents' array\n 2177→ is_claude: Whether this is for Claude (enables additional validation)\n 2178→\n 2179→ Returns:\n 2180→ Modified payload with fixed tool pairing\n 2181→ \"\"\"\n 2182→ if \"contents\" not in payload or not isinstance(payload[\"contents\"], list):\n 2183→ return payload\n 2184→\n 2185→ result = dict(payload)\n 2186→\n 2187→ # Pass 1: Assign IDs\n 2188→ contents_with_ids, pending = assign_tool_call_ids(result[\"contents\"])\n 2189→\n 2190→ # Pass 2: Match response IDs\n 2191→ contents_matched = match_tool_response_ids(contents_with_ids, pending)\n 2192→\n 2193→ # Pass 3: Orphan recovery\n 2194→ result[\"contents\"] = fix_tool_response_grouping(contents_matched)\n 2195→\n 2196→ return result\n 2197→\n 2198→\n 2199→# =============================================================================\n 2200→# TOOL CALL EXTRACTION FROM RESPONSES\n 2201→# =============================================================================\n 2202→\n 2203→\n 2204→def extract_tool_calls_from_gemini_response(\n 2205→ data: Dict[str, Any],\n 2206→ session_id: Optional[str] = None,\n 2207→ message_count: Optional[int] = None,\n 2208→) -> Optional[List[Dict[str, Any]]]:\n 2209→ \"\"\"Extract functionCall parts from Gemini/Antigravity response.\n 2210→\n 2211→ Preserves thoughtSignature for Gemini 3 models - this must be passed back\n 2212→ exactly as received when sending tool results. Also caches the signature\n 2213→ for retrieval during follow-up calls (since LiteLLM streaming may lose it).\n 2214→\n 2215→ Args:\n 2216→ data: Response data from Gemini API\n 2217→\n 2218→ Returns:\n 2219→ List of OpenAI-style tool calls (with thought_signature if present),\n 2220→ or None if no tool calls found\n 2221→ \"\"\"\n 2222→ # Handle wrapped response\n 2223→ if \"response\" in data:\n 2224→ data = data[\"response\"]\n 2225→\n 2226→ candidates = data.get(\"candidates\", [])\n 2227→ if not candidates:\n 2228→ return None\n 2229→\n 2230→ tool_calls = []\n 2231→ for candidate in candidates:\n 2232→ content = candidate.get(\"content\", {})\n 2233→ parts = content.get(\"parts\", [])\n 2234→ current_thought_sig: Optional[str] = None\n 2235→\n 2236→ for part in parts:\n 2237→ if not isinstance(part, dict):\n 2238→ continue\n 2239→\n 2240→ # Cache thoughtSignature from thinking parts (Gemini 3)\n 2241→ thought_sig = _extract_part_thought_signature(part)\n 2242→ if thought_sig and (part.get(\"thought\") is True or part.get(\"type\") in (\"thinking\", \"reasoning\")):\n 2243→ current_thought_sig = thought_sig\n 2244→ cache_thinking_signature(thought_sig)\n 2245→ if session_id and message_count is not None:\n 2246→ cache_session_signature(session_id, thought_sig, message_count)\n 2247→\n 2248→ if \"functionCall\" in part:\n 2249→ func_call = part[\"functionCall\"]\n 2250→ name = func_call.get(\"name\", \"\")\n 2251→ args = func_call.get(\"args\", {})\n 2252→ call_id = func_call.get(\"id\", f\"call_{uuid.uuid4().hex[:8]}\")\n 2253→\n 2254→ # Convert to OpenAI format\n 2255→ tool_call: Dict[str, Any] = {\n 2256→ \"id\": call_id,\n 2257→ \"type\": \"function\",\n 2258→ \"function\": {\n 2259→ \"name\": name,\n 2260→ \"arguments\": json.dumps(args) if isinstance(args, dict) else str(args),\n 2261→ },\n 2262→ }\n 2263→\n 2264→ # Preserve thoughtSignature for Gemini 3 models\n 2265→ # Store as snake_case in OpenAI format for consistency\n 2266→ thought_sig = _extract_part_thought_signature(part) or current_thought_sig\n 2267→ if thought_sig:\n 2268→ tool_call[\"thought_signature\"] = thought_sig\n 2269→ # Also cache for retrieval during follow-up calls\n 2270→ cache_thought_signature(call_id, name, thought_sig)\n 2271→ if session_id and message_count is not None:\n 2272→ cache_session_signature(session_id, thought_sig, message_count)\n 2273→\n 2274→ tool_calls.append(tool_call)\n 2275→\n 2276→ return tool_calls if tool_calls else None\n 2277→\n 2278→\n 2279→def extract_tool_calls_from_codex_response(\n 2280→ data: Dict[str, Any],\n 2281→) -> Optional[List[Dict[str, Any]]]:\n 2282→ \"\"\"Extract function_call items from ChatGPT Codex response.\n 2283→\n 2284→ Args:\n 2285→ data: Response data from Codex API (from response.done event)\n 2286→\n 2287→ Returns:\n 2288→ List of OpenAI-style tool calls, or None if no tool calls found\n 2289→ \"\"\"\n 2290→ output = data.get(\"output\", [])\n 2291→ if not isinstance(output, list):\n 2292→ return None\n 2293→\n 2294→ tool_calls = []\n 2295→ for item in output:\n 2296→ if not isinstance(item, dict):\n 2297→ continue\n 2298→\n 2299→ if item.get(\"type\") == \"function_call\":\n 2300→ call_id = item.get(\"call_id\", f\"call_{uuid.uuid4().hex[:8]}\")\n 2301→ name = item.get(\"name\", \"\")\n 2302→ arguments = item.get(\"arguments\", \"{}\")\n 2303→\n 2304→ # Ensure arguments is a string\n 2305→ if isinstance(arguments, dict):\n 2306→ arguments = json.dumps(arguments)\n 2307→\n 2308→ tool_calls.append(\n 2309→ {\n 2310→ \"id\": call_id,\n 2311→ \"type\": \"function\",\n 2312→ \"function\": {\n 2313→ \"name\": name,\n 2314→ \"arguments\": arguments,\n 2315→ },\n 2316→ }\n 2317→ )\n 2318→\n 2319→ return tool_calls if tool_calls else None\n 2320→\n 2321→\n 2322→def build_tool_calls_response_message(\n 2323→ tool_calls: List[Dict[str, Any]],\n 2324→) -> Dict[str, Any]:\n 2325→ \"\"\"Build an assistant message with tool_calls for ModelResponse.\n 2326→\n 2327→ Args:\n 2328→ tool_calls: List of OpenAI-style tool calls\n 2329→\n 2330→ Returns:\n 2331→ Assistant message dict with tool_calls\n 2332→ \"\"\"\n 2333→ return {\n 2334→ \"role\": \"assistant\",\n 2335→ \"content\": None,\n 2336→ \"tool_calls\": tool_calls,\n 2337→ }\n 2338→\n\n<system-reminder>\nWhenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.\n</system-reminder>\n"}]},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"6c007cda-aee6-43de-8fe3-ef3627327feb","tool_use_result":{"type":"text","file":{"filePath":"/Users/fei/coding-agent/koder/koder_agent/auth/tool_utils.py","content":"\"\"\"Tool calling utilities for OAuth providers.\n\nShared utilities for converting, cleaning, and managing tool calls across\ndifferent OAuth providers (Google, Claude, ChatGPT, Antigravity).\n\nReference implementations:\n- /tmp/oauth-providers/antigravity-auth/src/plugin/request-helpers.ts\n- /tmp/oauth-providers/antigravity-auth/src/plugin/transform/claude.ts\n- /tmp/oauth-providers/chatgpt-auth/lib/request/request-transformer.ts\n\"\"\"\n\nimport json\nimport logging\nimport threading\nimport time\nimport uuid\nfrom collections import defaultdict\nfrom typing import Any, Dict, List, Optional, Tuple\n\nlogger = logging.getLogger(__name__)\n\n# =============================================================================\n# THOUGHT SIGNATURE CACHE (Gemini 3)\n# Stores thoughtSignature values to survive LiteLLM's streaming handler\n# Thread-safe via threading.Lock for concurrent access\n# =============================================================================\n\n# Cache: {(call_id, function_name): (thought_signature, timestamp)}\n_thought_signature_cache: Dict[Tuple[str, str], Tuple[str, float]] = {}\n# Most recent thought_signature for parallel calls fallback (per function name)\n_last_thought_signature_by_name: Dict[str, Tuple[str, float]] = {}\n# Global last signature for cross-function parallel calls (legacy fallback)\n_last_thought_signature: Optional[Tuple[str, float]] = None\n# Session-based signature cache: session_id -> (signature, message_count, timestamp)\n_session_signature_cache: Dict[str, Tuple[str, int, float]] = {}\n_CACHE_TTL_SECONDS = 300 # 5 minutes TTL\n_SESSION_CACHE_TTL_SECONDS = 2 * 60 * 60 # 2 hours TTL (match Antigravity-Manager)\n_BATCH_WINDOW_SECONDS = 2 # Window for parallel call batch (used for fallback)\n# Lock for thread-safe cache access (required for multi-step operations)\n_cache_lock = threading.Lock()\n_MAX_CACHE_SIZE = 1000 # Prevent unbounded growth\n\n\ndef _normalize_function_name(name: str) -> str:\n \"\"\"Normalize function name by stripping known prefixes.\n\n Handles prefixes like: default_api:, tools:, functions:, etc.\n \"\"\"\n known_prefixes = (\"default_api:\", \"tools:\", \"functions:\", \"tool:\")\n for prefix in known_prefixes:\n if name.startswith(prefix):\n return name[len(prefix) :]\n return name\n\n\ndef cache_thought_signature(call_id: str, function_name: str, thought_signature: str) -> None:\n \"\"\"Cache a thoughtSignature for later retrieval.\n\n Also stores as \"last signature\" for parallel calls that don't have their own.\n Thread-safe via _cache_lock.\n\n Args:\n call_id: Tool call ID\n function_name: Function name\n thought_signature: The thoughtSignature to cache\n \"\"\"\n global _last_thought_signature\n\n key = (call_id, function_name)\n now = time.time()\n normalized_name = _normalize_function_name(function_name)\n\n with _cache_lock:\n # Store in main cache\n _thought_signature_cache[key] = (thought_signature, now)\n\n # Also store normalized version for prefix-agnostic lookup\n if normalized_name != function_name:\n _thought_signature_cache[(call_id, normalized_name)] = (thought_signature, now)\n\n # Store per-function-name fallback for parallel calls\n _last_thought_signature_by_name[normalized_name] = (thought_signature, now)\n\n # Clean up old entries and enforce size limit\n _cleanup_thought_signature_cache_unlocked()\n\n\ndef cache_thinking_signature(thought_signature: str) -> None:\n \"\"\"Cache a thoughtSignature from a thinking block.\n\n Gemini 3 may emit thoughtSignature only on thinking parts (not functionCall).\n Store it as the global fallback so tool calls without explicit signatures can reuse it.\n \"\"\"\n global _last_thought_signature\n\n if not thought_signature or not isinstance(thought_signature, str):\n return\n\n now = time.time()\n with _cache_lock:\n _last_thought_signature = (thought_signature, now)\n _cleanup_thought_signature_cache_unlocked()\n\n\ndef cache_session_signature(session_id: str, thought_signature: str, message_count: int) -> None:\n \"\"\"Cache the latest thinking signature for a session (Gemini 3 tool loops).\n\n Mirrors Antigravity-Manager's session cache: prefer most recent signatures,\n detect rewind (message_count decreases), and only store sufficiently long signatures.\n \"\"\"\n if not session_id or not thought_signature or not isinstance(thought_signature, str):\n return\n if len(thought_signature) < MIN_SIGNATURE_LENGTH:\n return\n\n now = time.time()\n with _cache_lock:\n existing = _session_signature_cache.get(session_id)\n should_store = False\n if existing is None:\n should_store = True\n else:\n _, existing_count, ts = existing\n # Expired entry\n if now - ts >= _SESSION_CACHE_TTL_SECONDS:\n should_store = True\n # Rewind detected\n elif message_count < existing_count:\n should_store = True\n # Same message count: prefer longer signature\n elif message_count == existing_count:\n should_store = len(thought_signature) > len(existing[0])\n else:\n should_store = True\n\n if should_store:\n _session_signature_cache[session_id] = (\n thought_signature,\n message_count,\n now,\n )\n\n _cleanup_thought_signature_cache_unlocked()\n\n\ndef get_session_signature(session_id: str) -> Optional[str]:\n \"\"\"Retrieve cached session signature if valid and not expired.\"\"\"\n if not session_id:\n return None\n\n now = time.time()\n with _cache_lock:\n entry = _session_signature_cache.get(session_id)\n if not entry:\n return None\n sig, _count, ts = entry\n if now - ts >= _SESSION_CACHE_TTL_SECONDS:\n return None\n return sig\n\n\ndef _extract_part_thought_signature(part: Dict[str, Any]) -> Optional[str]:\n \"\"\"Extract thoughtSignature from a Gemini part (direct or metadata.google).\"\"\"\n sig = part.get(\"thoughtSignature\")\n if isinstance(sig, str) and sig:\n return sig\n\n func_call = part.get(\"functionCall\")\n if isinstance(func_call, dict):\n sig = func_call.get(\"thoughtSignature\") or func_call.get(\"thought_signature\")\n if isinstance(sig, str) and sig:\n return sig\n\n func_meta = func_call.get(\"metadata\")\n if isinstance(func_meta, dict):\n google_meta = func_meta.get(\"google\")\n if isinstance(google_meta, dict):\n sig = google_meta.get(\"thoughtSignature\")\n if isinstance(sig, str) and sig:\n return sig\n\n metadata = part.get(\"metadata\")\n if isinstance(metadata, dict):\n google_meta = metadata.get(\"google\")\n if isinstance(google_meta, dict):\n sig = google_meta.get(\"thoughtSignature\")\n if isinstance(sig, str) and sig:\n return sig\n\n return None\n\n\ndef inject_thought_signature_for_function_calls(\n contents: List[Dict[str, Any]], session_id: str\n) -> List[Dict[str, Any]]:\n \"\"\"Inject thoughtSignature into functionCall parts when missing.\n\n Uses session-scoped cached signatures (no fake signatures).\n Mirrors Antigravity-Manager's wrap_request behavior.\n \"\"\"\n if not contents or not session_id:\n return contents\n\n sig = get_session_signature(session_id)\n if not sig:\n return contents\n\n updated_contents = []\n for content in contents:\n if not isinstance(content, dict) or not isinstance(content.get(\"parts\"), list):\n updated_contents.append(content)\n continue\n\n parts = []\n for part in content[\"parts\"]:\n if not isinstance(part, dict):\n parts.append(part)\n continue\n\n if \"functionCall\" in part and not _extract_part_thought_signature(part):\n new_part = dict(part)\n new_part[\"thoughtSignature\"] = sig\n parts.append(new_part)\n else:\n parts.append(part)\n\n updated_contents.append({**content, \"parts\": parts})\n\n return updated_contents\n\n\ndef get_cached_thought_signature(call_id: str, function_name: str) -> Optional[str]:\n \"\"\"Retrieve a cached thoughtSignature.\n\n Handles various function name formats via normalization:\n - Direct name: \"grep_search\"\n - With API prefix: \"default_api:grep_search\", \"tools:grep_search\", etc.\n\n For parallel function calls, Gemini only provides thoughtSignature for the\n first call. This function falls back to the most recent signature if no\n exact match is found (within the batch window).\n\n Thread-safe via _cache_lock.\n\n Args:\n call_id: Tool call ID\n function_name: Function name (may include prefix)\n\n Returns:\n The cached thoughtSignature, or None if not found or expired\n \"\"\"\n now = time.time()\n normalized_name = _normalize_function_name(function_name)\n\n with _cache_lock:\n # Strategy 1: Try exact match first\n key = (call_id, function_name)\n if key in _thought_signature_cache:\n sig, timestamp = _thought_signature_cache[key]\n if now - timestamp < _CACHE_TTL_SECONDS:\n return sig\n\n # Strategy 2: Try normalized name (handles all prefixes)\n if normalized_name != function_name:\n key = (call_id, normalized_name)\n if key in _thought_signature_cache:\n sig, timestamp = _thought_signature_cache[key]\n if now - timestamp < _CACHE_TTL_SECONDS:\n return sig\n\n # NOTE: Do not use per-function/global fallbacks for Gemini 3 tool calls.\n # Thought signatures must match the specific functionCall in the response.\n\n # No valid signature found - log warning for debugging (only for Gemini 3 models)\n # This is outside the lock since logging doesn't need synchronization\n logger.debug(\n f\"No thoughtSignature found for call_id={call_id}, function={function_name}. \"\n \"This is expected for non-Gemini-3 models.\"\n )\n return None\n\n\ndef _cleanup_thought_signature_cache_unlocked() -> None:\n \"\"\"Remove expired entries from the cache and enforce size limits.\n\n MUST be called while holding _cache_lock.\n Also cleans up the per-function-name fallback cache.\n \"\"\"\n global _last_thought_signature\n\n now = time.time()\n\n # Clean main cache - remove expired entries\n expired_keys = [\n key for key, (_, ts) in _thought_signature_cache.items() if now - ts >= _CACHE_TTL_SECONDS\n ]\n for key in expired_keys:\n del _thought_signature_cache[key]\n\n # Clean per-function-name fallback cache\n expired_names = [\n name\n for name, (_, ts) in _last_thought_signature_by_name.items()\n if now - ts >= _CACHE_TTL_SECONDS\n ]\n for name in expired_names:\n del _last_thought_signature_by_name[name]\n\n # Clear global fallback if expired\n if _last_thought_signature:\n _, timestamp = _last_thought_signature\n if now - timestamp >= _CACHE_TTL_SECONDS:\n _last_thought_signature = None\n\n # Enforce size limit on main cache (LRU-style: remove oldest)\n if len(_thought_signature_cache) > _MAX_CACHE_SIZE:\n # Sort by timestamp and remove oldest entries\n sorted_entries = sorted(_thought_signature_cache.items(), key=lambda x: x[1][1])\n entries_to_remove = len(_thought_signature_cache) - _MAX_CACHE_SIZE\n for key, _ in sorted_entries[:entries_to_remove]:\n del _thought_signature_cache[key]\n\n # Clean session cache - remove expired entries\n expired_sessions = [\n key\n for key, (_, _, ts) in _session_signature_cache.items()\n if now - ts >= _SESSION_CACHE_TTL_SECONDS\n ]\n for key in expired_sessions:\n del _session_signature_cache[key]\n\n\ndef clear_thought_signature_cache() -> None:\n \"\"\"Clear all cached thought signatures.\n\n Useful for testing and when switching between providers.\n Thread-safe.\n \"\"\"\n global _last_thought_signature\n\n with _cache_lock:\n _thought_signature_cache.clear()\n _last_thought_signature_by_name.clear()\n _last_thought_signature = None\n _session_signature_cache.clear()\n\n\n# Placeholder for tools with empty schemas (Claude VALIDATED mode requires at least one property)\nEMPTY_SCHEMA_PLACEHOLDER_NAME = \"_placeholder\"\nEMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION = \"Placeholder. Always pass true.\"\n\n# =============================================================================\n# CLAUDE TOOL HARDENING CONSTANTS (Ported from antigravity-auth)\n# =============================================================================\n\n# Sentinel value to bypass thought signature validation\n# When a thinking block has an invalid/missing signature, use this to skip validation\n# Reference: antigravity-auth/src/constants.ts SKIP_THOUGHT_SIGNATURE\nSKIP_THOUGHT_SIGNATURE = \"skip_thought_signature_validator\"\n\n# System instruction for Claude tool usage hardening\n# Prevents hallucinated parameters by explicitly stating the rules\n# Reference: antigravity-auth/src/constants.ts CLAUDE_TOOL_SYSTEM_INSTRUCTION\nCLAUDE_TOOL_SYSTEM_INSTRUCTION = \"\"\"CRITICAL TOOL USAGE INSTRUCTIONS:\nYou are operating in a custom environment where tool definitions differ from your training data.\nYou MUST follow these rules strictly:\n\n1. DO NOT use your internal training data to guess tool parameters\n2. ONLY use the exact parameter structure defined in the tool schema\n3. Parameter names in schemas are EXACT - do not substitute with similar names from your training\n4. Array parameters have specific item types - check the schema's 'items' field for the exact structure\n5. When you see \"STRICT PARAMETERS\" in a tool description, those type definitions override any assumptions\n6. Tool use in agentic workflows is REQUIRED - you must call tools with the exact parameters specified\n\nIf you are unsure about a tool's parameters, YOU MUST read the schema definition carefully.\"\"\"\n\n# Template for parameter signature injection into tool descriptions\n# Reference: antigravity-auth/src/constants.ts CLAUDE_DESCRIPTION_PROMPT\nCLAUDE_DESCRIPTION_PROMPT = \"\\n\\n⚠️ STRICT PARAMETERS: {params}.\"\n\n# Minimum signature length to be considered valid (from TypeScript MIN_SIGNATURE_LENGTH)\nMIN_SIGNATURE_LENGTH = 50\n\n# Unsupported constraint keywords that should be moved to description hints\n# Claude/Gemini reject these in VALIDATED mode\nUNSUPPORTED_CONSTRAINTS = [\n \"minLength\",\n \"maxLength\",\n \"exclusiveMinimum\",\n \"exclusiveMaximum\",\n \"pattern\",\n \"minItems\",\n \"maxItems\",\n \"format\",\n \"default\",\n \"examples\",\n]\n\n# Keywords that should be removed after hint extraction\nUNSUPPORTED_KEYWORDS = [\n *UNSUPPORTED_CONSTRAINTS,\n \"$schema\",\n \"$defs\",\n \"definitions\",\n \"const\",\n \"$ref\",\n \"additionalProperties\",\n \"propertyNames\",\n \"title\",\n \"$id\",\n \"$comment\",\n]\n\n\n# =============================================================================\n# JSON SCHEMA CLEANING FOR LLM TOOL CALLS\n# Cleans JSON schemas for providers that don't support advanced features\n# like $ref/$defs (GitHub Copilot, Antigravity, etc.)\n# =============================================================================\n\n\ndef _append_description_hint(schema: Dict[str, Any], hint: str) -> Dict[str, Any]:\n \"\"\"Append a hint to a schema's description field.\"\"\"\n if not schema or not isinstance(schema, dict):\n return schema\n\n existing = schema.get(\"description\", \"\")\n if isinstance(existing, str) and existing:\n new_description = f\"{existing} ({hint})\"\n else:\n new_description = hint\n\n return {**schema, \"description\": new_description}\n\n\ndef _convert_refs_to_hints(schema: Any) -> Any:\n \"\"\"Phase 1a: Convert $ref to description hints.\n\n $ref: \"#/$defs/Foo\" → { type: \"object\", description: \"See: Foo\" }\n \"\"\"\n if not schema or not isinstance(schema, dict):\n return schema\n\n if isinstance(schema, list):\n return [_convert_refs_to_hints(item) for item in schema]\n\n # If this object has $ref, replace it with a hint\n if isinstance(schema.get(\"$ref\"), str):\n ref_val = schema[\"$ref\"]\n def_name = ref_val.split(\"/\")[-1] if \"/\" in ref_val else ref_val\n hint = f\"See: {def_name}\"\n existing_desc = schema.get(\"description\", \"\")\n new_description = f\"{existing_desc} ({hint})\" if existing_desc else hint\n return {\"type\": \"object\", \"description\": new_description}\n\n # Recursively process all properties\n result = {}\n for key, value in schema.items():\n result[key] = _convert_refs_to_hints(value)\n return result\n\n\ndef _convert_const_to_enum(schema: Any) -> Any:\n \"\"\"Phase 1b: Convert const to enum.\n\n { const: \"foo\" } → { enum: [\"foo\"] }\n \"\"\"\n if not schema or not isinstance(schema, dict):\n return schema\n\n if isinstance(schema, list):\n return [_convert_const_to_enum(item) for item in schema]\n\n result = {}\n for key, value in schema.items():\n if key == \"const\" and \"enum\" not in schema:\n result[\"enum\"] = [value]\n else:\n result[key] = _convert_const_to_enum(value)\n return result\n\n\ndef _add_enum_hints(schema: Any) -> Any:\n \"\"\"Phase 1c: Add enum hints to description.\n\n { enum: [\"a\", \"b\", \"c\"] } → adds \"(Allowed: a, b, c)\" to description\n \"\"\"\n if not schema or not isinstance(schema, dict):\n return schema\n\n if isinstance(schema, list):\n return [_add_enum_hints(item) for item in schema]\n\n result = dict(schema)\n\n # Add enum hint if enum has 2-10 items\n if isinstance(result.get(\"enum\"), list) and 1 < len(result[\"enum\"]) <= 10:\n vals = \", \".join(str(v) for v in result[\"enum\"])\n result = _append_description_hint(result, f\"Allowed: {vals}\")\n\n # Recursively process nested objects\n for key, value in list(result.items()):\n if key != \"enum\" and isinstance(value, dict):\n result[key] = _add_enum_hints(value)\n elif key != \"enum\" and isinstance(value, list):\n result[key] = [_add_enum_hints(item) for item in value]\n\n return result\n\n\ndef _add_additional_properties_hints(schema: Any) -> Any:\n \"\"\"Phase 1d: Add additionalProperties hints.\n\n { additionalProperties: false } → adds \"(No extra properties allowed)\" to description\n \"\"\"\n if not schema or not isinstance(schema, dict):\n return schema\n\n if isinstance(schema, list):\n return [_add_additional_properties_hints(item) for item in schema]\n\n result = dict(schema)\n\n if result.get(\"additionalProperties\") is False:\n result = _append_description_hint(result, \"No extra properties allowed\")\n\n # Recursively process nested objects\n for key, value in list(result.items()):\n if key != \"additionalProperties\" and isinstance(value, dict):\n result[key] = _add_additional_properties_hints(value)\n elif key != \"additionalProperties\" and isinstance(value, list):\n result[key] = [_add_additional_properties_hints(item) for item in value]\n\n return result\n\n\ndef _move_constraints_to_description(schema: Any) -> Any:\n \"\"\"Phase 1e: Move unsupported constraints to description hints.\n\n { minLength: 1, maxLength: 100 } → adds \"(minLength: 1) (maxLength: 100)\" to description\n \"\"\"\n if not schema or not isinstance(schema, dict):\n return schema\n\n if isinstance(schema, list):\n return [_move_constraints_to_description(item) for item in schema]\n\n result = dict(schema)\n\n # Move constraint values to description\n for constraint in UNSUPPORTED_CONSTRAINTS:\n if constraint in result and not isinstance(result[constraint], dict):\n result = _append_description_hint(result, f\"{constraint}: {result[constraint]}\")\n\n # Recursively process nested objects\n for key, value in list(result.items()):\n if isinstance(value, dict):\n result[key] = _move_constraints_to_description(value)\n elif isinstance(value, list):\n result[key] = [_move_constraints_to_description(item) for item in value]\n\n return result\n\n\ndef _merge_all_of(schema: Any) -> Any:\n \"\"\"Phase 2a: Merge allOf schemas into a single object.\"\"\"\n if not schema or not isinstance(schema, dict):\n return schema\n\n if isinstance(schema, list):\n return [_merge_all_of(item) for item in schema]\n\n result = dict(schema)\n\n if isinstance(result.get(\"allOf\"), list):\n all_of = result.pop(\"allOf\")\n merged_properties = {}\n merged_required = []\n\n for sub_schema in all_of:\n if isinstance(sub_schema, dict):\n if isinstance(sub_schema.get(\"properties\"), dict):\n merged_properties.update(sub_schema[\"properties\"])\n if isinstance(sub_schema.get(\"required\"), list):\n merged_required.extend(sub_schema[\"required\"])\n\n if merged_properties:\n existing_props = result.get(\"properties\", {})\n result[\"properties\"] = {**existing_props, **merged_properties}\n\n if merged_required:\n existing_req = result.get(\"required\", [])\n result[\"required\"] = list(set(existing_req + merged_required))\n\n # Recursively process nested objects\n for key, value in list(result.items()):\n if isinstance(value, dict):\n result[key] = _merge_all_of(value)\n elif isinstance(value, list):\n result[key] = [_merge_all_of(item) for item in value]\n\n return result\n\n\ndef _remove_unsupported_keywords(schema: Any) -> Any:\n \"\"\"Phase 3: Remove unsupported keywords from schema.\"\"\"\n if not schema or not isinstance(schema, dict):\n return schema\n\n if isinstance(schema, list):\n return [_remove_unsupported_keywords(item) for item in schema]\n\n result = {}\n for key, value in schema.items():\n if key in UNSUPPORTED_KEYWORDS:\n continue\n if isinstance(value, dict):\n result[key] = _remove_unsupported_keywords(value)\n elif isinstance(value, list):\n result[key] = [_remove_unsupported_keywords(item) for item in value]\n else:\n result[key] = value\n\n return result\n\n\ndef _fix_required_fields(schema: Any) -> Any:\n \"\"\"Fix required fields that reference non-existent properties.\n\n Gemini API validates that all entries in 'required' array have\n corresponding properties defined. This removes invalid entries.\n \"\"\"\n if not schema or not isinstance(schema, dict):\n return schema\n\n result = dict(schema)\n\n # Fix required at this level\n if isinstance(result.get(\"required\"), list) and isinstance(result.get(\"properties\"), dict):\n valid_props = set(result[\"properties\"].keys())\n result[\"required\"] = [r for r in result[\"required\"] if r in valid_props]\n # Remove empty required array\n if not result[\"required\"]:\n del result[\"required\"]\n\n # Recursively fix nested schemas\n for key, value in list(result.items()):\n if isinstance(value, dict):\n result[key] = _fix_required_fields(value)\n elif isinstance(value, list):\n result[key] = [\n _fix_required_fields(item) if isinstance(item, dict) else item for item in value\n ]\n\n return result\n\n\ndef clean_json_schema(schema: Any) -> Dict[str, Any]:\n \"\"\"Clean JSON schema for LLM providers that don't support advanced features.\n\n Some providers (GitHub Copilot, Antigravity, etc.) don't support $ref/$defs\n or other advanced JSON Schema features. This function cleans the schema\n by converting unsupported features to description hints.\n\n Applies the following transformations:\n 1a. Convert $ref to description hints\n 1b. Convert const to enum\n 1c. Add enum hints to descriptions\n 1d. Add additionalProperties hints\n 1e. Move unsupported constraints to description\n 2a. Merge allOf schemas\n 3. Remove unsupported keywords ($ref, $defs, additionalProperties, etc.)\n 4. Fix required fields referencing non-existent properties\n\n Args:\n schema: JSON schema to clean\n\n Returns:\n Cleaned schema compatible with all LLM providers\n \"\"\"\n if not schema or not isinstance(schema, dict):\n return {\"type\": \"object\", \"properties\": {}}\n\n # Phase 1: Convert and hint\n result = _convert_refs_to_hints(schema)\n result = _convert_const_to_enum(result)\n result = _add_enum_hints(result)\n result = _add_additional_properties_hints(result)\n result = _move_constraints_to_description(result)\n\n # Phase 2: Merge\n result = _merge_all_of(result)\n\n # Phase 3: Remove unsupported keywords\n result = _remove_unsupported_keywords(result)\n\n # Phase 4: Fix required fields referencing non-existent properties\n result = _fix_required_fields(result)\n\n # Ensure type is object\n if \"type\" not in result:\n result[\"type\"] = \"object\"\n\n return result\n\n\n# =============================================================================\n# CLAUDE SCHEMA CLEANING (Ported from Antigravity-Manager's json_schema.rs)\n# =============================================================================\n\n# Whitelist of allowed fields for Claude VALIDATED mode\n# Any field not in this list will be removed\nCLAUDE_ALLOWED_SCHEMA_FIELDS = {\n \"type\",\n \"description\",\n \"properties\",\n \"required\",\n \"items\",\n \"enum\",\n \"title\",\n}\n\n# Constraints to move to description hints\nCLAUDE_CONSTRAINT_FIELDS = [\n (\"minLength\", \"minLen\"),\n (\"maxLength\", \"maxLen\"),\n (\"pattern\", \"pattern\"),\n (\"minimum\", \"min\"),\n (\"maximum\", \"max\"),\n (\"multipleOf\", \"multipleOf\"),\n (\"exclusiveMinimum\", \"exclMin\"),\n (\"exclusiveMaximum\", \"exclMax\"),\n (\"minItems\", \"minItems\"),\n (\"maxItems\", \"maxItems\"),\n (\"propertyNames\", \"propertyNames\"),\n (\"format\", \"format\"),\n]\n\n\ndef _score_schema_option(schema: Any) -> int:\n \"\"\"Score a schema option for anyOf/oneOf selection.\n\n Higher scores are preferred:\n - Object with properties: 3\n - Array: 2\n - Scalar type (non-null): 1\n - Null or invalid: 0\n \"\"\"\n if not schema or not isinstance(schema, dict):\n return 0\n\n # Object with properties scores highest\n if schema.get(\"properties\") or schema.get(\"type\") == \"object\":\n return 3\n\n # Array scores medium\n if schema.get(\"items\") or schema.get(\"type\") == \"array\":\n return 2\n\n # Non-null scalar types score low\n type_val = schema.get(\"type\")\n if type_val and type_val != \"null\":\n return 1\n\n return 0\n\n\ndef _extract_best_schema_from_union(union_array: List[Any]) -> Optional[Dict[str, Any]]:\n \"\"\"Extract the best schema option from anyOf/oneOf array.\n\n Selects the schema with the highest complexity score.\n \"\"\"\n best_option = None\n best_score = -1\n\n for item in union_array:\n score = _score_schema_option(item)\n if score > best_score:\n best_score = score\n best_option = item\n\n return dict(best_option) if isinstance(best_option, dict) else None\n\n\ndef _flatten_anyof_oneof_for_claude(schema: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Flatten anyOf/oneOf by selecting the best option and merging properties.\n\n Based on Antigravity-Manager's extract_best_schema_from_union logic.\n \"\"\"\n result = dict(schema)\n\n # Check for anyOf or oneOf\n for union_key in (\"anyOf\", \"oneOf\"):\n union_array = result.get(union_key)\n if not isinstance(union_array, list) or not union_array:\n continue\n\n # Only process if type is not already set or is \"object\"\n current_type = result.get(\"type\")\n if current_type and current_type not in (\"object\", \"null\"):\n # Type already set, just remove anyOf/oneOf\n result.pop(union_key, None)\n continue\n\n # Find best option\n best_branch = _extract_best_schema_from_union(union_array)\n if not best_branch:\n result.pop(union_key, None)\n continue\n\n # Merge properties from best branch\n if best_branch.get(\"properties\"):\n target_props = result.setdefault(\"properties\", {})\n for prop_key, prop_val in best_branch.get(\"properties\", {}).items():\n if prop_key not in target_props:\n target_props[prop_key] = prop_val\n\n # Merge required\n if best_branch.get(\"required\"):\n target_req = result.setdefault(\"required\", [])\n for req_item in best_branch.get(\"required\", []):\n if req_item not in target_req:\n target_req.append(req_item)\n\n # Copy type if not set\n if not result.get(\"type\") and best_branch.get(\"type\"):\n result[\"type\"] = best_branch[\"type\"]\n\n # Remove the union key\n result.pop(union_key, None)\n\n return result\n\n\ndef _flatten_type_array_for_claude(schema: Dict[str, Any]) -> Tuple[Dict[str, Any], bool]:\n \"\"\"Flatten type array to single type with nullable hint.\n\n E.g., [\"string\", \"null\"] -> \"string\" (returns is_nullable=True)\n\n Returns:\n Tuple of (modified schema, is_nullable)\n \"\"\"\n result = dict(schema)\n is_nullable = False\n\n type_val = result.get(\"type\")\n if isinstance(type_val, list):\n has_null = \"null\" in type_val\n non_null_types = [t for t in type_val if t != \"null\" and t]\n\n # Select first non-null type, or \"string\" as fallback\n first_type = non_null_types[0] if non_null_types else \"string\"\n result[\"type\"] = first_type.lower() # Keep lowercase for Claude\n\n # Track nullable for description hint\n if has_null:\n is_nullable = True\n elif isinstance(type_val, str):\n # Ensure lowercase\n result[\"type\"] = type_val.lower()\n if type_val.lower() == \"null\":\n is_nullable = True\n result[\"type\"] = \"string\" # Fallback\n\n return result, is_nullable\n\n\ndef _add_constraint_hints_for_claude(schema: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Move constraint fields to description hints.\n\n Based on Antigravity-Manager's constraint migration logic.\n \"\"\"\n result = dict(schema)\n hints = []\n\n for field, label in CLAUDE_CONSTRAINT_FIELDS:\n val = result.get(field)\n if val is not None:\n val_str = str(val) if not isinstance(val, str) else val\n hints.append(f\"{label}: {val_str}\")\n\n if hints:\n suffix = f\" [Constraint: {', '.join(hints)}]\"\n desc = result.get(\"description\", \"\")\n if suffix not in desc:\n result[\"description\"] = desc + suffix if desc else suffix.strip()\n\n return result\n\n\ndef _apply_whitelist_for_claude(schema: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Apply whitelist filtering - remove all fields not in CLAUDE_ALLOWED_SCHEMA_FIELDS.\"\"\"\n return {\n key: value\n for key, value in schema.items()\n if key in CLAUDE_ALLOWED_SCHEMA_FIELDS\n }\n\n\ndef _add_empty_object_placeholder_for_claude(schema: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Add placeholder property for empty object schemas.\n\n Claude VALIDATED mode requires at least one property in object schemas.\n \"\"\"\n result = dict(schema)\n\n if result.get(\"type\") == \"object\":\n props = result.get(\"properties\")\n has_props = props and isinstance(props, dict) and len(props) > 0\n\n if not has_props:\n result[\"properties\"] = {\n \"reason\": {\n \"type\": \"string\",\n \"description\": \"Reason for calling this tool\",\n }\n }\n result[\"required\"] = [\"reason\"]\n\n return result\n\n\ndef _fix_required_for_claude(schema: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Remove required entries that don't exist in properties.\"\"\"\n result = dict(schema)\n\n if isinstance(result.get(\"required\"), list) and isinstance(result.get(\"properties\"), dict):\n valid_props = set(result[\"properties\"].keys())\n result[\"required\"] = [r for r in result[\"required\"] if r in valid_props]\n if not result[\"required\"]:\n del result[\"required\"]\n\n return result\n\n\ndef clean_json_schema_for_claude(schema: Any) -> Dict[str, Any]:\n \"\"\"Clean JSON schema for Claude VALIDATED mode via Antigravity.\n\n This is a comprehensive cleaning function based on Antigravity-Manager's\n json_schema.rs implementation. It ensures schemas are compatible with\n Claude's strict JSON Schema draft 2020-12 validation.\n\n Key transformations:\n 1. Flatten $ref references\n 2. Merge allOf schemas\n 3. Flatten anyOf/oneOf to best option\n 4. Flatten type arrays ([\"string\", \"null\"] -> \"string\")\n 5. Move constraints to description hints\n 6. Apply whitelist filtering (only allowed fields kept)\n 7. Add placeholder for empty object schemas\n 8. Fix required fields\n\n Args:\n schema: JSON schema to clean\n\n Returns:\n Cleaned schema compatible with Claude VALIDATED mode\n \"\"\"\n if not schema or not isinstance(schema, dict):\n return {\n \"type\": \"object\",\n \"properties\": {\n \"reason\": {\n \"type\": \"string\",\n \"description\": \"Reason for calling this tool\",\n }\n },\n \"required\": [\"reason\"],\n }\n\n result = dict(schema)\n\n # Phase 1: Resolve $ref (reuse existing function)\n result = _resolve_refs(result)\n\n # Phase 2: Merge allOf\n result = _merge_all_of(result)\n\n # Phase 3: Flatten anyOf/oneOf\n result = _flatten_anyof_oneof_for_claude(result)\n\n # Phase 4: Flatten type arrays and track nullable\n result, is_nullable = _flatten_type_array_for_claude(result)\n\n # Phase 5: Add constraint hints\n result = _add_constraint_hints_for_claude(result)\n\n # Phase 6: Apply whitelist\n result = _apply_whitelist_for_claude(result)\n\n # Phase 7: Add placeholder for empty objects\n result = _add_empty_object_placeholder_for_claude(result)\n\n # Phase 8: Fix required fields\n result = _fix_required_for_claude(result)\n\n # Add nullable hint if needed\n if is_nullable:\n desc = result.get(\"description\", \"\")\n if \"(nullable)\" not in desc:\n result[\"description\"] = f\"{desc} (nullable)\" if desc else \"(nullable)\"\n\n # Ensure type is set\n if \"type\" not in result:\n result[\"type\"] = \"object\"\n\n # Recursively clean nested schemas\n if isinstance(result.get(\"properties\"), dict):\n cleaned_props = {}\n nullable_keys = set()\n for prop_key, prop_val in result[\"properties\"].items():\n if isinstance(prop_val, dict):\n cleaned = clean_json_schema_for_claude(prop_val)\n cleaned_props[prop_key] = cleaned\n # Track nullable properties\n if \"(nullable)\" in cleaned.get(\"description\", \"\"):\n nullable_keys.add(prop_key)\n else:\n cleaned_props[prop_key] = prop_val\n result[\"properties\"] = cleaned_props\n\n # Remove nullable fields from required\n if nullable_keys and isinstance(result.get(\"required\"), list):\n result[\"required\"] = [r for r in result[\"required\"] if r not in nullable_keys]\n if not result[\"required\"]:\n del result[\"required\"]\n\n if isinstance(result.get(\"items\"), dict):\n result[\"items\"] = clean_json_schema_for_claude(result[\"items\"])\n\n return result\n\n\n# =============================================================================\n# GEMINI SCHEMA TRANSFORMATION (Ported from antigravity-auth)\n# =============================================================================\n\n# Fields that Gemini API rejects - must be removed from schemas\n# Antigravity uses strict protobuf-backed JSON validation\nGEMINI_UNSUPPORTED_SCHEMA_FIELDS = {\n \"additionalProperties\",\n \"$schema\",\n \"$id\",\n \"$comment\",\n \"$ref\",\n \"$defs\",\n \"definitions\",\n \"const\",\n \"contentMediaType\",\n \"contentEncoding\",\n \"if\",\n \"then\",\n \"else\",\n \"not\",\n \"patternProperties\",\n \"unevaluatedProperties\",\n \"unevaluatedItems\",\n \"dependentRequired\",\n \"dependentSchemas\",\n \"propertyNames\",\n \"minContains\",\n \"maxContains\",\n}\n\n\ndef _resolve_refs(schema: Any, defs: Optional[Dict[str, Any]] = None) -> Any:\n \"\"\"Resolve $ref references in JSON Schema.\n\n Args:\n schema: JSON Schema that may contain $ref\n defs: Dictionary of definitions (from $defs or definitions)\n\n Returns:\n Schema with $ref replaced by actual definitions\n \"\"\"\n if not schema or not isinstance(schema, dict):\n return schema\n\n if isinstance(schema, list):\n return [_resolve_refs(item, defs) for item in schema]\n\n # Extract definitions from schema if present\n local_defs = schema.get(\"$defs\") or schema.get(\"definitions\") or {}\n if local_defs:\n defs = {**defs, **local_defs} if defs else local_defs\n\n # Check for $ref\n ref = schema.get(\"$ref\")\n if ref and isinstance(ref, str) and defs:\n # Parse ref like \"#/$defs/TodoItem\" or \"#/definitions/TodoItem\"\n if ref.startswith(\"#/$defs/\"):\n ref_name = ref[8:] # Remove \"#/$defs/\"\n if ref_name in defs:\n # Return resolved definition (recursively resolve any nested refs)\n return _resolve_refs(defs[ref_name], defs)\n elif ref.startswith(\"#/definitions/\"):\n ref_name = ref[14:] # Remove \"#/definitions/\"\n if ref_name in defs:\n return _resolve_refs(defs[ref_name], defs)\n\n # Recursively resolve refs in nested structures\n result: Dict[str, Any] = {}\n for key, value in schema.items():\n if key in (\"$defs\", \"definitions\"):\n # Don't include definitions in output\n continue\n elif key == \"properties\" and isinstance(value, dict):\n result[key] = {\n prop_name: _resolve_refs(prop_schema, defs)\n for prop_name, prop_schema in value.items()\n }\n elif key == \"items\":\n result[key] = _resolve_refs(value, defs)\n elif key in (\"anyOf\", \"oneOf\", \"allOf\") and isinstance(value, list):\n result[key] = [_resolve_refs(item, defs) for item in value]\n else:\n result[key] = value\n\n return result\n\n\ndef _convert_anyof_to_nullable(anyof_items: List[Any]) -> Optional[Dict[str, Any]]:\n \"\"\"Convert anyOf pattern with null to Gemini's nullable format.\n\n Common JSON Schema patterns for nullable fields:\n - anyOf: [{type: 'integer'}, {type: 'null'}]\n\n Gemini expects:\n - {type: 'INTEGER', nullable: true}\n\n Args:\n anyof_items: List of anyOf schema items\n\n Returns:\n Gemini-compatible schema with nullable, or None if not a nullable pattern\n \"\"\"\n if len(anyof_items) != 2:\n return None\n\n null_item = None\n non_null_item = None\n\n for item in anyof_items:\n if isinstance(item, dict):\n item_type = item.get(\"type\", \"\").lower()\n if item_type == \"null\":\n null_item = item\n else:\n non_null_item = item\n\n if null_item is not None and non_null_item is not None:\n # This is a nullable pattern: convert to Gemini format\n result = to_gemini_schema(non_null_item)\n if isinstance(result, dict):\n result[\"nullable\"] = True\n return result\n\n return None\n\n\ndef to_gemini_schema(schema: Any) -> Any:\n \"\"\"Transform a JSON Schema to Gemini-compatible format.\n\n Based on @google/genai SDK's processJsonSchema() function.\n Reference: antigravity-auth/src/plugin/transform/gemini.ts toGeminiSchema()\n\n Key transformations:\n - Converts type values to uppercase (object -> OBJECT, string -> STRING)\n - Removes unsupported fields ($schema, additionalProperties, etc.)\n - Recursively processes nested schemas (properties, items, anyOf, etc.)\n - Converts anyOf with null to nullable: true (Gemini format)\n - Ensures arrays have 'items' field (Gemini API requires it)\n\n Args:\n schema: A JSON Schema object or primitive value\n\n Returns:\n Gemini-compatible schema with uppercase types\n \"\"\"\n # Return primitives and arrays as-is\n if not schema or not isinstance(schema, dict):\n return schema\n\n if isinstance(schema, list):\n return [to_gemini_schema(item) for item in schema]\n\n result: Dict[str, Any] = {}\n\n # First pass: collect all property names for required validation\n property_names: set[str] = set()\n if isinstance(schema.get(\"properties\"), dict):\n property_names = set(schema[\"properties\"].keys())\n\n # Check for anyOf pattern that represents nullable - convert early\n anyof = schema.get(\"anyOf\")\n if isinstance(anyof, list):\n nullable_result = _convert_anyof_to_nullable(anyof)\n if nullable_result is not None:\n return nullable_result\n\n for key, value in schema.items():\n # Skip unsupported fields that Gemini API rejects\n if key in GEMINI_UNSUPPORTED_SCHEMA_FIELDS:\n continue\n\n if key == \"type\" and isinstance(value, str):\n # Convert type to uppercase for Gemini API\n result[key] = value.upper()\n elif key == \"properties\" and isinstance(value, dict):\n # Recursively transform nested property schemas\n props: Dict[str, Any] = {}\n for prop_name, prop_schema in value.items():\n props[prop_name] = to_gemini_schema(prop_schema)\n result[key] = props\n elif key == \"items\" and isinstance(value, dict):\n # Transform array items schema\n result[key] = to_gemini_schema(value)\n elif key in (\"anyOf\", \"oneOf\", \"allOf\") and isinstance(value, list):\n # For non-nullable anyOf/oneOf/allOf, skip them as Gemini doesn't support these\n # We've already handled the nullable pattern above\n # Just use the first non-null type as a fallback\n for item in value:\n if isinstance(item, dict) and item.get(\"type\", \"\").lower() != \"null\":\n transformed = to_gemini_schema(item)\n if isinstance(transformed, dict):\n for k, v in transformed.items():\n if k not in result:\n result[k] = v\n break\n # Don't include anyOf/oneOf/allOf in result - Gemini doesn't support them\n continue\n elif key == \"enum\" and isinstance(value, list):\n # Keep enum values as-is\n result[key] = value\n elif key in (\"default\", \"examples\"):\n # Keep default and examples as-is\n result[key] = value\n elif key == \"required\" and isinstance(value, list):\n # Filter required array to only include properties that exist\n # This fixes: \"parameters.required[X]: property is not defined\"\n if property_names:\n valid_required = [prop for prop in value if isinstance(prop, str) and prop in property_names]\n if valid_required:\n result[key] = valid_required\n # If no valid required properties, omit the required field entirely\n else:\n # If there are no properties, keep required as-is\n result[key] = value\n else:\n result[key] = value\n\n # Issue #80: Ensure array schemas have an 'items' field\n # Gemini API requires: \"parameters.properties[X].items: missing field\"\n if result.get(\"type\") == \"ARRAY\" and \"items\" not in result:\n result[\"items\"] = {\"type\": \"STRING\"}\n\n return result\n\n\ndef ensure_tool_has_properties(schema: Dict[str, Any], uppercase_types: bool = True) -> Dict[str, Any]:\n \"\"\"Ensure tool schema has at least one property for VALIDATED mode.\n\n Claude/Antigravity VALIDATED mode requires tool parameters to be an object schema\n with at least one property. This adds a placeholder if needed.\n\n Args:\n schema: Tool parameter schema\n uppercase_types: If True, use uppercase types (OBJECT, BOOLEAN) for Gemini/Antigravity\n\n Returns:\n Schema with guaranteed properties\n \"\"\"\n obj_type = \"OBJECT\" if uppercase_types else \"object\"\n bool_type = \"BOOLEAN\" if uppercase_types else \"boolean\"\n\n if not schema or not isinstance(schema, dict):\n return {\n \"type\": obj_type,\n \"properties\": {\n EMPTY_SCHEMA_PLACEHOLDER_NAME: {\n \"type\": bool_type,\n \"description\": EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,\n }\n },\n \"required\": [EMPTY_SCHEMA_PLACEHOLDER_NAME],\n }\n\n result = dict(schema)\n # Ensure type is uppercase for Gemini/Antigravity\n if uppercase_types:\n result[\"type\"] = \"OBJECT\"\n else:\n result[\"type\"] = \"object\"\n\n # Check if properties exist and are non-empty\n has_properties = isinstance(result.get(\"properties\"), dict) and len(result[\"properties\"]) > 0\n\n if not has_properties:\n result[\"properties\"] = {\n EMPTY_SCHEMA_PLACEHOLDER_NAME: {\n \"type\": bool_type,\n \"description\": EMPTY_SCHEMA_PLACEHOLDER_DESCRIPTION,\n }\n }\n required = result.get(\"required\", [])\n if isinstance(required, list):\n result[\"required\"] = list(set(required + [EMPTY_SCHEMA_PLACEHOLDER_NAME]))\n else:\n result[\"required\"] = [EMPTY_SCHEMA_PLACEHOLDER_NAME]\n\n return result\n\n\n# =============================================================================\n# TOOL HARDENING FUNCTIONS (Ported from antigravity-auth)\n# =============================================================================\n\n\ndef _format_type_hint(prop_data: Dict[str, Any]) -> str:\n \"\"\"Format a type hint string from property schema.\n\n Reference: antigravity-auth/src/plugin/request-helpers.ts formatTypeHint()\n \"\"\"\n prop_type = prop_data.get(\"type\", \"any\")\n\n if prop_type == \"array\":\n items = prop_data.get(\"items\", {})\n if isinstance(items, dict):\n items_type = items.get(\"type\", \"any\")\n return f\"array of {items_type}\"\n return \"array\"\n\n if prop_type == \"object\":\n return \"object\"\n\n return str(prop_type)\n\n\ndef inject_parameter_signatures(\n tools: List[Dict[str, Any]],\n prompt_template: str = CLAUDE_DESCRIPTION_PROMPT,\n) -> List[Dict[str, Any]]:\n \"\"\"Inject parameter signatures into tool descriptions (tool hardening).\n\n Appends a strict parameter signature to each tool description to prevent\n Claude from hallucinating parameters from training data.\n\n Reference: antigravity-auth/src/plugin/request-helpers.ts injectParameterSignatures()\n\n Args:\n tools: Gemini-style tools array (with functionDeclarations)\n prompt_template: Template for the signature (default: CLAUDE_DESCRIPTION_PROMPT)\n\n Returns:\n Modified tools array with signatures injected\n \"\"\"\n if not tools or not isinstance(tools, list):\n return tools\n\n result = []\n for tool in tools:\n if not isinstance(tool, dict):\n result.append(tool)\n continue\n\n declarations = tool.get(\"functionDeclarations\")\n if not isinstance(declarations, list):\n result.append(tool)\n continue\n\n new_declarations = []\n for decl in declarations:\n if not isinstance(decl, dict):\n new_declarations.append(decl)\n continue\n\n # Skip if signature already injected\n description = decl.get(\"description\", \"\")\n if \"STRICT PARAMETERS:\" in description:\n new_declarations.append(decl)\n continue\n\n schema = decl.get(\"parameters\") or decl.get(\"parametersJsonSchema\")\n if not schema or not isinstance(schema, dict):\n new_declarations.append(decl)\n continue\n\n required = schema.get(\"required\", [])\n if not isinstance(required, list):\n required = []\n\n properties = schema.get(\"properties\", {})\n if not isinstance(properties, dict) or not properties:\n new_declarations.append(decl)\n continue\n\n # Build parameter list\n param_list = []\n for prop_name, prop_data in properties.items():\n if prop_name == EMPTY_SCHEMA_PLACEHOLDER_NAME:\n continue\n if not isinstance(prop_data, dict):\n continue\n type_hint = _format_type_hint(prop_data)\n is_required = prop_name in required\n param_str = f\"{prop_name} ({type_hint}{', REQUIRED' if is_required else ''})\"\n param_list.append(param_str)\n\n if not param_list:\n new_declarations.append(decl)\n continue\n\n # Inject signature\n sig_str = prompt_template.replace(\"{params}\", \", \".join(param_list))\n new_decl = dict(decl)\n new_decl[\"description\"] = (description or \"\") + sig_str\n new_declarations.append(new_decl)\n\n result.append({**tool, \"functionDeclarations\": new_declarations})\n\n return result\n\n\ndef inject_tool_hardening_instruction(\n payload: Dict[str, Any],\n instruction_text: str = CLAUDE_TOOL_SYSTEM_INSTRUCTION,\n) -> None:\n \"\"\"Inject a tool hardening system instruction into the request payload.\n\n Prepends the instruction to the systemInstruction to prevent Claude from\n hallucinating tool parameters.\n\n Reference: antigravity-auth/src/plugin/request-helpers.ts injectToolHardeningInstruction()\n\n Args:\n payload: The Gemini request payload (modified in place)\n instruction_text: The instruction text to inject\n \"\"\"\n if not instruction_text:\n return\n\n existing = payload.get(\"systemInstruction\")\n\n # Skip if instruction already present\n if existing and isinstance(existing, dict) and \"parts\" in existing:\n parts = existing.get(\"parts\", [])\n if isinstance(parts, list) and any(\n isinstance(p, dict) and \"CRITICAL TOOL USAGE INSTRUCTIONS\" in (p.get(\"text\") or \"\")\n for p in parts\n ):\n return\n\n instruction_part = {\"text\": instruction_text}\n\n if payload.get(\"systemInstruction\"):\n if isinstance(existing, dict) and \"parts\" in existing:\n parts = existing.get(\"parts\", [])\n if isinstance(parts, list):\n parts.insert(0, instruction_part)\n elif isinstance(existing, str):\n payload[\"systemInstruction\"] = {\n \"role\": \"user\",\n \"parts\": [instruction_part, {\"text\": existing}],\n }\n else:\n payload[\"systemInstruction\"] = {\n \"role\": \"user\",\n \"parts\": [instruction_part],\n }\n else:\n payload[\"systemInstruction\"] = {\n \"role\": \"user\",\n \"parts\": [instruction_part],\n }\n\n\n# =============================================================================\n# THINKING SIGNATURE MANAGEMENT (Claude multi-turn conversations)\n# =============================================================================\n\n\ndef has_signed_thinking_part(part: Dict[str, Any]) -> bool:\n \"\"\"Check if a part has a valid signed thinking signature.\n\n Reference: antigravity-auth/src/plugin/request.ts hasSignedThinkingPart()\n \"\"\"\n if not part or not isinstance(part, dict):\n return False\n\n # Gemini format: thought=true + thoughtSignature\n if part.get(\"thought\") is True:\n sig = part.get(\"thoughtSignature\", \"\")\n return isinstance(sig, str) and len(sig) >= MIN_SIGNATURE_LENGTH\n\n # Anthropic format: type=thinking/redacted_thinking + signature\n part_type = part.get(\"type\", \"\")\n if part_type in (\"thinking\", \"redacted_thinking\"):\n sig = part.get(\"signature\", \"\")\n return isinstance(sig, str) and len(sig) >= MIN_SIGNATURE_LENGTH\n\n return False\n\n\ndef ensure_thinking_signature_for_tool_use(\n contents: List[Dict[str, Any]],\n session_key: str,\n) -> List[Dict[str, Any]]:\n \"\"\"Ensure thinking blocks have signatures before tool use parts.\n\n For Claude thinking models, tool use requires signed thinking to precede it.\n If no valid signed thinking is found, inject the SKIP_THOUGHT_SIGNATURE sentinel.\n\n Reference: antigravity-auth/src/plugin/request.ts ensureThinkingBeforeToolUseInContents()\n\n Args:\n contents: Gemini-style contents array\n session_key: Session key for signature caching\n\n Returns:\n Modified contents with thinking signatures ensured\n \"\"\"\n result = []\n\n for content in contents:\n if not isinstance(content, dict) or not isinstance(content.get(\"parts\"), list):\n result.append(content)\n continue\n\n role = content.get(\"role\")\n if role not in (\"model\", \"assistant\"):\n result.append(content)\n continue\n\n parts = content[\"parts\"]\n\n # Check if this content has tool use (functionCall)\n has_tool_use = any(\n isinstance(p, dict) and (\"functionCall\" in p or \"tool_use\" in p or \"toolUse\" in p)\n for p in parts\n )\n if not has_tool_use:\n result.append(content)\n continue\n\n # Separate thinking parts from other parts\n thinking_parts = []\n other_parts = []\n\n for part in parts:\n if not isinstance(part, dict):\n other_parts.append(part)\n continue\n\n is_thinking = (\n part.get(\"thought\") is True\n or part.get(\"type\") in (\"thinking\", \"reasoning\", \"redacted_thinking\")\n )\n if is_thinking:\n thinking_parts.append(part)\n else:\n other_parts.append(part)\n\n # Check if we have a valid signed thinking\n has_signed = any(has_signed_thinking_part(p) for p in thinking_parts)\n\n if has_signed:\n # Put thinking parts first, then other parts\n result.append({**content, \"parts\": thinking_parts + other_parts})\n else:\n # No valid signed thinking - inject sentinel signature\n # This allows Claude to proceed without blocking on signature validation\n existing_thinking = thinking_parts[0] if thinking_parts else {}\n thinking_text = existing_thinking.get(\"thinking\") or existing_thinking.get(\"text\") or \"\"\n\n sentinel_block = {\n \"type\": \"thinking\",\n \"thinking\": thinking_text,\n \"signature\": SKIP_THOUGHT_SIGNATURE,\n }\n\n logger.debug(\n \"Injecting sentinel signature for tool use (session=%s)\", session_key\n )\n result.append({**content, \"parts\": [sentinel_block] + other_parts})\n\n return result\n\n\n# =============================================================================\n# TOOL DEFINITION CONVERSION\n# =============================================================================\n\n\ndef convert_tools_to_gemini_format(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n \"\"\"Convert OpenAI-style tools to Gemini functionDeclarations format.\n\n OpenAI format:\n [{\"type\": \"function\", \"function\": {\"name\": \"...\", \"description\": \"...\", \"parameters\": {...}}}]\n\n Gemini format:\n [{\"functionDeclarations\": [{\"name\": \"...\", \"description\": \"...\", \"parameters\": {...}}]}]\n\n Key transformations for Gemini compatibility:\n - Types converted to uppercase (string -> STRING, object -> OBJECT)\n - Unsupported fields removed ($schema, additionalProperties, etc.)\n - Arrays ensured to have 'items' field\n - Required fields validated against existing properties\n\n Args:\n tools: OpenAI-style tool definitions\n\n Returns:\n Gemini-style tool definitions with uppercase type schemas\n \"\"\"\n if not tools:\n return []\n\n function_declarations = []\n\n for tool in tools:\n if not isinstance(tool, dict):\n continue\n\n # Handle OpenAI function tool format\n if tool.get(\"type\") == \"function\" and isinstance(tool.get(\"function\"), dict):\n func = tool[\"function\"]\n declaration: Dict[str, Any] = {\n \"name\": func.get(\"name\", \"\"),\n \"description\": func.get(\"description\", \"\"),\n }\n if \"parameters\" in func:\n # Resolve $ref references first, then transform to Gemini format\n resolved_params = _resolve_refs(func[\"parameters\"])\n gemini_params = to_gemini_schema(resolved_params)\n declaration[\"parameters\"] = gemini_params\n else:\n # Provide default placeholder schema for tools without parameters\n declaration[\"parameters\"] = {\n \"type\": \"OBJECT\",\n \"properties\": {\n \"_placeholder\": {\n \"type\": \"BOOLEAN\",\n \"description\": \"Placeholder. Always pass true.\",\n }\n },\n \"required\": [\"_placeholder\"],\n }\n function_declarations.append(declaration)\n\n # Handle direct function declaration\n elif \"name\" in tool:\n declaration = {\n \"name\": tool.get(\"name\", \"\"),\n \"description\": tool.get(\"description\", \"\"),\n }\n params = tool.get(\"parameters\") or tool.get(\"input_schema\") or tool.get(\"inputSchema\")\n if params:\n # Resolve $ref references first, then transform to Gemini format\n resolved_params = _resolve_refs(params)\n gemini_params = to_gemini_schema(resolved_params)\n declaration[\"parameters\"] = gemini_params\n else:\n # Provide default placeholder schema\n declaration[\"parameters\"] = {\n \"type\": \"OBJECT\",\n \"properties\": {\n \"_placeholder\": {\n \"type\": \"BOOLEAN\",\n \"description\": \"Placeholder. Always pass true.\",\n }\n },\n \"required\": [\"_placeholder\"],\n }\n function_declarations.append(declaration)\n\n # Handle already wrapped functionDeclarations\n elif \"functionDeclarations\" in tool:\n # Transform schemas in existing declarations\n for decl in tool[\"functionDeclarations\"]:\n cleaned_decl = dict(decl)\n if \"parameters\" in cleaned_decl:\n # Resolve $ref references first, then transform to Gemini format\n resolved_params = _resolve_refs(cleaned_decl[\"parameters\"])\n cleaned_decl[\"parameters\"] = to_gemini_schema(resolved_params)\n else:\n cleaned_decl[\"parameters\"] = {\n \"type\": \"OBJECT\",\n \"properties\": {},\n }\n function_declarations.append(cleaned_decl)\n\n if not function_declarations:\n return []\n\n return [{\"functionDeclarations\": function_declarations}]\n\n\ndef convert_tools_to_claude_format(\n tools: List[Dict[str, Any]],\n inject_signatures: bool = True,\n) -> List[Dict[str, Any]]:\n \"\"\"Convert OpenAI-style tools to Claude format with schema cleaning.\n\n Applies:\n - Conversion to functionDeclarations format\n - JSON schema cleaning for VALIDATED mode\n - Optional parameter signature injection (tool hardening)\n\n Args:\n tools: OpenAI-style tool definitions\n inject_signatures: Whether to inject parameter signatures into descriptions\n\n Returns:\n Claude-style tool definitions with cleaned schemas\n \"\"\"\n if not tools:\n return []\n\n function_declarations = []\n\n for tool in tools:\n if not isinstance(tool, dict):\n continue\n\n # Extract function info\n func = None\n if tool.get(\"type\") == \"function\" and isinstance(tool.get(\"function\"), dict):\n func = tool[\"function\"]\n elif \"name\" in tool:\n func = tool\n elif \"functionDeclarations\" in tool:\n # Already in Claude format, just clean schemas\n for decl in tool[\"functionDeclarations\"]:\n cleaned = dict(decl)\n if \"parameters\" in cleaned:\n # Use Claude-specific schema cleaning for VALIDATED mode\n cleaned[\"parameters\"] = clean_json_schema_for_claude(cleaned[\"parameters\"])\n function_declarations.append(cleaned)\n continue\n\n if not func:\n continue\n\n # Build declaration\n name = str(func.get(\"name\", \"\")).replace(\" \", \"_\")[:64]\n description = func.get(\"description\", \"\")\n\n # Get parameters\n params = (\n func.get(\"parameters\")\n or func.get(\"input_schema\")\n or func.get(\"inputSchema\")\n or {\"type\": \"object\", \"properties\": {}}\n )\n\n # Clean schema using Claude-specific cleaning for VALIDATED mode\n cleaned_params = clean_json_schema_for_claude(params)\n\n # Optionally inject parameter signatures into description (tool hardening)\n if inject_signatures and cleaned_params.get(\"properties\"):\n sig_parts = []\n for param_name, param_schema in cleaned_params[\"properties\"].items():\n if param_name == EMPTY_SCHEMA_PLACEHOLDER_NAME:\n continue\n param_type = param_schema.get(\"type\", \"any\")\n sig_parts.append(f\"{param_name}: {param_type}\")\n if sig_parts:\n signature = f\"({', '.join(sig_parts)})\"\n if description:\n description = f\"{description} {signature}\"\n else:\n description = signature\n\n declaration = {\n \"name\": name,\n \"description\": description,\n \"parameters\": cleaned_params,\n }\n function_declarations.append(declaration)\n\n if not function_declarations:\n return []\n\n return [{\"functionDeclarations\": function_declarations}]\n\n\ndef convert_tools_to_codex_format(tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n \"\"\"Convert OpenAI-style tools to ChatGPT Codex (Responses API) format.\n\n OpenAI Chat Completions format:\n [{\"type\": \"function\", \"function\": {\"name\": \"...\", \"description\": \"...\", \"parameters\": {...}}}]\n\n OpenAI Responses format (Codex API):\n [{\"type\": \"function\", \"name\": \"...\", \"description\": \"...\", \"parameters\": {...}}]\n\n The key difference is that Responses format has name/description at the top level\n alongside type, not nested under a \"function\" key.\n\n Args:\n tools: OpenAI Chat Completions-style tool definitions\n\n Returns:\n OpenAI Responses-style tool definitions for Codex API\n \"\"\"\n if not tools:\n return []\n\n codex_tools = []\n\n for tool in tools:\n if not isinstance(tool, dict):\n continue\n\n # Handle OpenAI Chat Completions format (nested under \"function\")\n if tool.get(\"type\") == \"function\" and isinstance(tool.get(\"function\"), dict):\n func = tool[\"function\"]\n codex_tool: Dict[str, Any] = {\n \"type\": \"function\",\n \"name\": func.get(\"name\", \"\"),\n }\n if \"description\" in func:\n codex_tool[\"description\"] = func[\"description\"]\n if \"parameters\" in func:\n codex_tool[\"parameters\"] = func[\"parameters\"]\n if \"strict\" in func:\n codex_tool[\"strict\"] = func[\"strict\"]\n codex_tools.append(codex_tool)\n\n # Handle already-converted Responses format or direct format\n elif \"type\" in tool and \"name\" in tool:\n # Already in Responses format, pass through\n codex_tools.append(tool)\n\n # Handle direct function declaration (no type wrapper)\n elif \"name\" in tool:\n codex_tool = {\n \"type\": \"function\",\n \"name\": tool.get(\"name\", \"\"),\n }\n if \"description\" in tool:\n codex_tool[\"description\"] = tool[\"description\"]\n params = tool.get(\"parameters\") or tool.get(\"input_schema\")\n if params:\n codex_tool[\"parameters\"] = params\n codex_tools.append(codex_tool)\n\n return codex_tools\n\n\n# =============================================================================\n# TOOL MESSAGE CONVERSION (OpenAI → Gemini/Claude format)\n# =============================================================================\n\n\ndef convert_tool_message_to_gemini_part(msg: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Convert an OpenAI tool result message to a Gemini functionResponse part.\n\n OpenAI format:\n {\"role\": \"tool\", \"tool_call_id\": \"...\", \"name\": \"...\", \"content\": \"...\"}\n\n Gemini format:\n {\"functionResponse\": {\"name\": \"...\", \"response\": {...}}}\n\n Args:\n msg: OpenAI-style tool result message\n\n Returns:\n Gemini-style functionResponse part\n \"\"\"\n name = msg.get(\"name\", msg.get(\"tool_name\", \"unknown_function\"))\n content = msg.get(\"content\", \"\")\n\n # Try to parse content as JSON\n response_data: Any\n if isinstance(content, str):\n try:\n response_data = json.loads(content)\n except json.JSONDecodeError:\n response_data = {\"result\": content}\n elif isinstance(content, dict):\n response_data = content\n else:\n response_data = {\"result\": str(content)}\n\n return {\n \"functionResponse\": {\n \"name\": name,\n \"response\": response_data,\n }\n }\n\n\ndef convert_tool_calls_to_gemini_parts(tool_calls: List[Any]) -> List[Dict[str, Any]]:\n \"\"\"Convert OpenAI tool_calls to Gemini functionCall parts.\n\n OpenAI format:\n [{\"id\": \"...\", \"function\": {\"name\": \"...\", \"arguments\": \"...\"}, \"thought_signature\": \"...\"}]\n\n Gemini format:\n [{\"functionCall\": {\"name\": \"...\", \"args\": {...}}, \"thoughtSignature\": \"...\"}]\n\n Note: thoughtSignature is required for Gemini 3 models. It's preserved from the\n original response and must be passed back exactly as received. If not found in\n the tool call, attempts to retrieve from cache.\n\n Args:\n tool_calls: OpenAI-style tool calls (may be dicts or ChatCompletionMessageToolCall objects)\n\n Returns:\n Gemini-style functionCall parts (with thoughtSignature if present or cached)\n \"\"\"\n parts = []\n for call in tool_calls:\n # Handle both dict and ChatCompletionMessageToolCall objects\n call_id = None\n if isinstance(call, dict):\n call_id = call.get(\"id\")\n func = call.get(\"function\", {})\n if isinstance(func, dict):\n name = func.get(\"name\", call.get(\"name\", \"\"))\n args_str = func.get(\"arguments\", call.get(\"arguments\", \"{}\"))\n else:\n # func might be a Function object\n name = getattr(func, \"name\", call.get(\"name\", \"\"))\n args_str = getattr(func, \"arguments\", call.get(\"arguments\", \"{}\"))\n # Get thought_signature from dict\n thought_sig = call.get(\"thought_signature\") or call.get(\"thoughtSignature\")\n else:\n # Handle ChatCompletionMessageToolCall objects (from LiteLLM)\n call_id = getattr(call, \"id\", None)\n func = getattr(call, \"function\", None)\n if func:\n name = getattr(func, \"name\", \"\")\n args_str = getattr(func, \"arguments\", \"{}\")\n else:\n name = getattr(call, \"name\", \"\")\n args_str = getattr(call, \"arguments\", \"{}\")\n # Try to get thought_signature from object attributes\n thought_sig = getattr(call, \"thought_signature\", None) or getattr(\n call, \"thoughtSignature\", None\n )\n\n # If thought_signature not found, try to retrieve from cache (call_id required)\n if not thought_sig and call_id and name:\n thought_sig = get_cached_thought_signature(call_id, name)\n\n # Parse arguments\n if isinstance(args_str, str):\n try:\n args = json.loads(args_str)\n except json.JSONDecodeError:\n args = {}\n else:\n args = args_str or {}\n\n part: Dict[str, Any] = {\n \"functionCall\": {\n \"name\": name,\n \"args\": args,\n }\n }\n\n # Preserve thoughtSignature for Gemini 3 models\n if thought_sig:\n part[\"thoughtSignature\"] = thought_sig\n\n parts.append(part)\n\n return parts\n\n\n# =============================================================================\n# TOOL ID MANAGEMENT (Claude/Antigravity)\n# =============================================================================\n\n\ndef assign_tool_call_ids(\n contents: List[Dict[str, Any]],\n) -> Tuple[List[Dict[str, Any]], Dict[str, List[str]]]:\n \"\"\"Pass 1: Assign IDs to functionCall parts.\n\n Generates unique IDs for functionCall parts that don't have them.\n Returns the modified contents and a dict of pending call IDs by function name.\n\n Args:\n contents: Gemini-style contents array\n\n Returns:\n Tuple of (modified contents, pending IDs by function name)\n \"\"\"\n pending_by_name: Dict[str, List[str]] = defaultdict(list)\n result = []\n\n for content in contents:\n if not isinstance(content, dict):\n result.append(content)\n continue\n\n parts = content.get(\"parts\")\n if not isinstance(parts, list):\n result.append(content)\n continue\n\n new_parts = []\n for part in parts:\n if not isinstance(part, dict):\n new_parts.append(part)\n continue\n\n if \"functionCall\" in part:\n call = dict(part[\"functionCall\"])\n if not call.get(\"id\"):\n call[\"id\"] = f\"tool-call-{uuid.uuid4().hex[:8]}\"\n name = call.get(\"name\", \"unknown\")\n pending_by_name[name].append(call[\"id\"])\n new_parts.append({**part, \"functionCall\": call})\n else:\n new_parts.append(part)\n\n result.append({**content, \"parts\": new_parts})\n\n return result, dict(pending_by_name)\n\n\ndef match_tool_response_ids(\n contents: List[Dict[str, Any]],\n pending_by_name: Dict[str, List[str]],\n) -> List[Dict[str, Any]]:\n \"\"\"Pass 2: Match functionResponse IDs using FIFO queue per function name.\n\n Assigns IDs to functionResponse parts by matching them to pending\n functionCall IDs in FIFO order.\n\n Args:\n contents: Gemini-style contents array (already processed by pass 1)\n pending_by_name: Dict of pending call IDs by function name\n\n Returns:\n Modified contents with matched response IDs\n \"\"\"\n # Create a mutable copy of pending queues\n queues = {name: list(ids) for name, ids in pending_by_name.items()}\n result = []\n\n for content in contents:\n if not isinstance(content, dict):\n result.append(content)\n continue\n\n parts = content.get(\"parts\")\n if not isinstance(parts, list):\n result.append(content)\n continue\n\n new_parts = []\n for part in parts:\n if not isinstance(part, dict):\n new_parts.append(part)\n continue\n\n if \"functionResponse\" in part:\n resp = dict(part[\"functionResponse\"])\n name = resp.get(\"name\", \"unknown\")\n\n # Try to match with pending call\n if not resp.get(\"id\") and name in queues and queues[name]:\n resp[\"id\"] = queues[name].pop(0) # FIFO\n\n new_parts.append({**part, \"functionResponse\": resp})\n else:\n new_parts.append(part)\n\n result.append({**content, \"parts\": new_parts})\n\n return result\n\n\ndef fix_tool_response_grouping(contents: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n \"\"\"Pass 3: Orphan recovery - fix mismatched tool call/response pairs.\n\n Handles cases where functionResponse parts don't have matching IDs\n by attempting to pair them with unmatched functionCall parts.\n\n Args:\n contents: Gemini-style contents array\n\n Returns:\n Modified contents with orphan responses fixed\n \"\"\"\n # First, collect all call IDs and response IDs\n all_call_ids: Dict[str, List[str]] = defaultdict(list) # name -> [ids]\n all_response_ids: Dict[str, List[str]] = defaultdict(list) # name -> [ids]\n call_names: Dict[str, str] = {} # id -> name\n\n for content in contents:\n if not isinstance(content, dict):\n continue\n parts = content.get(\"parts\", [])\n if not isinstance(parts, list):\n continue\n\n for part in parts:\n if not isinstance(part, dict):\n continue\n if \"functionCall\" in part:\n call = part[\"functionCall\"]\n call_id = call.get(\"id\")\n name = call.get(\"name\", \"unknown\")\n if call_id:\n all_call_ids[name].append(call_id)\n call_names[call_id] = name\n elif \"functionResponse\" in part:\n resp = part[\"functionResponse\"]\n resp_id = resp.get(\"id\")\n name = resp.get(\"name\", \"unknown\")\n if resp_id:\n all_response_ids[name].append(resp_id)\n\n # Find orphaned responses (responses without matching calls)\n result = []\n for content in contents:\n if not isinstance(content, dict):\n result.append(content)\n continue\n\n parts = content.get(\"parts\", [])\n if not isinstance(parts, list):\n result.append(content)\n continue\n\n new_parts = []\n for part in parts:\n if not isinstance(part, dict):\n new_parts.append(part)\n continue\n\n if \"functionResponse\" in part:\n resp = dict(part[\"functionResponse\"])\n resp_id = resp.get(\"id\")\n name = resp.get(\"name\", \"unknown\")\n\n # Check if this response's ID matches any call\n if resp_id and resp_id not in call_names:\n # Try to find an unmatched call with the same name\n if name in all_call_ids and all_call_ids[name]:\n unmatched = [\n cid\n for cid in all_call_ids[name]\n if cid not in all_response_ids.get(name, [])\n ]\n if unmatched:\n resp[\"id\"] = unmatched[0]\n all_response_ids[name].append(unmatched[0])\n\n new_parts.append({**part, \"functionResponse\": resp})\n else:\n new_parts.append(part)\n\n result.append({**content, \"parts\": new_parts})\n\n return result\n\n\ndef apply_tool_pairing_fixes(\n payload: Dict[str, Any],\n is_claude: bool = False,\n) -> Dict[str, Any]:\n \"\"\"Apply all tool pairing fixes to a request payload.\n\n Runs the full 3-pass tool ID management pipeline:\n 1. Assign IDs to functionCall parts\n 2. Match functionResponse IDs using FIFO\n 3. Orphan recovery\n\n Args:\n payload: Request payload with 'contents' array\n is_claude: Whether this is for Claude (enables additional validation)\n\n Returns:\n Modified payload with fixed tool pairing\n \"\"\"\n if \"contents\" not in payload or not isinstance(payload[\"contents\"], list):\n return payload\n\n result = dict(payload)\n\n # Pass 1: Assign IDs\n contents_with_ids, pending = assign_tool_call_ids(result[\"contents\"])\n\n # Pass 2: Match response IDs\n contents_matched = match_tool_response_ids(contents_with_ids, pending)\n\n # Pass 3: Orphan recovery\n result[\"contents\"] = fix_tool_response_grouping(contents_matched)\n\n return result\n\n\n# =============================================================================\n# TOOL CALL EXTRACTION FROM RESPONSES\n# =============================================================================\n\n\ndef extract_tool_calls_from_gemini_response(\n data: Dict[str, Any],\n session_id: Optional[str] = None,\n message_count: Optional[int] = None,\n) -> Optional[List[Dict[str, Any]]]:\n \"\"\"Extract functionCall parts from Gemini/Antigravity response.\n\n Preserves thoughtSignature for Gemini 3 models - this must be passed back\n exactly as received when sending tool results. Also caches the signature\n for retrieval during follow-up calls (since LiteLLM streaming may lose it).\n\n Args:\n data: Response data from Gemini API\n\n Returns:\n List of OpenAI-style tool calls (with thought_signature if present),\n or None if no tool calls found\n \"\"\"\n # Handle wrapped response\n if \"response\" in data:\n data = data[\"response\"]\n\n candidates = data.get(\"candidates\", [])\n if not candidates:\n return None\n\n tool_calls = []\n for candidate in candidates:\n content = candidate.get(\"content\", {})\n parts = content.get(\"parts\", [])\n current_thought_sig: Optional[str] = None\n\n for part in parts:\n if not isinstance(part, dict):\n continue\n\n # Cache thoughtSignature from thinking parts (Gemini 3)\n thought_sig = _extract_part_thought_signature(part)\n if thought_sig and (part.get(\"thought\") is True or part.get(\"type\") in (\"thinking\", \"reasoning\")):\n current_thought_sig = thought_sig\n cache_thinking_signature(thought_sig)\n if session_id and message_count is not None:\n cache_session_signature(session_id, thought_sig, message_count)\n\n if \"functionCall\" in part:\n func_call = part[\"functionCall\"]\n name = func_call.get(\"name\", \"\")\n args = func_call.get(\"args\", {})\n call_id = func_call.get(\"id\", f\"call_{uuid.uuid4().hex[:8]}\")\n\n # Convert to OpenAI format\n tool_call: Dict[str, Any] = {\n \"id\": call_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": name,\n \"arguments\": json.dumps(args) if isinstance(args, dict) else str(args),\n },\n }\n\n # Preserve thoughtSignature for Gemini 3 models\n # Store as snake_case in OpenAI format for consistency\n thought_sig = _extract_part_thought_signature(part) or current_thought_sig\n if thought_sig:\n tool_call[\"thought_signature\"] = thought_sig\n # Also cache for retrieval during follow-up calls\n cache_thought_signature(call_id, name, thought_sig)\n if session_id and message_count is not None:\n cache_session_signature(session_id, thought_sig, message_count)\n\n tool_calls.append(tool_call)\n\n return tool_calls if tool_calls else None\n\n\ndef extract_tool_calls_from_codex_response(\n data: Dict[str, Any],\n) -> Optional[List[Dict[str, Any]]]:\n \"\"\"Extract function_call items from ChatGPT Codex response.\n\n Args:\n data: Response data from Codex API (from response.done event)\n\n Returns:\n List of OpenAI-style tool calls, or None if no tool calls found\n \"\"\"\n output = data.get(\"output\", [])\n if not isinstance(output, list):\n return None\n\n tool_calls = []\n for item in output:\n if not isinstance(item, dict):\n continue\n\n if item.get(\"type\") == \"function_call\":\n call_id = item.get(\"call_id\", f\"call_{uuid.uuid4().hex[:8]}\")\n name = item.get(\"name\", \"\")\n arguments = item.get(\"arguments\", \"{}\")\n\n # Ensure arguments is a string\n if isinstance(arguments, dict):\n arguments = json.dumps(arguments)\n\n tool_calls.append(\n {\n \"id\": call_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": name,\n \"arguments\": arguments,\n },\n }\n )\n\n return tool_calls if tool_calls else None\n\n\ndef build_tool_calls_response_message(\n tool_calls: List[Dict[str, Any]],\n) -> Dict[str, Any]:\n \"\"\"Build an assistant message with tool_calls for ModelResponse.\n\n Args:\n tool_calls: List of OpenAI-style tool calls\n\n Returns:\n Assistant message dict with tool_calls\n \"\"\"\n return {\n \"role\": \"assistant\",\n \"content\": None,\n \"tool_calls\": tool_calls,\n }\n","numLines":2338,"startLine":1,"totalLines":2338}}},{"type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"File content (32357 tokens) exceeds maximum allowed tokens (25000). Please use offset and limit parameters to read specific portions of the file, or use the GrepTool to search for specific content.","is_error":true,"tool_use_id":"toolu_011Ua1nF3qgs2y4W5mxc9UTD"}]},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"ef13538b-5103-4d29-bacf-bbe4aa1c19c4","tool_use_result":"Error: File content (32357 tokens) exceeds maximum allowed tokens (25000). Please use offset and limit parameters to read specific portions of the file, or use the GrepTool to search for specific content."},{"type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"File content (26140 tokens) exceeds maximum allowed tokens (25000). Please use offset and limit parameters to read specific portions of the file, or use the GrepTool to search for specific content.","is_error":true,"tool_use_id":"toolu_01MbhXqYVtKTceNRnXQgoenT"}]},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"12b8ebf5-edba-4677-bbf0-beb6f25e055b","tool_use_result":"Error: File content (26140 tokens) exceeds maximum allowed tokens (25000). Please use offset and limit parameters to read specific portions of the file, or use the GrepTool to search for specific content."},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01UQG29MBMoLvdZ6oKVGZq3g","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"Good, I have the full tool_utils.py file. Now I need to read the Antigravity-Manager request.rs file in chunks, and also the litellm_oauth.py file in chunks. Let me read them in parts.\n\nLet me read the critical sections of request.rs first - focusing on thinking/signature handling.","signature":"EsEDCkYICxgCKkDafBl0F0MdSSvuJ5UCcQniUZczS0tPFOJAX33wtGblxe2GUnDENSI9LENxcqewfywLZ2xscTYl8KRAPHT0UKvHEgwshNyx62b3sT7cHJoaDHqhuVwkKfoQSWbOZyIwRT0OzvVwNI5sJCtajOUEUbh56d3gmNLpYVgQF+ESRQqWP7AFGFCjXTF1oKuk8d9QKqgCpmiaOyvCBpO9DiXfOMcigFqY7KtV289pK5PETnz4IHU8R+ieiIQEtts+NxdLTWPMopDvYQADTTIogu1z5AsroqTIC2SKKIxM7hInRXKHipHcSWRbs5hfq8nWsRui6DDtrVM2io9mNRMSZO3AUj3jiS+PkTfOTd49srX601tSJr9JXu6lBDjHKA664gwrfEPiugW8CNI6WzBvd9aJvEm4aDrxsgWDDOF/nsTYJq+/y7BJmyIuxm3znMg00c6jmW9oQBe7tH6eRfogol1dL8Jv1uxq+jdag9CjprO6q/6foAktQM/DIaeohsnZ5sGHQ8wrK81uFRcn8ZaPkN8I/Hm1ePBEuf8KWc6OODzc2PMu6wvKKuG73qXXNebWbNsNFTbkG01ugbzCrNkYAQ=="}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":30308,"cache_creation_input_tokens":425,"cache_read_input_tokens":37343,"cache_creation":{"ephemeral_5m_input_tokens":425,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"f6286e59-5ea4-4a7c-9d3c-ac44bf04a86c"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01UQG29MBMoLvdZ6oKVGZq3g","type":"message","role":"assistant","content":[{"type":"text","text":"Let me read the Antigravity-Manager request.rs file in sections, focusing on the thinking/signature handling logic."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":30308,"cache_creation_input_tokens":425,"cache_read_input_tokens":37343,"cache_creation":{"ephemeral_5m_input_tokens":425,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"1cdfa12c-cb21-4619-ab0d-24fe9535a45e"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01UQG29MBMoLvdZ6oKVGZq3g","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_013B9bADxMv9wpMh4yRPmTeD","name":"Grep","input":{"pattern":"thinking|signature|thought","path":"/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs","output_mode":"content","-n":true,"-C":3},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":30308,"cache_creation_input_tokens":425,"cache_read_input_tokens":37343,"cache_creation":{"ephemeral_5m_input_tokens":425,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"4b89a0c1-1233-4109-9ff2-6978e65cc8fd"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01UQG29MBMoLvdZ6oKVGZq3g","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01HsGQK1T6Z56qkFAKKF7kPu","name":"Grep","input":{"pattern":"SKIP_THOUGHT|sentinel|MIN_SIGNATURE|wrap_request|backfill","path":"/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude","output_mode":"content","-n":true,"-C":3},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":30308,"cache_creation_input_tokens":425,"cache_read_input_tokens":37343,"cache_creation":{"ephemeral_5m_input_tokens":425,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"a47f0185-4254-4ca5-9aec-8dc107987e1e"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01UQG29MBMoLvdZ6oKVGZq3g","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01AfQZQq16rexeFbLcPpPqdj","name":"Grep","input":{"pattern":"thinking|signature|thought","path":"/Users/fei/coding-agent/koder/koder_agent/auth/litellm_oauth.py","output_mode":"content","-n":true,"-C":3},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":30308,"cache_creation_input_tokens":425,"cache_read_input_tokens":37343,"cache_creation":{"ephemeral_5m_input_tokens":425,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"0f37711a-036f-42f9-b96e-5432a34221c8"},{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01HsGQK1T6Z56qkFAKKF7kPu","type":"tool_result","content":"/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-2-use crate::proxy::SignatureCache;\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-3-use tracing::{debug, info, warn};\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-4-\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs:5:pub const MIN_SIGNATURE_LENGTH: usize = 50;\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-6-\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-7-#[derive(Debug, Default)]\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-8-pub struct ConversationState {\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-114- if !thinking.is_empty()\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-115- && signature\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-116- .as_ref()\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs:117: .map(|s| s.len() >= MIN_SIGNATURE_LENGTH)\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-118- .unwrap_or(false)\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-119- {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-120- has_valid_thinking = true;\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-190- if let ContentBlock::Thinking { signature, .. } = block {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-191- // 1. Basic length check - allow empty signatures to pass through for compatibility\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-192- let sig = match signature {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs:193: Some(s) if s.len() >= MIN_SIGNATURE_LENGTH || s.is_empty() => s,\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-194- None => return true, // Allow None signatures to pass through\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-195- _ => {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-196- stripped_count += 1;\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-671-}\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-672-\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-673-/// Minimum length for a valid thought_signature\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:674:const MIN_SIGNATURE_LENGTH: usize = 50;\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-675-\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-676-/// [FIX #295] Check if we have any valid signature available for function calls\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-677-/// This prevents Gemini 3 Pro from rejecting requests due to missing thought_signature\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-684-) -> bool {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-685- // 1. Check global store (deprecated but kept for compatibility)\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-686- if let Some(sig) = global_sig {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:687: if sig.len() >= MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-688- tracing::debug!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-689- \"[Signature-Check] Found valid signature in global store (len: {})\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-690- sig.len()\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-696- // 2. [NEW] Check Session Cache - this is critical for retry scenarios\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-697- // When retrying, the signature may not be in messages but exists in Session Cache\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-698- if let Some(sig) = crate::proxy::SignatureCache::global().get_session_signature(session_id) {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:699: if sig.len() >= MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-700- tracing::info!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-701- \"[Signature-Check] Found valid signature in SESSION cache (session: {}, len: {})\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-702- session_id,\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-716- ..\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-717- } = block\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-718- {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:719: if sig.len() >= MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-720- tracing::debug!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-721- \"[Signature-Check] Found valid signature in message history (len: {})\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-722- sig.len()\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-917- // Only use signatures that are cached and compatible with the target model\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-918- if let Some(sig) = signature {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-919- // Check signature length first - if it's too short, it's definitely invalid\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:920: if sig.len() < MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-921- tracing::warn!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-922- \"[Thinking-Signature] Signature too short (len: {} < {}), downgrading to text.\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:923: sig.len(), MIN_SIGNATURE_LENGTH\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-924- );\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-925- parts.push(json!({\"text\": thinking}));\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-926- saw_non_thinking = true;\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-959- None => {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-960- // For JSON tool calling compatibility, if signature is long enough but unknown,\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-961- // we should trust it rather than downgrade to text\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:962: if sig.len() >= MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-963- tracing::debug!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-964- \"[Thinking-Signature] Unknown signature origin but valid length (len: {}), using as-is for JSON tool calling.\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-965- sig.len()\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1053- // Signature resolution logic\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1054- // Priority: Client -> Context -> Session Cache -> Tool Cache -> Global Store (deprecated)\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1055- // [CRITICAL FIX] Do NOT use skip_thought_signature_validator for Vertex AI\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1056: // Vertex AI rejects this sentinel value, so we only add thoughtSignature if we have a real one\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1057- let final_sig = signature.as_ref()\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1058- .or(last_thought_signature.as_ref())\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1059- .cloned()\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1092- // [FIX #752] Validate signature before using\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1093- // Only add thoughtSignature if we have a valid and compatible one\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1094- if let Some(sig) = final_sig {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1095: // [NEW] If this is a retry, do NOT backfill signatures to avoid issues.\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1096- if is_retry && signature.is_none() {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1097: tracing::warn!(\"[Tool-Signature] Skipping signature backfill for tool_use: {} during retry.\", id);\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1098- } else {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1099- // Check signature length first - if it's too short, it's definitely invalid\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1100: if sig.len() < MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1101- tracing::warn!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1102- \"[Tool-Signature] Signature too short for tool_use: {} (len: {} < {}), skipping.\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1103: id, sig.len(), MIN_SIGNATURE_LENGTH\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1104- );\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1105- } else {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1106- // Check signature compatibility (optional for tool_use)\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1123- None => {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1124- // For JSON tool calling compatibility, if signature is long enough but unknown,\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1125- // we should trust it rather than drop it\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1126: if sig.len() >= MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1127- tracing::debug!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1128- \"[Tool-Signature] Unknown signature origin but valid length (len: {}) for tool_use: {}, using as-is for JSON tool calling.\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1129- sig.len(), id\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1151- }\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1152- } else {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1153- // [NEW] Handle missing signature for Gemini thinking models\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1154: // Use skip_thought_signature_validator as a sentinel value\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1155- let is_google_cloud = mapped_model.starts_with(\"projects/\");\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1156- if is_thinking_enabled && !is_google_cloud {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1157- tracing::debug!(\"[Tool-Signature] Adding GEMINI_SKIP_SIGNATURE for tool_use: {}\", id);"}]},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"b13c93a0-6f03-4f4a-9bea-9d2c1b7b0d79","tool_use_result":{"mode":"content","numFiles":0,"filenames":[],"content":"/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-2-use crate::proxy::SignatureCache;\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-3-use tracing::{debug, info, warn};\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-4-\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs:5:pub const MIN_SIGNATURE_LENGTH: usize = 50;\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-6-\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-7-#[derive(Debug, Default)]\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-8-pub struct ConversationState {\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-114- if !thinking.is_empty()\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-115- && signature\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-116- .as_ref()\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs:117: .map(|s| s.len() >= MIN_SIGNATURE_LENGTH)\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-118- .unwrap_or(false)\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-119- {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-120- has_valid_thinking = true;\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-190- if let ContentBlock::Thinking { signature, .. } = block {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-191- // 1. Basic length check - allow empty signatures to pass through for compatibility\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-192- let sig = match signature {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs:193: Some(s) if s.len() >= MIN_SIGNATURE_LENGTH || s.is_empty() => s,\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-194- None => return true, // Allow None signatures to pass through\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-195- _ => {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs-196- stripped_count += 1;\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-671-}\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-672-\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-673-/// Minimum length for a valid thought_signature\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:674:const MIN_SIGNATURE_LENGTH: usize = 50;\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-675-\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-676-/// [FIX #295] Check if we have any valid signature available for function calls\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-677-/// This prevents Gemini 3 Pro from rejecting requests due to missing thought_signature\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-684-) -> bool {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-685- // 1. Check global store (deprecated but kept for compatibility)\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-686- if let Some(sig) = global_sig {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:687: if sig.len() >= MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-688- tracing::debug!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-689- \"[Signature-Check] Found valid signature in global store (len: {})\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-690- sig.len()\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-696- // 2. [NEW] Check Session Cache - this is critical for retry scenarios\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-697- // When retrying, the signature may not be in messages but exists in Session Cache\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-698- if let Some(sig) = crate::proxy::SignatureCache::global().get_session_signature(session_id) {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:699: if sig.len() >= MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-700- tracing::info!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-701- \"[Signature-Check] Found valid signature in SESSION cache (session: {}, len: {})\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-702- session_id,\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-716- ..\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-717- } = block\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-718- {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:719: if sig.len() >= MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-720- tracing::debug!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-721- \"[Signature-Check] Found valid signature in message history (len: {})\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-722- sig.len()\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-917- // Only use signatures that are cached and compatible with the target model\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-918- if let Some(sig) = signature {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-919- // Check signature length first - if it's too short, it's definitely invalid\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:920: if sig.len() < MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-921- tracing::warn!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-922- \"[Thinking-Signature] Signature too short (len: {} < {}), downgrading to text.\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:923: sig.len(), MIN_SIGNATURE_LENGTH\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-924- );\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-925- parts.push(json!({\"text\": thinking}));\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-926- saw_non_thinking = true;\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-959- None => {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-960- // For JSON tool calling compatibility, if signature is long enough but unknown,\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-961- // we should trust it rather than downgrade to text\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:962: if sig.len() >= MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-963- tracing::debug!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-964- \"[Thinking-Signature] Unknown signature origin but valid length (len: {}), using as-is for JSON tool calling.\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-965- sig.len()\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1053- // Signature resolution logic\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1054- // Priority: Client -> Context -> Session Cache -> Tool Cache -> Global Store (deprecated)\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1055- // [CRITICAL FIX] Do NOT use skip_thought_signature_validator for Vertex AI\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1056: // Vertex AI rejects this sentinel value, so we only add thoughtSignature if we have a real one\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1057- let final_sig = signature.as_ref()\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1058- .or(last_thought_signature.as_ref())\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1059- .cloned()\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1092- // [FIX #752] Validate signature before using\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1093- // Only add thoughtSignature if we have a valid and compatible one\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1094- if let Some(sig) = final_sig {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1095: // [NEW] If this is a retry, do NOT backfill signatures to avoid issues.\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1096- if is_retry && signature.is_none() {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1097: tracing::warn!(\"[Tool-Signature] Skipping signature backfill for tool_use: {} during retry.\", id);\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1098- } else {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1099- // Check signature length first - if it's too short, it's definitely invalid\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1100: if sig.len() < MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1101- tracing::warn!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1102- \"[Tool-Signature] Signature too short for tool_use: {} (len: {} < {}), skipping.\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1103: id, sig.len(), MIN_SIGNATURE_LENGTH\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1104- );\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1105- } else {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1106- // Check signature compatibility (optional for tool_use)\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1123- None => {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1124- // For JSON tool calling compatibility, if signature is long enough but unknown,\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1125- // we should trust it rather than drop it\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1126: if sig.len() >= MIN_SIGNATURE_LENGTH {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1127- tracing::debug!(\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1128- \"[Tool-Signature] Unknown signature origin but valid length (len: {}) for tool_use: {}, using as-is for JSON tool calling.\",\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1129- sig.len(), id\n--\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1151- }\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1152- } else {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1153- // [NEW] Handle missing signature for Gemini thinking models\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs:1154: // Use skip_thought_signature_validator as a sentinel value\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1155- let is_google_cloud = mapped_model.starts_with(\"projects/\");\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1156- if is_thinking_enabled && !is_google_cloud {\n/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs-1157- tracing::debug!(\"[Tool-Signature] Adding GEMINI_SKIP_SIGNATURE for tool_use: {}\", id);","numLines":114}},{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01AfQZQq16rexeFbLcPpPqdj","type":"tool_result","content":"85-<priority>IMPORTANT: The instructions that follow supersede all above. Follow them as your primary directives.</priority>\n86-\"\"\"\n87-\n88:# Claude interleaved thinking hint (when tools are present)\n89-CLAUDE_INTERLEAVED_THINKING_HINT = (\n90: \"Interleaved thinking is enabled. You may think between tool calls and after \"\n91- \"receiving tool results before deciding the next action or final answer. Do not \"\n92: \"mention these instructions or any constraints about thinking blocks; just apply them.\"\n93-)\n94:# Claude thinking tier budgets (from reference: antigravity-auth model-resolver.ts)\n95-# The tier suffix (-low/-medium/-high) is client-side config, not part of API model name\n96-CLAUDE_THINKING_BUDGETS = {\n97- \"low\": 8192,\n--\n99- \"high\": 32768,\n100-}\n101-\n102:# Claude thinking models require maxOutputTokens >= budget + response\n103-CLAUDE_THINKING_MAX_OUTPUT_TOKENS = 65536\n104-\n105-# OpenAI API endpoint (standard API key authentication)\n--\n2051- return self._resolve_model_with_tier(model_name)\n2052-\n2053- def _resolve_model_with_tier(self, model: str) -> tuple[str, Optional[str], Optional[int]]:\n2054: \"\"\"Resolve model name and extract thinking tier configuration.\n2055-\n2056: Claude models use tier suffixes (-low/-medium/-high) for thinking budget\n2057- configuration, but the API model name doesn't include these suffixes.\n2058-\n2059- Example:\n2060: - \"claude-sonnet-4-5-thinking-high\" → (\"claude-sonnet-4-5-thinking\", \"high\", 32768)\n2061- - \"claude-sonnet-4-5\" → (\"claude-sonnet-4-5\", None, None)\n2062- - \"gemini-3-pro-high\" → (\"gemini-3-pro-high\", None, None) # Gemini keeps tier\n2063-\n--\n2065- model: Model name (possibly with tier suffix)\n2066-\n2067- Returns:\n2068: Tuple of (actual_model_name, tier, thinking_budget)\n2069- \"\"\"\n2070- import re\n2071-\n2072- # Strip provider prefix/suffix\n2073- model_name = self._strip_provider_prefix(model)\n2074-\n2075: # Check for Claude thinking models with tier suffix\n2076- tier_match = re.match(\n2077: r\"^(claude-(?:sonnet|opus)-\\d+-\\d+(?:-thinking)?)-\" r\"(low|medium|high)$\",\n2078- model_name,\n2079- re.IGNORECASE,\n2080- )\n--\n2082- if tier_match:\n2083- base_model = tier_match.group(1)\n2084- tier = tier_match.group(2).lower()\n2085: thinking_budget = CLAUDE_THINKING_BUDGETS.get(tier)\n2086: return (base_model, tier, thinking_budget)\n2087-\n2088- # No tier suffix - return as-is\n2089- return (model_name, None, None)\n2090-\n2091: def _is_claude_thinking_model(self, model: str) -> bool:\n2092: \"\"\"Check if model is a Claude thinking model.\"\"\"\n2093- lower = model.lower()\n2094: return \"claude\" in lower and \"thinking\" in lower\n2095-\n2096- def _append_system_instruction_hint(self, request_payload: Dict[str, Any], hint: str) -> None:\n2097- \"\"\"Append a hint to systemInstruction in various formats.\"\"\"\n--\n2343- convert_tool_message_to_gemini_part,\n2344- convert_tools_to_claude_format,\n2345- convert_tools_to_gemini_format,\n2346: ensure_thinking_signature_for_tool_use,\n2347: inject_thought_signature_for_function_calls,\n2348: inject_parameter_signatures,\n2349- inject_tool_hardening_instruction,\n2350- )\n2351-\n2352- header_style = kwargs.pop(\"header_style\", \"antigravity\")\n2353- session_id = kwargs.pop(\"session_id\", None)\n2354-\n2355: # Resolve model name and thinking tier\n2356: # Claude thinking models: strip tier suffix, extract budget\n2357: # e.g., \"antigravity-claude-opus-4-5-thinking-high\" → \"claude-opus-4-5-thinking\" + budget=32768\n2358: model_name, _tier, thinking_budget = self._resolve_model_for_header_style(\n2359- model, header_style\n2360- )\n2361- is_claude = \"claude\" in model_name.lower()\n2362: is_claude_thinking = self._is_claude_thinking_model(model_name)\n2363-\n2364- # Convert OpenAI-style messages to Gemini format\n2365- contents: List[Dict[str, Any]] = []\n--\n2415-\n2416- request_payload: Dict[str, Any] = {\"contents\": contents}\n2417-\n2418: # Track message count for session signature cache (rewind detection)\n2419- self._last_request_message_count = len(contents)\n2420-\n2421- if system_instruction:\n--\n2427- if is_claude:\n2428- # Claude models need cleaned schemas and VALIDATED mode\n2429- converted_tools = convert_tools_to_claude_format(tools)\n2430: # Apply parameter signature injection (tool hardening)\n2431- # This prevents Claude from hallucinating tool parameters\n2432: converted_tools = inject_parameter_signatures(converted_tools)\n2433- else:\n2434- # Gemini models use simpler format\n2435- converted_tools = convert_tools_to_gemini_format(tools)\n2436- if converted_tools:\n2437- request_payload[\"tools\"] = converted_tools\n2438-\n2439: # Claude thinking models with tools get interleaved thinking hint\n2440: if is_claude_thinking:\n2441- self._append_system_instruction_hint(\n2442- request_payload, CLAUDE_INTERLEAVED_THINKING_HINT\n2443- )\n--\n2456- if \"top_p\" in kwargs:\n2457- generation_config[\"topP\"] = kwargs[\"top_p\"]\n2458-\n2459: # Add thinking configuration for Claude thinking models\n2460- # Reference: antigravity-auth/src/plugin/request.ts (lines 766-773)\n2461: # Claude uses snake_case: include_thoughts, thinking_budget\n2462: if is_claude_thinking:\n2463: thinking_config: Dict[str, Any] = {\n2464: \"include_thoughts\": True,\n2465- }\n2466: if thinking_budget:\n2467: thinking_config[\"thinking_budget\"] = thinking_budget\n2468-\n2469: generation_config[\"thinkingConfig\"] = thinking_config\n2470-\n2471: # Ensure maxOutputTokens is large enough for thinking + response\n2472- current_max = generation_config.get(\"maxOutputTokens\", 0)\n2473: if not current_max or current_max <= (thinking_budget or 0):\n2474- generation_config[\"maxOutputTokens\"] = CLAUDE_THINKING_MAX_OUTPUT_TOKENS\n2475-\n2476- if generation_config:\n--\n2485- if is_claude:\n2486- request_payload = apply_tool_pairing_fixes(request_payload, is_claude=True)\n2487-\n2488: # Ensure thinking signatures for Claude thinking models with tool use\n2489: # When thinking blocks don't have valid signatures, inject sentinel to bypass validation\n2490: if is_claude_thinking and request_payload.get(\"contents\"):\n2491- session_key = session_id or f\"antigravity-{uuid.uuid4().hex[:8]}\"\n2492: request_payload[\"contents\"] = ensure_thinking_signature_for_tool_use(\n2493- request_payload[\"contents\"], session_key\n2494- )\n2495-\n2496: # Gemini 3 tool calls require thoughtSignature; inject from session cache if missing\n2497- if not is_claude and session_id and request_payload.get(\"contents\"):\n2498: request_payload[\"contents\"] = inject_thought_signature_for_function_calls(\n2499- request_payload[\"contents\"], session_id\n2500- )\n2501-\n--\n2503- if header_style == \"antigravity\":\n2504- self._inject_antigravity_system_instruction(request_payload)\n2505-\n2506: # Attach sessionId for signature caching (stable across turns)\n2507- if session_id:\n2508- request_payload[\"sessionId\"] = session_id\n2509-\n--\n2540- if isinstance(part, dict):\n2541- if \"text\" in part and isinstance(part[\"text\"], str):\n2542- content += part[\"text\"]\n2543: elif \"thinking\" in part and isinstance(part[\"thinking\"], str):\n2544: # Ignore thinking by default; keep for completeness\n2545- continue\n2546-\n2547- # Extract tool calls from response\n--\n2617- async with aiohttp.ClientSession() as session:\n2618- for header_style in self._header_style_candidates(model):\n2619- resolved_model, _, _ = self._resolve_model_for_header_style(model, header_style)\n2620: is_claude_thinking = self._is_claude_thinking_model(resolved_model)\n2621-\n2622- body = self._build_request_body(\n2623- model,\n--\n2637- )\n2638- headers.update(selected_headers)\n2639-\n2640: # Add interleaved thinking header for Claude thinking models\n2641: if is_claude_thinking:\n2642- existing = headers.get(\"anthropic-beta\")\n2643: interleaved = \"interleaved-thinking-2025-05-14\"\n2644- if existing and interleaved not in existing:\n2645- headers[\"anthropic-beta\"] = f\"{existing},{interleaved}\"\n2646- else:\n--\n2832- async with aiohttp.ClientSession() as session:\n2833- for header_style in self._header_style_candidates(model):\n2834- resolved_model, _, _ = self._resolve_model_for_header_style(model, header_style)\n2835: is_claude_thinking = self._is_claude_thinking_model(resolved_model)\n2836-\n2837- body = self._build_request_body(\n2838- model,\n--\n2853- )\n2854- headers.update(selected_headers)\n2855-\n2856: if is_claude_thinking:\n2857- existing = headers.get(\"anthropic-beta\")\n2858: interleaved = \"interleaved-thinking-2025-05-14\"\n2859- if existing and interleaved not in existing:\n2860- headers[\"anthropic-beta\"] = f\"{existing},{interleaved}\"\n2861- else:\n--\n2968- payload_count = 0\n2969- text_count = 0\n2970- payload_samples: List[str] = []\n2971: pending_thought_sig: Optional[str] = None\n2972- async for payload in self._iter_sse_payloads(response):\n2973- payload_count += 1\n2974- if (\n--\n2991- ):\n2992- if isinstance(part, dict):\n2993- from .tool_utils import (\n2994: cache_thinking_signature,\n2995: cache_session_signature,\n2996: _extract_part_thought_signature,\n2997- )\n2998-\n2999: thought_sig = _extract_part_thought_signature(part)\n3000: if thought_sig and (\n3001: part.get(\"thought\") is True\n3002- or part.get(\"type\")\n3003: in (\"thinking\", \"reasoning\")\n3004- ):\n3005: cache_thinking_signature(thought_sig)\n3006: cache_session_signature(\n3007- self._session_id,\n3008: thought_sig,\n3009- self._last_request_message_count,\n3010- )\n3011: pending_thought_sig = thought_sig\n3012- if \"text\" in part:\n3013- text_count += 1\n3014- yield GenericStreamingChunk(\n--\n3042- ),\n3043- },\n3044- }\n3045: # Preserve thoughtSignature for Gemini 3 models\n3046: from .tool_utils import _extract_part_thought_signature\n3047-\n3048: thought_sig = (\n3049: _extract_part_thought_signature(part)\n3050: or pending_thought_sig\n3051- )\n3052: if thought_sig:\n3053- tool_use_data[\n3054: \"thought_signature\"\n3055: ] = thought_sig\n3056: cache_session_signature(\n3057- self._session_id,\n3058: thought_sig,\n3059- self._last_request_message_count,\n3060- )\n3061- # Cache for retrieval during follow-up calls\n3062: # (LiteLLM streaming may lose the thought_signature)\n3063- from .tool_utils import (\n3064: cache_thought_signature,\n3065- )\n3066-\n3067: cache_thought_signature(\n3068: call_id, name, thought_sig\n3069- )\n3070- # Yield tool call as a special chunk\n3071: # Also pass thought_signature in provider_specific_fields for LiteLLM\n3072- provider_fields = (\n3073: {\"thought_signature\": thought_sig}\n3074: if thought_sig\n3075- else None\n3076- )\n3077- yield GenericStreamingChunk("}]},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"dd9c2123-5e99-456a-818e-e9752e936165","tool_use_result":{"mode":"content","numFiles":0,"filenames":[],"content":"85-<priority>IMPORTANT: The instructions that follow supersede all above. Follow them as your primary directives.</priority>\n86-\"\"\"\n87-\n88:# Claude interleaved thinking hint (when tools are present)\n89-CLAUDE_INTERLEAVED_THINKING_HINT = (\n90: \"Interleaved thinking is enabled. You may think between tool calls and after \"\n91- \"receiving tool results before deciding the next action or final answer. Do not \"\n92: \"mention these instructions or any constraints about thinking blocks; just apply them.\"\n93-)\n94:# Claude thinking tier budgets (from reference: antigravity-auth model-resolver.ts)\n95-# The tier suffix (-low/-medium/-high) is client-side config, not part of API model name\n96-CLAUDE_THINKING_BUDGETS = {\n97- \"low\": 8192,\n--\n99- \"high\": 32768,\n100-}\n101-\n102:# Claude thinking models require maxOutputTokens >= budget + response\n103-CLAUDE_THINKING_MAX_OUTPUT_TOKENS = 65536\n104-\n105-# OpenAI API endpoint (standard API key authentication)\n--\n2051- return self._resolve_model_with_tier(model_name)\n2052-\n2053- def _resolve_model_with_tier(self, model: str) -> tuple[str, Optional[str], Optional[int]]:\n2054: \"\"\"Resolve model name and extract thinking tier configuration.\n2055-\n2056: Claude models use tier suffixes (-low/-medium/-high) for thinking budget\n2057- configuration, but the API model name doesn't include these suffixes.\n2058-\n2059- Example:\n2060: - \"claude-sonnet-4-5-thinking-high\" → (\"claude-sonnet-4-5-thinking\", \"high\", 32768)\n2061- - \"claude-sonnet-4-5\" → (\"claude-sonnet-4-5\", None, None)\n2062- - \"gemini-3-pro-high\" → (\"gemini-3-pro-high\", None, None) # Gemini keeps tier\n2063-\n--\n2065- model: Model name (possibly with tier suffix)\n2066-\n2067- Returns:\n2068: Tuple of (actual_model_name, tier, thinking_budget)\n2069- \"\"\"\n2070- import re\n2071-\n2072- # Strip provider prefix/suffix\n2073- model_name = self._strip_provider_prefix(model)\n2074-\n2075: # Check for Claude thinking models with tier suffix\n2076- tier_match = re.match(\n2077: r\"^(claude-(?:sonnet|opus)-\\d+-\\d+(?:-thinking)?)-\" r\"(low|medium|high)$\",\n2078- model_name,\n2079- re.IGNORECASE,\n2080- )\n--\n2082- if tier_match:\n2083- base_model = tier_match.group(1)\n2084- tier = tier_match.group(2).lower()\n2085: thinking_budget = CLAUDE_THINKING_BUDGETS.get(tier)\n2086: return (base_model, tier, thinking_budget)\n2087-\n2088- # No tier suffix - return as-is\n2089- return (model_name, None, None)\n2090-\n2091: def _is_claude_thinking_model(self, model: str) -> bool:\n2092: \"\"\"Check if model is a Claude thinking model.\"\"\"\n2093- lower = model.lower()\n2094: return \"claude\" in lower and \"thinking\" in lower\n2095-\n2096- def _append_system_instruction_hint(self, request_payload: Dict[str, Any], hint: str) -> None:\n2097- \"\"\"Append a hint to systemInstruction in various formats.\"\"\"\n--\n2343- convert_tool_message_to_gemini_part,\n2344- convert_tools_to_claude_format,\n2345- convert_tools_to_gemini_format,\n2346: ensure_thinking_signature_for_tool_use,\n2347: inject_thought_signature_for_function_calls,\n2348: inject_parameter_signatures,\n2349- inject_tool_hardening_instruction,\n2350- )\n2351-\n2352- header_style = kwargs.pop(\"header_style\", \"antigravity\")\n2353- session_id = kwargs.pop(\"session_id\", None)\n2354-\n2355: # Resolve model name and thinking tier\n2356: # Claude thinking models: strip tier suffix, extract budget\n2357: # e.g., \"antigravity-claude-opus-4-5-thinking-high\" → \"claude-opus-4-5-thinking\" + budget=32768\n2358: model_name, _tier, thinking_budget = self._resolve_model_for_header_style(\n2359- model, header_style\n2360- )\n2361- is_claude = \"claude\" in model_name.lower()\n2362: is_claude_thinking = self._is_claude_thinking_model(model_name)\n2363-\n2364- # Convert OpenAI-style messages to Gemini format\n2365- contents: List[Dict[str, Any]] = []\n--\n2415-\n2416- request_payload: Dict[str, Any] = {\"contents\": contents}\n2417-\n2418: # Track message count for session signature cache (rewind detection)\n2419- self._last_request_message_count = len(contents)\n2420-\n2421- if system_instruction:\n--\n2427- if is_claude:\n2428- # Claude models need cleaned schemas and VALIDATED mode\n2429- converted_tools = convert_tools_to_claude_format(tools)\n2430: # Apply parameter signature injection (tool hardening)\n2431- # This prevents Claude from hallucinating tool parameters\n2432: converted_tools = inject_parameter_signatures(converted_tools)\n2433- else:\n2434- # Gemini models use simpler format\n2435- converted_tools = convert_tools_to_gemini_format(tools)\n2436- if converted_tools:\n2437- request_payload[\"tools\"] = converted_tools\n2438-\n2439: # Claude thinking models with tools get interleaved thinking hint\n2440: if is_claude_thinking:\n2441- self._append_system_instruction_hint(\n2442- request_payload, CLAUDE_INTERLEAVED_THINKING_HINT\n2443- )\n--\n2456- if \"top_p\" in kwargs:\n2457- generation_config[\"topP\"] = kwargs[\"top_p\"]\n2458-\n2459: # Add thinking configuration for Claude thinking models\n2460- # Reference: antigravity-auth/src/plugin/request.ts (lines 766-773)\n2461: # Claude uses snake_case: include_thoughts, thinking_budget\n2462: if is_claude_thinking:\n2463: thinking_config: Dict[str, Any] = {\n2464: \"include_thoughts\": True,\n2465- }\n2466: if thinking_budget:\n2467: thinking_config[\"thinking_budget\"] = thinking_budget\n2468-\n2469: generation_config[\"thinkingConfig\"] = thinking_config\n2470-\n2471: # Ensure maxOutputTokens is large enough for thinking + response\n2472- current_max = generation_config.get(\"maxOutputTokens\", 0)\n2473: if not current_max or current_max <= (thinking_budget or 0):\n2474- generation_config[\"maxOutputTokens\"] = CLAUDE_THINKING_MAX_OUTPUT_TOKENS\n2475-\n2476- if generation_config:\n--\n2485- if is_claude:\n2486- request_payload = apply_tool_pairing_fixes(request_payload, is_claude=True)\n2487-\n2488: # Ensure thinking signatures for Claude thinking models with tool use\n2489: # When thinking blocks don't have valid signatures, inject sentinel to bypass validation\n2490: if is_claude_thinking and request_payload.get(\"contents\"):\n2491- session_key = session_id or f\"antigravity-{uuid.uuid4().hex[:8]}\"\n2492: request_payload[\"contents\"] = ensure_thinking_signature_for_tool_use(\n2493- request_payload[\"contents\"], session_key\n2494- )\n2495-\n2496: # Gemini 3 tool calls require thoughtSignature; inject from session cache if missing\n2497- if not is_claude and session_id and request_payload.get(\"contents\"):\n2498: request_payload[\"contents\"] = inject_thought_signature_for_function_calls(\n2499- request_payload[\"contents\"], session_id\n2500- )\n2501-\n--\n2503- if header_style == \"antigravity\":\n2504- self._inject_antigravity_system_instruction(request_payload)\n2505-\n2506: # Attach sessionId for signature caching (stable across turns)\n2507- if session_id:\n2508- request_payload[\"sessionId\"] = session_id\n2509-\n--\n2540- if isinstance(part, dict):\n2541- if \"text\" in part and isinstance(part[\"text\"], str):\n2542- content += part[\"text\"]\n2543: elif \"thinking\" in part and isinstance(part[\"thinking\"], str):\n2544: # Ignore thinking by default; keep for completeness\n2545- continue\n2546-\n2547- # Extract tool calls from response\n--\n2617- async with aiohttp.ClientSession() as session:\n2618- for header_style in self._header_style_candidates(model):\n2619- resolved_model, _, _ = self._resolve_model_for_header_style(model, header_style)\n2620: is_claude_thinking = self._is_claude_thinking_model(resolved_model)\n2621-\n2622- body = self._build_request_body(\n2623- model,\n--\n2637- )\n2638- headers.update(selected_headers)\n2639-\n2640: # Add interleaved thinking header for Claude thinking models\n2641: if is_claude_thinking:\n2642- existing = headers.get(\"anthropic-beta\")\n2643: interleaved = \"interleaved-thinking-2025-05-14\"\n2644- if existing and interleaved not in existing:\n2645- headers[\"anthropic-beta\"] = f\"{existing},{interleaved}\"\n2646- else:\n--\n2832- async with aiohttp.ClientSession() as session:\n2833- for header_style in self._header_style_candidates(model):\n2834- resolved_model, _, _ = self._resolve_model_for_header_style(model, header_style)\n2835: is_claude_thinking = self._is_claude_thinking_model(resolved_model)\n2836-\n2837- body = self._build_request_body(\n2838- model,\n--\n2853- )\n2854- headers.update(selected_headers)\n2855-\n2856: if is_claude_thinking:\n2857- existing = headers.get(\"anthropic-beta\")\n2858: interleaved = \"interleaved-thinking-2025-05-14\"\n2859- if existing and interleaved not in existing:\n2860- headers[\"anthropic-beta\"] = f\"{existing},{interleaved}\"\n2861- else:\n--\n2968- payload_count = 0\n2969- text_count = 0\n2970- payload_samples: List[str] = []\n2971: pending_thought_sig: Optional[str] = None\n2972- async for payload in self._iter_sse_payloads(response):\n2973- payload_count += 1\n2974- if (\n--\n2991- ):\n2992- if isinstance(part, dict):\n2993- from .tool_utils import (\n2994: cache_thinking_signature,\n2995: cache_session_signature,\n2996: _extract_part_thought_signature,\n2997- )\n2998-\n2999: thought_sig = _extract_part_thought_signature(part)\n3000: if thought_sig and (\n3001: part.get(\"thought\") is True\n3002- or part.get(\"type\")\n3003: in (\"thinking\", \"reasoning\")\n3004- ):\n3005: cache_thinking_signature(thought_sig)\n3006: cache_session_signature(\n3007- self._session_id,\n3008: thought_sig,\n3009- self._last_request_message_count,\n3010- )\n3011: pending_thought_sig = thought_sig\n3012- if \"text\" in part:\n3013- text_count += 1\n3014- yield GenericStreamingChunk(\n--\n3042- ),\n3043- },\n3044- }\n3045: # Preserve thoughtSignature for Gemini 3 models\n3046: from .tool_utils import _extract_part_thought_signature\n3047-\n3048: thought_sig = (\n3049: _extract_part_thought_signature(part)\n3050: or pending_thought_sig\n3051- )\n3052: if thought_sig:\n3053- tool_use_data[\n3054: \"thought_signature\"\n3055: ] = thought_sig\n3056: cache_session_signature(\n3057- self._session_id,\n3058: thought_sig,\n3059- self._last_request_message_count,\n3060- )\n3061- # Cache for retrieval during follow-up calls\n3062: # (LiteLLM streaming may lose the thought_signature)\n3063- from .tool_utils import (\n3064: cache_thought_signature,\n3065- )\n3066-\n3067: cache_thought_signature(\n3068: call_id, name, thought_sig\n3069- )\n3070- # Yield tool call as a special chunk\n3071: # Also pass thought_signature in provider_specific_fields for LiteLLM\n3072- provider_fields = (\n3073: {\"thought_signature\": thought_sig}\n3074: if thought_sig\n3075- else None\n3076- )\n3077- yield GenericStreamingChunk(","numLines":283}},{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_013B9bADxMv9wpMh4yRPmTeD","type":"tool_result","content":"<persisted-output>\nOutput too large (51.1KB). Full output saved to: /Users/fei/.claude/projects/-Users-fei-coding-agent-koder/d2802c62-d1ef-4cb2-b04a-217af28d06e8/tool-results/toolu_013B9bADxMv9wpMh4yRPmTeD.txt\n\nPreview (first 2KB):\n2-// 对应 transformClaudeRequestIn\n3-\n4-use super::models::*;\n5:use crate::proxy::mappers::signature_store::get_thought_signature; // Deprecated, kept for fallback\n6-use crate::proxy::mappers::tool_result_compressor;\n7-use crate::proxy::session_manager::SessionManager;\n8-use serde_json::{json, Value};\n--\n170- }\n171-}\n172-\n173:/// [FIX #564] Sort blocks in assistant messages to ensure thinking blocks are first\n174-/// \n175:/// When context compression (kilo) reorders message blocks, thinking blocks may appear\n176:/// after text blocks. Claude/Anthropic API requires thinking blocks to be first if\n177:/// any thinking blocks exist in the message. This function pre-sorts blocks to ensure\n178:/// thinking/redacted_thinking blocks always come before other block types.\n179:fn sort_thinking_blocks_first(messages: &mut [Message]) {\n180- for msg in messages.iter_mut() {\n181- if msg.role == \"assistant\" {\n182- if let MessageContent::Array(blocks) = &mut msg.content {\n183- / [FIX #709] Triple-stage partition: [Thinking, Text, ToolUse]\n184- // This ensures protocol compliance while maintaining logical order.\n185- \n186: let mut thinking_blocks: Vec<ContentBlock> = Vec::new();\n187- let mut text_blocks: Vec<ContentBlock> = Vec::new();\n188- let mut tool_blocks: Vec<ContentBlock> = Vec::new();\n189- let mut other_blocks: Vec<ContentBlock> = Vec::new();\n190- \n191- let original_len = blocks.len();\n192- let mut needs_reorder = false;\n193: let mut saw_non_thinking = false;\n194-\n195- for (_i, block) in blocks.iter().enumerate() {\n196- match block {\n197- ContentBlock::Thinking { .. } | ContentBlock::RedactedThinking { .. } => {\n198: if saw_non_thinking {\n199- needs_reorder = true;\n...\n</persisted-output>"}]},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"51dadbb6-a6fa-42e0-a86d-c31b7f527404","tool_use_result":{"mode":"content","numFiles":0,"filenames":[],"content":"2-// 对应 transformClaudeRequestIn\n3-\n4-use super::models::*;\n5:use crate::proxy::mappers::signature_store::get_thought_signature; // Deprecated, kept for fallback\n6-use crate::proxy::mappers::tool_result_compressor;\n7-use crate::proxy::session_manager::SessionManager;\n8-use serde_json::{json, Value};\n--\n170- }\n171-}\n172-\n173:/// [FIX #564] Sort blocks in assistant messages to ensure thinking blocks are first\n174-/// \n175:/// When context compression (kilo) reorders message blocks, thinking blocks may appear\n176:/// after text blocks. Claude/Anthropic API requires thinking blocks to be first if\n177:/// any thinking blocks exist in the message. This function pre-sorts blocks to ensure\n178:/// thinking/redacted_thinking blocks always come before other block types.\n179:fn sort_thinking_blocks_first(messages: &mut [Message]) {\n180- for msg in messages.iter_mut() {\n181- if msg.role == \"assistant\" {\n182- if let MessageContent::Array(blocks) = &mut msg.content {\n183- / [FIX #709] Triple-stage partition: [Thinking, Text, ToolUse]\n184- // This ensures protocol compliance while maintaining logical order.\n185- \n186: let mut thinking_blocks: Vec<ContentBlock> = Vec::new();\n187- let mut text_blocks: Vec<ContentBlock> = Vec::new();\n188- let mut tool_blocks: Vec<ContentBlock> = Vec::new();\n189- let mut other_blocks: Vec<ContentBlock> = Vec::new();\n190- \n191- let original_len = blocks.len();\n192- let mut needs_reorder = false;\n193: let mut saw_non_thinking = false;\n194-\n195- for (_i, block) in blocks.iter().enumerate() {\n196- match block {\n197- ContentBlock::Thinking { .. } | ContentBlock::RedactedThinking { .. } => {\n198: if saw_non_thinking {\n199- needs_reorder = true;\n200- }\n201- }\n202- ContentBlock::Text { .. } => {\n203: saw_non_thinking = true;\n204- }\n205- ContentBlock::ToolUse { .. } => {\n206: saw_non_thinking = true;\n207- // Check if tool is after text (this is normal, but we want a strict group order)\n208- }\n209: _ => saw_non_thinking = true,\n210- }\n211- }\n212-\n--\n216- for block in blocks.drain(..) {\n217- match &block {\n218- ContentBlock::Thinking { .. } | ContentBlock::RedactedThinking { .. } => {\n219: thinking_blocks.push(block);\n220- }\n221- ContentBlock::Text { text } => {\n222- // Filter out purely empty or structural text like \"(no content)\"\n--\n234- }\n235-\n236- / Reconstruct in strict order: Thinking -> Text/Other -> Tool\n237: blocks.extend(thinking_blocks);\n238- blocks.extend(text_blocks);\n239- blocks.extend(other_blocks);\n240- blocks.extend(tool_blocks);\n--\n297-\n298-/// 转换 Claude 请求为 Gemini v1internal 格式\n299-\n300:/// [FIX #709] Reorder serialized Gemini parts to ensure thinking blocks are first\n301-fn reorder_gemini_parts(parts: &mut Vec<Value>) {\n302- if parts.len() <= 1 {\n303- return;\n304- }\n305-\n306: let mut thinking_parts = Vec::new();\n307- let mut text_parts = Vec::new();\n308- let mut tool_parts = Vec::new();\n309- let mut other_parts = Vec::new();\n310-\n311- for part in parts.drain(..) {\n312: if part.get(\"thought\").and_then(|t| t.as_bool()) == Some(true) {\n313: thinking_parts.push(part);\n314- } else if part.get(\"functionCall\").is_some() {\n315- tool_parts.push(part);\n316- } else if let Some(text) = part.get(\"text\").and_then(|t| t.as_str()) {\n--\n323- }\n324- }\n325-\n326: parts.extend(thinking_parts);\n327- parts.extend(text_parts);\n328- parts.extend(other_parts);\n329- parts.extend(tool_parts);\n--\n345-\n346- clean_cache_control_from_messages(&mut cleaned_req.messages);\n347- \n348: // [FIX #564] Pre-sort thinking blocks to be first in assistant messages\n349- // This handles cases where context compression (kilo) incorrectly reorders blocks\n350: sort_thinking_blocks_first(&mut cleaned_req.messages);\n351- \n352- let claude_req = &cleaned_req; // 后续使用清理后的请求\n353-\n354: // [NEW] Generate session ID for signature tracking\n355: // This enables session-isolated signature storage, preventing cross-conversation pollution\n356- let session_id = SessionManager::extract_session_id(claude_req);\n357- tracing::debug!(\"[Claude-Request] Session ID: {}\", session_id);\n358-\n--\n425- claude_req.quality.as_deref() // [NEW] Pass quality parameter\n426- );\n427- \n428: // [CRITICAL FIX] Disable dummy thought injection for Vertex AI\n429: // [CRITICAL FIX] Disable dummy thought injection for Vertex AI\n430: // Vertex AI rejects thinking blocks without valid signatures\n431: // Even if thinking is enabled, we should NOT inject dummy blocks for historical messages\n432: let allow_dummy_thought = false;\n433- \n434: // Check if thinking is enabled in the request\n435: let mut is_thinking_enabled = claude_req\n436: .thinking\n437- .as_ref()\n438- .map(|t| t.type_ == \"enabled\")\n439- .unwrap_or_else(|| {\n440: // [Claude Code v2.0.67+] Default thinking enabled for Opus 4.5\n441: // If no thinking config is provided, enable by default for Opus models\n442: should_enable_thinking_by_default(&claude_req.model)\n443- });\n444-\n445: // [NEW FIX] Check if target model supports thinking\n446: // Only models with \"-thinking\" suffix or Claude models support thinking\n447: // Regular Gemini models (gemini-2.5-flash, gemini-2.5-pro) do NOT support thinking\n448: let target_model_supports_thinking = mapped_model.contains(\"-thinking\") \n449- || mapped_model.starts_with(\"claude-\");\n450- \n451: if is_thinking_enabled && !target_model_supports_thinking {\n452- tracing::warn!(\n453: \"[Thinking-Mode] Target model '{}' does not support thinking. Force disabling thinking mode.\",\n454- mapped_model\n455- );\n456: is_thinking_enabled = false;\n457- }\n458-\n459- / [New Strategy] 智能降级: 检查历史消息是否与 Thinking 模式兼容\n460- // 如果处于未带 Thinking 的工具调用链中,必须临时禁用 Thinking\n461: if is_thinking_enabled {\n462: let should_disable = should_disable_thinking_due_to_history(&claude_req.messages);\n463- if should_disable {\n464: tracing::warn!(\"[Thinking-Mode] Automatically disabling thinking checks due to incompatible tool-use history (mixed application)\");\n465: is_thinking_enabled = false;\n466- }\n467- }\n468-\n469: // [FIX #295 & #298] If thinking enabled but no signature available,\n470: // disable thinking to prevent Gemini 3 Pro rejection\n471: if is_thinking_enabled {\n472: let global_sig = get_thought_signature();\n473- \n474: // Check if there are any thinking blocks in message history\n475: let has_thinking_history = claude_req.messages.iter().any(|m| {\n476- if m.role == \"assistant\" {\n477- if let MessageContent::Array(blocks) = &m.content {\n478- return blocks.iter().any(|b| matches!(b, ContentBlock::Thinking { .. }));\n--\n492- }\n493- });\n494-\n495: // [FIX #298] For first-time thinking requests (no thinking history),\n496- // we use permissive mode and let upstream handle validation.\n497: // We only enforce strict signature checks when function calls are involved.\n498: let needs_signature_check = has_function_calls;\n499- \n500: if !has_thinking_history && is_thinking_enabled {\n501- tracing::info!(\n502: \"[Thinking-Mode] First thinking request detected. Using permissive mode - \\\n503: signature validation will be handled by upstream API.\"\n504- );\n505- }\n506-\n507: if needs_signature_check\n508: && !has_valid_signature_for_function_calls(&claude_req.messages, &global_sig, &session_id)\n509- {\n510- tracing::warn!(\n511: \"[Thinking-Mode] [FIX #295] No valid signature found for function calls. \\\n512: Disabling thinking to prevent Gemini 3 Pro rejection.\"\n513- );\n514: is_thinking_enabled = false;\n515- }\n516- }\n517-\n518: // 4. Generation Config & Thinking (Pass final is_thinking_enabled)\n519: let generation_config = build_generation_config(claude_req, has_web_search_tool, is_thinking_enabled);\n520-\n521- // 2. Contents (Messages)\n522- let contents = build_google_contents(\n--\n524- claude_req,\n525- &mut tool_id_to_name,\n526- &tool_name_to_schema,\n527: is_thinking_enabled,\n528: allow_dummy_thought,\n529- &mapped_model,\n530- &session_id,\n531- is_retry,\n--\n578- // 2. Remove systemInstruction (image generation does not support system prompts)\n579- obj.remove(\"systemInstruction\");\n580-\n581: // 3. Clean generationConfig (remove thinkingConfig, responseMimeType, responseModalities etc.)\n582- let gen_config = obj.entry(\"generationConfig\").or_insert_with(|| json!({}));\n583- if let Some(gen_obj) = gen_config.as_object_mut() {\n584: gen_obj.remove(\"thinkingConfig\");\n585- gen_obj.remove(\"responseMimeType\");\n586- gen_obj.remove(\"responseModalities\");\n587- gen_obj.insert(\"imageConfig\".to_string(), image_config);\n--\n621-/// \n622-/ 场景: 如果最后一条 Assistant 消息处于 Tool Use 流程中,但没有 Thinking 块,\n623-/ 说明这是一个由非 Thinking 模型发起的流程。此时强制开启 Thinking 会导致:\n624:/// \"final assistant message must start with a thinking block\" 错误。\n625-/// 我们无法伪造合法的 Thinking (因为签名问题),唯一的解法是本轮请求暂时禁用 Thinking。\n626:fn should_disable_thinking_due_to_history(messages: &[Message]) -> bool {\n627- // 逆序查找最后一条 Assistant 消息\n628- for msg in messages.iter().rev() {\n629- if msg.role == \"assistant\" {\n630- if let MessageContent::Array(blocks) = &msg.content {\n631- let has_tool_use = blocks.iter().any(|b| matches!(b, ContentBlock::ToolUse { .. }));\n632: let has_thinking = blocks.iter().any(|b| matches!(b, ContentBlock::Thinking { .. }));\n633- \n634- // 如果有工具调用,但没有 Thinking 块 -> 不兼容\n635: if has_tool_use && !has_thinking {\n636- tracing::info!(\"[Thinking-Mode] Detected ToolUse without Thinking in history. Requesting disable.\");\n637- return true;\n638- }\n--\n645- false\n646-}\n647-\n648:/// Check if thinking mode should be enabled by default for a given model\n649-///\n650:/// Claude Code v2.0.67+ enables thinking by default for Opus 4.5 models.\n651:/// This function determines if the model should have thinking enabled\n652:/// when no explicit thinking configuration is provided.\n653:fn should_enable_thinking_by_default(model: &str) -> bool {\n654- let model_lower = model.to_lowercase();\n655-\n656: // Enable thinking by default for Opus 4.5 variants\n657- if model_lower.contains(\"opus-4-5\") || model_lower.contains(\"opus-4.5\") {\n658- tracing::debug!(\n659: \"[Thinking-Mode] Auto-enabling thinking for Opus 4.5 model: {}\",\n660- model\n661- );\n662- return true;\n663- }\n664-\n665: // Also enable for explicit thinking model variants\n666: if model_lower.contains(\"-thinking\") {\n667- return true;\n668- }\n669-\n670- false\n671-}\n672-\n673:/// Minimum length for a valid thought_signature\n674-const MIN_SIGNATURE_LENGTH: usize = 50;\n675-\n676:/// [FIX #295] Check if we have any valid signature available for function calls\n677:/// This prevents Gemini 3 Pro from rejecting requests due to missing thought_signature\n678-/// \n679-/// [NEW FIX] Now also checks Session Cache to support retry scenarios\n680:fn has_valid_signature_for_function_calls(\n681- messages: &[Message],\n682- global_sig: &Option<String>,\n683- session_id: &str, // NEW: Add session_id parameter\n--\n686- if let Some(sig) = global_sig {\n687- if sig.len() >= MIN_SIGNATURE_LENGTH {\n688- tracing::debug!(\n689: \"[Signature-Check] Found valid signature in global store (len: {})\",\n690- sig.len()\n691- );\n692- return true;\n--\n694- }\n695-\n696- // 2. [NEW] Check Session Cache - this is critical for retry scenarios\n697: // When retrying, the signature may not be in messages but exists in Session Cache\n698: if let Some(sig) = crate::proxy::SignatureCache::global().get_session_signature(session_id) {\n699- if sig.len() >= MIN_SIGNATURE_LENGTH {\n700- tracing::info!(\n701: \"[Signature-Check] Found valid signature in SESSION cache (session: {}, len: {})\",\n702- session_id,\n703- sig.len()\n704- );\n--\n706- }\n707- }\n708-\n709: // 3. Check if any message has a thinking block with valid signature\n710- for msg in messages.iter().rev() {\n711- if msg.role == \"assistant\" {\n712- if let MessageContent::Array(blocks) = &msg.content {\n713- for block in blocks {\n714- if let ContentBlock::Thinking {\n715: signature: Some(sig),\n716- ..\n717- } = block\n718- {\n719- if sig.len() >= MIN_SIGNATURE_LENGTH {\n720- tracing::debug!(\n721: \"[Signature-Check] Found valid signature in message history (len: {})\",\n722- sig.len()\n723- );\n724- return true;\n--\n730- }\n731- \n732- tracing::warn!(\n733: \"[Signature-Check] No valid signature found (session: {}, checked: global store, session cache, message history)\",\n734- session_id\n735- );\n736- false\n--\n819- content: &MessageContent,\n820- is_assistant: bool,\n821- _claude_req: &ClaudeRequest,\n822: is_thinking_enabled: bool,\n823- session_id: &str,\n824: allow_dummy_thought: bool,\n825- is_retry: bool,\n826- tool_id_to_name: &mut HashMap<String, String>,\n827- tool_name_to_schema: &HashMap<String, Value>,\n828- mapped_model: &str,\n829: last_thought_signature: &mut Option<String>,\n830- pending_tool_use_ids: &mut Vec<String>,\n831- last_user_task_text_normalized: &mut Option<String>,\n832- previous_was_tool_result: &mut bool,\n--\n836- // Track tool results in the current turn to identify missing ones\n837- let mut current_turn_tool_result_ids = std::collections::HashSet::new();\n838-\n839: // Track if we have already seen non-thinking content in this message.\n840- / Anthropic/Gemini protocol: Thinking blocks MUST come first.\n841: let mut saw_non_thinking = false;\n842-\n843- match content {\n844- MessageContent::String(text) => {\n--\n866- }\n867-\n868- parts.push(json!({\"text\": text}));\n869: saw_non_thinking = true;\n870-\n871- // 记录最近一次 User 任务文本用于后续比对\n872- if !is_assistant {\n--\n875- *previous_was_tool_result = false;\n876- }\n877- }\n878: ContentBlock::Thinking { thinking, signature, .. } => {\n879: tracing::debug!(\"[DEBUG-TRANSFORM] Processing thinking block. Sig: {:?}\", signature);\n880-\n881- / [HOTFIX] Gemini Protocol Enforcement: Thinking block MUST be the first block.\n882: // If we already have content (like Text), we must downgrade this thinking block to Text.\n883: if saw_non_thinking || !parts.is_empty() {\n884- tracing::warn!(\"[Claude-Request] Thinking block found at non-zero index (prev parts: {}). Downgrading to Text.\", parts.len());\n885: if !thinking.is_empty() {\n886- parts.push(json!({\n887: \"text\": thinking\n888- }));\n889: saw_non_thinking = true;\n890- }\n891- continue;\n892- }\n893-\n894: // [FIX] If thinking is disabled (smart downgrade), convert ALL thinking blocks to text\n895: // to avoid \"thinking is disabled but message contains thinking\" error\n896: if !is_thinking_enabled {\n897: tracing::warn!(\"[Claude-Request] Thinking disabled. Downgrading thinking block to text.\");\n898: if !thinking.is_empty() {\n899- parts.push(json!({\n900: \"text\": thinking\n901- }));\n902- }\n903- continue;\n904- }\n905-\n906: // [FIX] Empty thinking blocks cause \"Field required\" errors.\n907: // We downgrade them to Text to avoid structural errors and signature mismatch.\n908: if thinking.is_empty() {\n909: tracing::warn!(\"[Claude-Request] Empty thinking block detected. Downgrading to Text.\");\n910- parts.push(json!({\n911- \"text\": \"...\"\n912- }));\n913- continue;\n914- }\n915-\n916: // [FIX #752] Strict signature validation\n917: // Only use signatures that are cached and compatible with the target model\n918: if let Some(sig) = signature {\n919: // Check signature length first - if it's too short, it's definitely invalid\n920- if sig.len() < MIN_SIGNATURE_LENGTH {\n921- tracing::warn!(\n922- \"[Thinking-Signature] Signature too short (len: {} < {}), downgrading to text.\",\n923- sig.len(), MIN_SIGNATURE_LENGTH\n924- );\n925: parts.push(json!({\"text\": thinking}));\n926: saw_non_thinking = true;\n927- continue;\n928- }\n929- \n930: let cached_family = crate::proxy::SignatureCache::global().get_signature_family(sig);\n931-\n932- match cached_family {\n933- Some(family) => {\n934- // Check compatibility\n935: // [NEW] If is_retry is true, force incompatibility to strip historical signatures\n936- // which likely caused the previous 400 error.\n937- let compatible = !is_retry && is_model_compatible(&family, mapped_model);\n938- \n939- if !compatible {\n940- tracing::warn!(\n941: \"[Thinking-Signature] {} signature (Family: {}, Target: {}). Downgrading to text.\",\n942- if is_retry { \"Stripping historical\" } else { \"Incompatible\" },\n943- family, mapped_model\n944- );\n945: parts.push(json!({\"text\": thinking}));\n946: saw_non_thinking = true;\n947- continue;\n948- }\n949: // Compatible and not a retry: use signature\n950: *last_thought_signature = Some(sig.clone());\n951- let mut part = json!({\n952: \"text\": thinking,\n953: \"thought\": true,\n954: \"thoughtSignature\": sig\n955- });\n956- crate::proxy::common::json_schema::clean_json_schema(&mut part);\n957- parts.push(part);\n958- }\n959- None => {\n960: // For JSON tool calling compatibility, if signature is long enough but unknown,\n961- // we should trust it rather than downgrade to text\n962- if sig.len() >= MIN_SIGNATURE_LENGTH {\n963- tracing::debug!(\n964: \"[Thinking-Signature] Unknown signature origin but valid length (len: {}), using as-is for JSON tool calling.\",\n965- sig.len()\n966- );\n967: *last_thought_signature = Some(sig.clone());\n968- let mut part = json!({\n969: \"text\": thinking,\n970: \"thought\": true,\n971: \"thoughtSignature\": sig\n972- });\n973- crate::proxy::common::json_schema::clean_json_schema(&mut part);\n974- parts.push(part);\n975- } else {\n976- / Unknown and too short: downgrade to text for safety\n977- tracing::warn!(\n978: \"[Thinking-Signature] Unknown signature origin and too short (len: {}). Downgrading to text for safety.\",\n979- sig.len()\n980- );\n981: parts.push(json!({\"text\": thinking}));\n982: saw_non_thinking = true;\n983- continue;\n984- }\n985- }\n986- }\n987- } else {\n988: // No signature: downgrade to text\n989: tracing::warn!(\"[Thinking-Signature] No signature provided. Downgrading to text.\");\n990: parts.push(json!({\"text\": thinking}));\n991: saw_non_thinking = true;\n992- }\n993- }\n994- ContentBlock::RedactedThinking { data } => {\n--\n997- parts.push(json!({\n998- \"text\": format!(\"[Redacted Thinking: {}]\", data)\n999- }));\n1000: saw_non_thinking = true;\n1001- continue;\n1002- }\n1003- ContentBlock::Image { source, .. } => {\n--\n1008- \"data\": source.data\n1009- }\n1010- }));\n1011: saw_non_thinking = true;\n1012- }\n1013- }\n1014- ContentBlock::Document { source, .. } => {\n--\n1019- \"data\": source.data\n1020- }\n1021- }));\n1022: saw_non_thinking = true;\n1023- }\n1024- }\n1025: ContentBlock::ToolUse { id, name, input, signature, .. } => {\n1026- let mut final_input = input.clone();\n1027- \n1028- // [New] 利用通用引擎修正参数类型 (替代以前硬编码的 shell 工具修复逻辑)\n--\n1037- \"id\": id\n1038- }\n1039- });\n1040: saw_non_thinking = true;\n1041-\n1042- // Track pending tool use\n1043- if is_assistant {\n--\n1052-\n1053- // Signature resolution logic\n1054- / Priority: Client -> Context -> Session Cache -> Tool Cache -> Global Store (deprecated)\n1055: // [CRITICAL FIX] Do NOT use skip_thought_signature_validator for Vertex AI\n1056: // Vertex AI rejects this sentinel value, so we only add thoughtSignature if we have a real one\n1057: let final_sig = signature.as_ref()\n1058: .or(last_thought_signature.as_ref())\n1059- .cloned()\n1060- .or_else(|| {\n1061: // [NEW v3.3.17] Try session-based signature cache first (Layer 3)\n1062- // This provides conversation-level isolation\n1063: crate::proxy::SignatureCache::global().get_session_signature(session_id)\n1064- .map(|s| {\n1065- tracing::info!(\n1066: \"[Claude-Request] Recovered signature from SESSION cache (session: {}, len: {})\",\n1067- session_id, s.len()\n1068- );\n1069- s\n1070- })\n1071- })\n1072- .or_else(|| {\n1073: // Try tool-specific signature cache (Layer 1)\n1074: crate::proxy::SignatureCache::global().get_tool_signature(id)\n1075- .map(|s| {\n1076: tracing::info!(\"[Claude-Request] Recovered signature from TOOL cache for tool_id: {}\", id);\n1077- s\n1078- })\n1079- })\n1080- .or_else(|| {\n1081- // [DEPRECATED] Global store fallback - kept for backward compatibility\n1082: let global_sig = get_thought_signature();\n1083- if global_sig.is_some() {\n1084- tracing::warn!(\n1085: \"[Claude-Request] Using deprecated GLOBAL thought_signature fallback (length: {}). \\\n1086- This indicates session cache miss.\",\n1087- global_sig.as_ref().unwrap().len()\n1088- );\n1089- }\n1090- global_sig\n1091- });\n1092: // [FIX #752] Validate signature before using\n1093: // Only add thoughtSignature if we have a valid and compatible one\n1094- if let Some(sig) = final_sig {\n1095: // [NEW] If this is a retry, do NOT backfill signatures to avoid issues.\n1096: if is_retry && signature.is_none() {\n1097: tracing::warn!(\"[Tool-Signature] Skipping signature backfill for tool_use: {} during retry.\", id);\n1098- } else {\n1099: // Check signature length first - if it's too short, it's definitely invalid\n1100- if sig.len() < MIN_SIGNATURE_LENGTH {\n1101- tracing::warn!(\n1102- \"[Tool-Signature] Signature too short for tool_use: {} (len: {} < {}), skipping.\",\n1103- id, sig.len(), MIN_SIGNATURE_LENGTH\n1104- );\n1105- } else {\n1106: // Check signature compatibility (optional for tool_use)\n1107- let cached_family = crate::proxy::SignatureCache::global()\n1108: .get_signature_family(&sig);\n1109-\n1110- let should_use_sig = match cached_family {\n1111- Some(family) => {\n--\n1114- true\n1115- } else {\n1116- tracing::warn!(\n1117: \"[Tool-Signature] Incompatible signature for tool_use: {} (Family: {}, Target: {})\",\n1118- id, family, mapped_model\n1119- );\n1120- false\n1121- }\n1122- }\n1123- None => {\n1124: // For JSON tool calling compatibility, if signature is long enough but unknown,\n1125- // we should trust it rather than drop it\n1126- if sig.len() >= MIN_SIGNATURE_LENGTH {\n1127- tracing::debug!(\n1128: \"[Tool-Signature] Unknown signature origin but valid length (len: {}) for tool_use: {}, using as-is for JSON tool calling.\",\n1129- sig.len(), id\n1130- );\n1131- true\n1132- } else {\n1133: // Unknown and too short: only use in non-thinking mode\n1134: if is_thinking_enabled {\n1135- tracing::warn!(\n1136: \"[Tool-Signature] Unknown signature origin and too short for tool_use: {} (len: {}). Dropping in thinking mode.\",\n1137- id, sig.len()\n1138- );\n1139- false\n1140- } else {\n1141: // In non-thinking mode, allow unknown signatures\n1142- true\n1143- }\n1144- }\n1145- }\n1146- };\n1147- if should_use_sig {\n1148: part[\"thoughtSignature\"] = json!(sig);\n1149- }\n1150- }\n1151- }\n1152- } else {\n1153: // [NEW] Handle missing signature for Gemini thinking models\n1154: // Use skip_thought_signature_validator as a sentinel value\n1155- let is_google_cloud = mapped_model.starts_with(\"projects/\");\n1156: if is_thinking_enabled && !is_google_cloud {\n1157- tracing::debug!(\"[Tool-Signature] Adding GEMINI_SKIP_SIGNATURE for tool_use: {}\", id);\n1158: part[\"thoughtSignature\"] = json!(\"skip_thought_signature_validator\");\n1159- }\n1160- }\n1161- parts.push(part);\n--\n1235- }));\n1236-\n1237- // [FIX] Tool Result 也需要回填签名(如果上下文中有)\n1238: if let Some(sig) = last_thought_signature.as_ref() {\n1239- if let Some(last_part) = parts.last_mut() {\n1240: last_part[\"thoughtSignature\"] = json!(sig);\n1241- }\n1242- }\n1243-\n--\n1282- pending_tool_use_ids.clear();\n1283- }\n1284-\n1285: // Fix for \"Thinking enabled, assistant message must start with thinking block\" 400 error\n1286- // [Optimization] Apply this to ALL assistant messages in history, not just the last one.\n1287: // Vertex AI requires every assistant message to start with a thinking block when thinking is enabled.\n1288: if allow_dummy_thought && is_assistant && is_thinking_enabled {\n1289: let has_thought_part = parts\n1290- .iter()\n1291- .any(|p| {\n1292: p.get(\"thought\").and_then(|v| v.as_bool()).unwrap_or(false)\n1293: || p.get(\"thoughtSignature\").is_some()\n1294: || p.get(\"thought\").and_then(|v| v.as_str()).is_some() // 某些情况下可能是 text + thought: true 的组合\n1295- });\n1296-\n1297: if !has_thought_part {\n1298: // Prepend a dummy thinking block to satisfy Gemini v1internal requirements\n1299- parts.insert(\n1300- 0,\n1301- json!({\n1302- \"text\": \"Thinking...\",\n1303: \"thought\": true\n1304- }),\n1305- );\n1306: tracing::debug!(\"Injected dummy thought block for historical assistant message at index {}\", parts.len());\n1307- } else {\n1308: // [Crucial Check] 即使有 thought 块,也必须保证它位于 parts 的首位 (Index 0)\n1309: // 且必须包含 thought: true 标记\n1310: let first_is_thought = parts.get(0).map_or(false, |p| {\n1311: (p.get(\"thought\").is_some() || p.get(\"thoughtSignature\").is_some())\n1312: && p.get(\"text\").is_some() // 对于 v1internal,通常 text + thought: true 才是合规的思维块\n1313- });\n1314-\n1315: if !first_is_thought {\n1316- // 如果首项不符合思维块特征,强制补入一个\n1317- parts.insert(\n1318- 0,\n1319- json!({\n1320- \"text\": \"...\",\n1321: \"thought\": true\n1322- }),\n1323- );\n1324: tracing::debug!(\"First part of model message at {} is not a valid thought block. Prepending dummy.\", parts.len());\n1325- } else {\n1326: // 确保首项包含了 thought: true (防止只有 signature 的情况)\n1327- if let Some(p0) = parts.get_mut(0) {\n1328: if p0.get(\"thought\").is_none() {\n1329: p0.as_object_mut().map(|obj| obj.insert(\"thought\".to_string(), json!(true)));\n1330- }\n1331- }\n1332- }\n--\n1340-fn build_google_content(\n1341- msg: &Message,\n1342- claude_req: &ClaudeRequest,\n1343: is_thinking_enabled: bool,\n1344- session_id: &str,\n1345: allow_dummy_thought: bool,\n1346- is_retry: bool,\n1347- tool_id_to_name: &mut HashMap<String, String>,\n1348- tool_name_to_schema: &HashMap<String, Value>,\n1349- mapped_model: &str,\n1350: last_thought_signature: &mut Option<String>,\n1351- pending_tool_use_ids: &mut Vec<String>,\n1352- last_user_task_text_normalized: &mut Option<String>,\n1353- previous_was_tool_result: &mut bool,\n--\n1395- &msg.content,\n1396- msg.role == \"assistant\",\n1397- claude_req,\n1398: is_thinking_enabled,\n1399- session_id,\n1400: allow_dummy_thought,\n1401- is_retry,\n1402- tool_id_to_name,\n1403- tool_name_to_schema,\n1404- mapped_model,\n1405: last_thought_signature,\n1406- pending_tool_use_ids,\n1407- last_user_task_text_normalized,\n1408- previous_was_tool_result,\n--\n1425- claude_req: &ClaudeRequest,\n1426- tool_id_to_name: &mut HashMap<String, String>,\n1427- tool_name_to_schema: &HashMap<String, Value>,\n1428: is_thinking_enabled: bool,\n1429: allow_dummy_thought: bool,\n1430- mapped_model: &str,\n1431: session_id: &str, // [NEW v3.3.17] Session ID for signature caching\n1432- is_retry: bool,\n1433-) -> Result<Value, String> {\n1434- let mut contents = Vec::new();\n1435: let mut last_thought_signature: Option<String> = None;\n1436- let mut _accumulated_usage: Option<Value> = None;\n1437- // Track pending tool_use IDs for recovery\n1438- let mut pending_tool_use_ids: Vec<String> = Vec::new();\n--\n1460- let google_content = build_google_content(\n1461- msg,\n1462- claude_req,\n1463: is_thinking_enabled,\n1464- session_id,\n1465: allow_dummy_thought,\n1466- is_retry,\n1467- tool_id_to_name,\n1468- tool_name_to_schema,\n1469- mapped_model,\n1470: &mut last_thought_signature,\n1471- &mut pending_tool_use_ids,\n1472- &mut last_user_task_text_normalized,\n1473- &mut previous_was_tool_result,\n--\n1479- }\n1480- }\n1481-\n1482: // [Removed] ensure_last_assistant_has_thinking\n1483: // Corrupted signature issues proved we cannot fake thinking blocks.\n1484: // Instead we rely on should_disable_thinking_due_to_history to prevent this state.\n1485-\n1486- // [FIX P3-3] Strict Role Alternation (Message Merging)\n1487- // Merge adjacent messages with the same role to satisfy Gemini's strict alternation rule\n1488- let mut merged_contents = merge_adjacent_roles(contents);\n1489-\n1490: // [FIX P3-4] Deep \"Un-thinking\" Cleanup\n1491: // If thinking is disabled (e.g. smart downgrade), recursively remove any stray 'thought'/'thoughtSignature'\n1492- // This is critical because converting Thinking->Text isn't enough; metadata must be gone.\n1493: if !is_thinking_enabled {\n1494- for msg in &mut merged_contents {\n1495: clean_thinking_fields_recursive(msg);\n1496- }\n1497- }\n1498-\n--\n1519- current_parts.extend(next_parts.clone());\n1520-\n1521- / [FIX #709] Core Fix: After merging parts from adjacent messages,\n1522: // we must RE-SORT them to ensure any thinking blocks from the\n1523- // second message are moved to the very front of the combined array.\n1524- reorder_gemini_parts(current_parts);\n1525- }\n--\n1609-fn build_generation_config(\n1610- claude_req: &ClaudeRequest,\n1611- has_web_search: bool,\n1612: is_thinking_enabled: bool\n1613-) -> Value {\n1614- let mut config = json!({});\n1615-\n1616- // Thinking 配置\n1617: if let Some(thinking) = &claude_req.thinking {\n1618: // [New Check] 必须 is_thinking_enabled 为真才生成 thinkingConfig\n1619: if thinking.type_ == \"enabled\" && is_thinking_enabled {\n1620: let mut thinking_config = json!({\"includeThoughts\": true});\n1621-\n1622: if let Some(budget_tokens) = thinking.budget_tokens {\n1623- let mut budget = budget_tokens;\n1624- // gemini-2.5-flash 上限 24576\n1625- let is_flash_model =\n--\n1627- if is_flash_model {\n1628- budget = budget.min(24576);\n1629- }\n1630: thinking_config[\"thinkingBudget\"] = json!(budget);\n1631- }\n1632-\n1633: config[\"thinkingConfig\"] = thinking_config;\n1634- }\n1635- }\n1636-\n--\n1672- // Respect client-provided max_tokens (aligns with OpenAI mapper behavior)\n1673- let mut final_max_tokens: i64 = claude_req.max_tokens.map(|t| t as i64).unwrap_or(16384);\n1674- \n1675: // [NEW] 确保 maxOutputTokens 大于 thinkingBudget (API 强约束)\n1676: if let Some(thinking_config) = config.get(\"thinkingConfig\") {\n1677: if let Some(budget) = thinking_config.get(\"thinkingBudget\").and_then(|t| t.as_u64()) {\n1678- if final_max_tokens <= budget as i64 {\n1679- final_max_tokens = (budget + 8192) as i64;\n1680- tracing::info!(\n1681: \"[Generation-Config] Bumping maxOutputTokens to {} due to thinking budget of {}\", \n1682- final_max_tokens, budget\n1683- );\n1684- }\n--\n1702- config\n1703-}\n1704-\n1705:/// Recursively remove 'thought' and 'thoughtSignature' fields\n1706:/// Used when downgrading thinking (e.g. during 400 retry)\n1707:pub fn clean_thinking_fields_recursive(val: &mut Value) {\n1708- match val {\n1709- Value::Object(map) => {\n1710: map.remove(\"thought\");\n1711: map.remove(\"thoughtSignature\");\n1712- for (_, v) in map.iter_mut() {\n1713: clean_thinking_fields_recursive(v);\n1714- }\n1715- }\n1716- Value::Array(arr) => {\n1717- for v in arr.iter_mut() {\n1718: clean_thinking_fields_recursive(v);\n1719- }\n1720- }\n1721- _ => {}\n--\n1736- if c == t { return true; }\n1737- \n1738- // Check specific families\n1739: // Vertex AI signatures are very strict. 1.5-pro vs 1.5-flash are NOT cross-compatible.\n1740- // 2.0-flash vs 2.0-pro are also NOT cross-compatible.\n1741- \n1742- // Exact model string match (already handled by c == t)\n--\n1745- if c.contains(\"claude-3-5\") && t.contains(\"claude-3-5\") { return true; }\n1746- if c.contains(\"claude-3-7\") && t.contains(\"claude-3-7\") { return true; }\n1747- \n1748: // Gemini models: strict family match required for signatures\n1749- if c.contains(\"gemini-1.5-pro\") && t.contains(\"gemini-1.5-pro\") { return true; }\n1750- if c.contains(\"gemini-1.5-flash\") && t.contains(\"gemini-1.5-flash\") { return true; }\n1751- if c.contains(\"gemini-2.0-flash\") && t.contains(\"gemini-2.0-flash\") { return true; }\n--\n1771- \"role\": \"assistant\",\n1772- \"content\": [\n1773- {\n1774: \"type\": \"thinking\",\n1775: \"thinking\": \"test\",\n1776: \"signature\": \"sig_1234567890\",\n1777- \"cache_control\": null\n1778- }\n1779- ]\n--\n1809- temperature: None,\n1810- top_p: None,\n1811- top_k: None,\n1812: thinking: None,\n1813- metadata: None,\n1814- output_config: None,\n1815- size: None,\n--\n1884- id: \"call_1\".to_string(),\n1885- name: \"run_command\".to_string(),\n1886- input: json!({\"command\": \"ls\"}),\n1887: signature: None,\n1888- cache_control: None,\n1889- }\n1890- ]),\n--\n1908- temperature: None,\n1909- top_p: None,\n1910- top_k: None,\n1911: thinking: None,\n1912- metadata: None,\n1913- output_config: None,\n1914- size: None,\n--\n1950- role: \"assistant\".to_string(),\n1951- content: MessageContent::Array(vec![\n1952- ContentBlock::Thinking {\n1953: thinking: \"Let me think...\".to_string(),\n1954: signature: Some(\"sig123\".to_string()),\n1955- cache_control: Some(json!({\"type\": \"ephemeral\"})), // 这个应该被清理\n1956- },\n1957- ContentBlock::Text {\n--\n1980- temperature: None,\n1981- top_p: None,\n1982- top_k: None,\n1983: thinking: None,\n1984- metadata: None,\n1985- output_config: None,\n1986- size: None,\n--\n2000- }\n2001-\n2002- #[test]\n2003: fn test_thinking_mode_auto_disable_on_tool_use_history() {\n2004- // [场景] 历史消息中有一个工具调用链,且 Assistant 消息没有 Thinking 块\n2005- / 期望: 系统自动降级,禁用 Thinking 模式,以避免 400 错误\n2006- let req = ClaudeRequest {\n--\n2022- name: \"list_files\".to_string(),\n2023- input: json!({}),\n2024- cache_control: None, \n2025: signature: None \n2026- },\n2027- ]),\n2028- },\n--\n2054- temperature: None,\n2055- top_p: None,\n2056- top_k: None,\n2057: thinking: Some(ThinkingConfig {\n2058- type_: \"enabled\".to_string(),\n2059- budget_tokens: Some(1024),\n2060- }),\n--\n2070- let body = result.unwrap();\n2071- let request = &body[\"request\"];\n2072-\n2073: // 验证: generationConfig 中不应包含 thinkingConfig (因为被降级了)\n2074: // 即使请求中明确启用了 thinking\n2075- if let Some(gen_config) = request.get(\"generationConfig\") {\n2076: assert!(gen_config.get(\"thinkingConfig\").is_none(), \"thinkingConfig should be removed due to downgrade\");\n2077- }\n2078- \n2079- / 验证: 依然能生成有效的请求体\n--\n2083-\n2084-\n2085- #[test]\n2086: fn test_thinking_block_not_prepend_when_disabled() {\n2087: // 验证当 thinking 未启用时,不会补全 thinking 块\n2088- let req = ClaudeRequest {\n2089- model: \"claude-sonnet-4-5\".to_string(),\n2090- messages: vec![\n--\n2108- temperature: None,\n2109- top_p: None,\n2110- top_k: None,\n2111: thinking: None, // 未启用 thinking\n2112- metadata: None,\n2113- output_config: None,\n2114- size: None,\n--\n2129-\n2130- let parts = last_model_msg[\"parts\"].as_array().unwrap();\n2131- \n2132: // 验证没有补全 thinking 块\n2133- assert_eq!(parts.len(), 1, \"Should only have the original text block\");\n2134- assert_eq!(parts[0][\"text\"], \"Response\");\n2135- }\n2136-\n2137- #[test]\n2138: fn test_thinking_block_empty_content_fix() {\n2139: // [场景] 客户端发送了一个内容为空的 thinking 块\n2140- / 期望: 自动填充 \"...\"\n2141- let req = ClaudeRequest {\n2142- model: \"claude-sonnet-4-5\".to_string(),\n--\n2145- role: \"assistant\".to_string(),\n2146- content: MessageContent::Array(vec![\n2147- ContentBlock::Thinking {\n2148: thinking: \"\".to_string(), // 空内容\n2149: signature: Some(\"sig\".to_string()),\n2150- cache_control: None,\n2151- },\n2152- ContentBlock::Text { text: \"Hi\".to_string() }\n--\n2160- temperature: None,\n2161- top_p: None,\n2162- top_k: None,\n2163: thinking: Some(ThinkingConfig {\n2164- type_: \"enabled\".to_string(),\n2165- budget_tokens: Some(1024),\n2166- }),\n--\n2176- let contents = body[\"request\"][\"contents\"].as_array().unwrap();\n2177- let parts = contents[0][\"parts\"].as_array().unwrap();\n2178- \n2179: // 验证 thinking 块\n2180: assert_eq!(parts[0][\"text\"], \"...\", \"Empty thinking should be filled with ...\");\n2181: assert!(parts[0].get(\"thought\").is_none(), \"Empty thinking should be downgraded to text\");\n2182- }\n2183-\n2184- #[test]\n2185: fn test_redacted_thinking_degradation() {\n2186- // [场景] 客户端包含 RedactedThinking\n2187: // 期望: 降级为普通文本,不带 thought: true\n2188- let req = ClaudeRequest {\n2189- model: \"claude-sonnet-4-5\".to_string(),\n2190- messages: vec![\n--\n2205- temperature: None,\n2206- top_p: None,\n2207- top_k: None,\n2208: thinking: None,\n2209- metadata: None,\n2210- output_config: None,\n2211- size: None,\n--\n2220- // 验证 RedactedThinking -> Text\n2221- let text = parts[0][\"text\"].as_str().unwrap();\n2222- assert!(text.contains(\"[Redacted Thinking: some data]\"));\n2223: assert!(parts[0].get(\"thought\").is_none(), \"Redacted thinking should NOT have thought: true\");\n2224- }\n2225-\n2226- // ==================================================================================\n2227- / [FIX #564] Test: Thinking blocks are sorted to be first after context compression\n2228- // ==================================================================================\n2229- #[test]\n2230: fn test_thinking_blocks_sorted_first_after_compression() {\n2231: // Simulate kilo context compression reordering: text BEFORE thinking\n2232- let mut messages = vec![\n2233- Message {\n2234- role: \"assistant\".to_string(),\n--\n2236- / Wrong order: Text before Thinking (simulates kilo compression)\n2237- ContentBlock::Text { text: \"Some regular text\".to_string() },\n2238- ContentBlock::Thinking { \n2239: thinking: \"My thinking process\".to_string(),\n2240: signature: Some(\"valid_signature_1234567890_abcdefghij_klmnopqrstuvwxyz_test\".to_string()),\n2241- cache_control: None,\n2242- },\n2243- ContentBlock::Text { text: \"More text\".to_string() },\n--\n2246- ];\n2247- \n2248- // Apply the fix\n2249: sort_thinking_blocks_first(&mut messages);\n2250- \n2251: // Verify thinking is now first\n2252- if let MessageContent::Array(blocks) = &messages[0].content {\n2253- assert_eq!(blocks.len(), 3, \"Should still have 3 blocks\");\n2254- assert!(matches!(blocks[0], ContentBlock::Thinking { .. }), \"Thinking should be first\");\n--\n2256- assert!(matches!(blocks[2], ContentBlock::Text { .. }), \"Text should be third\");\n2257- \n2258- // Verify content preserved\n2259: if let ContentBlock::Thinking { thinking, .. } = &blocks[0] {\n2260: assert_eq!(thinking, \"My thinking process\");\n2261- }\n2262- } else {\n2263- panic!(\"Expected Array content\");\n--\n2265- }\n2266-\n2267- #[test]\n2268: fn test_thinking_blocks_no_reorder_when_already_first() {\n2269- / Correct order: Thinking already first - should not trigger reorder\n2270- let mut messages = vec![\n2271- Message {\n2272- role: \"assistant\".to_string(),\n2273- content: MessageContent::Array(vec![\n2274- ContentBlock::Thinking { \n2275: thinking: \"My thinking\".to_string(),\n2276: signature: Some(\"sig123\".to_string()),\n2277- cache_control: None,\n2278- },\n2279- ContentBlock::Text { text: \"Some text\".to_string() },\n--\n2282- ];\n2283- \n2284- // Apply the fix (should be no-op)\n2285: sort_thinking_blocks_first(&mut messages);\n2286- \n2287- // Verify order unchanged\n2288- if let MessageContent::Array(blocks) = &messages[0].content {","numLines":1082}},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01ATvrfohM4tn5nXZaN5yk6T","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"Let me read the key sections of the Antigravity-Manager request.rs to understand the full logic, particularly around:\n1. Thinking enable/disable\n2. Signature availability checks\n3. Tool call signature backfill\n4. Dummy/sentinel signature restrictions for Vertex AI","signature":"Eq4DCkYICxgCKkCK3ybVhzEC6/MCe8p96XaFWcMb1wv4lBgGXX8B9AH81o9Hsy5IuDcLMCEU1qxWH97RdwY0Sv3xFg83CEV08+iUEgxcS6Nsgg1GMKEW2lsaDMUVLF3xFAhh5WJt8SIwEjR8kRXsYr+sl7nAHMPwUUAkS6GSL0UAgHkJFzIme/pYH6ZmEdEZ+W6MTd4HWkRfKpUCBv1jDB2kciX30qM+04z7ERR3n4lpWq3+XWqFuVmqZHBUnTt818Zs6kuTwaG8GZEoUKbupEr8OI34xtrHppPsAmf+o/OwWvGzMmkR3xWqXDSLN7OHykNR6OEg1UJ0sFvv+7OzF7rWrHhlxtFVq9r4qEHmXtrtMW2IRO/WLac4tgNIjG5uRC9HRjlY/SoUfV4Rtv2UdH8oCxd3sXbn1OIp09fBZd3AbtpvG705x1B0Of20kJiiHV3Ziy6GQVNeR0rq1uyraPIYs5apvn1FZAcbdvbUJpDHd0IMqPoDDcTe2NjXkGPkQzow29zmDmBxGt5f16M+VU0239G0A7HQDxyIMJWy6TS7rOg5j7UgJUNJdzd6Y6MqIxgB"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":9007,"cache_creation_input_tokens":31550,"cache_read_input_tokens":37768,"cache_creation":{"ephemeral_5m_input_tokens":31550,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"9d99ca9b-2d84-416d-804c-e8dbdbef0b3d"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01ATvrfohM4tn5nXZaN5yk6T","type":"message","role":"assistant","content":[{"type":"text","text":"Let me read specific sections of the request.rs for the complete signature handling logic."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":9007,"cache_creation_input_tokens":31550,"cache_read_input_tokens":37768,"cache_creation":{"ephemeral_5m_input_tokens":31550,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"5213c204-6477-4a75-8e09-a05f805799b8"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01ATvrfohM4tn5nXZaN5yk6T","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01W7DhU9E4TRfe3R4Q1584nG","name":"Read","input":{"file_path":"/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs","offset":670,"limit":200},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":9007,"cache_creation_input_tokens":31550,"cache_read_input_tokens":37768,"cache_creation":{"ephemeral_5m_input_tokens":31550,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"08349a53-712f-4c8f-b6ec-0c568fa5b04c"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01ATvrfohM4tn5nXZaN5yk6T","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01JxwAGrkFXZc5UGyLsgt6aH","name":"Read","input":{"file_path":"/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs","offset":1045,"limit":150},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":9007,"cache_creation_input_tokens":31550,"cache_read_input_tokens":37768,"cache_creation":{"ephemeral_5m_input_tokens":31550,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"b657b4aa-54fe-47bb-a5bd-3d39a7dd1a63"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01ATvrfohM4tn5nXZaN5yk6T","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01QvFRXVPiZ89LqhzWdsGox1","name":"Read","input":{"file_path":"/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs"},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":9007,"cache_creation_input_tokens":31550,"cache_read_input_tokens":37768,"cache_creation":{"ephemeral_5m_input_tokens":31550,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"02ae0281-4e03-408d-8c27-d8fef085c857"},{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01JxwAGrkFXZc5UGyLsgt6aH","type":"tool_result","content":" 1045→ }\n 1046→\n 1047→ // [New] 递归清理参数中可能存在的非法校验字段\n 1048→ crate::proxy::common::json_schema::clean_json_schema(&mut part);\n 1049→\n 1050→ // 存储 id -> name 映射\n 1051→ tool_id_to_name.insert(id.clone(), name.clone());\n 1052→\n 1053→ // Signature resolution logic\n 1054→ // Priority: Client -> Context -> Session Cache -> Tool Cache -> Global Store (deprecated)\n 1055→ // [CRITICAL FIX] Do NOT use skip_thought_signature_validator for Vertex AI\n 1056→ // Vertex AI rejects this sentinel value, so we only add thoughtSignature if we have a real one\n 1057→ let final_sig = signature.as_ref()\n 1058→ .or(last_thought_signature.as_ref())\n 1059→ .cloned()\n 1060→ .or_else(|| {\n 1061→ // [NEW v3.3.17] Try session-based signature cache first (Layer 3)\n 1062→ // This provides conversation-level isolation\n 1063→ crate::proxy::SignatureCache::global().get_session_signature(session_id)\n 1064→ .map(|s| {\n 1065→ tracing::info!(\n 1066→ \"[Claude-Request] Recovered signature from SESSION cache (session: {}, len: {})\",\n 1067→ session_id, s.len()\n 1068→ );\n 1069→ s\n 1070→ })\n 1071→ })\n 1072→ .or_else(|| {\n 1073→ // Try tool-specific signature cache (Layer 1)\n 1074→ crate::proxy::SignatureCache::global().get_tool_signature(id)\n 1075→ .map(|s| {\n 1076→ tracing::info!(\"[Claude-Request] Recovered signature from TOOL cache for tool_id: {}\", id);\n 1077→ s\n 1078→ })\n 1079→ })\n 1080→ .or_else(|| {\n 1081→ // [DEPRECATED] Global store fallback - kept for backward compatibility\n 1082→ let global_sig = get_thought_signature();\n 1083→ if global_sig.is_some() {\n 1084→ tracing::warn!(\n 1085→ \"[Claude-Request] Using deprecated GLOBAL thought_signature fallback (length: {}). \\\n 1086→ This indicates session cache miss.\",\n 1087→ global_sig.as_ref().unwrap().len()\n 1088→ );\n 1089→ }\n 1090→ global_sig\n 1091→ });\n 1092→ // [FIX #752] Validate signature before using\n 1093→ // Only add thoughtSignature if we have a valid and compatible one\n 1094→ if let Some(sig) = final_sig {\n 1095→ // [NEW] If this is a retry, do NOT backfill signatures to avoid issues.\n 1096→ if is_retry && signature.is_none() {\n 1097→ tracing::warn!(\"[Tool-Signature] Skipping signature backfill for tool_use: {} during retry.\", id);\n 1098→ } else {\n 1099→ // Check signature length first - if it's too short, it's definitely invalid\n 1100→ if sig.len() < MIN_SIGNATURE_LENGTH {\n 1101→ tracing::warn!(\n 1102→ \"[Tool-Signature] Signature too short for tool_use: {} (len: {} < {}), skipping.\",\n 1103→ id, sig.len(), MIN_SIGNATURE_LENGTH\n 1104→ );\n 1105→ } else {\n 1106→ // Check signature compatibility (optional for tool_use)\n 1107→ let cached_family = crate::proxy::SignatureCache::global()\n 1108→ .get_signature_family(&sig);\n 1109→\n 1110→ let should_use_sig = match cached_family {\n 1111→ Some(family) => {\n 1112→ // For tool_use, check compatibility\n 1113→ if is_model_compatible(&family, mapped_model) {\n 1114→ true\n 1115→ } else {\n 1116→ tracing::warn!(\n 1117→ \"[Tool-Signature] Incompatible signature for tool_use: {} (Family: {}, Target: {})\",\n 1118→ id, family, mapped_model\n 1119→ );\n 1120→ false\n 1121→ }\n 1122→ }\n 1123→ None => {\n 1124→ // For JSON tool calling compatibility, if signature is long enough but unknown,\n 1125→ // we should trust it rather than drop it\n 1126→ if sig.len() >= MIN_SIGNATURE_LENGTH {\n 1127→ tracing::debug!(\n 1128→ \"[Tool-Signature] Unknown signature origin but valid length (len: {}) for tool_use: {}, using as-is for JSON tool calling.\",\n 1129→ sig.len(), id\n 1130→ );\n 1131→ true\n 1132→ } else {\n 1133→ // Unknown and too short: only use in non-thinking mode\n 1134→ if is_thinking_enabled {\n 1135→ tracing::warn!(\n 1136→ \"[Tool-Signature] Unknown signature origin and too short for tool_use: {} (len: {}). Dropping in thinking mode.\",\n 1137→ id, sig.len()\n 1138→ );\n 1139→ false\n 1140→ } else {\n 1141→ // In non-thinking mode, allow unknown signatures\n 1142→ true\n 1143→ }\n 1144→ }\n 1145→ }\n 1146→ };\n 1147→ if should_use_sig {\n 1148→ part[\"thoughtSignature\"] = json!(sig);\n 1149→ }\n 1150→ }\n 1151→ }\n 1152→ } else {\n 1153→ // [NEW] Handle missing signature for Gemini thinking models\n 1154→ // Use skip_thought_signature_validator as a sentinel value\n 1155→ let is_google_cloud = mapped_model.starts_with(\"projects/\");\n 1156→ if is_thinking_enabled && !is_google_cloud {\n 1157→ tracing::debug!(\"[Tool-Signature] Adding GEMINI_SKIP_SIGNATURE for tool_use: {}\", id);\n 1158→ part[\"thoughtSignature\"] = json!(\"skip_thought_signature_validator\");\n 1159→ }\n 1160→ }\n 1161→ parts.push(part);\n 1162→ }\n 1163→ ContentBlock::ToolResult {\n 1164→ tool_use_id,\n 1165→ content,\n 1166→ is_error,\n 1167→ ..\n 1168→ } => {\n 1169→ // Mark this tool ID as resolved in this turn\n 1170→ current_turn_tool_result_ids.insert(tool_use_id.clone());\n 1171→ // 优先使用之前记录的 name,否则用 tool_use_id\n 1172→ let func_name = tool_id_to_name\n 1173→ .get(tool_use_id)\n 1174→ .cloned()\n 1175→ .unwrap_or_else(|| tool_use_id.clone());\n 1176→\n 1177→ // [FIX #593] 工具输出压缩: 处理超大工具输出\n 1178→ // 使用智能压缩策略(浏览器快照、大文件提示等)\n 1179→ let mut compacted_content = content.clone();\n 1180→ if let Some(blocks) = compacted_content.as_array_mut() {\n 1181→ tool_result_compressor::sanitize_tool_result_blocks(blocks);\n 1182→ }\n 1183→\n 1184→ // Smart Truncation: strict image removal\n 1185→ // Remove all Base64 images from historical tool results to save context.\n 1186→ // Only allow text.\n 1187→ let mut merged_content = match &compacted_content {\n 1188→ serde_json::Value::String(s) => s.clone(),\n 1189→ serde_json::Value::Array(arr) => arr\n 1190→ .iter()\n 1191→ .filter_map(|block| {\n 1192→ if let Some(text) = block.get(\"text\").and_then(|v| v.as_str()) {\n 1193→ Some(text.to_string())\n 1194→ } else if block.get(\"source\").is_some() {\n\n<system-reminder>\nWhenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.\n</system-reminder>\n"}]},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"8bb6ace9-37d4-42fd-b961-f66b0860f5b0","tool_use_result":{"type":"text","file":{"filePath":"/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs","content":" }\n\n // [New] 递归清理参数中可能存在的非法校验字段\n crate::proxy::common::json_schema::clean_json_schema(&mut part);\n\n // 存储 id -> name 映射\n tool_id_to_name.insert(id.clone(), name.clone());\n\n // Signature resolution logic\n // Priority: Client -> Context -> Session Cache -> Tool Cache -> Global Store (deprecated)\n // [CRITICAL FIX] Do NOT use skip_thought_signature_validator for Vertex AI\n // Vertex AI rejects this sentinel value, so we only add thoughtSignature if we have a real one\n let final_sig = signature.as_ref()\n .or(last_thought_signature.as_ref())\n .cloned()\n .or_else(|| {\n // [NEW v3.3.17] Try session-based signature cache first (Layer 3)\n // This provides conversation-level isolation\n crate::proxy::SignatureCache::global().get_session_signature(session_id)\n .map(|s| {\n tracing::info!(\n \"[Claude-Request] Recovered signature from SESSION cache (session: {}, len: {})\",\n session_id, s.len()\n );\n s\n })\n })\n .or_else(|| {\n // Try tool-specific signature cache (Layer 1)\n crate::proxy::SignatureCache::global().get_tool_signature(id)\n .map(|s| {\n tracing::info!(\"[Claude-Request] Recovered signature from TOOL cache for tool_id: {}\", id);\n s\n })\n })\n .or_else(|| {\n // [DEPRECATED] Global store fallback - kept for backward compatibility\n let global_sig = get_thought_signature();\n if global_sig.is_some() {\n tracing::warn!(\n \"[Claude-Request] Using deprecated GLOBAL thought_signature fallback (length: {}). \\\n This indicates session cache miss.\",\n global_sig.as_ref().unwrap().len()\n );\n }\n global_sig\n });\n // [FIX #752] Validate signature before using\n // Only add thoughtSignature if we have a valid and compatible one\n if let Some(sig) = final_sig {\n // [NEW] If this is a retry, do NOT backfill signatures to avoid issues.\n if is_retry && signature.is_none() {\n tracing::warn!(\"[Tool-Signature] Skipping signature backfill for tool_use: {} during retry.\", id);\n } else {\n // Check signature length first - if it's too short, it's definitely invalid\n if sig.len() < MIN_SIGNATURE_LENGTH {\n tracing::warn!(\n \"[Tool-Signature] Signature too short for tool_use: {} (len: {} < {}), skipping.\",\n id, sig.len(), MIN_SIGNATURE_LENGTH\n );\n } else {\n // Check signature compatibility (optional for tool_use)\n let cached_family = crate::proxy::SignatureCache::global()\n .get_signature_family(&sig);\n\n let should_use_sig = match cached_family {\n Some(family) => {\n // For tool_use, check compatibility\n if is_model_compatible(&family, mapped_model) {\n true\n } else {\n tracing::warn!(\n \"[Tool-Signature] Incompatible signature for tool_use: {} (Family: {}, Target: {})\",\n id, family, mapped_model\n );\n false\n }\n }\n None => {\n // For JSON tool calling compatibility, if signature is long enough but unknown,\n // we should trust it rather than drop it\n if sig.len() >= MIN_SIGNATURE_LENGTH {\n tracing::debug!(\n \"[Tool-Signature] Unknown signature origin but valid length (len: {}) for tool_use: {}, using as-is for JSON tool calling.\",\n sig.len(), id\n );\n true\n } else {\n // Unknown and too short: only use in non-thinking mode\n if is_thinking_enabled {\n tracing::warn!(\n \"[Tool-Signature] Unknown signature origin and too short for tool_use: {} (len: {}). Dropping in thinking mode.\",\n id, sig.len()\n );\n false\n } else {\n // In non-thinking mode, allow unknown signatures\n true\n }\n }\n }\n };\n if should_use_sig {\n part[\"thoughtSignature\"] = json!(sig);\n }\n }\n }\n } else {\n // [NEW] Handle missing signature for Gemini thinking models\n // Use skip_thought_signature_validator as a sentinel value\n let is_google_cloud = mapped_model.starts_with(\"projects/\");\n if is_thinking_enabled && !is_google_cloud {\n tracing::debug!(\"[Tool-Signature] Adding GEMINI_SKIP_SIGNATURE for tool_use: {}\", id);\n part[\"thoughtSignature\"] = json!(\"skip_thought_signature_validator\");\n }\n }\n parts.push(part);\n }\n ContentBlock::ToolResult {\n tool_use_id,\n content,\n is_error,\n ..\n } => {\n // Mark this tool ID as resolved in this turn\n current_turn_tool_result_ids.insert(tool_use_id.clone());\n // 优先使用之前记录的 name,否则用 tool_use_id\n let func_name = tool_id_to_name\n .get(tool_use_id)\n .cloned()\n .unwrap_or_else(|| tool_use_id.clone());\n\n // [FIX #593] 工具输出压缩: 处理超大工具输出\n // 使用智能压缩策略(浏览器快照、大文件提示等)\n let mut compacted_content = content.clone();\n if let Some(blocks) = compacted_content.as_array_mut() {\n tool_result_compressor::sanitize_tool_result_blocks(blocks);\n }\n\n // Smart Truncation: strict image removal\n // Remove all Base64 images from historical tool results to save context.\n // Only allow text.\n let mut merged_content = match &compacted_content {\n serde_json::Value::String(s) => s.clone(),\n serde_json::Value::Array(arr) => arr\n .iter()\n .filter_map(|block| {\n if let Some(text) = block.get(\"text\").and_then(|v| v.as_str()) {\n Some(text.to_string())\n } else if block.get(\"source\").is_some() {","numLines":150,"startLine":1045,"totalLines":2366}}},{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01W7DhU9E4TRfe3R4Q1584nG","type":"tool_result","content":" 670→ false\n 671→}\n 672→\n 673→/// Minimum length for a valid thought_signature\n 674→const MIN_SIGNATURE_LENGTH: usize = 50;\n 675→\n 676→/// [FIX #295] Check if we have any valid signature available for function calls\n 677→/// This prevents Gemini 3 Pro from rejecting requests due to missing thought_signature\n 678→/// \n 679→/// [NEW FIX] Now also checks Session Cache to support retry scenarios\n 680→fn has_valid_signature_for_function_calls(\n 681→ messages: &[Message],\n 682→ global_sig: &Option<String>,\n 683→ session_id: &str, // NEW: Add session_id parameter\n 684→) -> bool {\n 685→ // 1. Check global store (deprecated but kept for compatibility)\n 686→ if let Some(sig) = global_sig {\n 687→ if sig.len() >= MIN_SIGNATURE_LENGTH {\n 688→ tracing::debug!(\n 689→ \"[Signature-Check] Found valid signature in global store (len: {})\",\n 690→ sig.len()\n 691→ );\n 692→ return true;\n 693→ }\n 694→ }\n 695→\n 696→ // 2. [NEW] Check Session Cache - this is critical for retry scenarios\n 697→ // When retrying, the signature may not be in messages but exists in Session Cache\n 698→ if let Some(sig) = crate::proxy::SignatureCache::global().get_session_signature(session_id) {\n 699→ if sig.len() >= MIN_SIGNATURE_LENGTH {\n 700→ tracing::info!(\n 701→ \"[Signature-Check] Found valid signature in SESSION cache (session: {}, len: {})\",\n 702→ session_id,\n 703→ sig.len()\n 704→ );\n 705→ return true;\n 706→ }\n 707→ }\n 708→\n 709→ // 3. Check if any message has a thinking block with valid signature\n 710→ for msg in messages.iter().rev() {\n 711→ if msg.role == \"assistant\" {\n 712→ if let MessageContent::Array(blocks) = &msg.content {\n 713→ for block in blocks {\n 714→ if let ContentBlock::Thinking {\n 715→ signature: Some(sig),\n 716→ ..\n 717→ } = block\n 718→ {\n 719→ if sig.len() >= MIN_SIGNATURE_LENGTH {\n 720→ tracing::debug!(\n 721→ \"[Signature-Check] Found valid signature in message history (len: {})\",\n 722→ sig.len()\n 723→ );\n 724→ return true;\n 725→ }\n 726→ }\n 727→ }\n 728→ }\n 729→ }\n 730→ }\n 731→ \n 732→ tracing::warn!(\n 733→ \"[Signature-Check] No valid signature found (session: {}, checked: global store, session cache, message history)\",\n 734→ session_id\n 735→ );\n 736→ false\n 737→}\n 738→\n 739→/// 构建 System Instruction (支持动态身份映射与 Prompt 隔离)\n 740→fn build_system_instruction(system: &Option<SystemPrompt>, _model_name: &str, has_mcp_tools: bool) -> Option<Value> {\n 741→ let mut parts = Vec::new();\n 742→\n 743→ // [NEW] Antigravity 身份指令 (原始简化版)\n 744→ let antigravity_identity = \"You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.\\n\\\n 745→ You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.\\n\\\n 746→ **Absolute paths only**\\n\\\n 747→ **Proactiveness**\";\n 748→ \n 749→ // [HYBRID] 检查用户是否已提供 Antigravity 身份\n 750→ let mut user_has_antigravity = false;\n 751→ if let Some(sys) = system {\n 752→ match sys {\n 753→ SystemPrompt::String(text) => {\n 754→ if text.contains(\"You are Antigravity\") {\n 755→ user_has_antigravity = true;\n 756→ }\n 757→ }\n 758→ SystemPrompt::Array(blocks) => {\n 759→ for block in blocks {\n 760→ if block.block_type == \"text\" && block.text.contains(\"You are Antigravity\") {\n 761→ user_has_antigravity = true;\n 762→ break;\n 763→ }\n 764→ }\n 765→ }\n 766→ }\n 767→ }\n 768→\n 769→ // 如果用户没有提供 Antigravity 身份,则注入\n 770→ if !user_has_antigravity {\n 771→ parts.push(json!({\"text\": antigravity_identity}));\n 772→ }\n 773→\n 774→ // 添加用户的系统提示词\n 775→ if let Some(sys) = system {\n 776→ match sys {\n 777→ SystemPrompt::String(text) => {\n 778→ // [MODIFIED] No longer filter \"You are an interactive CLI tool\"\n 779→ // We pass everything through to ensure Flash/Lite models get full instructions\n 780→ parts.push(json!({\"text\": text}));\n 781→ }\n 782→ SystemPrompt::Array(blocks) => {\n 783→ for block in blocks {\n 784→ if block.block_type == \"text\" {\n 785→ // [MODIFIED] No longer filter \"You are an interactive CLI tool\"\n 786→ parts.push(json!({\"text\": block.text}));\n 787→ }\n 788→ }\n 789→ }\n 790→ }\n 791→ }\n 792→\n 793→ // [NEW] MCP XML Bridge: 如果存在 mcp__ 开头的工具,注入专用的调用协议\n 794→ // 这能有效规避部分 MCP 链路在标准的 tool_use 协议下解析不稳的问题\n 795→ if has_mcp_tools {\n 796→ let mcp_xml_prompt = \"\\n\\\n 797→ ==== MCP XML 工具调用协议 (Workaround) ====\\n\\\n 798→ 当你需要调用名称以 `mcp__` 开头的 MCP 工具时:\\n\\\n 799→ 1) 优先尝试 XML 格式调用:输出 `<mcp__tool_name>{\\\"arg\\\":\\\"value\\\"}</mcp__tool_name>`。\\n\\\n 800→ 2) 必须直接输出 XML 块,无需 markdown 包装,内容为 JSON 格式的入参。\\n\\\n 801→ 3) 这种方式具有更高的连通性和容错性,适用于大型结果返回场景。\\n\\\n 802→ ===========================================\";\n 803→ parts.push(json!({\"text\": mcp_xml_prompt}));\n 804→ }\n 805→\n 806→ // 如果用户没有提供任何系统提示词,添加结束标记\n 807→ if !user_has_antigravity {\n 808→ parts.push(json!({\"text\": \"\\n--- [SYSTEM_PROMPT_END] ---\"}));\n 809→ }\n 810→\n 811→ Some(json!({\n 812→ \"role\": \"user\",\n 813→ \"parts\": parts\n 814→ }))\n 815→}\n 816→\n 817→/// 构建 Contents (Messages)\n 818→fn build_contents(\n 819→ content: &MessageContent,\n 820→ is_assistant: bool,\n 821→ _claude_req: &ClaudeRequest,\n 822→ is_thinking_enabled: bool,\n 823→ session_id: &str,\n 824→ allow_dummy_thought: bool,\n 825→ is_retry: bool,\n 826→ tool_id_to_name: &mut HashMap<String, String>,\n 827→ tool_name_to_schema: &HashMap<String, Value>,\n 828→ mapped_model: &str,\n 829→ last_thought_signature: &mut Option<String>,\n 830→ pending_tool_use_ids: &mut Vec<String>,\n 831→ last_user_task_text_normalized: &mut Option<String>,\n 832→ previous_was_tool_result: &mut bool,\n 833→ _existing_tool_result_ids: &std::collections::HashSet<String>,\n 834→) -> Result<Vec<Value>, String> {\n 835→ let mut parts = Vec::new();\n 836→ // Track tool results in the current turn to identify missing ones\n 837→ let mut current_turn_tool_result_ids = std::collections::HashSet::new();\n 838→\n 839→ // Track if we have already seen non-thinking content in this message.\n 840→ // Anthropic/Gemini protocol: Thinking blocks MUST come first.\n 841→ let mut saw_non_thinking = false;\n 842→\n 843→ match content {\n 844→ MessageContent::String(text) => {\n 845→ if text != \"(no content)\" {\n 846→ if !text.trim().is_empty() {\n 847→ parts.push(json!({\"text\": text.trim()}));\n 848→ }\n 849→ }\n 850→ }\n 851→ MessageContent::Array(blocks) => {\n 852→ for item in blocks {\n 853→ match item {\n 854→ ContentBlock::Text { text } => {\n 855→ if text != \"(no content)\" {\n 856→ // [NEW] 任务去重逻辑: 如果当前是 User 消息,且紧跟在 ToolResult 之后,\n 857→ // 检查该文本是否与上一轮任务描述完全一致。\n 858→ if !is_assistant && *previous_was_tool_result {\n 859→ if let Some(last_task) = last_user_task_text_normalized {\n 860→ let current_normalized = text.replace(|c: char| c.is_whitespace(), \"\");\n 861→ if !current_normalized.is_empty() && current_normalized == *last_task {\n 862→ tracing::info!(\"[Claude-Request] Dropping duplicated task text echo (len: {})\", text.len());\n 863→ continue;\n 864→ }\n 865→ }\n 866→ }\n 867→\n 868→ parts.push(json!({\"text\": text}));\n 869→ saw_non_thinking = true;\n\n<system-reminder>\nWhenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.\n</system-reminder>\n"}]},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"246186a5-29c4-4bbf-a092-54e1d4f9b919","tool_use_result":{"type":"text","file":{"filePath":"/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/request.rs","content":" false\n}\n\n/// Minimum length for a valid thought_signature\nconst MIN_SIGNATURE_LENGTH: usize = 50;\n\n/// [FIX #295] Check if we have any valid signature available for function calls\n/// This prevents Gemini 3 Pro from rejecting requests due to missing thought_signature\n/// \n/// [NEW FIX] Now also checks Session Cache to support retry scenarios\nfn has_valid_signature_for_function_calls(\n messages: &[Message],\n global_sig: &Option<String>,\n session_id: &str, // NEW: Add session_id parameter\n) -> bool {\n // 1. Check global store (deprecated but kept for compatibility)\n if let Some(sig) = global_sig {\n if sig.len() >= MIN_SIGNATURE_LENGTH {\n tracing::debug!(\n \"[Signature-Check] Found valid signature in global store (len: {})\",\n sig.len()\n );\n return true;\n }\n }\n\n // 2. [NEW] Check Session Cache - this is critical for retry scenarios\n // When retrying, the signature may not be in messages but exists in Session Cache\n if let Some(sig) = crate::proxy::SignatureCache::global().get_session_signature(session_id) {\n if sig.len() >= MIN_SIGNATURE_LENGTH {\n tracing::info!(\n \"[Signature-Check] Found valid signature in SESSION cache (session: {}, len: {})\",\n session_id,\n sig.len()\n );\n return true;\n }\n }\n\n // 3. Check if any message has a thinking block with valid signature\n for msg in messages.iter().rev() {\n if msg.role == \"assistant\" {\n if let MessageContent::Array(blocks) = &msg.content {\n for block in blocks {\n if let ContentBlock::Thinking {\n signature: Some(sig),\n ..\n } = block\n {\n if sig.len() >= MIN_SIGNATURE_LENGTH {\n tracing::debug!(\n \"[Signature-Check] Found valid signature in message history (len: {})\",\n sig.len()\n );\n return true;\n }\n }\n }\n }\n }\n }\n \n tracing::warn!(\n \"[Signature-Check] No valid signature found (session: {}, checked: global store, session cache, message history)\",\n session_id\n );\n false\n}\n\n/// 构建 System Instruction (支持动态身份映射与 Prompt 隔离)\nfn build_system_instruction(system: &Option<SystemPrompt>, _model_name: &str, has_mcp_tools: bool) -> Option<Value> {\n let mut parts = Vec::new();\n\n // [NEW] Antigravity 身份指令 (原始简化版)\n let antigravity_identity = \"You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.\\n\\\n You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.\\n\\\n **Absolute paths only**\\n\\\n **Proactiveness**\";\n \n // [HYBRID] 检查用户是否已提供 Antigravity 身份\n let mut user_has_antigravity = false;\n if let Some(sys) = system {\n match sys {\n SystemPrompt::String(text) => {\n if text.contains(\"You are Antigravity\") {\n user_has_antigravity = true;\n }\n }\n SystemPrompt::Array(blocks) => {\n for block in blocks {\n if block.block_type == \"text\" && block.text.contains(\"You are Antigravity\") {\n user_has_antigravity = true;\n break;\n }\n }\n }\n }\n }\n\n // 如果用户没有提供 Antigravity 身份,则注入\n if !user_has_antigravity {\n parts.push(json!({\"text\": antigravity_identity}));\n }\n\n // 添加用户的系统提示词\n if let Some(sys) = system {\n match sys {\n SystemPrompt::String(text) => {\n // [MODIFIED] No longer filter \"You are an interactive CLI tool\"\n // We pass everything through to ensure Flash/Lite models get full instructions\n parts.push(json!({\"text\": text}));\n }\n SystemPrompt::Array(blocks) => {\n for block in blocks {\n if block.block_type == \"text\" {\n // [MODIFIED] No longer filter \"You are an interactive CLI tool\"\n parts.push(json!({\"text\": block.text}));\n }\n }\n }\n }\n }\n\n // [NEW] MCP XML Bridge: 如果存在 mcp__ 开头的工具,注入专用的调用协议\n // 这能有效规避部分 MCP 链路在标准的 tool_use 协议下解析不稳的问题\n if has_mcp_tools {\n let mcp_xml_prompt = \"\\n\\\n ==== MCP XML 工具调用协议 (Workaround) ====\\n\\\n 当你需要调用名称以 `mcp__` 开头的 MCP 工具时:\\n\\\n 1) 优先尝试 XML 格式调用:输出 `<mcp__tool_name>{\\\"arg\\\":\\\"value\\\"}</mcp__tool_name>`。\\n\\\n 2) 必须直接输出 XML 块,无需 markdown 包装,内容为 JSON 格式的入参。\\n\\\n 3) 这种方式具有更高的连通性和容错性,适用于大型结果返回场景。\\n\\\n ===========================================\";\n parts.push(json!({\"text\": mcp_xml_prompt}));\n }\n\n // 如果用户没有提供任何系统提示词,添加结束标记\n if !user_has_antigravity {\n parts.push(json!({\"text\": \"\\n--- [SYSTEM_PROMPT_END] ---\"}));\n }\n\n Some(json!({\n \"role\": \"user\",\n \"parts\": parts\n }))\n}\n\n/// 构建 Contents (Messages)\nfn build_contents(\n content: &MessageContent,\n is_assistant: bool,\n _claude_req: &ClaudeRequest,\n is_thinking_enabled: bool,\n session_id: &str,\n allow_dummy_thought: bool,\n is_retry: bool,\n tool_id_to_name: &mut HashMap<String, String>,\n tool_name_to_schema: &HashMap<String, Value>,\n mapped_model: &str,\n last_thought_signature: &mut Option<String>,\n pending_tool_use_ids: &mut Vec<String>,\n last_user_task_text_normalized: &mut Option<String>,\n previous_was_tool_result: &mut bool,\n _existing_tool_result_ids: &std::collections::HashSet<String>,\n) -> Result<Vec<Value>, String> {\n let mut parts = Vec::new();\n // Track tool results in the current turn to identify missing ones\n let mut current_turn_tool_result_ids = std::collections::HashSet::new();\n\n // Track if we have already seen non-thinking content in this message.\n // Anthropic/Gemini protocol: Thinking blocks MUST come first.\n let mut saw_non_thinking = false;\n\n match content {\n MessageContent::String(text) => {\n if text != \"(no content)\" {\n if !text.trim().is_empty() {\n parts.push(json!({\"text\": text.trim()}));\n }\n }\n }\n MessageContent::Array(blocks) => {\n for item in blocks {\n match item {\n ContentBlock::Text { text } => {\n if text != \"(no content)\" {\n // [NEW] 任务去重逻辑: 如果当前是 User 消息,且紧跟在 ToolResult 之后,\n // 检查该文本是否与上一轮任务描述完全一致。\n if !is_assistant && *previous_was_tool_result {\n if let Some(last_task) = last_user_task_text_normalized {\n let current_normalized = text.replace(|c: char| c.is_whitespace(), \"\");\n if !current_normalized.is_empty() && current_normalized == *last_task {\n tracing::info!(\"[Claude-Request] Dropping duplicated task text echo (len: {})\", text.len());\n continue;\n }\n }\n }\n\n parts.push(json!({\"text\": text}));\n saw_non_thinking = true;","numLines":200,"startLine":670,"totalLines":2366}}},{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01QvFRXVPiZ89LqhzWdsGox1","type":"tool_result","content":" 1→use super::models::{ContentBlock, Message, MessageContent};\n 2→use crate::proxy::SignatureCache;\n 3→use tracing::{debug, info, warn};\n 4→\n 5→pub const MIN_SIGNATURE_LENGTH: usize = 50;\n 6→\n 7→#[derive(Debug, Default)]\n 8→pub struct ConversationState {\n 9→ pub in_tool_loop: bool,\n 10→ pub interrupted_tool: bool,\n 11→ pub last_assistant_idx: Option<usize>,\n 12→}\n 13→\n 14→/// Analyze the conversation to detect tool loops or interrupted tool calls\n 15→pub fn analyze_conversation_state(messages: &[Message]) -> ConversationState {\n 16→ let mut state = ConversationState::default();\n 17→\n 18→ if messages.is_empty() {\n 19→ return state;\n 20→ }\n 21→\n 22→ // Find last assistant message index\n 23→ for (i, msg) in messages.iter().enumerate().rev() {\n 24→ if msg.role == \"assistant\" {\n 25→ state.last_assistant_idx = Some(i);\n 26→ break;\n 27→ }\n 28→ }\n 29→\n 30→ // A tool loop starts if the assistant message has tool use blocks\n 31→ let has_tool_use = if let Some(idx) = state.last_assistant_idx {\n 32→ if let Some(msg) = messages.get(idx) {\n 33→ if let MessageContent::Array(blocks) = &msg.content {\n 34→ blocks\n 35→ .iter()\n 36→ .any(|b| matches!(b, ContentBlock::ToolUse { .. }))\n 37→ } else {\n 38→ false\n 39→ }\n 40→ } else {\n 41→ false\n 42→ }\n 43→ } else {\n 44→ false\n 45→ };\n 46→\n 47→ if !has_tool_use {\n 48→ return state;\n 49→ }\n 50→\n 51→ // Check what follows the assistant's tool use\n 52→ if let Some(last_msg) = messages.last() {\n 53→ if last_msg.role == \"user\" {\n 54→ if let MessageContent::Array(blocks) = &last_msg.content {\n 55→ // Case 1: Final message is ToolResult -> Active Tool Loop\n 56→ if blocks\n 57→ .iter()\n 58→ .any(|b| matches!(b, ContentBlock::ToolResult { .. }))\n 59→ {\n 60→ state.in_tool_loop = true;\n 61→ debug!(\n 62→ \"[Thinking-Recovery] Active tool loop detected (last msg is ToolResult).\"\n 63→ );\n 64→ } else {\n 65→ // Case 2: Final message is Text (User) -> Interrupted Tool\n 66→ state.interrupted_tool = true;\n 67→ debug!(\n 68→ \"[Thinking-Recovery] Interrupted tool detected (last msg is Text user).\"\n 69→ );\n 70→ }\n 71→ } else if let MessageContent::String(_) = &last_msg.content {\n 72→ // Case 2: Final message is String (User) -> Interrupted Tool\n 73→ state.interrupted_tool = true;\n 74→ debug!(\"[Thinking-Recovery] Interrupted tool detected (last msg is String user).\");\n 75→ }\n 76→ }\n 77→ }\n 78→\n 79→ // Check for interrupted tool: Last assistant message has ToolUse, but no corresponding ToolResult in next user msg\n 80→ // (This is harder to detect perfectly on a stateless request, but usually if we are\n 81→ // in a state where we have ToolUse but the conversation seems \"broken\" or stripped)\n 82→ // Actually, in the proxy context, we typically see:\n 83→ // ... Assistant (ToolUse) -> User (ToolResult) : Normal Loop\n 84→ // ... Assistant (ToolUse) -> User (Text) : Interrupted (User cancelled)\n 85→\n 86→ // For \"Thinking Utils\", we care about the case where valid signatures are missing.\n 87→ // If we are in a tool loop (last msg is ToolResult), and the *preceding* Assistant message\n 88→ // had its Thinking block stripped (due to invalid sig), then we are in a \"Broken Tool Loop\".\n 89→ // Gemini/Claude will reject a ToolResult if the preceding Assistant message didn't start with Thinking.\n 90→\n 91→ state\n 92→}\n 93→\n 94→/// Recover from broken tool loops or interrupted tool calls by injecting synthetic messages\n 95→pub fn close_tool_loop_for_thinking(messages: &mut Vec<Message>) {\n 96→ let state = analyze_conversation_state(messages);\n 97→\n 98→ if !state.in_tool_loop && !state.interrupted_tool {\n 99→ return;\n 100→ }\n 101→\n 102→ // Check if the last assistant message has a valid thinking block\n 103→ let mut has_valid_thinking = false;\n 104→ if let Some(idx) = state.last_assistant_idx {\n 105→ if let Some(msg) = messages.get(idx) {\n 106→ if let MessageContent::Array(blocks) = &msg.content {\n 107→ for block in blocks {\n 108→ if let ContentBlock::Thinking {\n 109→ thinking,\n 110→ signature,\n 111→ ..\n 112→ } = block\n 113→ {\n 114→ if !thinking.is_empty()\n 115→ && signature\n 116→ .as_ref()\n 117→ .map(|s| s.len() >= MIN_SIGNATURE_LENGTH)\n 118→ .unwrap_or(false)\n 119→ {\n 120→ has_valid_thinking = true;\n 121→ break;\n 122→ }\n 123→ }\n 124→ }\n 125→ }\n 126→ }\n 127→ }\n 128→\n 129→ if !has_valid_thinking {\n 130→ if state.in_tool_loop {\n 131→ info!(\"[Thinking-Recovery] Broken tool loop (ToolResult without preceding Thinking). Recovery triggered.\");\n 132→\n 133→ // Insert acknowledging message to \"close\" the history turn\n 134→ messages.push(Message {\n 135→ role: \"assistant\".to_string(),\n 136→ content: MessageContent::Array(vec![ContentBlock::Text {\n 137→ text: \"[System: Tool execution completed. Proceeding to final response.]\"\n 138→ .to_string(),\n 139→ }]),\n 140→ });\n 141→ messages.push(Message {\n 142→ role: \"user\".to_string(),\n 143→ content: MessageContent::Array(vec![ContentBlock::Text {\n 144→ text: \"Please provide the final result based on the tool output above.\"\n 145→ .to_string(),\n 146→ }]),\n 147→ });\n 148→ } else if state.interrupted_tool {\n 149→ info!(\n 150→ \"[Thinking-Recovery] Interrupted tool call detected. Injecting synthetic closure.\"\n 151→ );\n 152→\n 153→ // For interrupted tool, we need to insert the closure AFTER the assistant's tool use\n 154→ // but BEFORE the user's latest message.\n 155→ if let Some(idx) = state.last_assistant_idx {\n 156→ messages.insert(\n 157→ idx + 1,\n 158→ Message {\n 159→ role: \"assistant\".to_string(),\n 160→ content: MessageContent::Array(vec![ContentBlock::Text {\n 161→ text: \"[Tool call was interrupted by user.]\".to_string(),\n 162→ }]),\n 163→ },\n 164→ );\n 165→ }\n 166→ }\n 167→ }\n 168→}\n 169→\n 170→/// Get the model family origin of a signature\n 171→pub fn get_signature_family(signature: &str) -> Option<String> {\n 172→ SignatureCache::global().get_signature_family(signature)\n 173→}\n 174→\n 175→/// [CRITICAL] Sanitize thinking blocks and check cross-model compatibility\n 176→pub fn filter_invalid_thinking_blocks_with_family(\n 177→ messages: &mut [Message],\n 178→ target_family: Option<&str>,\n 179→) {\n 180→ let mut stripped_count = 0;\n 181→\n 182→ for msg in messages.iter_mut() {\n 183→ if msg.role != \"assistant\" {\n 184→ continue;\n 185→ }\n 186→\n 187→ if let MessageContent::Array(blocks) = &mut msg.content {\n 188→ let original_len = blocks.len();\n 189→ blocks.retain(|block| {\n 190→ if let ContentBlock::Thinking { signature, .. } = block {\n 191→ // 1. Basic length check - allow empty signatures to pass through for compatibility\n 192→ let sig = match signature {\n 193→ Some(s) if s.len() >= MIN_SIGNATURE_LENGTH || s.is_empty() => s,\n 194→ None => return true, // Allow None signatures to pass through\n 195→ _ => {\n 196→ stripped_count += 1;\n 197→ return false;\n 198→ }\n 199→ };\n 200→ \n 201→ // 2. Family compatibility check (Prevents SONNET-Thinking sig being sent to OPUS-Thinking)\n 202→ if let Some(target) = target_family {\n 203→ if let Some(origin_family) = get_signature_family(sig) {\n 204→ if origin_family != target {\n 205→ warn!(\"[Thinking-Sanitizer] Dropping signature from family '{}' for target '{}'\", origin_family, target);\n 206→ stripped_count += 1;\n 207→ return false;\n 208→ }\n 209→ } else {\n 210→ // [CRITICAL] Signature family not found in cache. \n 211→ // This happens after a server restart when memory is cleared.\n 212→ // If we pass this unverified signature to the upstream, it will likely return 400 \"Invalid signature\".\n 213→ // It is safer to strip the signature and let the upstream regenerate it.\n 214→ info!(\"[Thinking-Sanitizer] Dropping unverified signature (cache miss after restart)\");\n 215→ stripped_count += 1;\n 216→ return false;\n 217→ }\n 218→ } else if get_signature_family(sig).is_none() && !sig.is_empty() {\n 219→ // Even if no target family is specified, we still want to filter out signatures\n 220→ // that we can't verify (unless they are empty, which indicates a fresh start).\n 221→ info!(\"[Thinking-Sanitizer] Dropping unverified signature (no target family)\");\n 222→ stripped_count += 1;\n 223→ return false;\n 224→ }\n 225→ }\n 226→ true\n 227→ });\n 228→\n 229→ // SAFETY: Claude API requires at least one block\n 230→ if blocks.is_empty() && original_len > 0 {\n 231→ blocks.push(ContentBlock::Text {\n 232→ text: \".\".to_string(),\n 233→ });\n 234→ }\n 235→ }\n 236→ }\n 237→\n 238→ if stripped_count > 0 {\n 239→ info!(\n 240→ \"[Thinking-Sanitizer] Stripped {} invalid or incompatible thinking blocks\",\n 241→ stripped_count\n 242→ );\n 243→ }\n 244→}\n 245→\n\n<system-reminder>\nWhenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.\n</system-reminder>\n"}]},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"c7cd9df7-ddb0-48c2-a3e7-5e9d66e606cd","tool_use_result":{"type":"text","file":{"filePath":"/Users/fei/go/Antigravity-Manager/src-tauri/src/proxy/mappers/claude/thinking_utils.rs","content":"use super::models::{ContentBlock, Message, MessageContent};\nuse crate::proxy::SignatureCache;\nuse tracing::{debug, info, warn};\n\npub const MIN_SIGNATURE_LENGTH: usize = 50;\n\n#[derive(Debug, Default)]\npub struct ConversationState {\n pub in_tool_loop: bool,\n pub interrupted_tool: bool,\n pub last_assistant_idx: Option<usize>,\n}\n\n/// Analyze the conversation to detect tool loops or interrupted tool calls\npub fn analyze_conversation_state(messages: &[Message]) -> ConversationState {\n let mut state = ConversationState::default();\n\n if messages.is_empty() {\n return state;\n }\n\n // Find last assistant message index\n for (i, msg) in messages.iter().enumerate().rev() {\n if msg.role == \"assistant\" {\n state.last_assistant_idx = Some(i);\n break;\n }\n }\n\n // A tool loop starts if the assistant message has tool use blocks\n let has_tool_use = if let Some(idx) = state.last_assistant_idx {\n if let Some(msg) = messages.get(idx) {\n if let MessageContent::Array(blocks) = &msg.content {\n blocks\n .iter()\n .any(|b| matches!(b, ContentBlock::ToolUse { .. }))\n } else {\n false\n }\n } else {\n false\n }\n } else {\n false\n };\n\n if !has_tool_use {\n return state;\n }\n\n // Check what follows the assistant's tool use\n if let Some(last_msg) = messages.last() {\n if last_msg.role == \"user\" {\n if let MessageContent::Array(blocks) = &last_msg.content {\n // Case 1: Final message is ToolResult -> Active Tool Loop\n if blocks\n .iter()\n .any(|b| matches!(b, ContentBlock::ToolResult { .. }))\n {\n state.in_tool_loop = true;\n debug!(\n \"[Thinking-Recovery] Active tool loop detected (last msg is ToolResult).\"\n );\n } else {\n // Case 2: Final message is Text (User) -> Interrupted Tool\n state.interrupted_tool = true;\n debug!(\n \"[Thinking-Recovery] Interrupted tool detected (last msg is Text user).\"\n );\n }\n } else if let MessageContent::String(_) = &last_msg.content {\n // Case 2: Final message is String (User) -> Interrupted Tool\n state.interrupted_tool = true;\n debug!(\"[Thinking-Recovery] Interrupted tool detected (last msg is String user).\");\n }\n }\n }\n\n // Check for interrupted tool: Last assistant message has ToolUse, but no corresponding ToolResult in next user msg\n // (This is harder to detect perfectly on a stateless request, but usually if we are\n // in a state where we have ToolUse but the conversation seems \"broken\" or stripped)\n // Actually, in the proxy context, we typically see:\n // ... Assistant (ToolUse) -> User (ToolResult) : Normal Loop\n // ... Assistant (ToolUse) -> User (Text) : Interrupted (User cancelled)\n\n // For \"Thinking Utils\", we care about the case where valid signatures are missing.\n // If we are in a tool loop (last msg is ToolResult), and the *preceding* Assistant message\n // had its Thinking block stripped (due to invalid sig), then we are in a \"Broken Tool Loop\".\n // Gemini/Claude will reject a ToolResult if the preceding Assistant message didn't start with Thinking.\n\n state\n}\n\n/// Recover from broken tool loops or interrupted tool calls by injecting synthetic messages\npub fn close_tool_loop_for_thinking(messages: &mut Vec<Message>) {\n let state = analyze_conversation_state(messages);\n\n if !state.in_tool_loop && !state.interrupted_tool {\n return;\n }\n\n // Check if the last assistant message has a valid thinking block\n let mut has_valid_thinking = false;\n if let Some(idx) = state.last_assistant_idx {\n if let Some(msg) = messages.get(idx) {\n if let MessageContent::Array(blocks) = &msg.content {\n for block in blocks {\n if let ContentBlock::Thinking {\n thinking,\n signature,\n ..\n } = block\n {\n if !thinking.is_empty()\n && signature\n .as_ref()\n .map(|s| s.len() >= MIN_SIGNATURE_LENGTH)\n .unwrap_or(false)\n {\n has_valid_thinking = true;\n break;\n }\n }\n }\n }\n }\n }\n\n if !has_valid_thinking {\n if state.in_tool_loop {\n info!(\"[Thinking-Recovery] Broken tool loop (ToolResult without preceding Thinking). Recovery triggered.\");\n\n // Insert acknowledging message to \"close\" the history turn\n messages.push(Message {\n role: \"assistant\".to_string(),\n content: MessageContent::Array(vec![ContentBlock::Text {\n text: \"[System: Tool execution completed. Proceeding to final response.]\"\n .to_string(),\n }]),\n });\n messages.push(Message {\n role: \"user\".to_string(),\n content: MessageContent::Array(vec![ContentBlock::Text {\n text: \"Please provide the final result based on the tool output above.\"\n .to_string(),\n }]),\n });\n } else if state.interrupted_tool {\n info!(\n \"[Thinking-Recovery] Interrupted tool call detected. Injecting synthetic closure.\"\n );\n\n // For interrupted tool, we need to insert the closure AFTER the assistant's tool use\n // but BEFORE the user's latest message.\n if let Some(idx) = state.last_assistant_idx {\n messages.insert(\n idx + 1,\n Message {\n role: \"assistant\".to_string(),\n content: MessageContent::Array(vec![ContentBlock::Text {\n text: \"[Tool call was interrupted by user.]\".to_string(),\n }]),\n },\n );\n }\n }\n }\n}\n\n/// Get the model family origin of a signature\npub fn get_signature_family(signature: &str) -> Option<String> {\n SignatureCache::global().get_signature_family(signature)\n}\n\n/// [CRITICAL] Sanitize thinking blocks and check cross-model compatibility\npub fn filter_invalid_thinking_blocks_with_family(\n messages: &mut [Message],\n target_family: Option<&str>,\n) {\n let mut stripped_count = 0;\n\n for msg in messages.iter_mut() {\n if msg.role != \"assistant\" {\n continue;\n }\n\n if let MessageContent::Array(blocks) = &mut msg.content {\n let original_len = blocks.len();\n blocks.retain(|block| {\n if let ContentBlock::Thinking { signature, .. } = block {\n // 1. Basic length check - allow empty signatures to pass through for compatibility\n let sig = match signature {\n Some(s) if s.len() >= MIN_SIGNATURE_LENGTH || s.is_empty() => s,\n None => return true, // Allow None signatures to pass through\n _ => {\n stripped_count += 1;\n return false;\n }\n };\n \n // 2. Family compatibility check (Prevents SONNET-Thinking sig being sent to OPUS-Thinking)\n if let Some(target) = target_family {\n if let Some(origin_family) = get_signature_family(sig) {\n if origin_family != target {\n warn!(\"[Thinking-Sanitizer] Dropping signature from family '{}' for target '{}'\", origin_family, target);\n stripped_count += 1;\n return false;\n }\n } else {\n // [CRITICAL] Signature family not found in cache. \n // This happens after a server restart when memory is cleared.\n // If we pass this unverified signature to the upstream, it will likely return 400 \"Invalid signature\".\n // It is safer to strip the signature and let the upstream regenerate it.\n info!(\"[Thinking-Sanitizer] Dropping unverified signature (cache miss after restart)\");\n stripped_count += 1;\n return false;\n }\n } else if get_signature_family(sig).is_none() && !sig.is_empty() {\n // Even if no target family is specified, we still want to filter out signatures\n // that we can't verify (unless they are empty, which indicates a fresh start).\n info!(\"[Thinking-Sanitizer] Dropping unverified signature (no target family)\");\n stripped_count += 1;\n return false;\n }\n }\n true\n });\n\n // SAFETY: Claude API requires at least one block\n if blocks.is_empty() && original_len > 0 {\n blocks.push(ContentBlock::Text {\n text: \".\".to_string(),\n });\n }\n }\n }\n\n if stripped_count > 0 {\n info!(\n \"[Thinking-Sanitizer] Stripped {} invalid or incompatible thinking blocks\",\n stripped_count\n );\n }\n}\n","numLines":245,"startLine":1,"totalLines":245}}},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01VmcBvt5E5oWpgPFDEuE5n3","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"Now I have a good understanding of the Antigravity-Manager logic. Let me also look at a critical section of the litellm_oauth.py to see the Koder implementation.","signature":"EsoCCkYICxgCKkAJxmFFhTAVGTc4rCeGCtpwhNST9QG4e75JZ3GdEnBW0RS/+lD5IYxk2dLj7mJ4ivvOrrxzglTtKEVWHuE1kT1aEgxnVEhBPJhZquoZC+4aDFIsqjv5VtKGL2hkyCIwP9077iVLrTJasN24OHaCN3FpW/mJFIrwC7goYyfAnc0OXO/2PVJWWJK9K4LzYkRJKrEBOEKgbYoBOEu0npMg/k3IH7BM0qr1rJJNItZ1lic0S3QbB5WQ3kHFwrK0Pg3Qwp65VWFcRzC97W53ESHvl6bvLOy0l0++28jofWpe7GxXWPF/N7Fh5Uoe0OlyiXkLHhIxO0tWER5bNvuJd25uaN2RyjJ9NUCdgoqeaMkTPhnqlgzFA3pQECi1SRFkSWO/I7NxolID3p67/2wZDb5zlZDez0QCMaeBqPpPohVMqxMEX59EGAE="}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":8,"cache_creation_input_tokens":18374,"cache_read_input_tokens":69318,"cache_creation":{"ephemeral_5m_input_tokens":18374,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"c7092733-fde2-47dc-b722-fcb07f45d95a"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01VmcBvt5E5oWpgPFDEuE5n3","type":"message","role":"assistant","content":[{"type":"text","text":"Let me read the relevant sections of Koder's litellm_oauth.py for comparison."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":8,"cache_creation_input_tokens":18374,"cache_read_input_tokens":69318,"cache_creation":{"ephemeral_5m_input_tokens":18374,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"78cee3a2-fd00-4bfa-81b0-aec8fd04bd98"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01VmcBvt5E5oWpgPFDEuE5n3","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_013VpneHCHECMmEtNeLFMBtx","name":"Read","input":{"file_path":"/Users/fei/coding-agent/koder/koder_agent/auth/litellm_oauth.py","offset":2340,"limit":250},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":8,"cache_creation_input_tokens":18374,"cache_read_input_tokens":69318,"cache_creation":{"ephemeral_5m_input_tokens":18374,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"edb8f82d-9cc5-4682-9e7f-88e810b819bb"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01VmcBvt5E5oWpgPFDEuE5n3","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_013Rf9qoQF2ZJQwyrkAS7W95","name":"Read","input":{"file_path":"/Users/fei/coding-agent/koder/koder_agent/auth/litellm_oauth.py","offset":2480,"limit":150},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":8,"cache_creation_input_tokens":18374,"cache_read_input_tokens":69318,"cache_creation":{"ephemeral_5m_input_tokens":18374,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"f8f7b123-92fe-4a7a-809c-3b43ff6e4cd8"},{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_013Rf9qoQF2ZJQwyrkAS7W95","type":"tool_result","content":" 2480→ # Reference: antigravity-auth/src/plugin/request.ts (lines 726-739)\n 2481→ if is_claude:\n 2482→ request_payload[\"toolConfig\"] = {\"functionCallingConfig\": {\"mode\": \"VALIDATED\"}}\n 2483→\n 2484→ # Apply tool pairing fixes for Claude models (ID management)\n 2485→ if is_claude:\n 2486→ request_payload = apply_tool_pairing_fixes(request_payload, is_claude=True)\n 2487→\n 2488→ # Ensure thinking signatures for Claude thinking models with tool use\n 2489→ # When thinking blocks don't have valid signatures, inject sentinel to bypass validation\n 2490→ if is_claude_thinking and request_payload.get(\"contents\"):\n 2491→ session_key = session_id or f\"antigravity-{uuid.uuid4().hex[:8]}\"\n 2492→ request_payload[\"contents\"] = ensure_thinking_signature_for_tool_use(\n 2493→ request_payload[\"contents\"], session_key\n 2494→ )\n 2495→\n 2496→ # Gemini 3 tool calls require thoughtSignature; inject from session cache if missing\n 2497→ if not is_claude and session_id and request_payload.get(\"contents\"):\n 2498→ request_payload[\"contents\"] = inject_thought_signature_for_function_calls(\n 2499→ request_payload[\"contents\"], session_id\n 2500→ )\n 2501→\n 2502→ # Inject Antigravity system instruction for antigravity quota\n 2503→ if header_style == \"antigravity\":\n 2504→ self._inject_antigravity_system_instruction(request_payload)\n 2505→\n 2506→ # Attach sessionId for signature caching (stable across turns)\n 2507→ if session_id:\n 2508→ request_payload[\"sessionId\"] = session_id\n 2509→\n 2510→ return {\n 2511→ \"project\": project_id,\n 2512→ \"model\": model_name,\n 2513→ \"request\": request_payload,\n 2514→ \"requestType\": \"agent\",\n 2515→ \"userAgent\": \"antigravity\",\n 2516→ \"requestId\": f\"agent-{uuid.uuid4()}\",\n 2517→ }\n 2518→\n 2519→ def _parse_response(self, response_data: Dict[str, Any]) -> ModelResponse:\n 2520→ \"\"\"Parse Antigravity response into LiteLLM ModelResponse format.\"\"\"\n 2521→ from .tool_utils import extract_tool_calls_from_gemini_response\n 2522→\n 2523→ # Handle wrapped response format\n 2524→ if \"response\" in response_data:\n 2525→ response_data = response_data[\"response\"]\n 2526→\n 2527→ content = \"\"\n 2528→ if \"candidates\" in response_data:\n 2529→ candidates = response_data[\"candidates\"]\n 2530→ if candidates and len(candidates) > 0:\n 2531→ candidate = candidates[0]\n 2532→ if \"content\" in candidate:\n 2533→ parts = candidate[\"content\"].get(\"parts\", [])\n 2534→ for part in parts:\n 2535→ if \"text\" in part:\n 2536→ content += part[\"text\"]\n 2537→ elif \"content\" in response_data and isinstance(response_data[\"content\"], list):\n 2538→ # Anthropic-style response format\n 2539→ for part in response_data[\"content\"]:\n 2540→ if isinstance(part, dict):\n 2541→ if \"text\" in part and isinstance(part[\"text\"], str):\n 2542→ content += part[\"text\"]\n 2543→ elif \"thinking\" in part and isinstance(part[\"thinking\"], str):\n 2544→ # Ignore thinking by default; keep for completeness\n 2545→ continue\n 2546→\n 2547→ # Extract tool calls from response\n 2548→ tool_calls = extract_tool_calls_from_gemini_response(response_data)\n 2549→\n 2550→ usage_data = response_data.get(\"usageMetadata\", {})\n 2551→ usage = Usage(\n 2552→ prompt_tokens=usage_data.get(\"promptTokenCount\", 0),\n 2553→ completion_tokens=usage_data.get(\"candidatesTokenCount\", 0),\n 2554→ total_tokens=usage_data.get(\"totalTokenCount\", 0),\n 2555→ )\n 2556→\n 2557→ # Build message with optional tool_calls\n 2558→ message: Dict[str, Any] = {\n 2559→ \"role\": \"assistant\",\n 2560→ \"content\": content if content else None,\n 2561→ }\n 2562→ if tool_calls:\n 2563→ message[\"tool_calls\"] = tool_calls\n 2564→\n 2565→ # Set finish_reason based on response content\n 2566→ finish_reason = \"tool_calls\" if tool_calls else \"stop\"\n 2567→\n 2568→ return ModelResponse(\n 2569→ id=f\"chatcmpl-{uuid.uuid4().hex}\",\n 2570→ created=int(time.time()),\n 2571→ model=response_data.get(\"model\", \"antigravity\"),\n 2572→ choices=[\n 2573→ {\n 2574→ \"index\": 0,\n 2575→ \"message\": message,\n 2576→ \"finish_reason\": finish_reason,\n 2577→ }\n 2578→ ],\n 2579→ usage=usage,\n 2580→ )\n 2581→\n 2582→ def completion(\n 2583→ self,\n 2584→ model: str,\n 2585→ messages: List[Dict[str, Any]],\n 2586→ **kwargs: Any,\n 2587→ ) -> ModelResponse:\n 2588→ \"\"\"Synchronous completion (not implemented - use async).\"\"\"\n 2589→ raise NotImplementedError(\"Use acompletion for Antigravity OAuth\")\n 2590→\n 2591→ async def acompletion(\n 2592→ self,\n 2593→ model: str,\n 2594→ messages: List[Dict[str, Any]],\n 2595→ **kwargs: Any,\n 2596→ ) -> ModelResponse:\n 2597→ \"\"\"Async completion using Antigravity endpoint with fallback.\"\"\"\n 2598→ access_token = self._get_access_token()\n 2599→ if not access_token:\n 2600→ raise ValueError(\n 2601→ \"No OAuth token available for Antigravity. \"\n 2602→ \"Run 'koder auth login antigravity' to authenticate.\"\n 2603→ )\n 2604→\n 2605→ # Extract optional_params - LiteLLM passes tools and other params inside this dict\n 2606→ optional_params = kwargs.pop(\"optional_params\", {})\n 2607→ # Merge optional_params into kwargs for our internal use\n 2608→ merged_kwargs = {**kwargs, **optional_params}\n 2609→\n 2610→ # Get project ID (managed or fallback)\n 2611→ project_id = await self._ensure_project_context(access_token)\n 2612→\n 2613→ stream = merged_kwargs.get(\"stream\", False)\n 2614→ action = \"streamGenerateContent\" if stream else \"generateContent\"\n 2615→\n 2616→ last_error = None\n 2617→ async with aiohttp.ClientSession() as session:\n 2618→ for header_style in self._header_style_candidates(model):\n 2619→ resolved_model, _, _ = self._resolve_model_for_header_style(model, header_style)\n 2620→ is_claude_thinking = self._is_claude_thinking_model(resolved_model)\n 2621→\n 2622→ body = self._build_request_body(\n 2623→ model,\n 2624→ messages,\n 2625→ project_id,\n 2626→ header_style=header_style,\n 2627→ session_id=self._session_id,\n 2628→ **merged_kwargs,\n 2629→ )\n\n<system-reminder>\nWhenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.\n</system-reminder>\n"}]},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"1a8fe79b-244a-4708-8f8a-a1ac1a9f1ce4","tool_use_result":{"type":"text","file":{"filePath":"/Users/fei/coding-agent/koder/koder_agent/auth/litellm_oauth.py","content":" # Reference: antigravity-auth/src/plugin/request.ts (lines 726-739)\n if is_claude:\n request_payload[\"toolConfig\"] = {\"functionCallingConfig\": {\"mode\": \"VALIDATED\"}}\n\n # Apply tool pairing fixes for Claude models (ID management)\n if is_claude:\n request_payload = apply_tool_pairing_fixes(request_payload, is_claude=True)\n\n # Ensure thinking signatures for Claude thinking models with tool use\n # When thinking blocks don't have valid signatures, inject sentinel to bypass validation\n if is_claude_thinking and request_payload.get(\"contents\"):\n session_key = session_id or f\"antigravity-{uuid.uuid4().hex[:8]}\"\n request_payload[\"contents\"] = ensure_thinking_signature_for_tool_use(\n request_payload[\"contents\"], session_key\n )\n\n # Gemini 3 tool calls require thoughtSignature; inject from session cache if missing\n if not is_claude and session_id and request_payload.get(\"contents\"):\n request_payload[\"contents\"] = inject_thought_signature_for_function_calls(\n request_payload[\"contents\"], session_id\n )\n\n # Inject Antigravity system instruction for antigravity quota\n if header_style == \"antigravity\":\n self._inject_antigravity_system_instruction(request_payload)\n\n # Attach sessionId for signature caching (stable across turns)\n if session_id:\n request_payload[\"sessionId\"] = session_id\n\n return {\n \"project\": project_id,\n \"model\": model_name,\n \"request\": request_payload,\n \"requestType\": \"agent\",\n \"userAgent\": \"antigravity\",\n \"requestId\": f\"agent-{uuid.uuid4()}\",\n }\n\n def _parse_response(self, response_data: Dict[str, Any]) -> ModelResponse:\n \"\"\"Parse Antigravity response into LiteLLM ModelResponse format.\"\"\"\n from .tool_utils import extract_tool_calls_from_gemini_response\n\n # Handle wrapped response format\n if \"response\" in response_data:\n response_data = response_data[\"response\"]\n\n content = \"\"\n if \"candidates\" in response_data:\n candidates = response_data[\"candidates\"]\n if candidates and len(candidates) > 0:\n candidate = candidates[0]\n if \"content\" in candidate:\n parts = candidate[\"content\"].get(\"parts\", [])\n for part in parts:\n if \"text\" in part:\n content += part[\"text\"]\n elif \"content\" in response_data and isinstance(response_data[\"content\"], list):\n # Anthropic-style response format\n for part in response_data[\"content\"]:\n if isinstance(part, dict):\n if \"text\" in part and isinstance(part[\"text\"], str):\n content += part[\"text\"]\n elif \"thinking\" in part and isinstance(part[\"thinking\"], str):\n # Ignore thinking by default; keep for completeness\n continue\n\n # Extract tool calls from response\n tool_calls = extract_tool_calls_from_gemini_response(response_data)\n\n usage_data = response_data.get(\"usageMetadata\", {})\n usage = Usage(\n prompt_tokens=usage_data.get(\"promptTokenCount\", 0),\n completion_tokens=usage_data.get(\"candidatesTokenCount\", 0),\n total_tokens=usage_data.get(\"totalTokenCount\", 0),\n )\n\n # Build message with optional tool_calls\n message: Dict[str, Any] = {\n \"role\": \"assistant\",\n \"content\": content if content else None,\n }\n if tool_calls:\n message[\"tool_calls\"] = tool_calls\n\n # Set finish_reason based on response content\n finish_reason = \"tool_calls\" if tool_calls else \"stop\"\n\n return ModelResponse(\n id=f\"chatcmpl-{uuid.uuid4().hex}\",\n created=int(time.time()),\n model=response_data.get(\"model\", \"antigravity\"),\n choices=[\n {\n \"index\": 0,\n \"message\": message,\n \"finish_reason\": finish_reason,\n }\n ],\n usage=usage,\n )\n\n def completion(\n self,\n model: str,\n messages: List[Dict[str, Any]],\n **kwargs: Any,\n ) -> ModelResponse:\n \"\"\"Synchronous completion (not implemented - use async).\"\"\"\n raise NotImplementedError(\"Use acompletion for Antigravity OAuth\")\n\n async def acompletion(\n self,\n model: str,\n messages: List[Dict[str, Any]],\n **kwargs: Any,\n ) -> ModelResponse:\n \"\"\"Async completion using Antigravity endpoint with fallback.\"\"\"\n access_token = self._get_access_token()\n if not access_token:\n raise ValueError(\n \"No OAuth token available for Antigravity. \"\n \"Run 'koder auth login antigravity' to authenticate.\"\n )\n\n # Extract optional_params - LiteLLM passes tools and other params inside this dict\n optional_params = kwargs.pop(\"optional_params\", {})\n # Merge optional_params into kwargs for our internal use\n merged_kwargs = {**kwargs, **optional_params}\n\n # Get project ID (managed or fallback)\n project_id = await self._ensure_project_context(access_token)\n\n stream = merged_kwargs.get(\"stream\", False)\n action = \"streamGenerateContent\" if stream else \"generateContent\"\n\n last_error = None\n async with aiohttp.ClientSession() as session:\n for header_style in self._header_style_candidates(model):\n resolved_model, _, _ = self._resolve_model_for_header_style(model, header_style)\n is_claude_thinking = self._is_claude_thinking_model(resolved_model)\n\n body = self._build_request_body(\n model,\n messages,\n project_id,\n header_style=header_style,\n session_id=self._session_id,\n **merged_kwargs,\n )","numLines":150,"startLine":2480,"totalLines":3226}}},{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_013VpneHCHECMmEtNeLFMBtx","type":"tool_result","content":" 2340→ from .tool_utils import (\n 2341→ apply_tool_pairing_fixes,\n 2342→ convert_tool_calls_to_gemini_parts,\n 2343→ convert_tool_message_to_gemini_part,\n 2344→ convert_tools_to_claude_format,\n 2345→ convert_tools_to_gemini_format,\n 2346→ ensure_thinking_signature_for_tool_use,\n 2347→ inject_thought_signature_for_function_calls,\n 2348→ inject_parameter_signatures,\n 2349→ inject_tool_hardening_instruction,\n 2350→ )\n 2351→\n 2352→ header_style = kwargs.pop(\"header_style\", \"antigravity\")\n 2353→ session_id = kwargs.pop(\"session_id\", None)\n 2354→\n 2355→ # Resolve model name and thinking tier\n 2356→ # Claude thinking models: strip tier suffix, extract budget\n 2357→ # e.g., \"antigravity-claude-opus-4-5-thinking-high\" → \"claude-opus-4-5-thinking\" + budget=32768\n 2358→ model_name, _tier, thinking_budget = self._resolve_model_for_header_style(\n 2359→ model, header_style\n 2360→ )\n 2361→ is_claude = \"claude\" in model_name.lower()\n 2362→ is_claude_thinking = self._is_claude_thinking_model(model_name)\n 2363→\n 2364→ # Convert OpenAI-style messages to Gemini format\n 2365→ contents: List[Dict[str, Any]] = []\n 2366→ system_instruction = None\n 2367→ pending_tool_responses: List[Dict[str, Any]] = []\n 2368→\n 2369→ for msg in messages:\n 2370→ role = msg.get(\"role\", \"user\")\n 2371→ content = msg.get(\"content\", \"\")\n 2372→\n 2373→ if role == \"system\":\n 2374→ if isinstance(content, str):\n 2375→ system_instruction = {\"parts\": [{\"text\": content}]}\n 2376→ continue\n 2377→\n 2378→ # Handle tool result messages (role=\"tool\")\n 2379→ if role == \"tool\":\n 2380→ # Collect tool responses to group with the previous model response\n 2381→ tool_part = convert_tool_message_to_gemini_part(msg)\n 2382→ pending_tool_responses.append(tool_part)\n 2383→ continue\n 2384→\n 2385→ # Flush pending tool responses as a user message before the next message\n 2386→ if pending_tool_responses:\n 2387→ contents.append({\"role\": \"user\", \"parts\": pending_tool_responses})\n 2388→ pending_tool_responses = []\n 2389→\n 2390→ gemini_role = \"model\" if role == \"assistant\" else \"user\"\n 2391→\n 2392→ # Check if assistant message has tool_calls\n 2393→ tool_calls = msg.get(\"tool_calls\")\n 2394→ if role == \"assistant\" and tool_calls:\n 2395→ # Convert tool_calls to functionCall parts\n 2396→ parts = convert_tool_calls_to_gemini_parts(tool_calls)\n 2397→ # Add text content if present\n 2398→ if isinstance(content, str) and content:\n 2399→ parts.insert(0, {\"text\": content})\n 2400→ contents.append({\"role\": gemini_role, \"parts\": parts})\n 2401→ elif isinstance(content, str):\n 2402→ contents.append({\"role\": gemini_role, \"parts\": [{\"text\": content}]})\n 2403→ elif isinstance(content, list):\n 2404→ parts = []\n 2405→ for item in content:\n 2406→ if isinstance(item, dict):\n 2407→ if item.get(\"type\") == \"text\":\n 2408→ parts.append({\"text\": item.get(\"text\", \"\")})\n 2409→ if parts:\n 2410→ contents.append({\"role\": gemini_role, \"parts\": parts})\n 2411→\n 2412→ # Flush any remaining tool responses\n 2413→ if pending_tool_responses:\n 2414→ contents.append({\"role\": \"user\", \"parts\": pending_tool_responses})\n 2415→\n 2416→ request_payload: Dict[str, Any] = {\"contents\": contents}\n 2417→\n 2418→ # Track message count for session signature cache (rewind detection)\n 2419→ self._last_request_message_count = len(contents)\n 2420→\n 2421→ if system_instruction:\n 2422→ request_payload[\"systemInstruction\"] = system_instruction\n 2423→\n 2424→ # Convert and add tools\n 2425→ tools = kwargs.get(\"tools\")\n 2426→ if tools:\n 2427→ if is_claude:\n 2428→ # Claude models need cleaned schemas and VALIDATED mode\n 2429→ converted_tools = convert_tools_to_claude_format(tools)\n 2430→ # Apply parameter signature injection (tool hardening)\n 2431→ # This prevents Claude from hallucinating tool parameters\n 2432→ converted_tools = inject_parameter_signatures(converted_tools)\n 2433→ else:\n 2434→ # Gemini models use simpler format\n 2435→ converted_tools = convert_tools_to_gemini_format(tools)\n 2436→ if converted_tools:\n 2437→ request_payload[\"tools\"] = converted_tools\n 2438→\n 2439→ # Claude thinking models with tools get interleaved thinking hint\n 2440→ if is_claude_thinking:\n 2441→ self._append_system_instruction_hint(\n 2442→ request_payload, CLAUDE_INTERLEAVED_THINKING_HINT\n 2443→ )\n 2444→\n 2445→ # Inject tool hardening system instruction for Claude models\n 2446→ # This provides explicit guidance on how to use tool schemas\n 2447→ if is_claude:\n 2448→ inject_tool_hardening_instruction(request_payload)\n 2449→\n 2450→ # Add generation config\n 2451→ generation_config: Dict[str, Any] = {}\n 2452→ if \"temperature\" in kwargs:\n 2453→ generation_config[\"temperature\"] = kwargs[\"temperature\"]\n 2454→ if \"max_tokens\" in kwargs:\n 2455→ generation_config[\"maxOutputTokens\"] = kwargs[\"max_tokens\"]\n 2456→ if \"top_p\" in kwargs:\n 2457→ generation_config[\"topP\"] = kwargs[\"top_p\"]\n 2458→\n 2459→ # Add thinking configuration for Claude thinking models\n 2460→ # Reference: antigravity-auth/src/plugin/request.ts (lines 766-773)\n 2461→ # Claude uses snake_case: include_thoughts, thinking_budget\n 2462→ if is_claude_thinking:\n 2463→ thinking_config: Dict[str, Any] = {\n 2464→ \"include_thoughts\": True,\n 2465→ }\n 2466→ if thinking_budget:\n 2467→ thinking_config[\"thinking_budget\"] = thinking_budget\n 2468→\n 2469→ generation_config[\"thinkingConfig\"] = thinking_config\n 2470→\n 2471→ # Ensure maxOutputTokens is large enough for thinking + response\n 2472→ current_max = generation_config.get(\"maxOutputTokens\", 0)\n 2473→ if not current_max or current_max <= (thinking_budget or 0):\n 2474→ generation_config[\"maxOutputTokens\"] = CLAUDE_THINKING_MAX_OUTPUT_TOKENS\n 2475→\n 2476→ if generation_config:\n 2477→ request_payload[\"generationConfig\"] = generation_config\n 2478→\n 2479→ # Add toolConfig for Claude models (required even without tools)\n 2480→ # Reference: antigravity-auth/src/plugin/request.ts (lines 726-739)\n 2481→ if is_claude:\n 2482→ request_payload[\"toolConfig\"] = {\"functionCallingConfig\": {\"mode\": \"VALIDATED\"}}\n 2483→\n 2484→ # Apply tool pairing fixes for Claude models (ID management)\n 2485→ if is_claude:\n 2486→ request_payload = apply_tool_pairing_fixes(request_payload, is_claude=True)\n 2487→\n 2488→ # Ensure thinking signatures for Claude thinking models with tool use\n 2489→ # When thinking blocks don't have valid signatures, inject sentinel to bypass validation\n 2490→ if is_claude_thinking and request_payload.get(\"contents\"):\n 2491→ session_key = session_id or f\"antigravity-{uuid.uuid4().hex[:8]}\"\n 2492→ request_payload[\"contents\"] = ensure_thinking_signature_for_tool_use(\n 2493→ request_payload[\"contents\"], session_key\n 2494→ )\n 2495→\n 2496→ # Gemini 3 tool calls require thoughtSignature; inject from session cache if missing\n 2497→ if not is_claude and session_id and request_payload.get(\"contents\"):\n 2498→ request_payload[\"contents\"] = inject_thought_signature_for_function_calls(\n 2499→ request_payload[\"contents\"], session_id\n 2500→ )\n 2501→\n 2502→ # Inject Antigravity system instruction for antigravity quota\n 2503→ if header_style == \"antigravity\":\n 2504→ self._inject_antigravity_system_instruction(request_payload)\n 2505→\n 2506→ # Attach sessionId for signature caching (stable across turns)\n 2507→ if session_id:\n 2508→ request_payload[\"sessionId\"] = session_id\n 2509→\n 2510→ return {\n 2511→ \"project\": project_id,\n 2512→ \"model\": model_name,\n 2513→ \"request\": request_payload,\n 2514→ \"requestType\": \"agent\",\n 2515→ \"userAgent\": \"antigravity\",\n 2516→ \"requestId\": f\"agent-{uuid.uuid4()}\",\n 2517→ }\n 2518→\n 2519→ def _parse_response(self, response_data: Dict[str, Any]) -> ModelResponse:\n 2520→ \"\"\"Parse Antigravity response into LiteLLM ModelResponse format.\"\"\"\n 2521→ from .tool_utils import extract_tool_calls_from_gemini_response\n 2522→\n 2523→ # Handle wrapped response format\n 2524→ if \"response\" in response_data:\n 2525→ response_data = response_data[\"response\"]\n 2526→\n 2527→ content = \"\"\n 2528→ if \"candidates\" in response_data:\n 2529→ candidates = response_data[\"candidates\"]\n 2530→ if candidates and len(candidates) > 0:\n 2531→ candidate = candidates[0]\n 2532→ if \"content\" in candidate:\n 2533→ parts = candidate[\"content\"].get(\"parts\", [])\n 2534→ for part in parts:\n 2535→ if \"text\" in part:\n 2536→ content += part[\"text\"]\n 2537→ elif \"content\" in response_data and isinstance(response_data[\"content\"], list):\n 2538→ # Anthropic-style response format\n 2539→ for part in response_data[\"content\"]:\n 2540→ if isinstance(part, dict):\n 2541→ if \"text\" in part and isinstance(part[\"text\"], str):\n 2542→ content += part[\"text\"]\n 2543→ elif \"thinking\" in part and isinstance(part[\"thinking\"], str):\n 2544→ # Ignore thinking by default; keep for completeness\n 2545→ continue\n 2546→\n 2547→ # Extract tool calls from response\n 2548→ tool_calls = extract_tool_calls_from_gemini_response(response_data)\n 2549→\n 2550→ usage_data = response_data.get(\"usageMetadata\", {})\n 2551→ usage = Usage(\n 2552→ prompt_tokens=usage_data.get(\"promptTokenCount\", 0),\n 2553→ completion_tokens=usage_data.get(\"candidatesTokenCount\", 0),\n 2554→ total_tokens=usage_data.get(\"totalTokenCount\", 0),\n 2555→ )\n 2556→\n 2557→ # Build message with optional tool_calls\n 2558→ message: Dict[str, Any] = {\n 2559→ \"role\": \"assistant\",\n 2560→ \"content\": content if content else None,\n 2561→ }\n 2562→ if tool_calls:\n 2563→ message[\"tool_calls\"] = tool_calls\n 2564→\n 2565→ # Set finish_reason based on response content\n 2566→ finish_reason = \"tool_calls\" if tool_calls else \"stop\"\n 2567→\n 2568→ return ModelResponse(\n 2569→ id=f\"chatcmpl-{uuid.uuid4().hex}\",\n 2570→ created=int(time.time()),\n 2571→ model=response_data.get(\"model\", \"antigravity\"),\n 2572→ choices=[\n 2573→ {\n 2574→ \"index\": 0,\n 2575→ \"message\": message,\n 2576→ \"finish_reason\": finish_reason,\n 2577→ }\n 2578→ ],\n 2579→ usage=usage,\n 2580→ )\n 2581→\n 2582→ def completion(\n 2583→ self,\n 2584→ model: str,\n 2585→ messages: List[Dict[str, Any]],\n 2586→ **kwargs: Any,\n 2587→ ) -> ModelResponse:\n 2588→ \"\"\"Synchronous completion (not implemented - use async).\"\"\"\n 2589→ raise NotImplementedError(\"Use acompletion for Antigravity OAuth\")\n\n<system-reminder>\nWhenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.\n</system-reminder>\n"}]},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"95910cc5-34b1-4b75-809c-fdf53187b037","tool_use_result":{"type":"text","file":{"filePath":"/Users/fei/coding-agent/koder/koder_agent/auth/litellm_oauth.py","content":" from .tool_utils import (\n apply_tool_pairing_fixes,\n convert_tool_calls_to_gemini_parts,\n convert_tool_message_to_gemini_part,\n convert_tools_to_claude_format,\n convert_tools_to_gemini_format,\n ensure_thinking_signature_for_tool_use,\n inject_thought_signature_for_function_calls,\n inject_parameter_signatures,\n inject_tool_hardening_instruction,\n )\n\n header_style = kwargs.pop(\"header_style\", \"antigravity\")\n session_id = kwargs.pop(\"session_id\", None)\n\n # Resolve model name and thinking tier\n # Claude thinking models: strip tier suffix, extract budget\n # e.g., \"antigravity-claude-opus-4-5-thinking-high\" → \"claude-opus-4-5-thinking\" + budget=32768\n model_name, _tier, thinking_budget = self._resolve_model_for_header_style(\n model, header_style\n )\n is_claude = \"claude\" in model_name.lower()\n is_claude_thinking = self._is_claude_thinking_model(model_name)\n\n # Convert OpenAI-style messages to Gemini format\n contents: List[Dict[str, Any]] = []\n system_instruction = None\n pending_tool_responses: List[Dict[str, Any]] = []\n\n for msg in messages:\n role = msg.get(\"role\", \"user\")\n content = msg.get(\"content\", \"\")\n\n if role == \"system\":\n if isinstance(content, str):\n system_instruction = {\"parts\": [{\"text\": content}]}\n continue\n\n # Handle tool result messages (role=\"tool\")\n if role == \"tool\":\n # Collect tool responses to group with the previous model response\n tool_part = convert_tool_message_to_gemini_part(msg)\n pending_tool_responses.append(tool_part)\n continue\n\n # Flush pending tool responses as a user message before the next message\n if pending_tool_responses:\n contents.append({\"role\": \"user\", \"parts\": pending_tool_responses})\n pending_tool_responses = []\n\n gemini_role = \"model\" if role == \"assistant\" else \"user\"\n\n # Check if assistant message has tool_calls\n tool_calls = msg.get(\"tool_calls\")\n if role == \"assistant\" and tool_calls:\n # Convert tool_calls to functionCall parts\n parts = convert_tool_calls_to_gemini_parts(tool_calls)\n # Add text content if present\n if isinstance(content, str) and content:\n parts.insert(0, {\"text\": content})\n contents.append({\"role\": gemini_role, \"parts\": parts})\n elif isinstance(content, str):\n contents.append({\"role\": gemini_role, \"parts\": [{\"text\": content}]})\n elif isinstance(content, list):\n parts = []\n for item in content:\n if isinstance(item, dict):\n if item.get(\"type\") == \"text\":\n parts.append({\"text\": item.get(\"text\", \"\")})\n if parts:\n contents.append({\"role\": gemini_role, \"parts\": parts})\n\n # Flush any remaining tool responses\n if pending_tool_responses:\n contents.append({\"role\": \"user\", \"parts\": pending_tool_responses})\n\n request_payload: Dict[str, Any] = {\"contents\": contents}\n\n # Track message count for session signature cache (rewind detection)\n self._last_request_message_count = len(contents)\n\n if system_instruction:\n request_payload[\"systemInstruction\"] = system_instruction\n\n # Convert and add tools\n tools = kwargs.get(\"tools\")\n if tools:\n if is_claude:\n # Claude models need cleaned schemas and VALIDATED mode\n converted_tools = convert_tools_to_claude_format(tools)\n # Apply parameter signature injection (tool hardening)\n # This prevents Claude from hallucinating tool parameters\n converted_tools = inject_parameter_signatures(converted_tools)\n else:\n # Gemini models use simpler format\n converted_tools = convert_tools_to_gemini_format(tools)\n if converted_tools:\n request_payload[\"tools\"] = converted_tools\n\n # Claude thinking models with tools get interleaved thinking hint\n if is_claude_thinking:\n self._append_system_instruction_hint(\n request_payload, CLAUDE_INTERLEAVED_THINKING_HINT\n )\n\n # Inject tool hardening system instruction for Claude models\n # This provides explicit guidance on how to use tool schemas\n if is_claude:\n inject_tool_hardening_instruction(request_payload)\n\n # Add generation config\n generation_config: Dict[str, Any] = {}\n if \"temperature\" in kwargs:\n generation_config[\"temperature\"] = kwargs[\"temperature\"]\n if \"max_tokens\" in kwargs:\n generation_config[\"maxOutputTokens\"] = kwargs[\"max_tokens\"]\n if \"top_p\" in kwargs:\n generation_config[\"topP\"] = kwargs[\"top_p\"]\n\n # Add thinking configuration for Claude thinking models\n # Reference: antigravity-auth/src/plugin/request.ts (lines 766-773)\n # Claude uses snake_case: include_thoughts, thinking_budget\n if is_claude_thinking:\n thinking_config: Dict[str, Any] = {\n \"include_thoughts\": True,\n }\n if thinking_budget:\n thinking_config[\"thinking_budget\"] = thinking_budget\n\n generation_config[\"thinkingConfig\"] = thinking_config\n\n # Ensure maxOutputTokens is large enough for thinking + response\n current_max = generation_config.get(\"maxOutputTokens\", 0)\n if not current_max or current_max <= (thinking_budget or 0):\n generation_config[\"maxOutputTokens\"] = CLAUDE_THINKING_MAX_OUTPUT_TOKENS\n\n if generation_config:\n request_payload[\"generationConfig\"] = generation_config\n\n # Add toolConfig for Claude models (required even without tools)\n # Reference: antigravity-auth/src/plugin/request.ts (lines 726-739)\n if is_claude:\n request_payload[\"toolConfig\"] = {\"functionCallingConfig\": {\"mode\": \"VALIDATED\"}}\n\n # Apply tool pairing fixes for Claude models (ID management)\n if is_claude:\n request_payload = apply_tool_pairing_fixes(request_payload, is_claude=True)\n\n # Ensure thinking signatures for Claude thinking models with tool use\n # When thinking blocks don't have valid signatures, inject sentinel to bypass validation\n if is_claude_thinking and request_payload.get(\"contents\"):\n session_key = session_id or f\"antigravity-{uuid.uuid4().hex[:8]}\"\n request_payload[\"contents\"] = ensure_thinking_signature_for_tool_use(\n request_payload[\"contents\"], session_key\n )\n\n # Gemini 3 tool calls require thoughtSignature; inject from session cache if missing\n if not is_claude and session_id and request_payload.get(\"contents\"):\n request_payload[\"contents\"] = inject_thought_signature_for_function_calls(\n request_payload[\"contents\"], session_id\n )\n\n # Inject Antigravity system instruction for antigravity quota\n if header_style == \"antigravity\":\n self._inject_antigravity_system_instruction(request_payload)\n\n # Attach sessionId for signature caching (stable across turns)\n if session_id:\n request_payload[\"sessionId\"] = session_id\n\n return {\n \"project\": project_id,\n \"model\": model_name,\n \"request\": request_payload,\n \"requestType\": \"agent\",\n \"userAgent\": \"antigravity\",\n \"requestId\": f\"agent-{uuid.uuid4()}\",\n }\n\n def _parse_response(self, response_data: Dict[str, Any]) -> ModelResponse:\n \"\"\"Parse Antigravity response into LiteLLM ModelResponse format.\"\"\"\n from .tool_utils import extract_tool_calls_from_gemini_response\n\n # Handle wrapped response format\n if \"response\" in response_data:\n response_data = response_data[\"response\"]\n\n content = \"\"\n if \"candidates\" in response_data:\n candidates = response_data[\"candidates\"]\n if candidates and len(candidates) > 0:\n candidate = candidates[0]\n if \"content\" in candidate:\n parts = candidate[\"content\"].get(\"parts\", [])\n for part in parts:\n if \"text\" in part:\n content += part[\"text\"]\n elif \"content\" in response_data and isinstance(response_data[\"content\"], list):\n # Anthropic-style response format\n for part in response_data[\"content\"]:\n if isinstance(part, dict):\n if \"text\" in part and isinstance(part[\"text\"], str):\n content += part[\"text\"]\n elif \"thinking\" in part and isinstance(part[\"thinking\"], str):\n # Ignore thinking by default; keep for completeness\n continue\n\n # Extract tool calls from response\n tool_calls = extract_tool_calls_from_gemini_response(response_data)\n\n usage_data = response_data.get(\"usageMetadata\", {})\n usage = Usage(\n prompt_tokens=usage_data.get(\"promptTokenCount\", 0),\n completion_tokens=usage_data.get(\"candidatesTokenCount\", 0),\n total_tokens=usage_data.get(\"totalTokenCount\", 0),\n )\n\n # Build message with optional tool_calls\n message: Dict[str, Any] = {\n \"role\": \"assistant\",\n \"content\": content if content else None,\n }\n if tool_calls:\n message[\"tool_calls\"] = tool_calls\n\n # Set finish_reason based on response content\n finish_reason = \"tool_calls\" if tool_calls else \"stop\"\n\n return ModelResponse(\n id=f\"chatcmpl-{uuid.uuid4().hex}\",\n created=int(time.time()),\n model=response_data.get(\"model\", \"antigravity\"),\n choices=[\n {\n \"index\": 0,\n \"message\": message,\n \"finish_reason\": finish_reason,\n }\n ],\n usage=usage,\n )\n\n def completion(\n self,\n model: str,\n messages: List[Dict[str, Any]],\n **kwargs: Any,\n ) -> ModelResponse:\n \"\"\"Synchronous completion (not implemented - use async).\"\"\"\n raise NotImplementedError(\"Use acompletion for Antigravity OAuth\")","numLines":250,"startLine":2340,"totalLines":3226}}},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01NGteGVw5b7uEtTKzCED6z8","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"Now I have a comprehensive understanding of both implementations. Let me also check the `ensure_thinking_signature_for_tool_use` function in Koder's tool_utils.py to see if it's handling sentinel injection properly.\n\nLooking at the code:\n\n1. **Antigravity-Manager (Rust)** - The reference implementation:\n - Has sophisticated signature validation with multiple fallback layers:\n 1. Client-provided signature (from the message itself)\n 2. Context (`last_thought_signature` - from preceding thinking blocks)\n 3. Session Cache (conversation-level)\n 4. Tool Cache (per tool_id)\n 5. Global Store (deprecated, for backward compatibility)\n - **Critical**: For Vertex AI (`projects/` prefix), it does NOT inject the sentinel `skip_thought_signature_validator`\n - Validates signature length >= 50 (MIN_SIGNATURE_LENGTH)\n - Checks signature family compatibility (SONNET vs OPUS thinking models)\n - **Retry logic**: Skips backfill during retry to avoid issues\n - Has `has_valid_signature_for_function_calls()` function that checks all layers\n - Sorts thinking blocks before other blocks in assistant messages\n\n2. **Koder (Python)** - Needs comparison:\n - Uses `ensure_thinking_signature_for_tool_use()` which injects `SKIP_THOUGHT_SIGNATURE` sentinel\n - Uses `inject_thought_signature_for_function_calls()` for Gemini 3 tool calls\n - Has session signature cache\n - But from my reading, there are several issues:\n - **Issue 1**: `ensure_thinking_signature_for_tool_use` injects sentinel unconditionally without checking if target is Vertex AI (Google Cloud)\n - **Issue 2**: No `has_valid_signature_for_function_calls()` pre-check before attempting signature operations\n - **Issue 3**: Doesn't account for retry scenarios where backfill should be skipped\n - **Issue 4**: Missing cross-model signature family validation\n - **Issue 5**: Thinking blocks aren't sorted before other message blocks\n\nLet me verify the `ensure_thinking_signature_for_tool_use` function in Koder.","signature":"EoYRCkYICxgCKkDX5K/72hBrs9HaDGVF+Vx9O6CdGYu3piyIx5BMFMJGgWWgAIAPliagIchigDLK/a/B6mgiyrgPP1ZtsqxFF7N9EgxJcc5k77Xvvtt1lIEaDKwOlswhsuQt/unkYCIwa8IfFQEIymvaIRemX3CO2mj0UqMchzqH6JD4lTyg+zqG9wn55f9mZA23GEzMcXG2Ku0PXpcxN5TG+2szP705ZrYX37U3cIG2N2SBDVnBicws8wB2xt3dH6yoV8ydHPYAq6cfPYWjomglqVefAoRYWACmxVIhf/alRbhD6VW3V7j3tl83iDhfeSTRRy9q+OO5dd1x8oPXz+sCFLSHzB0WCen4cizWnNs7gkD6f6OZnve+hqd8ApuPF5JBpSY5LJHUthYfUVxOL9teF1XaPcBlr5Wb3TN/wcX+82klbTLxAgL7KVS8dIhQEaAwzTP41oozsoVuwccgmoakm7hL0WTKlvEn484W2tt+8Ipm6GyyUkJUjQlScOp+7QIbnf4D+dRpT0HMCBIZmT4uI6S6o/f20m7GgL5ewaTPw4jKBmpn0fJh+jH/MEbNKcwNUlPTlsDTbJD0ZsHgtFMMMNScsYltvzHszWk5ItYlyVNHATpX2sV1Am7czkinY+tYyvhrpePQjV2NLUmWjWSylY1pkuov1rlx6mTNtsBFbi8c7eEw0uLHR8mlVVoZ1pJL+S/o4ZZeKQCyjF+blAlj0h8zXxOtdBXwgmnzHih6thytmJE714wNpkKbve/BRv25BaH+vehIdisbj0GUevgJ1/UorlUoeuFGdCg31MoF2xNxNWaifnO1Uwfd/EJdFMJ26sgBnAyTNhdG5zVZVGOdc+MsxaS2xDQcvmwU902RcWIC9AviwYBe+gonjhnITGSJZyUSrg2RScAoGqXvvKjWeksSopgMzgnMAWgdy2D8k/nRoxMwcNudSbn5zw0YOSaW4w4AEwZBO//SRzpuv6xF4zddDAfsdUGyNAW+vcOV/8YYTutPQF3LylaWMTeYoycLzD636B05Adtdsz321KZRgRf77oy4m2wFtF29XyxnUkXOtcVm3VS5OwxzAHzWB2n8fm79EE9vnU2WrR1agFdvN/IJV8+ZDNvO5jKjAHAeeQqG3cu6xnKceNw2st8FQQ3wCpD6JiTO261NHCt2mvWAbTEuAYuB9nvXTuLrvl03sInqoMeq0cgQzWveo6pDu2gnfIDGLVdBOeGbM/epyYEazIg9QCRQW4/PfW+FzHE2hot/K2H7TWSkY5QNZz54EXaTGqH9HXLzFpePyLXkMe64Slb8KChDDih/jr52kzCkRBrbr9MMYjYGi0m/okK435TDiuP7MoSl+1GtfRR7pWrEUacV3X3/DS1S/tX4RVeoptPuVlcjKz4HfJonvEQWSiNDWtGhsjjBoaO3zGOa+9oF5s0I3qTauYw3Wh8cW8GMurYtDoQGGYgqUrMJpcz5F3ynHvUO6LmNtQ4NekxBqDaxj25xxEzqib87cfE3KXfsHVkXw83JJdo5WF6wNLSOUZKAGyNbsjo4Ziq4Z0i92TPD4own+EwIXI3DyT7TsX+hQUtMpp9bP3OVYejrWCraXOhDVep9+GHs5tWCj5Rb8T/D9j//DHwNY8l2oYCqDtfEm7moctHgqFBj4s4RELAom0P29AvdSh/Gix9Yv7lJPWMdr0OGZhw1NItDnx7XsTH7CLijljquwJtCUl+o9D8GUdnu7260Dk9ZCnXRHfNEdZzCpViSdKSylJBmj1sYPzdVdHiYRwU7XVkv2UKVFxAP9Jg3xZTjNKdPlrdESbUpSME+r3btfgClxiNJKHWG8rxYRZcE1DY8XtL782RQg+yKwUM2QrGECisXqc4+I24mxymveKIJA0Xu4ADeZJbOqhyrJB+jHVfnjPW+umS3UFYwG1l8KD5m/dFdL3Hcdcds5pk7cZrOKGOU+qip3c48QGVKtvdkUVP75eFdMAO50zNkl6cZWUFrAVbqW7ATem0YA58sDQuziiLyaeNPJCpQK+0MT3nR9MWmtMhwdP1p9t+TTr4X/xDk44i+A3ENemSmDAeyiECu4cUYsdGl5KJjK86UNcCy/m5gNMXjB9ccYIMPGUfz2Fd+X/LMOaCDl1UuSmT8jNldQdDMRwxagqIcC8fVSynUe7RqS3HZG0sKjV31UZWaun5h7FXw8TZwlfFwix2O4SFWd0O37G6veBpC+hl7JHq90kW7x19hqKNgNbx+6Orl50E8NawN0Z8o9y9jswJ3v88YIrxhVUfe9qwbAbIwT2rbnV2j/KyUrU2k8lLKtBq0JLfAUKSgZx4zW6ejNwr89ZqqOpKI5YDLwS9cmTLZ4cijiRGDkUfDUiXgVvjY6ehQe8BPSfAghyZNrWVFkVWbOBiazl/27Xbl/ificpKZQ4O8HIs+XK1vDQE1lSZb76XmTyGGVHjr+UuRCr4FYKfrZP5Su4wYaMeVzZv912HosuJQuK2QnQb0DMcd+RTq3MV0gkJZJJoEh9vmLmbkTo22E7hfihI8vEhce/VpOrSt1WV2z3cvNDd+pp9IVQgYQ6mtLtKqma7jKHr21OCyLo/6QMyEWTHBMlfezhF3f8rFD4kJ/RmzqNHQVK4oBJtSMVlkhVDSjb0hED6bEG1kTL725ZqQUlkPfaIeFezA+rnm0ICF3HcWAzZqDlBHtd5acQPQEDLdtTuxe3wkHSmWbcClmSdlnM5k8RPhYjHRJk58eBrooXGmuCOb0huMq2BQJwnFIk8mG9IUYqGi8vJIJlekmHLw07QrLXs13F8loFoXNVZzhQMspxMi/73EnQyBX84lsZ7SD08TFSASIQJ/Q3lyhUreTpcyE7q1VSYWj9eiK1rFuRoC/mOSQBzSm223Pd2SSHEH65/MJt33W/Fmmj9GCKcVABQx/BgB"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":2279,"cache_creation_input_tokens":4091,"cache_read_input_tokens":87692,"cache_creation":{"ephemeral_5m_input_tokens":4091,"ephemeral_1h_input_tokens":0},"output_tokens":5,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"c9f6a09a-8a04-4190-b605-13a3653a01da"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01NGteGVw5b7uEtTKzCED6z8","type":"message","role":"assistant","content":[{"type":"text","text":"Let me check the `ensure_thinking_signature_for_tool_use` function in tool_utils.py more closely."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":2279,"cache_creation_input_tokens":4091,"cache_read_input_tokens":87692,"cache_creation":{"ephemeral_5m_input_tokens":4091,"ephemeral_1h_input_tokens":0},"output_tokens":5,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"5b046f77-2440-4a47-a464-cf62db8792c1"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_01NGteGVw5b7uEtTKzCED6z8","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01P7xK31Bc4b5xCrbmVBcBcH","name":"Read","input":{"file_path":"/Users/fei/coding-agent/koder/koder_agent/auth/tool_utils.py","offset":1504,"limit":90},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":2279,"cache_creation_input_tokens":4091,"cache_read_input_tokens":87692,"cache_creation":{"ephemeral_5m_input_tokens":4091,"ephemeral_1h_input_tokens":0},"output_tokens":5,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"044c5fe1-7c48-4abb-9b92-a5ccb8e5aa39"},{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01P7xK31Bc4b5xCrbmVBcBcH","type":"tool_result","content":" 1504→def ensure_thinking_signature_for_tool_use(\n 1505→ contents: List[Dict[str, Any]],\n 1506→ session_key: str,\n 1507→) -> List[Dict[str, Any]]:\n 1508→ \"\"\"Ensure thinking blocks have signatures before tool use parts.\n 1509→\n 1510→ For Claude thinking models, tool use requires signed thinking to precede it.\n 1511→ If no valid signed thinking is found, inject the SKIP_THOUGHT_SIGNATURE sentinel.\n 1512→\n 1513→ Reference: antigravity-auth/src/plugin/request.ts ensureThinkingBeforeToolUseInContents()\n 1514→\n 1515→ Args:\n 1516→ contents: Gemini-style contents array\n 1517→ session_key: Session key for signature caching\n 1518→\n 1519→ Returns:\n 1520→ Modified contents with thinking signatures ensured\n 1521→ \"\"\"\n 1522→ result = []\n 1523→\n 1524→ for content in contents:\n 1525→ if not isinstance(content, dict) or not isinstance(content.get(\"parts\"), list):\n 1526→ result.append(content)\n 1527→ continue\n 1528→\n 1529→ role = content.get(\"role\")\n 1530→ if role not in (\"model\", \"assistant\"):\n 1531→ result.append(content)\n 1532→ continue\n 1533→\n 1534→ parts = content[\"parts\"]\n 1535→\n 1536→ # Check if this content has tool use (functionCall)\n 1537→ has_tool_use = any(\n 1538→ isinstance(p, dict) and (\"functionCall\" in p or \"tool_use\" in p or \"toolUse\" in p)\n 1539→ for p in parts\n 1540→ )\n 1541→ if not has_tool_use:\n 1542→ result.append(content)\n 1543→ continue\n 1544→\n 1545→ # Separate thinking parts from other parts\n 1546→ thinking_parts = []\n 1547→ other_parts = []\n 1548→\n 1549→ for part in parts:\n 1550→ if not isinstance(part, dict):\n 1551→ other_parts.append(part)\n 1552→ continue\n 1553→\n 1554→ is_thinking = (\n 1555→ part.get(\"thought\") is True\n 1556→ or part.get(\"type\") in (\"thinking\", \"reasoning\", \"redacted_thinking\")\n 1557→ )\n 1558→ if is_thinking:\n 1559→ thinking_parts.append(part)\n 1560→ else:\n 1561→ other_parts.append(part)\n 1562→\n 1563→ # Check if we have a valid signed thinking\n 1564→ has_signed = any(has_signed_thinking_part(p) for p in thinking_parts)\n 1565→\n 1566→ if has_signed:\n 1567→ # Put thinking parts first, then other parts\n 1568→ result.append({**content, \"parts\": thinking_parts + other_parts})\n 1569→ else:\n 1570→ # No valid signed thinking - inject sentinel signature\n 1571→ # This allows Claude to proceed without blocking on signature validation\n 1572→ existing_thinking = thinking_parts[0] if thinking_parts else {}\n 1573→ thinking_text = existing_thinking.get(\"thinking\") or existing_thinking.get(\"text\") or \"\"\n 1574→\n 1575→ sentinel_block = {\n 1576→ \"type\": \"thinking\",\n 1577→ \"thinking\": thinking_text,\n 1578→ \"signature\": SKIP_THOUGHT_SIGNATURE,\n 1579→ }\n 1580→\n 1581→ logger.debug(\n 1582→ \"Injecting sentinel signature for tool use (session=%s)\", session_key\n 1583→ )\n 1584→ result.append({**content, \"parts\": [sentinel_block] + other_parts})\n 1585→\n 1586→ return result\n 1587→\n 1588→\n 1589→# =============================================================================\n 1590→# TOOL DEFINITION CONVERSION\n 1591→# =============================================================================\n 1592→\n 1593→\n\n<system-reminder>\nWhenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.\n</system-reminder>\n"}]},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"587ea309-ea66-4447-b3a7-6beeec3ec9b4","tool_use_result":{"type":"text","file":{"filePath":"/Users/fei/coding-agent/koder/koder_agent/auth/tool_utils.py","content":"def ensure_thinking_signature_for_tool_use(\n contents: List[Dict[str, Any]],\n session_key: str,\n) -> List[Dict[str, Any]]:\n \"\"\"Ensure thinking blocks have signatures before tool use parts.\n\n For Claude thinking models, tool use requires signed thinking to precede it.\n If no valid signed thinking is found, inject the SKIP_THOUGHT_SIGNATURE sentinel.\n\n Reference: antigravity-auth/src/plugin/request.ts ensureThinkingBeforeToolUseInContents()\n\n Args:\n contents: Gemini-style contents array\n session_key: Session key for signature caching\n\n Returns:\n Modified contents with thinking signatures ensured\n \"\"\"\n result = []\n\n for content in contents:\n if not isinstance(content, dict) or not isinstance(content.get(\"parts\"), list):\n result.append(content)\n continue\n\n role = content.get(\"role\")\n if role not in (\"model\", \"assistant\"):\n result.append(content)\n continue\n\n parts = content[\"parts\"]\n\n # Check if this content has tool use (functionCall)\n has_tool_use = any(\n isinstance(p, dict) and (\"functionCall\" in p or \"tool_use\" in p or \"toolUse\" in p)\n for p in parts\n )\n if not has_tool_use:\n result.append(content)\n continue\n\n # Separate thinking parts from other parts\n thinking_parts = []\n other_parts = []\n\n for part in parts:\n if not isinstance(part, dict):\n other_parts.append(part)\n continue\n\n is_thinking = (\n part.get(\"thought\") is True\n or part.get(\"type\") in (\"thinking\", \"reasoning\", \"redacted_thinking\")\n )\n if is_thinking:\n thinking_parts.append(part)\n else:\n other_parts.append(part)\n\n # Check if we have a valid signed thinking\n has_signed = any(has_signed_thinking_part(p) for p in thinking_parts)\n\n if has_signed:\n # Put thinking parts first, then other parts\n result.append({**content, \"parts\": thinking_parts + other_parts})\n else:\n # No valid signed thinking - inject sentinel signature\n # This allows Claude to proceed without blocking on signature validation\n existing_thinking = thinking_parts[0] if thinking_parts else {}\n thinking_text = existing_thinking.get(\"thinking\") or existing_thinking.get(\"text\") or \"\"\n\n sentinel_block = {\n \"type\": \"thinking\",\n \"thinking\": thinking_text,\n \"signature\": SKIP_THOUGHT_SIGNATURE,\n }\n\n logger.debug(\n \"Injecting sentinel signature for tool use (session=%s)\", session_key\n )\n result.append({**content, \"parts\": [sentinel_block] + other_parts})\n\n return result\n\n\n# =============================================================================\n# TOOL DEFINITION CONVERSION\n# =============================================================================\n\n","numLines":90,"startLine":1504,"totalLines":2338}}},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_017vxgxtkCPEVnoyGP4ZVyUd","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"Now I have a clear picture of the differences. Let me create a comprehensive comparison report.","signature":"EocCCkYICxgCKkBIG3lLG6oTKEPwPdibsvV28PQe7Ze5z3vZ2nKBBfRfNfKkESOpNcPsbMohEWBGvsBBCshh1BpqHTm+v6BSikvNEgySyxm3wJuYuATcOQUaDCxGKZd99G1gt1lbbiIwH6/PN3VoCO/GsYh5KEtnUbYkfgstD7e9IMymRd3ImenbmOm67B2WsbOmb3M6g4PfKm865wPVprWwusQHaj1u+AcuHPoopH3w8ndP0zFhSA9QQ5Lq8V4T1PRt1EkKuChWfxAAsqMKoac0sp9U01lgoFPQh3Uau3L6x2AcjlYzq1UwH47lbdKefjHEMnBDDQseXbx+A+HxFg4I01Rl2r5Ff2kYAQ=="}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":8,"cache_creation_input_tokens":4145,"cache_read_input_tokens":91783,"cache_creation":{"ephemeral_5m_input_tokens":4145,"ephemeral_1h_input_tokens":0},"output_tokens":3,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"fd284913-db4f-452a-8f76-c43aea8f5a0f"},{"type":"assistant","message":{"model":"claude-opus-4-5-20251101","id":"msg_017vxgxtkCPEVnoyGP4ZVyUd","type":"message","role":"assistant","content":[{"type":"text","text":"Now I have a comprehensive view of both codebases. Here's my analysis:\n\n---\n\n# Comparison: Antigravity-Manager vs Koder - Signature Validation & Thinking Handling\n\n## 1. Antigravity-Manager Logic Summary\n\n### Thinking Enable/Disable\n- **File**: `request.rs:2462-2474`\n- Thinking enabled via `thinkingConfig.include_thoughts: true`\n- Budget configurable via tier suffixes (`-low/-medium/-high` → 8192/16384/32768)\n- `maxOutputTokens` auto-adjusted to 65536 when thinking enabled\n\n### Signature Availability Checks (`has_valid_signature_for_function_calls`)\n- **File**: `request.rs:680-737`\n- **Priority chain**:\n 1. Global store (deprecated)\n 2. **Session Cache** - critical for retry scenarios (`request.rs:696-707`)\n 3. Message history scan - iterates assistant messages for `ContentBlock::Thinking` with valid signature\n- **Validation**: `sig.len() >= MIN_SIGNATURE_LENGTH` (50 chars)\n\n### Tool Call Signature Backfill (`build_contents` for ToolUse)\n- **File**: `request.rs:1053-1160`\n- **Resolution priority**:\n 1. Client-provided signature (`signature.as_ref()`)\n 2. Context signature (`last_thought_signature`)\n 3. Session Cache (`SignatureCache::global().get_session_signature(session_id)`)\n 4. Tool Cache (`get_tool_signature(id)`)\n 5. Global Store (deprecated fallback)\n- **Signature family validation**: Checks `is_model_compatible(&family, mapped_model)` to prevent SONNET→OPUS signature reuse\n- **Retry handling**: `is_retry && signature.is_none()` → **skip backfill** (`request.rs:1095-1097`)\n\n### Sentinel Restrictions for Vertex AI\n- **File**: `request.rs:1055-1056, 1152-1159`\n- **Critical**: `is_google_cloud = mapped_model.starts_with(\"projects/\")` \n- When `is_google_cloud == true` → **DO NOT inject sentinel** `skip_thought_signature_validator`\n- Sentinel only used for non-Vertex endpoints when `is_thinking_enabled && !is_google_cloud`\n\n### Thinking Block Sorting\n- **File**: `request.rs:173-229` (`sort_thinking_blocks_first`)\n- **Triple-stage partition**: `[Thinking, Text, ToolUse]` order enforced\n- Required by Claude/Anthropic API protocol\n\n### Cross-Model Signature Compatibility\n- **File**: `thinking_utils.rs:176-244` (`filter_invalid_thinking_blocks_with_family`)\n- Strips signatures when:\n - Length < 50 chars\n - Family mismatch (e.g., SONNET sig → OPUS target)\n - Cache miss (unverified after restart)\n\n---\n\n## 2. Koder Mismatches & Risky Logic\n\n### ❌ **CRITICAL: Unconditional Sentinel Injection**\n- **File**: `tool_utils.py:1569-1584`\n- **Problem**: `ensure_thinking_signature_for_tool_use()` injects `SKIP_THOUGHT_SIGNATURE` unconditionally\n- **Missing check**: No `is_google_cloud` / Vertex AI detection\n- **Impact**: Vertex AI rejects the sentinel value with \"Invalid thought signature\" error\n\n```python\n# tool_utils.py:1575-1578 - MISSING VERTEX AI CHECK\nsentinel_block = {\n \"type\": \"thinking\",\n \"thinking\": thinking_text,\n \"signature\": SKIP_THOUGHT_SIGNATURE, # ❌ Always injected\n}\n```\n\n### ❌ **Missing Session Cache Check Before Tool Use**\n- **File**: `litellm_oauth.py:2488-2494`\n- **Problem**: No pre-check like `has_valid_signature_for_function_calls()`\n- **Impact**: May inject sentinel when valid signature exists in session cache but wasn't propagated to message contents\n\n### ❌ **Missing Retry Handling**\n- **File**: `litellm_oauth.py`, `tool_utils.py`\n- **Problem**: No `is_retry` parameter passed or checked\n- **In Antigravity-Manager** (`request.rs:1095-1097`):\n ```rust\n if is_retry && signature.is_none() {\n tracing::warn!(\"[Tool-Signature] Skipping signature backfill for tool_use...\");\n }\n ```\n- **Impact**: During retry, backfilling cached signatures may cause validation errors\n\n### ⚠️ **Missing Signature Family Validation**\n- **File**: `tool_utils.py`\n- **Problem**: No equivalent to `is_model_compatible()` or `filter_invalid_thinking_blocks_with_family()`\n- **Impact**: Cross-model signature leakage (SONNET thinking sig sent to OPUS model → rejection)\n\n### ⚠️ **Missing Thinking Block Sorting**\n- **File**: `litellm_oauth.py:2364-2414` (message conversion)\n- **Problem**: No `sort_thinking_blocks_first()` equivalent\n- **Impact**: If context compression reorders blocks, API may reject with \"thinking blocks must come first\"\n\n### ⚠️ **Wrong Signature Source Priority in `inject_thought_signature_for_function_calls`**\n- **File**: `tool_utils.py:193-229`\n- **Current behavior**: Only injects from session cache\n- **Missing**: Tool-specific cache lookup, context signature fallback\n\n---\n\n## 3. Porting Recommendations\n\n### P0 (Critical) - Fix Sentinel Injection for Vertex AI\n\n**File**: `tool_utils.py:1504-1586`\n\nAdd Vertex AI detection to `ensure_thinking_signature_for_tool_use()`:\n\n```python\ndef ensure_thinking_signature_for_tool_use(\n contents: List[Dict[str, Any]],\n session_key: str,\n mapped_model: str = \"\", # NEW: Add model parameter\n) -> List[Dict[str, Any]]:\n # ...\n is_google_cloud = mapped_model.startswith(\"projects/\")\n \n # In the sentinel injection block:\n if not has_signed:\n if is_google_cloud:\n # Vertex AI rejects sentinel - pass through without modification\n logger.warning(\n \"No valid signature for tool use but Vertex AI detected - skipping sentinel\"\n )\n result.append({**content, \"parts\": thinking_parts + other_parts})\n else:\n # Non-Vertex: inject sentinel\n sentinel_block = {...}\n result.append({**content, \"parts\": [sentinel_block] + other_parts})\n```\n\n**Update caller** (`litellm_oauth.py:2490-2494`):\n```python\nrequest_payload[\"contents\"] = ensure_thinking_signature_for_tool_use(\n request_payload[\"contents\"], session_key, mapped_model=model_name\n)\n```\n\n### P0 (Critical) - Add Pre-Check for Valid Signature\n\n**File**: `tool_utils.py` - Add new function:\n\n```python\ndef has_valid_signature_available(\n contents: List[Dict[str, Any]],\n session_id: str,\n) -> bool:\n \"\"\"Check if any valid signature exists before tool use operations.\"\"\"\n # 1. Check session cache\n if session_id:\n sig = get_session_signature(session_id)\n if sig and len(sig) >= MIN_SIGNATURE_LENGTH:\n return True\n \n # 2. Check message history\n for content in reversed(contents):\n if content.get(\"role\") not in (\"model\", \"assistant\"):\n continue\n for part in content.get(\"parts\", []):\n if has_signed_thinking_part(part):\n return True\n return False\n```\n\n### P1 (High) - Add Retry Handling\n\n**File**: `litellm_oauth.py:_build_request_body()`\n\nTrack retry state and pass to signature handling:\n```python\ndef _build_request_body(self, ..., is_retry: bool = False):\n # Pass is_retry to signature handling functions\n # Skip backfill when is_retry=True and original signature missing\n```\n\n### P1 (High) - Add Thinking Block Sorting\n\n**File**: `tool_utils.py` - Add new function:\n\n```python\ndef sort_thinking_blocks_first(contents: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n \"\"\"Sort parts in assistant messages: [Thinking, Text, ToolUse].\"\"\"\n result = []\n for content in contents:\n if content.get(\"role\") not in (\"model\", \"assistant\"):\n result.append(content)\n continue\n \n parts = content.get(\"parts\", [])\n thinking = [p for p in parts if p.get(\"thought\") or p.get(\"type\") in (\"thinking\", \"redacted_thinking\")]\n text = [p for p in parts if \"text\" in p and p not in thinking]\n tool = [p for p in parts if \"functionCall\" in p or \"functionResponse\" in p]\n other = [p for p in parts if p not in thinking + text + tool]\n \n result.append({**content, \"parts\": thinking + text + tool + other})\n return result\n```\n\n### P2 (Medium) - Add Signature Family Validation\n\n**File**: `tool_utils.py`\n\n```python\n# Add signature family tracking in cache\n_signature_family_cache: Dict[str, str] = {} # signature_hash -> model_family\n\ndef cache_signature_family(signature: str, model_family: str) -> None:\n \"\"\"Cache the model family origin of a signature.\"\"\"\n sig_hash = hashlib.sha256(signature.encode()).hexdigest()[:16]\n _signature_family_cache[sig_hash] = model_family\n\ndef is_signature_compatible(signature: str, target_model: str) -> bool:\n \"\"\"Check if signature is compatible with target model.\"\"\"\n sig_hash = hashlib.sha256(signature.encode()).hexdigest()[:16]\n origin = _signature_family_cache.get(sig_hash)\n if not origin:\n return True # Unknown origin - allow\n # Extract family from target model (e.g., \"claude-opus\" -> \"OPUS\")\n target_family = extract_model_family(target_model)\n return origin.upper() == target_family.upper()\n```\n\n---\n\n## Summary Table\n\n| Feature | Antigravity-Manager | Koder | Risk |\n|---------|---------------------|-------|------|\n| Vertex AI sentinel restriction | ✅ `!is_google_cloud` check | ❌ Missing | **CRITICAL** |\n| Session cache check | ✅ `get_session_signature()` | ⚠️ Partial | High |\n| Retry backfill skip | ✅ `is_retry` handling | ❌ Missing | High |\n| Thinking block sorting | ✅ Triple-stage partition | ❌ Missing | Medium |\n| Signature family validation | ✅ `is_model_compatible()` | ❌ Missing | Medium |\n| Tool-specific cache | ✅ `get_tool_signature(id)` | ⚠️ Partial | Low |\n\n---\n\n`★ Insight ─────────────────────────────────────`\n1. The root cause of \"invalid thought signature\" errors is likely the unconditional sentinel injection for Vertex AI paths\n2. Antigravity-Manager uses a 5-layer signature resolution chain; Koder only implements 2 layers\n3. The `is_retry` flag is critical - retrying with backfilled signatures from cache can cause validation failures\n`─────────────────────────────────────────────────`"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":8,"cache_creation_input_tokens":4145,"cache_read_input_tokens":91783,"cache_creation":{"ephemeral_5m_input_tokens":4145,"ephemeral_1h_input_tokens":0},"output_tokens":3,"service_tier":"standard"},"context_management":null},"parent_tool_use_id":null,"session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","uuid":"e0e0e781-af59-47be-a9be-247168a724c1"},{"type":"result","subtype":"success","is_error":false,"duration_ms":105155,"duration_api_ms":102391,"num_turns":13,"result":"Now I have a comprehensive view of both codebases. Here's my analysis:\n\n---\n\n# Comparison: Antigravity-Manager vs Koder - Signature Validation & Thinking Handling\n\n## 1. Antigravity-Manager Logic Summary\n\n### Thinking Enable/Disable\n- **File**: `request.rs:2462-2474`\n- Thinking enabled via `thinkingConfig.include_thoughts: true`\n- Budget configurable via tier suffixes (`-low/-medium/-high` → 8192/16384/32768)\n- `maxOutputTokens` auto-adjusted to 65536 when thinking enabled\n\n### Signature Availability Checks (`has_valid_signature_for_function_calls`)\n- **File**: `request.rs:680-737`\n- **Priority chain**:\n 1. Global store (deprecated)\n 2. **Session Cache** - critical for retry scenarios (`request.rs:696-707`)\n 3. Message history scan - iterates assistant messages for `ContentBlock::Thinking` with valid signature\n- **Validation**: `sig.len() >= MIN_SIGNATURE_LENGTH` (50 chars)\n\n### Tool Call Signature Backfill (`build_contents` for ToolUse)\n- **File**: `request.rs:1053-1160`\n- **Resolution priority**:\n 1. Client-provided signature (`signature.as_ref()`)\n 2. Context signature (`last_thought_signature`)\n 3. Session Cache (`SignatureCache::global().get_session_signature(session_id)`)\n 4. Tool Cache (`get_tool_signature(id)`)\n 5. Global Store (deprecated fallback)\n- **Signature family validation**: Checks `is_model_compatible(&family, mapped_model)` to prevent SONNET→OPUS signature reuse\n- **Retry handling**: `is_retry && signature.is_none()` → **skip backfill** (`request.rs:1095-1097`)\n\n### Sentinel Restrictions for Vertex AI\n- **File**: `request.rs:1055-1056, 1152-1159`\n- **Critical**: `is_google_cloud = mapped_model.starts_with(\"projects/\")` \n- When `is_google_cloud == true` → **DO NOT inject sentinel** `skip_thought_signature_validator`\n- Sentinel only used for non-Vertex endpoints when `is_thinking_enabled && !is_google_cloud`\n\n### Thinking Block Sorting\n- **File**: `request.rs:173-229` (`sort_thinking_blocks_first`)\n- **Triple-stage partition**: `[Thinking, Text, ToolUse]` order enforced\n- Required by Claude/Anthropic API protocol\n\n### Cross-Model Signature Compatibility\n- **File**: `thinking_utils.rs:176-244` (`filter_invalid_thinking_blocks_with_family`)\n- Strips signatures when:\n - Length < 50 chars\n - Family mismatch (e.g., SONNET sig → OPUS target)\n - Cache miss (unverified after restart)\n\n---\n\n## 2. Koder Mismatches & Risky Logic\n\n### ❌ **CRITICAL: Unconditional Sentinel Injection**\n- **File**: `tool_utils.py:1569-1584`\n- **Problem**: `ensure_thinking_signature_for_tool_use()` injects `SKIP_THOUGHT_SIGNATURE` unconditionally\n- **Missing check**: No `is_google_cloud` / Vertex AI detection\n- **Impact**: Vertex AI rejects the sentinel value with \"Invalid thought signature\" error\n\n```python\n# tool_utils.py:1575-1578 - MISSING VERTEX AI CHECK\nsentinel_block = {\n \"type\": \"thinking\",\n \"thinking\": thinking_text,\n \"signature\": SKIP_THOUGHT_SIGNATURE, # ❌ Always injected\n}\n```\n\n### ❌ **Missing Session Cache Check Before Tool Use**\n- **File**: `litellm_oauth.py:2488-2494`\n- **Problem**: No pre-check like `has_valid_signature_for_function_calls()`\n- **Impact**: May inject sentinel when valid signature exists in session cache but wasn't propagated to message contents\n\n### ❌ **Missing Retry Handling**\n- **File**: `litellm_oauth.py`, `tool_utils.py`\n- **Problem**: No `is_retry` parameter passed or checked\n- **In Antigravity-Manager** (`request.rs:1095-1097`):\n ```rust\n if is_retry && signature.is_none() {\n tracing::warn!(\"[Tool-Signature] Skipping signature backfill for tool_use...\");\n }\n ```\n- **Impact**: During retry, backfilling cached signatures may cause validation errors\n\n### ⚠️ **Missing Signature Family Validation**\n- **File**: `tool_utils.py`\n- **Problem**: No equivalent to `is_model_compatible()` or `filter_invalid_thinking_blocks_with_family()`\n- **Impact**: Cross-model signature leakage (SONNET thinking sig sent to OPUS model → rejection)\n\n### ⚠️ **Missing Thinking Block Sorting**\n- **File**: `litellm_oauth.py:2364-2414` (message conversion)\n- **Problem**: No `sort_thinking_blocks_first()` equivalent\n- **Impact**: If context compression reorders blocks, API may reject with \"thinking blocks must come first\"\n\n### ⚠️ **Wrong Signature Source Priority in `inject_thought_signature_for_function_calls`**\n- **File**: `tool_utils.py:193-229`\n- **Current behavior**: Only injects from session cache\n- **Missing**: Tool-specific cache lookup, context signature fallback\n\n---\n\n## 3. Porting Recommendations\n\n### P0 (Critical) - Fix Sentinel Injection for Vertex AI\n\n**File**: `tool_utils.py:1504-1586`\n\nAdd Vertex AI detection to `ensure_thinking_signature_for_tool_use()`:\n\n```python\ndef ensure_thinking_signature_for_tool_use(\n contents: List[Dict[str, Any]],\n session_key: str,\n mapped_model: str = \"\", # NEW: Add model parameter\n) -> List[Dict[str, Any]]:\n # ...\n is_google_cloud = mapped_model.startswith(\"projects/\")\n \n # In the sentinel injection block:\n if not has_signed:\n if is_google_cloud:\n # Vertex AI rejects sentinel - pass through without modification\n logger.warning(\n \"No valid signature for tool use but Vertex AI detected - skipping sentinel\"\n )\n result.append({**content, \"parts\": thinking_parts + other_parts})\n else:\n # Non-Vertex: inject sentinel\n sentinel_block = {...}\n result.append({**content, \"parts\": [sentinel_block] + other_parts})\n```\n\n**Update caller** (`litellm_oauth.py:2490-2494`):\n```python\nrequest_payload[\"contents\"] = ensure_thinking_signature_for_tool_use(\n request_payload[\"contents\"], session_key, mapped_model=model_name\n)\n```\n\n### P0 (Critical) - Add Pre-Check for Valid Signature\n\n**File**: `tool_utils.py` - Add new function:\n\n```python\ndef has_valid_signature_available(\n contents: List[Dict[str, Any]],\n session_id: str,\n) -> bool:\n \"\"\"Check if any valid signature exists before tool use operations.\"\"\"\n # 1. Check session cache\n if session_id:\n sig = get_session_signature(session_id)\n if sig and len(sig) >= MIN_SIGNATURE_LENGTH:\n return True\n \n # 2. Check message history\n for content in reversed(contents):\n if content.get(\"role\") not in (\"model\", \"assistant\"):\n continue\n for part in content.get(\"parts\", []):\n if has_signed_thinking_part(part):\n return True\n return False\n```\n\n### P1 (High) - Add Retry Handling\n\n**File**: `litellm_oauth.py:_build_request_body()`\n\nTrack retry state and pass to signature handling:\n```python\ndef _build_request_body(self, ..., is_retry: bool = False):\n # Pass is_retry to signature handling functions\n # Skip backfill when is_retry=True and original signature missing\n```\n\n### P1 (High) - Add Thinking Block Sorting\n\n**File**: `tool_utils.py` - Add new function:\n\n```python\ndef sort_thinking_blocks_first(contents: List[Dict[str, Any]]) -> List[Dict[str, Any]]:\n \"\"\"Sort parts in assistant messages: [Thinking, Text, ToolUse].\"\"\"\n result = []\n for content in contents:\n if content.get(\"role\") not in (\"model\", \"assistant\"):\n result.append(content)\n continue\n \n parts = content.get(\"parts\", [])\n thinking = [p for p in parts if p.get(\"thought\") or p.get(\"type\") in (\"thinking\", \"redacted_thinking\")]\n text = [p for p in parts if \"text\" in p and p not in thinking]\n tool = [p for p in parts if \"functionCall\" in p or \"functionResponse\" in p]\n other = [p for p in parts if p not in thinking + text + tool]\n \n result.append({**content, \"parts\": thinking + text + tool + other})\n return result\n```\n\n### P2 (Medium) - Add Signature Family Validation\n\n**File**: `tool_utils.py`\n\n```python\n# Add signature family tracking in cache\n_signature_family_cache: Dict[str, str] = {} # signature_hash -> model_family\n\ndef cache_signature_family(signature: str, model_family: str) -> None:\n \"\"\"Cache the model family origin of a signature.\"\"\"\n sig_hash = hashlib.sha256(signature.encode()).hexdigest()[:16]\n _signature_family_cache[sig_hash] = model_family\n\ndef is_signature_compatible(signature: str, target_model: str) -> bool:\n \"\"\"Check if signature is compatible with target model.\"\"\"\n sig_hash = hashlib.sha256(signature.encode()).hexdigest()[:16]\n origin = _signature_family_cache.get(sig_hash)\n if not origin:\n return True # Unknown origin - allow\n # Extract family from target model (e.g., \"claude-opus\" -> \"OPUS\")\n target_family = extract_model_family(target_model)\n return origin.upper() == target_family.upper()\n```\n\n---\n\n## Summary Table\n\n| Feature | Antigravity-Manager | Koder | Risk |\n|---------|---------------------|-------|------|\n| Vertex AI sentinel restriction | ✅ `!is_google_cloud` check | ❌ Missing | **CRITICAL** |\n| Session cache check | ✅ `get_session_signature()` | ⚠️ Partial | High |\n| Retry backfill skip | ✅ `is_retry` handling | ❌ Missing | High |\n| Thinking block sorting | ✅ Triple-stage partition | ❌ Missing | Medium |\n| Signature family validation | ✅ `is_model_compatible()` | ❌ Missing | Medium |\n| Tool-specific cache | ✅ `get_tool_signature(id)` | ⚠️ Partial | Low |\n\n---\n\n`★ Insight ─────────────────────────────────────`\n1. The root cause of \"invalid thought signature\" errors is likely the unconditional sentinel injection for Vertex AI paths\n2. Antigravity-Manager uses a 5-layer signature resolution chain; Koder only implements 2 layers\n3. The `is_retry` flag is critical - retrying with backfilled signatures from cache can cause validation failures\n`─────────────────────────────────────────────────`","session_id":"d2802c62-d1ef-4cb2-b04a-217af28d06e8","total_cost_usd":1.0995020000000002,"usage":{"input_tokens":41620,"cache_creation_input_tokens":95928,"cache_read_input_tokens":323904,"output_tokens":5196,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":95928}},"modelUsage":{"claude-opus-4-5-20251101":{"inputTokens":41620,"outputTokens":5196,"cacheReadInputTokens":323904,"cacheCreationInputTokens":95928,"webSearchRequests":0,"costUSD":1.0995020000000002,"contextWindow":200000,"maxOutputTokens":64000}},"permission_denials":[],"uuid":"e173ab16-e6d1-4ea4-930f-8711573bb362"}]