Compare commits

...

92 Commits

Author SHA1 Message Date
abeatrix 93e0bd7564 chore(tsconfig): normalize path aliases and exclude stories
- Remove deprecated `baseUrl` field and use explicit `./src`-based paths
- Align alias paths in root and webview tsconfigs for consistency
- Exclude Storybook stories and decorator from webview app build
2025-11-21 09:57:36 -08:00
Bee 4d395deefd fix: improve error handling and ui for auth failures (#7591) 2025-11-21 08:56:28 -08:00
CandiedUniverse 834a5b1df2 fix(compaction): Use consistent icon for compaction (#7598) 2025-11-21 05:41:58 -08:00
CandiedUniverse 3089233298 feat(hooks): Implement Hooks tab in Rules & Workflows modal [ENG-1325] (#7547)
* feat(hooks): Add hooks tab to Rules & Workflows modal

* feat(hooks): Implement hooks tab content in Rules & Workflows modal

* feat(hooks): Enable creating new hooks in modal from dropdown selection list

* feat(hooks): Change hook template scripts to use bash

* feat(hooks): Windows not yet supported for hooks, so grey-out toggle on windows

* feat(hooks): Improvements to PR as per Cline reviewing the changes before code review

* feat(hooks): Implement tests for hook management (what the UI does under the hood)

* feat(hooks): Changes as per code review feedback from humans
2025-11-20 19:47:39 -08:00
Tomás Barreiro f2b7347a5c Add ApiKeys to the remote config (#7595) 2025-11-20 18:59:49 -08:00
Bee 04bfef75cf feat: replace robot icon with custom cline-bot icon font (#7594)
- Add cline-bot icon font assets (SVG, TTF, WOFF) generated from IcoMoon
- Register custom icon font in VS Code extension manifest
- Replace PNG-based command icon with font-based cline-icon
- Update terminal icon references from generic "robot" to "cline-icon"

This provides a consistent branded icon across the extension and improves visual identity by using the official Cline bot logo instead of the generic robot icon from codicon that was updated by VS Code.
2025-11-20 18:12:44 -08:00
Bee 716e8f236b feat(storybook): add OnboardingView story (#7578)
* chore: clear onboarding models on deactivate

* feat(storybook): add OnboardingView story

- Added OnboardingView component to Storybook with new story
- Integrated onboarding models from shared constants
- Updated MockApp to conditionally render OnboardingView based on onboardingModels state
- Renamed WelcomeScreen story to Welcome for clarity
- Added interaction tests for onboarding buttons (Get Started/Use your own API key)
- Configured onboarding models in mock state to support new story

This enables visual testing and documentation of the user onboarding flow within Storybook.

* Update Storybook missing vscode theme color

* Update task name

* typo
2025-11-20 17:21:28 -08:00
Alex Ker f2ddab71f1 updated baseten docs to include kimi instructions and updated location (#7588)
Co-authored-by: AlexKer <AlexKer@users.noreply.github.com>
2025-11-20 16:04:46 -08:00
canvrno 0b56a45a65 Add thinking level setting for Gemini 3.0 Pro (#7539)
* Added thinking level setting for Gemini 3.0 Pro

* changset
2025-11-20 10:48:31 -08:00
Bee d6ebd2438a fix: parse mentions/commands in tool results and before auto-condense (#7575)
* fix: parse mentions/commands in tool results and before auto-condense

**Changes:**
- Move `loadContext` call before auto-condense check to ensure slash commands and mentions are parsed before context condensing occurs
- Extract parsing logic into reusable `parseInputBlock` helper function
- Add recursive handling for `tool_result` blocks containing nested content arrays
- Remove duplicate `loadContext` calls from conditional branches

**Why:**
Previously, mentions (@file.ts) and slash commands in tool results (like attempt_completion feedback) were not expanded because parsing only handled top-level text blocks. Tool handlers return content arrays within tool_result blocks per Anthropic's API format.

Additionally, `loadContext` was called after the auto-condense check, meaning if condensing was triggered, user commands wouldn't be parsed and could be lost during summarization.

**Result:**
- All user feedback with @mentions or /commands is properly expanded regardless of nesting level
- Commands are detected before context management operations
- Cleaner code flow with single parsing point

* preserve array structure in backward-compatible tool results

When using the backward-compatible "cline" tool use ID, spread array
content directly into userMessageContent instead of wrapping it in
createToolResultBlock. This prevents array content from being
JSON.stringify'd and losing its block structure (e.g., tool_result
blocks with array content).

Previously, array content like [{type: "tool_result", content: [...]}]
was being converted to {type: "text", text: "[...]"}, which prevented
loadContext from properly parsing tool_result blocks.

* clean up

* fix(task): preserve block structure when processing string content

Instead of returning only the processed content, now properly updates the
block.content property with the processed text wrapped in an array and
returns the complete block object. This ensures the block structure is
maintained throughout the processing pipeline rather than being discarded.
2025-11-20 10:38:27 -08:00
Alex Ker 4c07c7e5c5 added Kimi K2 Thinking to static models list and set as default (#7511)
* kimik2 thinking added to static model dropdown

* numerical separators

* don't set kimi k2 thinking as default

---------

Co-authored-by: AlexKer <AlexKer@users.noreply.github.com>
2025-11-20 00:58:19 -08:00
Bee ab66a5fd93 fix: disable switch for required rules to prevent toggling (#7580)
Update RuleRow component to use isDisabled for both the switch disabled state and tooltip visibility, ensuring required rules cannot be toggled off by users. Previously used separate logic that may have miscalibrated disabling for required remote rules.
2025-11-19 23:25:30 -08:00
celestial-vault bd1d6159fc automatically derive openrouter modelinfo based on modelId when calling getModel() (#7568) 2025-11-19 21:16:48 -08:00
Bee 7f2d28716f chore: clear onboarding models on deactivate (#7569) 2025-11-19 18:01:58 -08:00
Toshii 653727db2a updating parser for webfetch to handle current format (#7571) 2025-11-19 17:44:01 -08:00
Bee d3c2f1878d fix(api): attach reasoning details to tool blocks (#7567)
* fix: Centralize reasoning details within thinking blocks

This commit refactors how reasoning details are managed across the system, integrating them directly into `ClineAssistantThinkingBlock` to improve consistency and reduce complexity.

Previously, `reasoning_details` were often explicitly deleted or inconsistently handled, leading to their loss or difficulty in tracking. This change ensures that reasoning details are always associated with their corresponding thinking blocks.

Key changes include:
- `StreamResponseHandler`: The `ReasoningHandler`'s `getCurrentReasoning` method now directly returns a `ClineAssistantThinkingBlock` which encapsulates the reasoning content and its `summary` (formerly `details`). The separate `getThinkingBlock` method has been removed.
- `convertToOpenAiMessages`: Explicit deletion of `part.reasoning_details` for `thinking` parts is replaced by setting it to `undefined` with a comment, indicating that these details are now expected to be part of the thinking block in the stream.
- `Task`: Simplified streaming logic by directly consuming the `ClineAssistantThinkingBlock` from `reasonsHandler.getCurrentReasoning()`. Redundant temporary variables for reasoning content and details have been removed.

This refactoring centralizes the management of reasoning details, providing a more robust and streamlined approach to handling assistant thinking processes.

* fix(api): attach reasoning details to tool blocks and improve logging

Updates validity of reasoning details within tool blocks and enhances debugging visibility.

- Modify `StreamResponseHandler` to append reasoning details/summary to finalized tool use blocks.
- Update `convertToOpenAiMessages` to extract and aggregate `reasoning_details` from tool messages instead of discarding them.
- Add `Logger.debug` calls in `ClineHandler` and OpenAI transformation for better observability of message chunks and conversion.
- Remove redundant `continue` statements in `ClineHandler` stream processing loop.

* clean up

* remove Logger
2025-11-19 17:28:20 -08:00
CellenLee ba92be9401 feat: add kimi-k2-thinking and kimi-k2-thinking-turbo (#7386) 2025-11-19 15:49:46 -08:00
Bee 66eb5a62ba feat: Enable native tool calling for Baseten and Kimi K2 models (#7562)
* feat: Enable native tool calling for Baseten and Kimi K2 models

Introduces native tool calling capabilities for Baseten and Kimi K2 models, aligning with the OpenAI Chat Completions API specification for function calling.

This change includes:
- Updating the `ApiHandler` interface and `createMessage` methods to accept an optional `tools` parameter.
- Implementing a `ToolCallProcessor` to incrementally build and emit tool call payloads from streaming deltas.
- Modifying the `BasetenHandler` to pass `tools` to the Baseten API and process `tool_calls` deltas.
- Updating the `ClineHandler` to process `tool_calls` deltas received from the Kimi K2 model.
- Enhancing the `CompletionStreamChunk` to include `ToolCall` and `ToolCallDelta` types.
- Marking Baseten and Kimi K2 models in their respective definitions with `native_tool_calling: true`.
- Adjustments to streaming logic in handlers to allow multiple delta types (content, tool_calls, reasoning) to be processed from a single chunk.

* add changeset

* clean up
2025-11-19 15:37:10 -08:00
Bee 499ee22b3b fix(task): update UI with final usage after stream completion (#7552)
Ensure the UI displays accurate token usage and costs by updating the API request message when the stream completes. This commit adds a call to updateApiReqMsg followed by saving messages and posting state to the webview, which occurs before finalizing tool calls. This ensures users see the final usage statistics (input/output tokens, cache tokens, and total cost) reflected in the interface immediately after stream processing.
2025-11-19 02:54:31 -08:00
CandiedUniverse 7abeae5019 feat(hooks): Implement TaskComplete hook (#7510) 2025-11-18 23:43:57 -08:00
Bee accf47cb52 fix: await presentAssistantMessage calls to prevent race condition (#7548)
* fix: await presentAssistantMessage calls to prevent race condition

Add await to all presentAssistantMessage() calls to ensure proper
sequencing of message presentation. Previously, the method was called
without awaiting, which could cause race conditions when streaming
tool use content blocks. This ensures that message presentation
completes before continuing execution, particularly important when
handling multiple content blocks or tool interactions.

* revert pr change
2025-11-18 17:48:15 -08:00
Bee 556d3e6f79 fix: rules modal positioning (#7546)
Add overflow-y-auto to the modal container to allow scrolling when content exceeds viewport height. This fixes an issue where modal content would be inaccessible on smaller screens or with large rule sets.
2025-11-18 16:23:48 -08:00
Bee 9e35048db2 feat: add support for Responses API for openai-native provider [ENG-1227] [ENG-1311] (#7504)
* feat: add support for Responses API for openai-native provider [ENG-1227]

- Upgrade openai dependency to v6.9.0 to use the Responses API
- Implement internal handling for reasoning/thinking and redacted output
- Align Anthropic handler message types with the latest SDK interfaces
- Clean up obsolete tooling imports related to tool-use handling
- Enable newer OpenAI capabilities while keeping provider APIs consistent

* Add openai_native_response_api feature flag

* clean up

* clean up 2

* add back gpt-5.1 models

* use call_id
2025-11-18 16:20:45 -08:00
Ara 9b0f2b82ef v3.38.1 Release Notes (#7544) 2025-11-18 14:32:41 -08:00
Bee c2c23054b9 fix: Remove 'signature' from sanitizeAnthropicContentBlock (#7543)
* fix: Remove 'signature' from sanitizeAnthropicContentBlock

Remove 'signature' from sanitizeAnthropicContentBlock as the signature field is required by Anthropic when thinking is enabled.

* Add Changeset

* empty commit

---------

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2025-11-18 14:10:34 -08:00
Bee 3baaa5c8b4 refactor: replace custom UI toggle with shadcn Switch component (#7308)
* refactor(webview-ui): replace custom UI toggle with shadcn Switch component

- Add @radix-ui/react-switch dependency (v1.2.6) https://ui.shadcn.com/docs/components/switch
- Refactor ClineRulesToggleModal to use Radix Switch instead of VSCode buttons
- Improve button styling with reduced padding and adjusted icon sizes
- Enhance form layout with conditional rendering based on expansion state
- Update input field styling with better focus states and border handling

This change provides a more consistent UI experience by leveraging Radix UI's
accessible Switch component while maintaining the same functionality.

* clean up

* clean up

* update switch color

* adjust

* revert unrelated changes

* size

* toggle

* Update webview-ui/src/components/cline-rules/RuleRow.tsx

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-11-18 12:39:50 -08:00
github-actions[bot] abafcc7290 Changeset version bump (#7473)
* v3.38.0 Release Notes

- Gemini 3 Pro Preview model
- AquaVoice Avalon model for voice-to-text dictation

- Automatic context truncation when AWS Bedrock token usage rate limits are exceeded
- SAP AI SDK JS packages upgraded to latest major version
- SAP provider OrchestrationClient now matches OrchestrationModuleConfig type and no longer uses invalid promptTemplating property
- Removed new_task tool from system prompts, updated slash command prompts, and added helper function for native tool calling validation

* Update CHANGELOG.md

---------

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2025-11-18 12:15:10 -08:00
Bee d82aa0add9 feat: add Gemini 3.0 Pro to onboarding list (#7542)
- Add `google/gemini-3-pro-preview` to `CLINE_ONBOARDING_MODELS`.
- Configure model details including context window, pricing, and capabilities (images, prompt cache).
- Enable users to select the new Gemini 3.0 Pro model during setup.
2025-11-18 11:49:08 -08:00
Bee abe4721a0b feat: add thought signature support for Gemini SDK [ENG-1320] (#7536)
* feat: add thought signature support for Gemini SDK

Update @google/genai dependency from v1.15.0 to v1.30.0, including nested deps like google-auth-library. Enhance API interfaces with JSDoc comments and new fields such as signature, id, and redacted_data in ApiStreamThinkingChunk to support thought signatures from Gemini SDK as requested. This improves integration with Gemini's reasoning capabilities and ensures compatibility with updated SDK features.

* add changeset

* meaning val check

* typo

* either

* Do not use think budget with gemini-3
2025-11-18 10:57:53 -08:00
Bee 60d55b69a8 fix: Only update reasoning UI when content changes (#7540)
This commit addresses two issues related to how reasoning messages are processed and displayed.

Previously, the `say` function was called on every iteration of the reasoning stream loop, even if the current chunk contained no new reasoning content. This caused unnecessary UI updates and could lead to errors if a task was cancelled mid-stream. The `say` call is now conditional, only executing when new `chunk.reasoning` is available.

Additionally, the final reasoning block was only appended to the assistant's message history if a signature was present. This meant reasoning could be lost from the UI if the task was cancelled before a signature was generated. The logic is now updated to append the reasoning block if either a message or a signature exists.
2025-11-18 10:57:11 -08:00
Ara d18e0271d3 Fix cancellation for background terminal commands (#7521)
* refactor(task): improve background command cancellation with better error handling

Enhance the cancelBackgroundCommand method with:
- Consolidated early return conditions for cleaner code
- Proper async/await for process termination
- Comprehensive error handling with try-catch blocks for each operation
- Improved logging for termination success/failure scenarios
- Updated cancellation notification message
- Use finally block to ensure notification is always sent

Improve StandaloneTerminalProcess.terminate() with:
- Better guard clauses and early returns
- Enhanced error handling for SIGTERM and SIGKILL operations
- More detailed logging for graceful vs forced termination
- Fallback to SIGKILL if SIGTERM fails immediately

Fix critical issue where terminate() method was not accessible on the merged promise object returned by executeCommand, preventing Task.cancelBackgroundCommand() from properly killing background processes.

* Fix: add cancel ui

* Fix: add cancel ui

* Fix: add cancel ui

* Fix: add cancel ui
2025-11-18 10:41:58 -08:00
Ara af71f9da90 fix: resolve double quote escaping in Windows cmd.exe for Background Exec mode (#7523)
Fixes #7470

When Terminal Execution Mode is set to "Background Exec", commands with
double quotes were being incorrectly escaped on Windows cmd.exe, causing
commands like `echo "\""` or `type "test.txt"` to fail.

The issue was that cmd.exe requires the /s flag and outer quotes when
passing commands with special characters via spawn(). Changed from
`["/c", command]` to `["/s", "/c", `"${command}"`]` for cmd.exe only.

This is a minimal Windows-specific fix that:
- Only affects Windows cmd.exe (PowerShell and Unix shells unchanged)
- Uses standard Windows cmd.exe syntax for proper quote handling
- No changes to process execution flow or behavior
2025-11-18 10:17:37 -08:00
canvrno 2a1c8826aa Add Gemini 3.0 to featuredModels (#7537) 2025-11-18 10:13:06 -08:00
Ara 9a54f2d246 fix(auth): enable provider persistence when applying model changes (#7530)
- Change `UpdateProviderPartial` persist flag from false to true in `applyModelChange`
- Add missing newline at end of state.proto file

This ensures that model changes are properly persisted to storage when users
update their provider configuration through the wizard.
2025-11-18 10:05:01 -08:00
canvrno d928d58a40 Feat: Gemini 3.0 prompt/tool changes (#7532)
* Enhanced Gemini 3.0 support in Cline

* Updated Gemini 3.0 snapshots

* Update src/utils/model-utils.ts

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>

* Updated system prompt

* Update src/core/api/providers/gemini.ts

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>

* Pricing change, narrowed native tool spec to just gemini 3 on vertex

* Update src/core/prompts/system-prompt/registry/ClineToolSet.ts

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>

---------

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2025-11-18 10:02:43 -08:00
canvrno 31859b5fda Add Gemini 3.0 to Gemini provider (#7533)
* Added Gemini 3.0 to Gemnini provider

* Add thinking option for Gemini 3.0
2025-11-18 09:20:19 -08:00
Ara 0d5d89e8c7 feat(bedrock): add context window error detection and retry handling (#7515)
* feat(bedrock): add context window error detection and retry handling

Add proper context window error detection for AWS Bedrock provider to enable automatic retry with context truncation. Previously, context window errors were yielded as error text instead of being thrown, preventing the retry mechanism from handling them.

Changes:
- Detect ValidationException errors matching context window patterns in both Converse API and stream processing
- Throw context window errors instead of yielding them as text to trigger retry logic
- Add checkIsBedrockContextWindowError() function to identify Bedrock-specific context limit errors
- Support multiple error message patterns (input too long, context exceed, maximum tokens, etc.)
- Handle nested error structures from Vercel AI SDK and AWS SDK

This enables automatic context management when Bedrock models hit token limits, improving reliability and user experience.

* Fix: raise errors
2025-11-18 09:09:47 -08:00
Bee af34451eec fix: remove h-full from TaskTimeline (#7525) 2025-11-18 02:10:35 -08:00
Bee 027a4f6386 fix: remove automatic native tool calls inference (#7522)
Remove automatic enablement of native tool calls for next-gen models and providers. The feature should be controlled exclusively by explicit user settings (feature flag and global state) rather than being automatically inferred based on the model type during experimental state.

Changes:
- Removed `isNextGenModelProvider` import (no longer needed)
- Eliminated `inferredNativeToolCalls` logic that auto-enabled the feature for next-gen models
- Simplified `enableNativeToolCalls` to only check explicit feature flag and global state settings
- Makes behavior more predictable and user-controlled
2025-11-18 00:49:36 -08:00
Bee 49642882c5 fix: ensure tool arguments are streamed during native tool calling [ENG-1305] (#7508)
* fix: ensure tool arguments are streamed during file operations

- Update userMessageContentReady condition to include streaming tool arguments, not just new content blocks
- Add null check for input object in tool-use-handler to prevent errors
- Improve partial JSON parsing with better fallback handling
- Replace console.log with Logger.debug for tool call chunks
- Add clarifying comments for lock mechanism and streaming behavior

This fixes an issue where new file content was not being properly streamed to tools during write operations, causing the UI to stop updating while tool arguments were being received.

* Add changeset

* typo

* fix(task): reset content index to execute tool blocks during streaming

Reset the currentStreamingContentIndex to the first tool block position
when tool blocks are present in the assistant message. This ensures that
tool blocks are properly executed instead of being skipped when the index
advances past them or goes out of bounds during content streaming.

Previously, the index could advance beyond tool blocks, causing them to
remain unexecuted. Now, when tool blocks are detected, the index is
explicitly set to textBlocks.length (the start of tool blocks) and
userMessageContentReady is set to false to trigger execution.

* fix(task): reset stream index to enable tool block execution

Reset currentStreamingContentIndex to the first tool block position when
tool blocks are present in the assistant message. This ensures that
presentAssistantMessage processes tool blocks instead of text blocks
during streaming, allowing tool blocks to be executed properly while
streaming is in progress.

The index is set to textBlocks.length, which points to where tool blocks
start in the content array, enabling correct sequential processing of
tools during the streaming phase.

* fix(streaming): improve tool execution flow and prevent control flow fall-through

- Add continue statements after yielding content in cline provider to prevent unintended fall-through behavior
- Mark all streamed tool uses as partial to ensure proper state tracking
- Allow complete tool blocks to bypass presentation lock for immediate execution during streaming
- Simplify userMessageContentReady reset logic and remove redundant tool_call check

These changes improve tool execution responsiveness by allowing completed tools to execute without waiting for the presentation lock, while ensuring proper control flow and state management throughout the streaming process.

* revert WriteToFileToolHandler
2025-11-17 23:50:04 -08:00
Bee 21ed6bc432 fix: do not add MCP tool with invalid names as native tools (#7516)
* fix: do not add MCP tool with invalid names as native tools

- Filter out MCP tools with names >= 64 characters to avoid provider API rejection
- Reduce nanoid length from default (21) to 5 characters for server UIDs

Provider APIs reject tool registration when tool names exceed 64 characters.
This change prevents registration errors by skipping tools with long names
and generating shorter UIDs to minimize the constructed name length
(uid + identifier + tool name).

* Add Changeset

* Update src/services/mcp/McpHub.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update src/core/prompts/system-prompt/registry/ClineToolSet.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-17 23:24:17 -08:00
Bee da2689f885 fix: correct TaskTimeline height (#7520)
* fix: correct TaskTimeline height

- Remove TIMELINE_HEIGHT constant in favor of h-full and h-4 utilities
- Replace inline styles with Tailwind classes for better maintainability
- Change timeline blocks from rounded-xs to rounded-full for consistency
- Fix timeline display being cut off due to incorrect height constraints

This refactor resolves the visual layout issue where timeline items were
truncated while improving code consistency by leveraging Tailwind's
utility-first approach throughout the component.

* add changeset
2025-11-17 23:05:09 -08:00
CandiedUniverse 5049326f02 fix(hooks): Fix two minor cancel-resume issues (#7502)
* fix(hooks): Fix cancel: true returned by TaskResume

* fix(hooks): Prevent TaskCancel from being triggered twice by TaskStart cancel and by TaskResume cancel scenarios
2025-11-17 14:44:16 -08:00
Ara b02ce46a57 Fix: Vercel provider token usage (#7481) 2025-11-17 14:15:32 -08:00
Saoud Rizwan de974737c8 fix: improve layout and styling in OnboardingView component for small width viewport (#7391) 2025-11-17 13:35:13 -08:00
Bee d072156e9a fix(account): memoize credits history table component (#7439)
Use React.memo to wrap CreditsHistoryTable, reducing unnecessary re-renders
when props are unchanged and improving performance of the account view that makes it looks like it glinches.
2025-11-17 11:36:19 -08:00
celestial-vault 4939309a09 fix openrouter defaulting modelId when modelInfo is not present (#7482) 2025-11-15 13:50:29 -08:00
CandiedUniverse 1a07ca7906 fix(hooks): Honor '"cancel": true' in hook JSON output (#7479) 2025-11-14 20:37:16 -08:00
Bee c1eefbad3f refactor(api): unify provider message type with ClineStorageMessage (#7478)
* refactor: replace Anthropic MessageParam with ClineStorageMessage type

Replace Anthropic SDK's MessageParam type with the new ClineStorageMessage type across API providers and tests in the effort of storing api messages in a type safe environment that we can expand from and avoid adding undocumented properties to Anthropc Message type that are not visible to the downstream services.

This change:

- Removes dependency on @anthropic-ai/sdk types in multiple providers
- Introduces ClineStorageMessage from shared messages module
- Updates method signatures in Dify, OpenAI, LiteLLM, and ClaudeCode handlers
- Updates corresponding test files to use the new type

This decouples the codebase from Anthropic-specific types and standardizes message handling using an internal storage format across all providers that  improves type-safety, preparing for the properties added by the Response API use.

As ClineStorageMessage is an extension of the Anthropic Message type, everything should work the same with no breaking changes. Green CI is expected.

* clean up
2025-11-14 20:24:56 -08:00
canvrno 1bfdce9b84 Remove new_task from system prompts (#7350)
* Removed new_task from system prompts, updated slash command prompt, added helper function for native tool calling checks

* Update src/core/prompts/system-prompt/registry/PromptBuilder.ts

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>

* Update src/core/task/index.ts

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>

* Updates with requested changes for PR #7350

* Updated package-lock.json

---------

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2025-11-14 17:57:47 -08:00
canvrno b002cdacdb Maint: package updates (#7477)
* maint: package updates

* Updated download-ripgrep script for compatability with new tar dependency
2025-11-14 16:09:03 -08:00
CandiedUniverse cf4005b25e fix(hooks): Reorder the UI elements so that PreToolUse appears above tool (#7449)
* fix(hooks): Reorder the UI elements so that PreToolUse appears above tool

* fix(hooks): Prevent PreToolUse hook from migrating down the screen

* fix(hooks): PreToolUse reordering should apply to 'tool', 'command', 'use_mcp_server', and 'browser_action_launch'  message types
2025-11-14 15:40:23 -08:00
Bee 1494d145d5 feat: support feature flag payload & remote dynamic onboarding model list (#7454)
* feat: support feature flag payload & dynamic onboarding model list

- Updated proto to use OnboardingModelGroup instead of bool flag for flexible onboarding
- Added getClineOnboardingModels function with caching and remote overrides for dynamic model fetching
- Modified controller to fetch and pass onboarding models to webview
- Updated UI to use dynamic models for selection, enabling flexible onboarding
- Enhanced feature flag service to support non-boolean payloads for better configurability

* clearOnboardingModelsCache
2025-11-14 14:49:05 -08:00
canvrno 1ab4b3cc24 fix:SAP provider type error - See PR #6547 (#7475) 2025-11-14 14:15:13 -08:00
canvrno 535b653228 Added stronger prompting around the use of act_mode_respond (#7448) 2025-11-14 12:12:34 -08:00
Igor Tceglevskii 1335fa5452 Retire firebase (#7362) 2025-11-14 09:29:47 -08:00
yuvalman b2a4395f71 feat: upgrade sap ai-sdk-js packages major version (#6547)
* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version

* feat: upgrade sap-ai-sdk major version
2025-11-14 09:11:03 -08:00
Toshii ae34a3a8c5 adding state variable for clineWebToolsEnabled (noop) (#7455)
* adding state variable for clineWebToolsEnabled

* removing console log
2025-11-14 08:20:01 -08:00
github-actions[bot] 0fb4a6c7e9 v3.37.1 Release Notes (#7451)
* changeset version bump

* Updating CHANGELOG.md format

* Update changelog for version 3.37.1

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-11-13 17:42:42 -08:00
Saoud Rizwan 855db7d8d8 feat(models): Add free minimax/mimax-m2 model to the model picker (#7453)
* feat(models): Add free minimax/mimax-m2 model to the model picker

* Add free minimax/mimax-m2 model to model picker
2025-11-13 17:41:16 -08:00
CandiedUniverse bb375b78ca fix(hooks): Prevent PreToolUse hook from running before attempt_completion tool (#7450) 2025-11-13 16:14:13 -08:00
CandiedUniverse 31af254f0a fix(hooks): Run PreToolUse only after approval (#7446)
* fix(hooks): Run PreToolUse only after approval; get it working for read_file first

* fix(hooks): Run PreToolUse only after approval; get it working for six more tools now

* fix(hooks): Run PreToolUse only after approval; get it working for the remaining six tools now

* fix(hooks): Implement HookExecution type to avoid using 'any'
2025-11-13 15:41:57 -08:00
github-actions[bot] 2745cdd54b Changeset version bump (#7358)
* v3.37.0 Release Notes

- GPT-5.1 with model-specific prompting: tailored system prompts, tool usage, focus chain, and deep-planning optimizations
- Nous Research provider with Hermes 4 model family and custom system prompts
- Model-family breakouts for deep-planning prompting, laying groundwork for enhanced slash commands
- Expanded HTTP proxy support throughout the codebase
- Improved focus chain prompting for frontier models (Anthropic, OpenAI, Gemini, xAI)

- Duplicate tool results prevention through existence checking
- XML entity escaping in model content processor
- Commit message generation in command palette
- OpenAI Compatible provider temperature parameter type conversion

- Added missing proto generation step in CONTRIBUTING.md
- New `npm run dev` script for streamlined terminal workflow (fixes #7335)

* Adding image optimizations

* Adding image optimizations

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2025-11-13 11:47:42 -08:00
celestial-vault c94c6fd8f1 Fix CLI auth state persistence with explicit flush mechanism (#7445)
Fixes issue where 'cline auth' command would lose all configuration due to process termination race condition.

Root cause: StateManager uses 500ms debounced persistence, but CLI process terminated before setTimeout callback could fire.

Solution: Implemented explicit flushPendingState() mechanism:
- Added StateManager.flushPendingState() method for immediate persistence
- Refactored to extract shared persistence logic (DRY)
- Added flushPendingState gRPC endpoint
- CLI now calls flush instead of using 5s sleep workaround

Results:
- Deterministic persistence (no race condition)
- Faster auth flow (~2s vs 7s)
- Cleaner, more maintainable code
2025-11-13 11:34:17 -08:00
Ara a87664318e Adding Gpt-5.1 to model picker and onboarding list (#7444)
* feat(settings): add GPT-5.1 to Model picker featured models

* adding

* adding

* adding
2025-11-13 11:20:08 -08:00
Ara ba70718c83 Remove Qwen3 coder from Cerebras providers (#7404)
* Remove Qwen3 coder from Cerebras providers

* Update Cerebras Docs to include new model `zai-glm-4.6` and remove `qwen-3-coder-480b-free` and `qwen-3-coder-480b` entries.

---------

Co-authored-by: Juan Pablo <juan@cline.bot>
2025-11-13 11:13:25 -08:00
canvrno cf8dd1c150 Feat:Enhanced support for OpenAI GPT 5.1 (#7443)
* Comprehensive changes to better support GPT 5.1 - System prompt, tools, deep-planning, focus chain, etc.

* Fix typos

* Fix more typos
2025-11-13 11:06:23 -08:00
Bee e714c74ec4 fix(anthropic): sanitize messages to SDK MessageParam shape (#7441)
- Use Anthropic SDK types and return Array<Messages.MessageParam>
- Replace removeReasoningDetails with removeUnknownParams
- Strip unsupported fields (e.g., reasoning_details) and normalize role
- Keep string content unchanged; map array content to known blocks
- Continue adding ephemeral cache_control to targeted user messages

This ensures only Anthropic-supported fields are sent, improving type safety and preventing API errors.
2025-11-13 10:28:40 -08:00
Sarah Fortune a6f8b33895 Change the label in the webview to say Enterprise Rules/Workflows instead of Remote Rules/Workflows (#7440) 2025-11-13 10:15:27 -08:00
Saoud Rizwan 02abbcf045 feat: add AGENTS.md support (#7437)
* feat: add AGENTS.md support

* Update webview-ui/src/components/cline-rules/RuleRow.tsx

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update webview-ui/src/components/cline-rules/ClineRulesToggleModal.tsx

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update font size for documentation link in ClineRulesToggleModal component

* docs: add support for AGENTS.md standard in Cline rules documentation

* fix: delete agents.md

* Add AGENTS.md support

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-13 09:42:24 -08:00
Bee 8ca2706cca chore: cleanup leftover code from anthropic provider (#7434)
Follow up from https://github.com/cline/cline/pull/7399

- Only add the redacted reasoning block when a reasoningSignature is present,
  instead of checking message length. This aligns with Claude extended thinking
  requirements and prevents unsignatured reasoning content from being sent.
- Remove leftover thinkingDeltaAccumulator from the Anthropic provider.
2025-11-12 18:33:13 -08:00
Bee e747d211e6 refactor: standardize reasoning yield types across providers [ENG-1226] (#7399)
* refactor(api): standardize reasoning yield types across providers

- Unify reasoning output format in Anthropic, Cline, and Minimax handlers
- Change "ant_thinking" and "reasoning_details" to "reasoning" type
- Add signature and redacted_data properties for consistency
- Wrap message_start cases in braces for scoping
- Consolidate yields to reduce redundancy and improve maintainability

* VercelAIGatewayHandler

* feat: add model information tracking to tasks and messages

Add modelId field to TaskResponse and TaskItem proto messages, and introduce ClineModelInfo message type to track provider and model IDs throughout the system. Update API transform functions to use ClineStorageMessage types and refactor message handling to support model information tracking.

This enables better tracking and auditing of which AI models are used for specific tasks and messages, improving observability and allowing for model-specific analytics.

* clean up protos

* remove console log

* minimax

* use new interface

* clean up
2025-11-12 15:33:48 -08:00
Bee 19aa81a1cc fix(dev): add back CLINE_ENVIRONMENT_OVERRIDE support (#7427)
CLINE_ENVIRONMENT_OVERRIDE was removed in https://github.com/cline/cline/pull/6621 accidentally. This PR adds it back:
Prioritize CLINE_ENVIRONMENT_OVERRIDE over CLINE_ENVIRONMENT when
setting the runtime environment at module load.
This enables temporary/test-specific environment selection without
modifying the base env var. Existing behavior is unchanged when the
override is not set. Updated inline comment for clarity.
2025-11-12 14:58:53 -08:00
Bee f5f3654966 refactor: Extract model info into method in WriteToFileToolHandler (#7420)
* refactor: Extract provider and model info into method in WriteToFileToolHandler

- Introduce private getModelInfo method to centralize extraction of providerId and modelId
- Replace duplicated telemetry extraction logic across multiple function calls
- Update telemetry service invocations to use the new method's return values for consistency and reduced code duplication/script>

* Update src/core/task/tools/handlers/WriteToFileToolHandler.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-11-12 14:40:51 -08:00
Bee 344b99988b feat: add native tool calls tracking to task events (#7429)
Add `isNativeToolCall` parameter to telemetry service to track when
assistant turns and provider API errors occur with native tool calls
enabled. This enables better analytics and debugging of native tool
call behavior across conversation turns.
2025-11-12 13:03:41 -08:00
Bee 7d3c39bcdb feat: make baseUrl dynamic by removing static field (#7428)
Remove the static _baseUrl field and replace all references with direct calls to ClineEnv.config().apiBaseUrl. This ensures the base URL updates correctly when configuration changes, fixing an issue where the URL remained static even after configuration updates.
2025-11-12 12:38:13 -08:00
celestial-vault 33c1692f8a add remotely configured rules and workflows (#7411)
* add remotely configured rules and workflows

* fix toggles state not being passes to webview on updates; minor format updates

---------

Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
2025-11-12 10:33:19 -08:00
Bee 3be3ffae4c fix: prevent duplicate tool results by adding existence check (#7419)
* fix: prevent duplicate tool results by adding existence check

Add a check in ToolResultUtils to skip adding a tool result if one already exists for the same tool_use_id, logging a warning to avoid redundant entries in userMessageContent and maintain message integrity. Introduces Logger import for warning output.

* add changeset
2025-11-11 21:37:11 -08:00
murkvin 87c6708fbe fix: restore commit msg generation functionality to command palette (#7417)
Co-authored-by: Kevin Murphy <murkvin@amazon.com>
Co-authored-by: CandiedUniverse <132302818+candieduniverse@users.noreply.github.com>
2025-11-11 17:36:30 -08:00
Juan Pablo Flores b296706bc0 docs: add guidance for handling strings with quotes in JSON payloads for hooks (#7396)
* docs: add guidance for handling strings with quotes in JSON payloads in hooks documentation

- Introduced a new section on using jq's --arg flag for proper escaping of unescaped quote characters in JSON output.
- Provided a code example demonstrating how to handle complex strings or nested JSON structures safely.

This update enhances the documentation by clarifying how to manage JSON payloads effectively within hooks.

* docs: clarify context modification behavior in hooks documentation

- Updated the explanation regarding context modifications and their effect on AI decisions.
- Emphasized the need to return `cancel: true` in PreToolUse hooks to block actions effectively.

This change enhances the clarity of the documentation, ensuring users understand how to implement immediate effects in their hooks.

---------

Co-authored-by: CandiedUniverse <132302818+candieduniverse@users.noreply.github.com>
2025-11-11 15:24:52 -08:00
canvrno 7fdc82ae23 Renamed Nous proto config strings (#7416)
* Renamed Nous proto config strings

* Revert "feat: migrate terminal execution mode default to background" (#7412)

This reverts commit 0b7393f50e.

---------

Co-authored-by: Ara <arafat.da.khan@gmail.com>
2025-11-11 14:42:13 -08:00
Bee 246ed87350 fix: ensure temperature parameter is explicitly converted to number (#7397)
* fix(openai): ensure temperature parameter is explicitly converted to number

Changed temperature assignment to explicitly check for undefined and convert
the value to Number type before use. This prevents potential type issues when
the temperature configuration is provided as a string or other non-number type,
ensuring consistent numeric handling for the OpenAI API.

* set 0 tempature to undefined

* add changeset
2025-11-11 14:10:21 -08:00
Ara a28465151f Revert "feat: migrate terminal execution mode default to background" (#7412)
This reverts commit 0b7393f50e.
2025-11-11 12:53:18 -08:00
Saoud Rizwan f1967bc3a1 feat: Add OAuth 2.1 authentication support for remote MCP servers (#7376) 2025-11-11 12:35:11 -08:00
Bee ccc83d6728 feat: add feature flag to toggle between new and old onboarding view [ENG-1224] (#7410)
* feat: add feature flag to toggle between new and old onboarding view

Add a new feature flag `show_onboarding_flow` that controls whether users see the new onboarding experience or the legacy welcome view. This enables A/B testing and gradual rollout of the new onboarding flow, and gives me better control when model list has changed and the onboarding model list is outdated.

Changes:
- Add ONBOARDING feature flag (enabled by default)
- Add showOnboardingFlow to ExtensionState and proto definitions
- Add getOnboardingEnabled() method to FeatureFlagsService
- Update App component to conditionally render OnboardingView or WelcomeView based on flag
- Extend ExtensionStateContext with showOnboardingFlow state management

This allows for controlled rollout and easy rollback if issues arise with the new onboarding experience.

* default true

* default to false unless e2e test

* showOnboardingFlow default to off
2025-11-11 11:33:42 -08:00
Szymon Stasik c151d719c8 fix: Handle tool_use blocks in Claude Code backward compatibility path (#7394)
- Transform tool_use content blocks to tool_calls format
- Map Anthropic tool_use structure to ApiStreamToolCallsChunk
- Fixes 'tool_use is not supported yet' error
- Resolves 'Current ask promise was ignored' downstream errors
2025-11-11 11:13:22 -08:00
canvrno cc25833963 Add Nous Research provider (#7141)
* Added Nous Research provider

* Fix casing on import
2025-11-11 10:43:12 -08:00
canvrno 2ef3b7cf0f Nous Hermes-4 family system prompt (#7142)
* Hermes-4 model family system prompt

* Update src/core/prompts/system-prompt/variants/hermes/overrides.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-11-11 10:14:24 -08:00
Mike Mikula 19d7bd5198 fix: Fix XML entity escaping in model content processor (#7385)
* refactor(task): replace HTML escaping logic with model-specific content fixes

Updated ExecuteCommandToolHandler and WriteToFileToolHandler to utilize a new utility function, applyModelContentFixes, for handling model-specific quirks. This change centralizes the logic for fixing escaped characters and invalid characters, improving maintainability and consistency across command execution and file writing processes. Additionally, introduced ModelContentProcessor to encapsulate the new content processing logic.

* test(ModelContentProcessor): add comprehensive unit tests for applyModelContentFixes

Introduced a new test suite for the ModelContentProcessor, covering various scenarios for the applyModelContentFixes function. Tests include model ID detection, file type handling, orchestration logic, and integration with real-world use cases, ensuring robust validation of content processing for different model types and file formats.

* fix: add changeset for XML escaping bug fix

* refactor(ModelContentProcessor): make modelId parameter optional in applyModelContentFixes

Updated the applyModelContentFixes function to accept an optional modelId parameter, allowing for fixes to be applied even when the model ID is not provided. Adjusted related logic in ExecuteCommandToolHandler and added a test case to verify this new behavior.
2025-11-11 07:26:27 -08:00
Ara 121066f938 feat: migrate terminal execution mode default to background (#7368)
- Add one-time migration to set all users to backgroundExec mode
- Change default terminal execution mode from vscodeTerminal to backgroundExec
- Update UI labels to clarify background mode is recommended
- Add migration sentinel flag to prevent re-running

This migration improves the default user experience by using background
terminal execution, which provides a cleaner UI and better performance
compared to the interactive VSCode terminal mode. Existing users will be
automatically migrated once, while new users will get the improved default.
2025-11-10 14:06:32 -08:00
Juan Pablo Flores f9b88318ea docs(dictation): add notice on Windows support (#7059)
* docs(dictation): remove Windows support from system requirements

- Add note indicating dictation is currently unavailable on Windows
- Remove Windows FFmpeg installation instructions from the list
- Clarify that Windows support is planned for a future release

This update reflects the current state of the feature and sets proper user expectations about platform availability.

* Update docs/features/dictation.mdx

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-10 13:26:10 -08:00
Ara 1d64f64f43 Enable voice mode for linux also (#7369) 2025-11-10 12:19:41 -08:00
317 changed files with 14335 additions and 5241 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix: do not retry request automatically on auth failure.
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Added change to hide the context window usage message from env details when using next gen models and before the usage has reached an elevated state
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix task timeline display height.
@@ -1,6 +0,0 @@
---
"claude-dev": patch
---
Docs: Add missing proto generation step in CONTRIBUTING.md and new `npm run dev` script for easier terminal workflow (fixes #7335)
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Created model-family breakouts for deep-planning prompting, and laid groundwork for similar changes for other slash commands.
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Use HTTP proxies in more places
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Ensure tool arguments are streamed during file operations when native tool calling is enabled.
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Added thinking level setting for Gemini 3.0 Pro
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Feat: add thought signature support for Gemini SDK
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Feat: Enable native tool calling for Baseten and Kimi K2 models
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Replaces generic robot icon with Cline logo across VS Code UI
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": minor
---
Add Kimi K2 Thinking to Baseten Provider
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Skip MCP tool with invalid name (e.g. name too long) when native tool calling is enabled.
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
Adjusted prompting around focus chain, particularly for next-get/native tool calling models.
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix Anthropic provider missing signature param when thinking is enabled.
+21
View File
@@ -165,6 +165,27 @@
},
"console": "integratedTerminal",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "Open Storybook",
"type": "node",
"request": "launch",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run",
"storybook"
],
"cwd": "${workspaceFolder}/webview-ui",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"serverReadyAction": {
"pattern": "Local:.*http://localhost:([0-9]+)",
"uriFormat": "http://localhost:%s",
"action": "openExternally"
},
"env": {
"IS_DEV": "true"
}
}
]
}
+20
View File
@@ -263,6 +263,26 @@
"watch"
],
"command": "rm -rf ${workspaceFolder}/dist/tmp/user && mkdir -p ${workspaceFolder}/dist/tmp/user"
},
{
"type": "npm",
"script": "storybook",
"group": "build",
"problemMatcher": [],
"isBackground": false,
"label": "npm: storybook",
"dependsOn": [
"npm: protos",
"npm: build:webview"
],
"presentation": {
"reveal": "always"
},
"options": {
"env": {
"IS_DEV": "true"
}
}
}
],
"inputs": [
+3
View File
@@ -20,6 +20,9 @@ eslint-rules/**
.husky/**
.env
# cli
cli/**
# Custom
**/demo.gif
.nvmrc
+46
View File
@@ -1,5 +1,51 @@
# Changelog
## [3.38.1]
### Fixed
- Fixed handling of 'signature' field in sanitizeAnthropicContentBlock to properly preserve it when thinking is enabled, as required by Anthropic's API.
## [3.38.0]
### Added
- Gemini 3 Pro Preview model
- AquaVoice Avalon model for voice-to-text dictation
### Fixed
- Automatic context truncation when AWS Bedrock token usage rate limits are exceeded
- Removed new_task tool from system prompts, updated slash command prompts, and added helper function for native tool calling validation
## [3.37.1]
- Comprehensive changes to better support GPT 5.1 - System prompt, tools, deep-planning, focus chain, etc.
- Add AGENTS.md support
- feat(models): Add free minimax/mimax-m2 model to the model picker
## [3.37.0]
### Added
- GPT-5.1 with model-specific prompting: tailored system prompts, tool usage, focus chain, and deep-planning optimizations
- Nous Research provider with Hermes 4 model family and custom system prompts
- Switched to Aqua Voice's Avalon model in speech to text transcription
- Added Linux support for speech to text
- Model-family breakouts for deep-planning prompting, laying groundwork for enhanced slash commands
- Expanded HTTP proxy support throughout the codebase
- Improved focus chain prompting for frontier models (Anthropic, OpenAI, Gemini, xAI)
### Fixed
- Duplicate tool results prevention through existence checking
- XML entity escaping in model content processor
- Commit message generation in command palette
- OpenAI Compatible provider temperature parameter type conversion
## Documentation
- Added missing proto generation step in CONTRIBUTING.md
- New `npm run dev` script for streamlined terminal workflow (fixes #7335)
## [3.36.1]
- fix: remove native tool calling support from Gemini and XAI provider due to invalid tool names issues
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
<svg xmlns="http://www.w3.org/2000/svg">
<metadata>
<json>
<![CDATA[
{
"fontFamily": "cline-bot",
"majorVersion": 1,
"minorVersion": 0,
"fontURL": "https://cline.bot",
"designerURL": "https://cline.bot",
"licenseURL": "https://cline.bot",
"version": "Version 1.0",
"fontId": "cline-bot",
"psName": "cline-bot",
"subFamily": "Regular",
"fullName": "cline-bot",
"description": "Font generated by IcoMoon."
}
]]>
</json>
</metadata>
<defs>
<font id="cline-bot" horiz-adv-x="1024">
<font-face units-per-em="1024" ascent="960" descent="-64" />
<missing-glyph horiz-adv-x="1024" />
<glyph unicode="&#x20;" horiz-adv-x="512" d="" />
<glyph unicode="&#xe900;" glyph-name="cline" data-tags="cline" horiz-adv-x="977" d="M964.553 383.11l-60.285 121.406v69.495c0 115.545-92.939 209.321-207.647 209.321h-102.986c7.536 15.071 11.722 32.654 11.722 51.074 0 64.471-51.912 116.383-115.545 116.383s-115.545-51.912-115.545-116.383 4.186-35.166 11.722-51.074h-102.986c-114.708 0-207.647-93.776-207.647-209.321v-69.495l-61.959-121.406c-5.861-11.722-5.861-26.793 0-38.515l61.959-119.732v-69.495c0-115.545 92.939-209.321 207.647-209.321h415.294c114.708 0 207.647 93.776 207.647 209.321v69.495l60.285 119.732c5.861 11.722 5.861 25.956 0 38.515v0zM426.178 284.311c0-52.749-42.702-95.451-94.613-95.451s-94.613 42.702-94.613 95.451v169.132c0 52.749 42.702 95.451 94.613 95.451s94.613-42.702 94.613-95.451v-169.132zM731.787 284.311c0-52.749-42.702-95.451-94.613-95.451s-94.613 42.702-94.613 95.451v169.132c0 52.749 42.702 95.451 94.613 95.451s94.613-42.702 94.613-95.451v-169.132z" />
</font></defs></svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.
Binary file not shown.
+6 -5
View File
@@ -4,7 +4,6 @@ import (
"context"
"fmt"
"strings"
"time"
"github.com/cline/cli/pkg/cli/global"
"github.com/cline/cli/pkg/cli/task"
@@ -76,10 +75,11 @@ func QuickSetupFromFlags(ctx context.Context, provider, apiKey, modelID, baseURL
}
}
// WORKAROUND: Wait for debounced state persistence to complete
// Fixes `cline auth` issue when ran in docker environments
// TODO: implement better solution w/ changes in StateManager
time.Sleep(600 * time.Millisecond)
// Flush pending state changes to disk immediately
// This ensures all configuration changes are persisted before the instance terminates
if _, err := manager.GetClient().State.FlushPendingState(ctx, &cline.EmptyRequest{}); err != nil {
return fmt.Errorf("failed to flush pending state: %w", err)
}
// Success message
fmt.Printf("\n✓ Successfully configured %s provider\n", GetProviderDisplayName(providerEnum))
@@ -176,6 +176,7 @@ func validateQuickSetupProvider(providerID string) (cline.ApiProvider, error) {
cline.ApiProvider_XAI: true,
cline.ApiProvider_CEREBRAS: true,
cline.ApiProvider_OLLAMA: true,
cline.ApiProvider_NOUSRESEARCH: true,
}
if !supportedProviders[provider] {
+3
View File
@@ -26,6 +26,7 @@ func GetBYOProviderList() []BYOProviderOption {
{Name: "Google Gemini", Provider: cline.ApiProvider_GEMINI},
{Name: "Ollama", Provider: cline.ApiProvider_OLLAMA},
{Name: "Cerebras", Provider: cline.ApiProvider_CEREBRAS},
{Name: "NousResearch", Provider: cline.ApiProvider_NOUSRESEARCH},
{Name: "Oracle Code Assist", Provider: cline.ApiProvider_OCA},
}
}
@@ -100,6 +101,8 @@ func GetBYOProviderPlaceholder(provider cline.ApiProvider) string {
return "e.g., qwen3-coder:30b"
case cline.ApiProvider_CEREBRAS:
return "e.g., gpt-oss-120b"
case cline.ApiProvider_NOUSRESEARCH:
return "e.g., Hermes-4-405B"
case cline.ApiProvider_OCA:
return "e.g., oca/llama4"
default:
+8
View File
@@ -111,6 +111,7 @@ func (r *ProviderListResult) GetAllReadyProviders() []*ProviderDisplay {
cline.ApiProvider_GEMINI,
cline.ApiProvider_OLLAMA,
cline.ApiProvider_CEREBRAS,
cline.ApiProvider_NOUSRESEARCH,
cline.ApiProvider_OCA,
cline.ApiProvider_HICAP,
}
@@ -241,6 +242,8 @@ func mapProviderStringToEnum(providerStr string) (cline.ApiProvider, bool) {
return cline.ApiProvider_OCA, true
case "hicap":
return cline.ApiProvider_HICAP, true
case "nousResearch":
return cline.ApiProvider_NOUSRESEARCH, true
default:
return cline.ApiProvider_ANTHROPIC, false // Return 0 value with false
}
@@ -274,6 +277,8 @@ func GetProviderIDForEnum(provider cline.ApiProvider) string {
return "oca"
case cline.ApiProvider_HICAP:
return "hicap"
case cline.ApiProvider_NOUSRESEARCH:
return "nousResearch"
default:
return ""
}
@@ -353,6 +358,8 @@ func GetProviderDisplayName(provider cline.ApiProvider) string {
return "Oracle Code Assist"
case cline.ApiProvider_HICAP:
return "Hicap"
case cline.ApiProvider_NOUSRESEARCH:
return "NousResearch"
default:
return "Unknown"
}
@@ -475,6 +482,7 @@ func DetectAllConfiguredProviders(ctx context.Context, manager *task.Manager) ([
{cline.ApiProvider_OLLAMA, "ollamaBaseUrl"}, // Ollama uses baseUrl instead of API key
{cline.ApiProvider_CEREBRAS, "cerebrasApiKey"},
{cline.ApiProvider_HICAP, "hicapApiKey"},
{cline.ApiProvider_NOUSRESEARCH, "nousResearchApiKey"},
}
for _, providerCheck := range providersToCheck {
@@ -163,6 +163,15 @@ func GetProviderFields(provider cline.ApiProvider) (ProviderFields, error) {
ActModeProviderSpecificModelIDField: "actModeHicapModelId",
}, nil
case cline.ApiProvider_NOUSRESEARCH:
return ProviderFields{
APIKeyField: "nousResearchApiKey",
PlanModeModelIDField: "planModeApiModelId",
ActModeModelIDField: "actModeApiModelId",
PlanModeProviderSpecificModelIDField: "planModeNousResearchModelId",
ActModeProviderSpecificModelIDField: "actModeNousResearchModelId",
}, nil
default:
return ProviderFields{}, fmt.Errorf("unsupported provider: %v", provider)
}
@@ -278,6 +287,8 @@ func setAPIKeyField(apiConfig *cline.ModelsApiConfiguration, fieldName string, v
apiConfig.OcaApiKey = value
case "hicapApiKey":
apiConfig.HicapApiKey = value
case "nousResearchApiKey":
apiConfig.NousResearchApiKey = value
}
}
@@ -302,6 +313,9 @@ func setProviderSpecificModelID(apiConfig *cline.ModelsApiConfiguration, fieldNa
case "planModeHicapModelId":
apiConfig.PlanModeHicapModelId = value
apiConfig.ActModeHicapModelId = value
case "planModeNousResearchModelId":
apiConfig.PlanModeNousResearchModelId = value
apiConfig.ActModeNousResearchModelId = value
}
}
+1 -1
View File
@@ -517,7 +517,7 @@ func (pw *ProviderWizard) applyModelChange(provider cline.ApiProvider, modelID s
ModelInfo: modelInfo,
}
return UpdateProviderPartial(pw.ctx, pw.manager, provider, updates, false)
return UpdateProviderPartial(pw.ctx, pw.manager, provider, updates, true)
}
// SwitchToBYOProvider switches to a BYO provider that's already configured.
+1 -77
View File
@@ -221,83 +221,7 @@ func (p *ToolResultParser) ParseCodeDefinitions(content string) string {
// ParseWebFetch formats webFetch tool results with content preview
func (p *ToolResultParser) ParseWebFetch(content, url string) string {
if content == "" {
return fmt.Sprintf("*Fetched content from %s (empty response)*", url)
}
lines := strings.Split(content, "\n")
var result strings.Builder
// Try to extract title
var title string
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "#") && !strings.HasPrefix(trimmed, "##") {
title = strings.TrimSpace(strings.TrimPrefix(trimmed, "#"))
break
}
}
if title != "" {
result.WriteString(fmt.Sprintf("**Title:** %s\n\n", title))
}
// Show preview of content
result.WriteString("**Preview:**\n")
charCount := 0
maxChars := 500
previewLines := []string{}
for _, line := range lines {
// Skip markdown headers
if strings.HasPrefix(strings.TrimSpace(line), "#") {
continue
}
trimmed := strings.TrimSpace(line)
if trimmed == "" {
continue
}
if charCount+len(trimmed) > maxChars {
break
}
previewLines = append(previewLines, trimmed)
charCount += len(trimmed)
}
result.WriteString(strings.Join(previewLines, " "))
result.WriteString("...\n\n")
// Extract sections
sections := []string{}
for _, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "##") {
section := strings.TrimSpace(strings.TrimPrefix(trimmed, "##"))
sections = append(sections, section)
if len(sections) >= 5 {
break
}
}
}
if len(sections) > 0 {
result.WriteString("**Sections Found:**\n")
for _, section := range sections {
result.WriteString(fmt.Sprintf("- %s\n", section))
}
result.WriteString("\n")
}
// Word count estimate
wordCount := len(strings.Fields(content))
result.WriteString(fmt.Sprintf("*[Full content: ~%s]*", p.formatWordCount(wordCount)))
return result.String()
return ""
}
// detectLanguage returns syntax highlighting language based on file extension
+71
View File
@@ -145,6 +145,7 @@ const (
XAI = "xai"
CEREBRAS = "cerebras"
OCA = "oca"
NOUSRESEARCH = "nousResearch"
)
// AllProviders returns a slice of enabled provider IDs for the CLI build.
@@ -161,6 +162,7 @@ var AllProviders = []string{
"xai",
"cerebras",
"oca",
"nousResearch",
}
// ConfigField represents a configuration field requirement
@@ -318,6 +320,15 @@ var rawConfigFields = ` [
"fieldType": "password",
"placeholder": "Enter your API key"
},
{
"name": "nousResearchApiKey",
"type": "string",
"comment": "",
"category": "nousResearch",
"required": true,
"fieldType": "password",
"placeholder": "Enter your API key"
},
{
"name": "ulid",
"type": "string",
@@ -435,6 +446,15 @@ var rawConfigFields = ` [
"fieldType": "url",
"placeholder": "https://api.example.com"
},
{
"name": "minimaxApiLine",
"type": "string",
"comment": "",
"category": "general",
"required": false,
"fieldType": "string",
"placeholder": ""
},
{
"name": "ocaMode",
"type": "string",
@@ -775,6 +795,24 @@ var rawModelDefinitions = ` {
"supportsImages": false,
"supportsPromptCache": false,
"description": "A compact 20B open-weight Mixture-of-Experts language model designed for strong reasoning and tool use, ideal for edge devices and local inference."
},
"qwen.qwen3-coder-30b-a3b-v1:0": {
"maxTokens": 8192,
"contextWindow": 262144,
"inputPrice": 0,
"outputPrice": 0,
"supportsImages": false,
"supportsPromptCache": false,
"description": "Qwen3 Coder 30B MoE model with 3.3B activated parameters, optimized for code generation and analysis with 256K context window."
},
"qwen.qwen3-coder-480b-a35b-v1:0": {
"maxTokens": 8192,
"contextWindow": 262144,
"inputPrice": 0,
"outputPrice": 1,
"supportsImages": false,
"supportsPromptCache": false,
"description": "Qwen3 Coder 480B flagship MoE model with 35B activated parameters, designed for complex coding tasks with advanced reasoning capabilities and 256K context window."
}
},
"gemini": {
@@ -1263,6 +1301,26 @@ var rawModelDefinitions = ` {
"supportsPromptCache": false,
"description": "SOTA performance with ~1500 tokens/s"
}
},
"nousResearch": {
"Hermes-4-405B": {
"maxTokens": 8192,
"contextWindow": 128000,
"inputPrice": 0,
"outputPrice": 0,
"supportsImages": false,
"supportsPromptCache": false,
"description": "This is the largest model in the Hermes 4 family, and it is the fullest expression of our design, focused on advanced reasoning and creative depth rather than optimizing inference speed or cost."
},
"Hermes-4-70B": {
"maxTokens": 8192,
"contextWindow": 128000,
"inputPrice": 0,
"outputPrice": 0,
"supportsImages": false,
"supportsPromptCache": false,
"description": "This incarnation of Hermes 4 balances scale and size. It handles complex reasoning tasks, while staying fast and cost effective. A versatile choice for many use cases."
}
}
}`
@@ -1432,6 +1490,18 @@ func GetProviderDefinitions() (map[string]ProviderDefinition, error) {
HasDynamicModels: false,
SetupInstructions: `Configure Oca API credentials`,
}
// NousResearch
definitions["nousResearch"] = ProviderDefinition{
ID: "nousResearch",
Name: "NousResearch",
RequiredFields: getFieldsByProvider("nousResearch", configFields, true),
OptionalFields: getFieldsByProvider("nousResearch", configFields, false),
Models: modelDefinitions["nousResearch"],
DefaultModelID: "Hermes-4-405B",
HasDynamicModels: false,
SetupInstructions: `Configure NousResearch API credentials`,
}
return definitions, nil
}
@@ -1459,6 +1529,7 @@ func GetProviderDisplayName(providerID string) string {
"xai": "X AI (Grok)",
"cerebras": "Cerebras",
"oca": "Oca",
"nousResearch": "NousResearch",
}
if name, exists := displayNames[providerID]; exists {
+2 -2
View File
@@ -189,6 +189,7 @@
"provider-config/fireworks",
"provider-config/zai",
"provider-config/gcp-vertex-ai",
"provider-config/baseten",
{
"group": "AWS Bedrock",
"pages": [
@@ -215,8 +216,7 @@
"provider-config/vscode-language-model-api",
"provider-config/sap-aicore",
"provider-config/vercel-ai-gateway",
"provider-config/requesty",
"provider-config/baseten"
"provider-config/requesty"
]
}
]
+14
View File
@@ -81,6 +81,20 @@ your-project/
Cline's system prompt, on the other hand, is not user-editable ([here's where you can find it](https://github.com/cline/cline/blob/main/src/core/prompts/system.ts)). For a broader look at prompt engineering best practices, check out [this resource](https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/overview).
### AGENTS.md Standard Support
Cline also supports the [AGENTS.md](https://agents.md/) standard as a fallback
(in addition to Cline Rules) by automatically detecting `AGENTS.md` files in
your workspace root. This allows you to use the same rules file across different AI
coding tools.
```
your-project/
├── AGENTS.md
├── src/
└── ...
```
### Tips for Writing Effective Cline Rules
- Be Clear and Concise: Use simple language and avoid ambiguity.
+5 -2
View File
@@ -3,7 +3,7 @@ title: "Dictation"
description: "Communicate with Cline using your voice for faster, more natural AI collaboration"
---
Dictation transforms how you work with AI. Instead of typing out complex thoughts, you speak naturally and share your complete intent. This isn't just about speed - though voice is faster - it's about unlocking the kind of fluid collaboration that typing can't match.
Dictation transforms how you work with AI. Instead of typing out complex thoughts, you speak naturally and share your complete intent. This isn't just about speed - though voice is faster - it's about enabling fluid collaboration that typing can't match.
## Why Voice Changes Everything
@@ -35,11 +35,14 @@ Dictation works with any AI model you've configured. The transcription happens t
## System Requirements
<Note>
Dictation is currently not available on Windows. Support for Windows is planned for a future release.
</Note>
Dictation uses FFmpeg to capture your voice across all platforms:
- **macOS**: FFmpeg (via Homebrew: `brew install ffmpeg`)
- **Linux**: FFmpeg (via apt: `sudo apt-get install ffmpeg`)
- **Windows**: FFmpeg (via winget: `winget install Gyan.FFmpeg`)
If you don't have FFmpeg installed, Cline will automatically detect this and prompt you to install it with a single click.
+51 -23
View File
@@ -76,7 +76,7 @@ echo "$input" | jq -r '.timestamp | type'
This example script demonstrates the key mechanics of hook input/output: reading the JSON payload from stdin with `input=$(cat)`, and using `jq` to inspect the data structure and field types that your hook receives. This helps you understand what data is available before building more complex hook logic.
#### Make it executable
**Make it executable**
```bash
chmod +x .clinerules/hooks/TaskStart
@@ -92,6 +92,32 @@ Start a task in Cline and verify your hook executes.
Start with a simple hook that just logs information before building complex validation logic. This helps you understand the data structure and timing.
</Tip>
## What You Can Build
Once you understand the basics, hooks open up creative possibilities:
<CardGroup cols={2}>
<Card title="Intelligent Code Review" icon="code-branch">
Run linters or custom validators before files get saved. Block commits that don't pass checks. Track code quality metrics over time.
</Card>
<Card title="Security Enforcement" icon="shield-halved">
Prevent operations that violate security policies. Detect when sensitive data might be exposed. Audit all file access for compliance.
</Card>
<Card title="Development Analytics" icon="chart-line">
Measure how long different operations take. Identify patterns in how the AI works. Generate productivity reports from hook data.
</Card>
<Card title="Integration Hub" icon="plug">
Connect to issue trackers when certain keywords appear. Update project management tools. Sync with external APIs at the right moments.
</Card>
</CardGroup>
The key is combining hooks with external tools. A hook can be the glue between Cline's workflow and the rest of your development ecosystem.
## Hook Types
Cline provides multiple hook types that let you tap into different stages of the AI workflow. They're organized into categories based on their trigger points and use cases.
@@ -341,22 +367,6 @@ Context injection affects future decisions, not current ones. When a hook runs:
This means PreToolUse hooks are for blocking bad actions, while PostToolUse hooks are for learning from completed ones.
## What You Can Build
Once you understand the basics, hooks open up creative possibilities:
- **Intelligent Code Review**:
Run linters or custom validators before files get saved. Block commits that don't pass checks. Track code quality metrics over time.
- **Security Enforcement**:
Prevent operations that violate security policies. Detect when sensitive data might be exposed. Audit all file access for compliance.
- **Development Analytics**: Measure how long different operations take. Identify patterns in how the AI works. Generate productivity reports from hook data.
- **Integration Hub**: Connect to issue trackers when certain keywords appear. Update project management tools. Sync with external APIs at the right moments.
The key is combining hooks with external tools. A hook can be the glue between Cline's workflow and the rest of your development ecosystem.
## Troubleshooting
### Hook Not Running
@@ -371,12 +381,30 @@ The key is combining hooks with external tools. A hook can be the glue between C
- Consider moving complex logic to a background process
### Context Not Affecting Behavior
- Remember: context affects FUTURE decisions, not the current tool
- The current AI behavior is based on the previous "API Request..." block
- Your `contextModification` gets injected into the NEXT "API Request..." block
- Use PreToolUse for validation (blocking) if you need immediate effect
- Ensure context modifications are clear and actionable
- Check that context isn't being truncated (50KB limit)
Remember that context modifications affect future AI decisions, not the current operation. The AI's current behavior is based on the previous "API Request..." block, and your `contextModification` gets injected into the next "API Request..." block. This means if you need immediate effect, you should use PreToolUse hooks for validation and return `cancel: true` in your hook's JSON response to block Cline from continuing.
When adding context, ensure your modifications are clear and actionable so the AI can understand and apply them effectively. Also check that your context isn't being truncated due to the 50KB limit, as this could prevent important information from reaching the AI.
### Handling Strings with Quotes in JSON Payloads
When your hook needs to include strings containing unescaped quote characters (`"`) in JSON output, use jq's `--arg` flag for proper escaping:
```bash
#!/usr/bin/env bash
# When $output contains unescaped quote characters (")...
output='{"foo":"bar"}'
# Use the --arg flag for automatic string escaping
jq -n --arg ctx "$output" '{cancel: false, contextModification: $ctx}'
# This will result in:
# {
# "cancel": false,
# "contextModification": "{\"foo\":\"bar\"}"
# }
```
The `--arg` flag automatically escapes special characters, preventing JSON parsing errors when your context modification includes complex strings or nested JSON structures.
<Warning>
Hooks run with the same permissions as VS Code. They can access all workspace files and environment variables. Review hooks from untrusted sources before enabling them.
+58 -6
View File
@@ -29,11 +29,33 @@ The "Remote Servers" tab allows you to connect to any MCP server that's accessib
2. Fill in the required information:
- **Server Name**: Provide a unique, descriptive name for the server
- **Server URL**: Enter the complete URL endpoint of the MCP server (e.g., `https://example.com/mcp-sse`)
- **Transport Type**: Select the connection protocol (Streamable HTTP is recommended for modern servers)
3. Click "Add Server" to initiate the connection
4. Cline will attempt to connect to the server and display the connection status
> **Note**: When connecting to a remote server, ensure you trust the source, as MCP servers can execute code in your environment.
#### Transport Types
Cline supports two transport protocols for remote MCP servers:
- **Streamable HTTP (Recommended)**: The modern MCP transport protocol with better performance, reliability, and full OAuth 2.1 authentication support. Use this for most remote servers.
- **SSE (Legacy)**: Server-Sent Events transport. Use this only if the server specifically requires SSE or doesn't support Streamable HTTP.
#### OAuth Authentication
Some MCP servers (like Vercel's MCP) require OAuth authentication to access your data securely. When connecting to an OAuth-enabled server:
1. Add the server as usual with its URL
2. If the server requires authentication, you'll see an error message asking to authenticate.
3. Click the **"Authenticate"** button that appears
4. Your browser will open to the server's authorization page
5. Sign in and grant permission
6. You'll be redirected back to Cline automatically
7. The server will connect and show a green status dot
Once authenticated, your credentials are securely stored and the server will reconnect automatically when you reload Cline. You won't need to authenticate again unless you delete the server or your credentials expire.
### Remote Server Discovery
If you're looking for MCP servers to connect to, several third-party marketplaces provide directories of available servers with various capabilities.
@@ -90,9 +112,20 @@ Toggle the switch next to each server to enable or disable it:
If a server fails to connect:
1. An error message will be displayed with details about the failure
2. Check that the server URL is correct and the server is running
3. Use the "Restart Server" button to attempt reconnection
4. If problems persist, you can delete the server and try adding it again
2. **For OAuth errors**: Click the "Authenticate" button to complete the authorization flow
3. Check that the server URL is correct and the server is running
4. Try selecting a different transport type (Streamable HTTP vs SSE)
5. Use the "Restart Server" button to attempt reconnection
6. If problems persist, you can delete the server and try adding it again
#### OAuth-Specific Issues
If you're having trouble authenticating with an OAuth-enabled server:
- **"Authentication required" persists**: Make sure you completed the authorization flow in your browser and didn't cancel it
- **Browser doesn't open**: Check your system's default browser settings and ensure external URLs can be opened
- **Redirect errors**: Verify you're using the latest version of Cline - older versions may not support OAuth
- **Reset authentication**: Delete the server and re-add it to start fresh with a new OAuth flow
### Advanced Configuration
@@ -105,10 +138,11 @@ For advanced users, Cline stores MCP server configurations in a JSON file that c
{
"mcpServers": {
"exampleServer": {
"url": "https://example.com/mcp-sse",
"url": "https://example.com/mcp-server",
"type": "streamableHttp",
"disabled": false,
"autoApprove": ["tool1", "tool2"],
"timeout": 30
"timeout": 60
}
}
}
@@ -117,9 +151,10 @@ For advanced users, Cline stores MCP server configurations in a JSON file that c
Key configuration options:
- **url**: The endpoint URL (for remote servers)
- **type**: Transport protocol - `"streamableHttp"` (recommended) or `"sse"` (legacy)
- **disabled**: Whether the server is currently enabled (true/false)
- **autoApprove**: List of tool names that don't require confirmation
- **timeout**: Maximum time in seconds to wait for server responses
- **timeout**: Maximum time in seconds to wait for server responses (default: 60)
For additional MCP settings, click the "Advanced MCP Settings" link to access VSCode settings.
@@ -130,3 +165,20 @@ Once connected, Cline can use the tools and resources provided by the MCP server
1. A tool approval prompt will appear (unless auto-approved)
2. Review the tool details and parameters before approving
3. The tool will execute and return results to Cline
### Example: Connecting to Vercel MCP
[Vercel MCP](https://vercel.com/docs/mcp/vercel-mcp) is an OAuth-enabled server that provides tools for managing your Vercel projects and deployments:
1. Click "Remote Servers" tab
2. Enter:
- **Server Name**: `vercel`
- **Server URL**: `https://mcp.vercel.com`
- **Transport Type**: Streamable HTTP (pre-selected)
3. Click "Add Server"
4. You'll see "Authentication required" - click the **"Authenticate"** button
5. Sign in to Vercel in your browser and authorize Cline
6. Return to Cline - the server will automatically connect
7. Vercel's tools (deploy, logs, projects) are now available to Cline!
Your Vercel authentication persists across sessions, so you won't need to re-authenticate each time you use Cline.
+6 -34
View File
@@ -5146,28 +5146,6 @@
"node": ">=6.0"
}
},
"node_modules/gray-matter/node_modules/argparse": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
"integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
"license": "MIT",
"dependencies": {
"sprintf-js": "~1.0.2"
}
},
"node_modules/gray-matter/node_modules/js-yaml": {
"version": "3.14.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz",
"integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==",
"license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
"esprima": "^4.0.0"
},
"bin": {
"js-yaml": "bin/js-yaml.js"
}
},
"node_modules/has-bigints": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz",
@@ -6490,9 +6468,9 @@
"license": "MIT"
},
"node_modules/js-yaml": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
"integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
"license": "MIT",
"dependencies": {
"argparse": "^2.0.1"
@@ -10235,12 +10213,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/sprintf-js": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
"integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
"license": "BSD-3-Clause"
},
"node_modules/stack-utils": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz",
@@ -10609,9 +10581,9 @@
}
},
"node_modules/tar-fs": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.0.tgz",
"integrity": "sha512-5Mty5y/sOF1YWj1J6GiBodjlDc05CUR8PKXrsnFAiSG0xA+GHeWLovaZPYUDXkH/1iKRf2+M5+OrRgzC7O9b7w==",
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.1.tgz",
"integrity": "sha512-LZA0oaPOc2fVo82Txf3gw+AkEd38szODlptMYejQUhndHMLQ9M059uXR+AfS7DNo0NpINvSqDsvyaCrBVkptWg==",
"license": "MIT",
"dependencies": {
"pump": "^3.0.0",
+4
View File
@@ -14,5 +14,9 @@
"description": "",
"dependencies": {
"mintlify": "^4.2.23"
},
"overrides": {
"tar-fs": "^3.1.1",
"js-yaml": "^4.1.1"
}
}
+14 -43
View File
@@ -3,7 +3,7 @@ title: "Baseten"
description: "Learn how to configure and use Baseten's Model APIs with Cline. Access frontier open-source models with enterprise-grade performance, reliability, and competitive pricing."
---
Baseten provides on-demand frontier model APIs designed for production applications, not just experimentation. Built on the Baseten Inference Stack, these APIs deliver enterprise-grade performance and reliability with optimized inference for leading open-source models from OpenAI, DeepSeek, Meta, Moonshot AI, and Alibaba Cloud.
Baseten provides on-demand frontier model APIs designed for production applications, not just experimentation. Built on the Baseten Inference Stack, these APIs deliver optimized inference for leading open-source models from OpenAI, DeepSeek, Moonshot AI, and Alibaba Cloud.
**Website:** [https://www.baseten.co/products/model-apis/](https://www.baseten.co/products/model-apis/)
@@ -14,13 +14,21 @@ Baseten provides on-demand frontier model APIs designed for production applicati
3. **Create a Key:** Generate a new API key. Give it a descriptive name (e.g., "Cline").
4. **Copy the Key:** Copy the API key immediately and store it securely.
### Configuration in Cline
1. **Open Cline Settings:** Click the settings icon (⚙️) in the Cline panel.
2. **Select Provider:** Choose "Baseten" from the "API Provider" dropdown.
3. **Enter API Key:** Paste your Baseten API key into the "Baseten API Key" field.
4. **Select Model:** Choose your desired model from the "Model" dropdown.
**IMPORTANT: For Kimi K2 Thinking:** To use the `moonshotai/Kimi-K2-Thinking` model, you must enable **Native Tool Call (Experimental)** in Cline settings. This setting allows Cline to call tools through their native tool processor and is required for this reasoning model to function properly.
### Supported Models
Cline supports all current models under Baseten Model APIs, including:
For the most updated pricing, please visit: https://www.baseten.co/products/model-apis/
Note: Kimi K2 0711, Llama 4 Maverick, and Llama 4 Scout Model APIs have been deprecated at 5pm PT on October 8th.
https://www.baseten.co/resources/changelog/model-api-deprecation-notice-kimi-k2-0711-scout-maverick/
- `moonshotai/Kimi-K2-Thinking` (Moonshot AI) - Enhanced reasoning capabilities with step-by-step thought processes (262K context) - \$0.60/\$2.50 per 1M tokens
- `zai-org/GLM-4.6` (Z AI) - Frontier open model with advanced agentic, reasoning and coding capabilities by Z AI (200k context) \$0.60/\$2.20 per 1M tokens
- `moonshotai/Kimi-K2-Instruct-0905` (Moonshot AI) - September update with enhanced capabilities (262K context) - \$0.60/\$2.50 per 1M tokens
- `openai/gpt-oss-120b` (OpenAI) - 120B MoE with strong reasoning capabilities (128K context) - \$0.10/\$0.50 per 1M tokens
@@ -31,13 +39,6 @@ https://www.baseten.co/resources/changelog/model-api-deprecation-notice-kimi-k2-
- `deepseek-ai/DeepSeek-V3.1` - Hybrid reasoning with advanced tool calling (163K context) - \$0.50/\$1.50 per 1M tokens
- `deepseek-ai/DeepSeek-V3-0324` - Fast general-purpose with enhanced reasoning (163K context) - \$0.77/\$0.77 per 1M tokens
### Configuration in Cline
1. **Open Cline Settings:** Click the settings icon (⚙️) in the Cline panel.
2. **Select Provider:** Choose "Baseten" from the "API Provider" dropdown.
3. **Enter API Key:** Paste your Baseten API key into the "Baseten API Key" field.
4. **Select Model:** Choose your desired model from the "Model" dropdown.
### Production-First Architecture
Baseten's Model APIs are built for production environments with several key advantages:
@@ -59,47 +60,17 @@ Baseten's Model APIs are built for production environments with several key adva
#### Developer Experience
- **OpenAI compatible API** - migrate by swapping a single URL
- **Drop-in replacement** for closed models with comprehensive observability
- **Drop-in replacement** for closed models with comprehensive observability and analytics
- **Seamless scaling** from Model APIs to dedicated deployments
### Special Features
#### Function Calling & Tool Use
All Baseten models support structured outputs, function calling, and tool use as part of the Baseten Inference Stack, making them ideal for agentic applications.
#### Reasoning Capabilities
DeepSeek models offer enhanced reasoning with step-by-step thought processes, while maintaining production-ready performance.
#### Long Context Support
- **Up to 1 million tokens** for Llama 4 models (Maverick and Scout)
- **262K tokens** for Qwen3 models
- **163K tokens** for DeepSeek models
- **Perfect for code repositories** and complex multi-turn conversations
#### Quantization Optimizations
Models are deployed with advanced quantization techniques (fp4, fp8, fp16) for optimal performance while maintaining quality.
### Migration from Other Providers
Baseten's OpenAI compatibility makes migration straightforward:
**From OpenAI:**
- Swap `api.openai.com` with `inference.baseten.co/v1`
- Keep existing request/response formats
- Benefit from significant cost savings
**From Other Providers:**
- Use standard OpenAI SDK format
- Maintain existing prompting strategies
- Access to newer open-source models
All Baseten models support structured outputs, function calling, and tool use as part of the Baseten Inference Stack, making them ideal for agentic applications and coding workflows.
### Tips and Notes
- **Model Selection:** Choose models based on your specific use case - reasoning models for complex tasks, coding models for development work, and flagship models for general applications.
- **Cost Optimization:** Baseten offers some of the most competitive pricing in the market, especially for open-source models.
- **Context Windows:** Take advantage of large context windows (up to 1M tokens) for including substantial codebases and documentation.
- **Enterprise Ready:** Baseten is designed for production use with enterprise-grade security, compliance, and reliability.
- **Dynamic Model Updates:** Cline automatically fetches the latest model list from Baseten, ensuring access to new models as they're released.
- **Dynamic Model Updates:** Cline automatically fetches the latest model list from Baseten, ensuring access to new models as they're released in real time.
- **Multi-Cloud Capacity Management (MCM):** Baseten's multi-cloud infrastructure ensures high availability and low latency globally.
- **Support:** Baseten provides dedicated support for production deployments and can work with you on dedicated resources as you scale.
+1 -2
View File
@@ -18,8 +18,7 @@ Cerebras delivers the world's fastest AI inference through their revolutionary w
Cline supports the following Cerebras models:
- `qwen-3-coder-480b-free` (Free tier) - High-performance coding model at no cost
- `qwen-3-coder-480b` - Flagship 480B parameter coding model
- `zai-glm-4.6` - Intelligent general purpose model with 1,500 tokens/s
- `qwen-3-235b-a22b-instruct-2507` - Advanced instruction-following model
- `qwen-3-235b-a22b-thinking-2507` - Reasoning model with step-by-step thinking
- `llama-3.3-70b` - Meta's Llama 3.3 model optimized for speed
-1422
View File
File diff suppressed because it is too large Load Diff
+46 -45
View File
@@ -1,47 +1,48 @@
{
"name": "cline-evals",
"version": "0.1.0",
"description": "Evaluation scripts and tools for Cline",
"main": "cli/dist/index.js",
"scripts": {
"build:cli": "cd cli && tsc",
"start:cli": "cd cli && node dist/index.js",
"dev:cli": "cd cli && ts-node src/index.ts",
"diff-eval": "./diff-edits/run_and_open_dashboard.sh",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"cline",
"evaluation",
"benchmark",
"diff-edits"
],
"author": "",
"license": "MIT",
"dependencies": {
"axios": "^1.12.0",
"better-sqlite3": "^12.4.1",
"chalk": "5.6.2",
"dotenv": "^16.5.0",
"commander": "^9.4.1",
"execa": "^5.1.1",
"node-fetch": "^2.7.0",
"ora": "^5.4.1",
"sqlite": "^4.1.2",
"tiktoken": "^1.0.21",
"uuid": "^9.0.0",
"yargs": "^17.6.2"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.3",
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.12",
"@types/uuid": "^9.0.0",
"@types/yargs": "^17.0.19",
"ts-node": "^10.9.1",
"typescript": "^4.9.4"
},
"overrides": {
"tar-fs": "^3.1.1"
}
"name": "cline-evals",
"version": "0.1.0",
"description": "Evaluation scripts and tools for Cline",
"main": "cli/dist/index.js",
"scripts": {
"build:cli": "cd cli && tsc",
"start:cli": "cd cli && node dist/index.js",
"dev:cli": "cd cli && ts-node src/index.ts",
"diff-eval": "./diff-edits/run_and_open_dashboard.sh",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"cline",
"evaluation",
"benchmark",
"diff-edits"
],
"author": "",
"license": "MIT",
"dependencies": {
"axios": "^1.12.0",
"better-sqlite3": "^12.4.1",
"chalk": "5.6.2",
"dotenv": "^16.5.0",
"commander": "^9.4.1",
"execa": "^5.1.1",
"node-fetch": "^2.7.0",
"ora": "^5.4.1",
"sqlite": "^4.1.2",
"tiktoken": "^1.0.21",
"uuid": "^9.0.0",
"yargs": "^17.6.2"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.3",
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.12",
"@types/uuid": "^9.0.0",
"@types/yargs": "^17.0.19",
"ts-node": "^10.9.1",
"typescript": "^4.9.4"
},
"overrides": {
"tar-fs": "^3.1.1",
"js-yaml": "^4.1.1"
}
}
+407 -929
View File
File diff suppressed because it is too large Load Diff
+30 -16
View File
@@ -2,7 +2,7 @@
"name": "claude-dev",
"displayName": "Cline",
"description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.",
"version": "3.36.1",
"version": "3.38.1",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -46,6 +46,15 @@
],
"main": "./dist/extension.js",
"contributes": {
"icons": {
"cline-icon": {
"description": "cline",
"default": {
"fontPath": "assets/icons/cline-bot.woff",
"fontCharacter": "\\e900"
}
}
},
"walkthroughs": [
{
"id": "ClineWalkthrough",
@@ -149,6 +158,12 @@
"category": "Cline",
"when": "cline.isDevMode"
},
{
"command": "cline.dev.expireMcpOAuthTokens",
"title": "Expire MCP OAuth Tokens (for testing)",
"category": "Cline",
"when": "cline.isDevMode"
},
{
"command": "cline.addToChat",
"title": "Add to Cline",
@@ -168,10 +183,7 @@
"command": "cline.generateGitCommitMessage",
"title": "Generate Commit Message with Cline",
"category": "Cline",
"icon": {
"light": "assets/icons/robot_panel_light.png",
"dark": "assets/icons/robot_panel_dark.png"
}
"icon": "$(cline-icon)"
},
{
"command": "cline.abortGitCommitMessage",
@@ -278,11 +290,11 @@
"commandPalette": [
{
"command": "cline.generateGitCommitMessage",
"when": "config.git.enabled && scmProvider == git && !cline.isGeneratingCommit"
"when": "config.git.enabled && !cline.isGeneratingCommit"
},
{
"command": "cline.abortGitCommitMessage",
"when": "config.git.enabled && scmProvider == git && cline.isGeneratingCommit"
"when": "config.git.enabled && cline.isGeneratingCommit"
}
]
},
@@ -331,7 +343,7 @@
"pretest": "npm run compile && npm run compile-tests && npm run compile-standalone && npm run lint",
"test": "npm-run-all test:unit test:integration",
"test:integration": "vscode-test",
"test:unit": "cross-env TS_NODE_PROJECT=./tsconfig.unit-test.json mocha",
"test:unit": "cross-env TS_NODE_PROJECT=./tsconfig.unit-test.json mocha # Use `UPDATE_SNAPSHOTS=true npm run test:unit` to rebuild prompt snapshots",
"test:coverage": "vscode-test --coverage",
"test:sca-server": "npx tsx watch scripts/test-standalone-core-api-server.ts",
"test:tp-orchestrator": "npx tsx scripts/testing-platform-orchestrator.ts",
@@ -353,7 +365,8 @@
"docs": "cd docs && npm run dev",
"docs:check-links": "cd docs && npm run check",
"docs:rename-file": "cd docs && npm run rename",
"report-issue": "node scripts/report-issue.js"
"report-issue": "node scripts/report-issue.js",
"storybook": "cd webview-ui && npm run storybook"
},
"lint-staged": {
"*": [
@@ -411,7 +424,7 @@
"@bufbuild/protobuf": "^2.2.5",
"@cerebras/cerebras_cloud_sdk": "^1.35.0",
"@google-cloud/vertexai": "^1.9.3",
"@google/genai": "^1.11.0",
"@google/genai": "^1.30.0",
"@grpc/grpc-js": "^1.9.15",
"@grpc/reflection": "^1.0.4",
"@mistralai/mistralai": "^1.5.0",
@@ -436,8 +449,8 @@
"@opentelemetry/sdk-trace-node": "^1.30.1",
"@opentelemetry/semantic-conventions": "^1.37.0",
"@playwright/test": "^1.55.1",
"@sap-ai-sdk/ai-api": "^1.17.0",
"@sap-ai-sdk/orchestration": "^1.17.0",
"@sap-ai-sdk/ai-api": "^2.1.0",
"@sap-ai-sdk/orchestration": "^2.1.0",
"@sentry/browser": "^9.12.0",
"@streamparser/json": "^0.0.22",
"@tailwindcss/vite": "^4.1.14",
@@ -455,7 +468,6 @@
"exceljs": "^4.4.0",
"execa": "^9.5.2",
"fast-deep-equal": "^3.1.3",
"firebase": "^11.2.0",
"fzf": "^0.5.2",
"get-folder-size": "^5.0.0",
"globby": "^14.0.2",
@@ -465,7 +477,6 @@
"image-size": "^2.0.2",
"isbinaryfile": "^5.0.2",
"jschardet": "^3.1.4",
"jwt-decode": "^4.0.0",
"mammoth": "^1.11.0",
"nanoid": "^5.1.6",
"nice-grpc": "^2.1.12",
@@ -473,7 +484,7 @@
"ollama": "^0.5.13",
"open": "^10.1.2",
"open-graph-scraper": "^6.9.0",
"openai": "^4.83.0",
"openai": "^6.9.0",
"os-name": "^6.0.0",
"p-mutex": "^1.0.0",
"p-timeout": "^6.1.4",
@@ -498,7 +509,10 @@
"zod": "^3.24.2"
},
"overrides": {
"tar-fs": ">=3.1.1"
"tar-fs": ">=3.1.1",
"tar": "^7.5.2",
"vite": "^7.1.11",
"js-yaml": "^4.1.1"
},
"c8": {
"reporter": [
+93 -4
View File
@@ -49,6 +49,9 @@ service FileService {
// Toggle a Windsurf rule (enable or disable)
rpc toggleWindsurfRule(ToggleWindsurfRuleRequest) returns (ClineRulesToggles);
// Toggle an Agents rule (enable or disable)
rpc toggleAgentsRule(ToggleAgentsRuleRequest) returns (ClineRulesToggles);
// Refreshes all rule toggles (Cline, External, and Workflows)
rpc refreshRules(EmptyRequest) returns (RefreshedRules);
@@ -66,6 +69,18 @@ service FileService {
// Opens or creates a focus chain checklist markdown file for editing
rpc openFocusChainFile(StringRequest) returns (Empty);
// Refreshes all hook toggles (discovers hooks and their enabled state)
rpc refreshHooks(EmptyRequest) returns (HooksToggles);
// Toggles a hook on or off via chmod +x/-x
rpc toggleHook(ToggleHookRequest) returns (ToggleHookResponse);
// Creates a new hook from template
rpc createHook(CreateHookRequest) returns (CreateHookResponse);
// Deletes an existing hook file
rpc deleteHook(DeleteHookRequest) returns (DeleteHookResponse);
}
// Response for refreshRules operation
@@ -74,8 +89,9 @@ message RefreshedRules {
ClineRulesToggles local_cline_rules_toggles = 2;
ClineRulesToggles local_cursor_rules_toggles = 3;
ClineRulesToggles local_windsurf_rules_toggles = 4;
ClineRulesToggles local_workflow_toggles = 5;
ClineRulesToggles global_workflow_toggles = 6;
ClineRulesToggles local_agents_rules_toggles = 5;
ClineRulesToggles local_workflow_toggles = 6;
ClineRulesToggles global_workflow_toggles = 7;
}
// Request to toggle a Windsurf rule
@@ -85,6 +101,13 @@ message ToggleWindsurfRuleRequest {
bool enabled = 3; // Whether to enable or disable the rule
}
// Request to toggle an Agents rule
message ToggleAgentsRuleRequest {
Metadata metadata = 1;
string rule_path = 2; // Path to the rule file
bool enabled = 3; // Whether to enable or disable the rule
}
// Request to convert a list of URIs to relative paths
message RelativePathsRequest {
Metadata metadata = 1;
@@ -156,10 +179,17 @@ message RuleFile {
bool already_exists = 3; // For createRuleFile, indicates if file already existed
}
// Enum for rule scope (local, global, or remote)
enum RuleScope {
LOCAL = 0;
GLOBAL = 1;
REMOTE = 2;
}
// Request to toggle a Cline rule
message ToggleClineRuleRequest {
Metadata metadata = 1;
bool is_global = 2; // Whether this is a global rule or workspace rule
RuleScope scope = 2; // Scope of the rule (local, global, or remote)
string rule_path = 3; // Path to the rule file
bool enabled = 4; // Whether to enable or disable the rule
}
@@ -173,6 +203,7 @@ message ClineRulesToggles {
message ToggleClineRules {
ClineRulesToggles global_cline_rules_toggles = 1;
ClineRulesToggles local_cline_rules_toggles = 2;
ClineRulesToggles remote_rules_toggles = 3;
}
// Request to toggle a Cursor rule
@@ -187,5 +218,63 @@ message ToggleWorkflowRequest {
Metadata metadata = 1;
string workflow_path = 2;
bool enabled = 3;
bool is_global = 4;
RuleScope scope = 4; // Scope of the workflow (local, global, or remote)
}
// Maps from hook name to enabled/disabled status
message HookInfo {
string name = 1;
bool enabled = 2;
string absolutePath = 3;
}
message WorkspaceHooks {
string workspace_name = 1;
repeated HookInfo hooks = 2;
}
message HooksToggles {
repeated HookInfo global_hooks = 1;
repeated WorkspaceHooks workspace_hooks = 2;
bool is_windows = 3; // Whether the system is Windows (toggles disabled)
}
// Request to toggle a hook
message ToggleHookRequest {
Metadata metadata = 1;
string hook_name = 2; // Name of the hook (e.g., "TaskStart")
bool is_global = 3; // Whether this is a global or workspace hook
bool enabled = 4; // Whether to enable (chmod +x) or disable (chmod -x)
optional string workspace_name = 5; // For multi-root workspaces, specifies which workspace
}
// Response for toggleHook operation
message ToggleHookResponse {
HooksToggles hooks_toggles = 1;
}
// Request to create a hook
message CreateHookRequest {
Metadata metadata = 1;
string hook_name = 2; // Name of the hook to create
bool is_global = 3; // Whether to create in global or workspace hooks directory
optional string workspace_name = 4; // For multi-root workspaces, specifies which workspace
}
// Response for createHook operation
message CreateHookResponse {
HooksToggles hooks_toggles = 1;
}
// Request to delete a hook
message DeleteHookRequest {
Metadata metadata = 1;
string hook_name = 2; // Name of the hook to delete
bool is_global = 3; // Whether this is a global or workspace hook
optional string workspace_name = 4; // For multi-root workspaces, specifies which workspace
}
// Response for deleteHook operation
message DeleteHookResponse {
HooksToggles hooks_toggles = 1;
}
+4
View File
@@ -18,6 +18,7 @@ service McpService {
rpc toggleToolAutoApprove(ToggleToolAutoApproveRequest) returns (McpServers);
rpc refreshMcpMarketplace(EmptyRequest) returns (McpMarketplaceCatalog);
rpc openMcpSettings(EmptyRequest) returns (Empty);
rpc authenticateMcpServer(StringRequest) returns (Empty);
// Subscribe to MCP marketplace catalog updates
rpc subscribeToMcpMarketplaceCatalog(EmptyRequest) returns (stream McpMarketplaceCatalog);
@@ -43,6 +44,7 @@ message AddRemoteMcpServerRequest {
Metadata metadata = 1;
string server_name = 2;
string server_url = 3;
optional string transport_type = 4;
}
message ToggleToolAutoApproveRequest {
@@ -91,6 +93,8 @@ message McpServer {
repeated McpResourceTemplate resource_templates = 7;
optional bool disabled = 8;
optional int32 timeout = 9;
optional bool oauth_required = 10;
optional string oauth_auth_status = 11;
}
message McpServers {
+7
View File
@@ -97,6 +97,7 @@ message OpenRouterModelInfo {
optional bool supports_global_endpoint = 11;
repeated ModelTier tiers = 12;
optional string name = 13;
optional double temperature = 14;
}
// Shared response message for model information
@@ -422,6 +423,7 @@ enum ApiProvider {
MINIMAX = 36;
HICAP = 37;
AIHUBMIX = 38;
NOUSRESEARCH = 39;
}
// Model info for OpenAI-compatible models
@@ -546,6 +548,7 @@ message ModelsApiConfiguration {
optional string aihubmix_api_key = 82;
optional string aihubmix_base_url = 83;
optional string aihubmix_app_code = 84;
optional string nous_research_api_key = 85;
// Plan mode configurations
optional ApiProvider plan_mode_api_provider = 100;
@@ -585,6 +588,8 @@ message ModelsApiConfiguration {
optional OpenRouterModelInfo plan_mode_hicap_model_info = 134;
optional string plan_mode_aihubmix_model_id = 135;
optional OpenAiCompatibleModelInfo plan_mode_aihubmix_model_info = 136;
optional string plan_mode_nous_research_model_id = 137;
optional string gemini_plan_mode_thinking_level = 138;
// Act mode configurations
optional ApiProvider act_mode_api_provider = 200;
@@ -624,4 +629,6 @@ message ModelsApiConfiguration {
optional OpenRouterModelInfo act_mode_hicap_model_info = 234;
optional string act_mode_aihubmix_model_id = 235;
optional OpenAiCompatibleModelInfo act_mode_aihubmix_model_info = 236;
optional string act_mode_nous_research_model_id = 237;
optional string gemini_act_mode_thinking_level = 238;
}
+17
View File
@@ -31,6 +31,7 @@ service StateService {
rpc installClineCli(EmptyRequest) returns (Empty);
rpc checkCliInstallation(EmptyRequest) returns (Boolean);
rpc getProcessInfo(EmptyRequest) returns (ProcessInfo);
rpc flushPendingState(EmptyRequest) returns (Empty);
}
message AutoApprovalActions {
@@ -89,6 +90,7 @@ message Secrets {
optional string oca_api_key = 37;
optional string oca_refresh_token = 38;
optional string hicap_api_key = 39;
optional string mcp_oauth_secrets = 40;
}
message Settings {
@@ -360,6 +362,7 @@ message UpdateSettingsRequest {
optional int32 subagent_terminal_output_line_limit = 30;
optional string cline_env = 31;
optional bool native_tool_call_enabled = 32;
optional OnboardingModelGroup onboarding_models = 33;
}
message UpdateTerminalConnectionTimeoutRequest {
@@ -387,3 +390,17 @@ message OnboardingProgressRequest {
optional bool completed = 3;
optional string model_selected = 4;
}
message OnboardingModelGroup {
repeated OnboardingModel models = 1;
}
message OnboardingModel {
string id = 1;
string name = 2;
int32 score = 3;
int32 latency = 4;
string badge = 5;
string group = 6;
OpenRouterModelInfo info = 7;
}
+2
View File
@@ -70,6 +70,7 @@ message TaskResponse {
int32 tokens_out = 8;
int32 cache_writes = 9;
int32 cache_reads = 10;
string model_id = 11;
}
// Request for getting task history with filtering
@@ -99,6 +100,7 @@ message TaskItem {
int32 tokens_out = 8;
int32 cache_writes = 9;
int32 cache_reads = 10;
string model_id = 11;
}
// Request for ask response operation
+7
View File
@@ -32,6 +32,7 @@ enum ClineAsk {
CONDENSE = 13;
REPORT_BUG = 14;
SUMMARIZE_TASK = 15;
ACT_MODE_RESPOND = 16;
}
// Enum for ClineSay types
@@ -184,6 +185,11 @@ message ClineApiReqInfo {
ApiReqRetryStatus retry_status = 9;
}
message ClineModelInfo {
string provider_id = 1;
string model_id = 2;
}
// Main ClineMessage type
message ClineMessage {
int64 ts = 1;
@@ -210,6 +216,7 @@ message ClineMessage {
ClineAskQuestion ask_question = 20;
ClineAskNewTask ask_new_task = 21;
ClineApiReqInfo api_req_info = 22;
ClineModelInfo model_info = 23;
}
// UiService provides methods for managing UI interactions
+1
View File
@@ -95,6 +95,7 @@ const ENABLED_PROVIDERS = [
"ollama", // Ollama local models
"cerebras", // Cerebras models
"oca", // Oracle Code Assist
"nousResearch", // NousResearch provider
]
/**
+1 -1
View File
@@ -11,7 +11,7 @@ import fs from "fs"
import https from "https"
import path from "path"
import { pipeline } from "stream/promises"
import tar from "tar"
import * as tar from "tar"
import { promisify } from "util"
import { createGunzip } from "zlib"
+3 -3
View File
@@ -1,5 +1,5 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo } from "@shared/api"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler } from "../../core/api/index"
import { ApiStream } from "../../core/api/transform/stream"
@@ -33,7 +33,7 @@ export class DifyHandler implements ApiHandler {
}
}
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
console.log("[DIFY DEBUG] createMessage called with:", {
systemPromptLength: systemPrompt?.length || 0,
messagesCount: messages?.length || 0,
@@ -255,7 +255,7 @@ export class DifyHandler implements ApiHandler {
}
}
private convertMessagesToQuery(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): string {
private convertMessagesToQuery(systemPrompt: string, messages: ClineStorageMessage[]): string {
// Dify's context is managed by `conversation_id`. The `query` should be the last user message.
// The system prompt is typically configured in the Dify App itself.
const lastUserMessage = messages.filter((m) => m.role === "user").pop()
+2 -31
View File
@@ -9,14 +9,6 @@ export interface EnvironmentConfig {
appBaseUrl: string
apiBaseUrl: string
mcpBaseUrl: string
firebase: {
apiKey: string
authDomain: string
projectId: string
storageBucket?: string
messagingSenderId?: string
appId?: string
}
}
class ClineEndpoint {
@@ -28,8 +20,8 @@ class ClineEndpoint {
private environment: Environment = Environment.production
private constructor() {
// Set environment at module load
const _env = process?.env?.CLINE_ENVIRONMENT
// Set environment at module load. Use override if provided.
const _env = process?.env?.CLINE_ENVIRONMENT_OVERRIDE || process?.env?.CLINE_ENVIRONMENT
if (_env && Object.values(Environment).includes(_env as Environment)) {
this.environment = _env as Environment
return
@@ -63,14 +55,6 @@ class ClineEndpoint {
appBaseUrl: "https://staging-app.cline.bot",
apiBaseUrl: "https://core-api.staging.int.cline.bot",
mcpBaseUrl: "https://core-api.staging.int.cline.bot/v1/mcp",
firebase: {
apiKey: "AIzaSyASSwkwX1kSO8vddjZkE5N19QU9cVQ0CIk",
authDomain: "cline-staging.firebaseapp.com",
projectId: "cline-staging",
storageBucket: "cline-staging.firebasestorage.app",
messagingSenderId: "853479478430",
appId: "1:853479478430:web:2de0dba1c63c3262d4578f",
},
}
case Environment.local:
return {
@@ -78,11 +62,6 @@ class ClineEndpoint {
appBaseUrl: "http://localhost:3000",
apiBaseUrl: "http://localhost:7777",
mcpBaseUrl: "https://api.cline.bot/v1/mcp",
firebase: {
apiKey: "AIzaSyD8wtkd1I-EICuAg6xgAQpRdwYTvwxZG2w",
authDomain: "cline-preview.firebaseapp.com",
projectId: "cline-preview",
},
}
default:
return {
@@ -90,14 +69,6 @@ class ClineEndpoint {
appBaseUrl: "https://app.cline.bot",
apiBaseUrl: "https://api.cline.bot",
mcpBaseUrl: "https://api.cline.bot/v1/mcp",
firebase: {
apiKey: "AIzaSyC5rx59Xt8UgwdU3PCfzUF7vCwmp9-K2vk",
authDomain: "cline-prod.firebaseapp.com",
projectId: "cline-prod",
storageBucket: "cline-prod.firebasestorage.app",
messagingSenderId: "941048379330",
appId: "1:941048379330:web:45058eedeefc5cdfcc485b",
},
}
}
}
+12 -3
View File
@@ -1,6 +1,6 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ApiConfiguration, ModelInfo, QwenApiRegions } from "@shared/api"
import { Mode } from "@shared/storage/types"
import { ClineStorageMessage } from "@/shared/messages/content"
import { ClineTool } from "@/shared/tools"
import { AIhubmixHandler } from "./providers/aihubmix"
import { AnthropicHandler } from "./providers/anthropic"
@@ -25,6 +25,7 @@ import { MinimaxHandler } from "./providers/minimax"
import { MistralHandler } from "./providers/mistral"
import { MoonshotHandler } from "./providers/moonshot"
import { NebiusHandler } from "./providers/nebius"
import { NousResearchHandler } from "./providers/nousresearch"
import { OcaHandler } from "./providers/oca"
import { OllamaHandler } from "./providers/ollama"
import { OpenAiHandler } from "./providers/openai"
@@ -46,9 +47,8 @@ import { ApiStream, ApiStreamUsageChunk } from "./transform/stream"
export type CommonApiHandlerOptions = {
onRetryAttempt?: ApiConfiguration["onRetryAttempt"]
}
export interface ApiHandler {
createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: ClineTool[]): ApiStream
createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: ClineTool[], useResponseApi?: boolean): ApiStream
getModel(): ApiHandlerModel
getApiStreamUsage?(): Promise<ApiStreamUsageChunk | undefined>
}
@@ -94,6 +94,7 @@ function createHandlerForProvider(
reasoningEffort: mode === "plan" ? options.planModeReasoningEffort : options.actModeReasoningEffort,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
geminiThinkingLevel: mode === "plan" ? options.geminiPlanModeThinkingLevel : options.geminiActModeThinkingLevel,
})
case "bedrock":
return new AwsBedrockHandler({
@@ -166,6 +167,7 @@ function createHandlerForProvider(
geminiBaseUrl: options.geminiBaseUrl,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
thinkingLevel: mode === "plan" ? options.geminiPlanModeThinkingLevel : options.geminiActModeThinkingLevel,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
ulid: options.ulid,
})
@@ -250,6 +252,7 @@ function createHandlerForProvider(
openRouterProviderSorting: options.openRouterProviderSorting,
openRouterModelId: mode === "plan" ? options.planModeOpenRouterModelId : options.actModeOpenRouterModelId,
openRouterModelInfo: mode === "plan" ? options.planModeOpenRouterModelInfo : options.actModeOpenRouterModelInfo,
geminiThinkingLevel: mode === "plan" ? options.geminiPlanModeThinkingLevel : options.geminiActModeThinkingLevel,
})
case "litellm":
return new LiteLlmHandler({
@@ -416,6 +419,12 @@ function createHandlerForProvider(
hicapApiKey: options.hicapApiKey,
hicapModelId: mode === "plan" ? options.planModeHicapModelId : options.actModeHicapModelId,
})
case "nousResearch":
return new NousResearchHandler({
onRetryAttempt: options.onRetryAttempt,
nousResearchApiKey: options.nousResearchApiKey,
apiModelId: mode === "plan" ? options.planModeNousResearchModelId : options.actModeNousResearchModelId,
})
default:
return new AnthropicHandler({
onRetryAttempt: options.onRetryAttempt,
@@ -1,8 +1,8 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { afterEach, beforeEach, describe, it } from "mocha"
import sinon from "sinon"
import "should"
import { ClaudeCodeHandler } from "@core/api/providers/claude-code"
import { ClineStorageMessage } from "@/shared/messages/content"
describe("ClaudeCodeHandler", () => {
let handler: ClaudeCodeHandler
@@ -71,7 +71,7 @@ describe("ClaudeCodeHandler", () => {
runClaudeCodeStub.returns(mockGenerator() as any)
const systemPrompt = "You are a helpful assistant."
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }]
const messages: ClineStorageMessage[] = [{ role: "user", content: "Hello" }]
const usageData: any[] = []
@@ -140,7 +140,7 @@ describe("ClaudeCodeHandler", () => {
runClaudeCodeStub.returns(mockGenerator() as any)
const systemPrompt = "You are a helpful assistant."
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }]
const messages: ClineStorageMessage[] = [{ role: "user", content: "Hello" }]
const usageData: any[] = []
@@ -199,7 +199,7 @@ describe("ClaudeCodeHandler", () => {
runClaudeCodeStub.returns(mockGenerator() as any)
const systemPrompt = "You are a helpful assistant."
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }]
const messages: ClineStorageMessage[] = [{ role: "user", content: "Hello" }]
const usageData: any[] = []
@@ -1,8 +1,8 @@
import Anthropic from "@anthropic-ai/sdk"
import { LiteLlmHandler, type LiteLlmModelInfoResponse } from "@core/api/providers/litellm"
import { convertToOpenAiMessages } from "@core/api/transform/openai-format"
import { expect } from "chai"
import sinon from "sinon"
import { ClineStorageMessage } from "@/shared/messages/content"
import { mockFetchForTesting } from "@/shared/net"
const fakeClient = {
@@ -109,7 +109,7 @@ describe("LiteLlmHandler", () => {
it("sends the system prompt and messages with the openai format", async () => {
const systemPrompt = "Test System Prompt"
const messages: Anthropic.Messages.MessageParam[] = [
const messages: ClineStorageMessage[] = [
{
role: "user",
content: "first message",
@@ -161,7 +161,7 @@ describe("LiteLlmHandler", () => {
it("inserts the cache control in the system prompt and the last two user messages", async () => {
const systemPrompt = "Test System Prompt"
const messages: Anthropic.Messages.MessageParam[] = [
const messages: ClineStorageMessage[] = [
{
role: "user",
content: "first message",
@@ -1,9 +1,9 @@
import { afterEach, before, beforeEach, describe, it } from "mocha"
import "should"
import { Anthropic } from "@anthropic-ai/sdk"
import { ApiHandlerOptions } from "@shared/api"
import axios from "axios"
import sinon from "sinon"
import { ClineStorageMessage } from "@/shared/messages/content"
import { OllamaHandler } from "../ollama"
describe("OllamaHandler", () => {
@@ -59,7 +59,7 @@ describe("OllamaHandler", () => {
} as any)
const systemPrompt = "You are a helpful assistant."
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }]
const messages: ClineStorageMessage[] = [{ role: "user", content: "Hello" }]
const result = []
const usageInfo = []
@@ -114,7 +114,7 @@ describe("OllamaHandler", () => {
}
const systemPrompt = "You are a helpful assistant."
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }]
const messages: ClineStorageMessage[] = [{ role: "user", content: "Hello" }]
// Start the request and catch the error
let errorMessage = ""
@@ -158,7 +158,7 @@ describe("OllamaHandler", () => {
} as any)
const systemPrompt = "You are a helpful assistant."
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }]
const messages: ClineStorageMessage[] = [{ role: "user", content: "Hello" }]
const result = []
@@ -204,7 +204,7 @@ describe("OllamaHandler", () => {
}
const systemPrompt = "You are a helpful assistant."
const messages: Anthropic.Messages.MessageParam[] = [{ role: "user", content: "Hello" }]
const messages: ClineStorageMessage[] = [{ role: "user", content: "Hello" }]
const result = []
+22 -45
View File
@@ -2,8 +2,8 @@ import { Anthropic } from "@anthropic-ai/sdk"
import { Tool as AnthropicTool } from "@anthropic-ai/sdk/resources/index"
import { Stream as AnthropicStream } from "@anthropic-ai/sdk/streaming"
import { AnthropicModelId, anthropicDefaultModelId, anthropicModels, CLAUDE_SONNET_1M_SUFFIX, ModelInfo } from "@shared/api"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ClineTool } from "@/shared/tools"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { sanitizeAnthropicMessages } from "../transform/anthropic-format"
@@ -43,7 +43,7 @@ export class AnthropicHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: ClineTool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: AnthropicTool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
@@ -74,19 +74,7 @@ export class AnthropicHandler implements ApiHandler {
case "claude-opus-4-1-20250805":
case "claude-3-opus-20240229":
case "claude-3-haiku-20240307": {
/*
The latest message will be the new user message, one before will be the assistant message from a previous request, and the user message before that will be a previously cached user message. So we need to mark the latest user message as ephemeral to cache it for the next request, and mark the second to last user message as ephemeral to let the server know the last message to retrieve from the cache for the current request..
*/
const userMsgIndices = messages.reduce((acc, msg, index) => {
if (msg.role === "user") {
acc.push(index)
}
return acc
}, [] as number[])
const lastUserMsgIndex = userMsgIndices[userMsgIndices.length - 1] ?? -1
const secondLastMsgUserIndex = userMsgIndices[userMsgIndices.length - 2] ?? -1
const anthropicMessages = sanitizeAnthropicMessages(messages, lastUserMsgIndex, secondLastMsgUserIndex)
const anthropicMessages = sanitizeAnthropicMessages(messages, true)
stream = await client.messages.create(
{
@@ -106,7 +94,7 @@ export class AnthropicHandler implements ApiHandler {
messages: anthropicMessages,
// tools, // cache breakpoints go from tools > system > messages, and since tools dont change, we can just set the breakpoint at the end of system (this avoids having to set a breakpoint at the end of tools which by itself does not meet min requirements for haiku caching)
stream: true,
tools: nativeToolsOn ? (tools as AnthropicTool[]) : undefined,
tools: nativeToolsOn ? tools : undefined,
// tool_choice options:
// - none: disables tool use, even if tools are provided. Claude will not call any tools.
// - auto: allows Claude to decide whether to call any provided tools or not. This is the default value when tools are provided.
@@ -135,29 +123,30 @@ export class AnthropicHandler implements ApiHandler {
max_tokens: model.info.maxTokens || 8192,
temperature: 0,
system: [{ text: systemPrompt, type: "text" }],
messages: sanitizeAnthropicMessages(messages),
// tools,
// tool_choice: { type: "auto" },
messages: sanitizeAnthropicMessages(messages, false),
tools: nativeToolsOn ? tools : undefined,
tool_choice: { type: "auto" },
stream: true,
})
break
}
}
let thinkingDeltaAccumulator = ""
const lastStartedToolCall = { id: "", name: "", arguments: "" }
for await (const chunk of stream) {
switch (chunk?.type) {
case "message_start":
// tells us cache reads/writes/input/output
const usage = chunk.message.usage
yield {
type: "usage",
inputTokens: usage.input_tokens || 0,
outputTokens: usage.output_tokens || 0,
cacheWriteTokens: usage.cache_creation_input_tokens || undefined,
cacheReadTokens: usage.cache_read_input_tokens || undefined,
{
// tells us cache reads/writes/input/output
const usage = chunk.message.usage
yield {
type: "usage",
inputTokens: usage.input_tokens || 0,
outputTokens: usage.output_tokens || 0,
cacheWriteTokens: usage.cache_creation_input_tokens || undefined,
cacheReadTokens: usage.cache_read_input_tokens || undefined,
}
}
break
case "message_delta":
@@ -178,15 +167,7 @@ export class AnthropicHandler implements ApiHandler {
yield {
type: "reasoning",
reasoning: chunk.content_block.thinking || "",
}
const thinking = chunk.content_block.thinking
const signature = chunk.content_block.signature
if (thinking && signature) {
yield {
type: "ant_thinking",
thinking,
signature,
}
signature: chunk.content_block.signature,
}
break
case "redacted_thinking":
@@ -194,10 +175,7 @@ export class AnthropicHandler implements ApiHandler {
yield {
type: "reasoning",
reasoning: "[Redacted thinking block]",
}
yield {
type: "ant_redacted_thinking",
data: chunk.content_block.data,
redacted_data: chunk.content_block.data,
}
break
case "tool_use":
@@ -231,15 +209,14 @@ export class AnthropicHandler implements ApiHandler {
type: "reasoning",
reasoning: chunk.delta.thinking,
}
thinkingDeltaAccumulator += chunk.delta.thinking
break
case "signature_delta":
// It's used when sending the thinking block back to the API
// API expects this in completed form, not as array of deltas
if (thinkingDeltaAccumulator && chunk.delta.signature) {
if (chunk.delta.signature) {
yield {
type: "ant_thinking",
thinking: thinkingDeltaAccumulator,
type: "reasoning",
reasoning: "", // reasoning text is already sent via thinking_delta
signature: chunk.delta.signature,
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { AskSageModelId, askSageDefaultModelId, askSageDefaultURL, askSageModels, ModelInfo } from "@shared/api"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from ".."
import { withRetry } from "../retry"
@@ -47,7 +47,7 @@ export class AskSageHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
try {
const model = this.getModel()
+15 -7
View File
@@ -1,12 +1,14 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { BasetenModelId, basetenDefaultModelId, basetenModels, ModelInfo } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
import { ToolCallProcessor } from "../transform/tool-call-processor"
interface BasetenHandlerOptions extends CommonApiHandlerOptions {
basetenApiKey?: string
@@ -98,10 +100,11 @@ export class BasetenHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const maxTokens = this.getOptimalMaxTokens(model)
const toolCallProcessor = new ToolCallProcessor()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
@@ -115,21 +118,22 @@ export class BasetenHandler implements ApiHandler {
stream: true,
stream_options: { include_usage: true },
temperature: 0,
tools,
tool_choice: tools && tools.length > 0 ? "auto" : undefined,
})
let didOutputUsage = false
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
const delta = chunk?.choices?.[0]?.delta
// Handle reasoning field if present (for reasoning models with parsed output)
if ((delta as any)?.reasoning) {
const reasoningContent = (delta as any).reasoning as string
if (delta && "reasoning" in delta && delta?.reasoning) {
const reasoning = typeof delta.reasoning === "string" ? delta.reasoning : JSON.stringify(delta.reasoning)
yield {
type: "reasoning",
reasoning: reasoningContent,
reasoning,
}
continue
}
// Handle content field
@@ -140,6 +144,10 @@ export class BasetenHandler implements ApiHandler {
}
}
if (delta?.tool_calls) {
yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
}
// Handle usage information - only output once
if (!didOutputUsage && chunk.usage) {
yield* this.yieldUsage(model.info, chunk.usage)
+23 -16
View File
@@ -1,4 +1,3 @@
import { Anthropic } from "@anthropic-ai/sdk"
// Import proper AWS SDK types
import type { ContentBlock, Message } from "@aws-sdk/client-bedrock-runtime"
import {
@@ -12,6 +11,7 @@ import { fromNodeProviderChain } from "@aws-sdk/credential-providers"
import { BedrockModelId, bedrockDefaultModelId, bedrockModels, CLAUDE_SONNET_1M_SUFFIX, ModelInfo } from "@shared/api"
import { calculateApiCostOpenAI, calculateApiCostQwen } from "@utils/cost"
import { ExtensionRegistryInfo } from "@/registry"
import { ClineStorageMessage } from "@/shared/messages/content"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToR1Format } from "../transform/r1-format"
@@ -121,7 +121,7 @@ export class AwsBedrockHandler implements ApiHandler {
}
@withRetry({ maxRetries: 4 })
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
// cross region inference requires prefixing the model id with the region
const rawModelId = await this.getModelId()
@@ -342,7 +342,7 @@ export class AwsBedrockHandler implements ApiHandler {
*/
private async *createDeepseekMessage(
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
messages: ClineStorageMessage[],
modelId: string,
model: { id: string; info: ModelInfo },
): ApiStream {
@@ -480,7 +480,7 @@ export class AwsBedrockHandler implements ApiHandler {
* First uses convertToR1Format to merge consecutive messages with the same role,
* then converts to the string format that DeepSeek R1 expects
*/
private formatDeepseekR1Prompt(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): string {
private formatDeepseekR1Prompt(systemPrompt: string, messages: ClineStorageMessage[]): string {
// First use convertToR1Format to merge consecutive messages with the same role
const r1Messages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages])
@@ -513,7 +513,7 @@ export class AwsBedrockHandler implements ApiHandler {
* Estimates token count based on text length (approximate)
* Note: This is a rough estimation, as the actual token count depends on the tokenizer
*/
private estimateInputTokens(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): number {
private estimateInputTokens(systemPrompt: string, messages: ClineStorageMessage[]): number {
// For Deepseek R1, we estimate the token count of the formatted prompt
// The formatted prompt includes special tokens and consistent formatting
const formattedPrompt = this.formatDeepseekR1Prompt(systemPrompt, messages)
@@ -680,11 +680,7 @@ export class AwsBedrockHandler implements ApiHandler {
}
}
} catch (error) {
console.error("Error processing Converse API response:", error)
yield {
type: "text",
text: `[ERROR] Failed to process response: ${error instanceof Error ? error.message : String(error)}`,
}
throw error
}
}
@@ -703,9 +699,20 @@ export class AwsBedrockHandler implements ApiHandler {
text: `[ERROR] Model stream error: ${chunk.modelStreamErrorException.message}`,
}
} else if (chunk.validationException) {
// Check if this is a context window error - if so, throw it
// so the retry mechanism can handle truncation
const message = chunk.validationException.message || ""
const isContextError = /input.*too long|context.*exceed|maximum.*token|input length.*max.*tokens/i.test(message)
if (isContextError) {
// Throw as exception so context management can handle it
throw chunk.validationException
}
// Otherwise yield as error text
yield {
type: "text",
text: `[ERROR] Validation error: ${chunk.validationException.message}`,
text: `[ERROR] Validation error: ${message}`,
}
} else if (chunk.throttlingException) {
yield {
@@ -779,7 +786,7 @@ export class AwsBedrockHandler implements ApiHandler {
*/
private async *createAnthropicMessage(
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
messages: ClineStorageMessage[],
modelId: string,
model: { id: string; info: ModelInfo },
enable1mContextWindow: boolean,
@@ -835,7 +842,7 @@ export class AwsBedrockHandler implements ApiHandler {
* Formats messages for models using the Converse API specification
* Used by both Anthropic and Nova models to avoid code duplication
*/
private formatMessagesForConverseAPI(messages: Anthropic.Messages.MessageParam[]): Message[] {
private formatMessagesForConverseAPI(messages: ClineStorageMessage[]): Message[] {
return messages.map((message) => {
// Determine role (user or assistant)
const role = message.role === "user" ? ConversationRole.USER : ConversationRole.ASSISTANT
@@ -968,7 +975,7 @@ export class AwsBedrockHandler implements ApiHandler {
*/
private async *createNovaMessage(
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
messages: ClineStorageMessage[],
modelId: string,
model: { id: string; info: ModelInfo },
): ApiStream {
@@ -1008,7 +1015,7 @@ export class AwsBedrockHandler implements ApiHandler {
*/
private async *createOpenAIMessage(
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
messages: ClineStorageMessage[],
modelId: string,
model: { id: string; info: ModelInfo },
): ApiStream {
@@ -1143,7 +1150,7 @@ export class AwsBedrockHandler implements ApiHandler {
*/
private async *createQwenMessage(
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
messages: ClineStorageMessage[],
modelId: string,
model: { id: string; info: ModelInfo },
): ApiStream {
+2 -2
View File
@@ -1,6 +1,6 @@
import { Anthropic } from "@anthropic-ai/sdk"
import Cerebras from "@cerebras/cerebras_cloud_sdk"
import { CerebrasModelId, cerebrasDefaultModelId, cerebrasModels, ModelInfo } from "@shared/api"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
@@ -46,7 +46,7 @@ export class CerebrasHandler implements ApiHandler {
baseDelay: 5000, // Start with 5 second delay
maxDelay: 60000, // Allow up to 60 second delays to respect rate limits
})
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
const client = this.ensureClient()
// Convert Anthropic messages to Cerebras format
+14 -3
View File
@@ -1,7 +1,7 @@
import type { Anthropic } from "@anthropic-ai/sdk"
import { filterMessagesForClaudeCode } from "@/integrations/claude-code/message-filter"
import { runClaudeCode } from "@/integrations/claude-code/run"
import { ClaudeCodeModelId, claudeCodeDefaultModelId, claudeCodeModels } from "@/shared/api"
import { ClineStorageMessage } from "@/shared/messages/content"
import { type ApiHandler, CommonApiHandlerOptions } from ".."
import { withRetry } from "../retry"
import { type ApiStream, ApiStreamUsageChunk } from "../transform/stream"
@@ -24,7 +24,7 @@ export class ClaudeCodeHandler implements ApiHandler {
baseDelay: 2000,
maxDelay: 15000,
})
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
// Filter out image blocks since Claude Code doesn't support them
const filteredMessages = filterMessagesForClaudeCode(messages)
@@ -113,7 +113,18 @@ export class ClaudeCodeHandler implements ApiHandler {
}
break
case "tool_use":
console.error(`tool_use is not supported yet. Received: ${JSON.stringify(content)}`)
// Yield tool_use blocks to the streaming pipeline for proper tool execution
yield {
type: "tool_calls",
tool_call: {
call_id: content.id,
function: {
id: content.id,
name: content.name,
arguments: content.input,
},
},
}
break
}
}
+15 -8
View File
@@ -1,4 +1,3 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo } from "@shared/api"
import { shouldSkipReasoningForModel } from "@utils/model-utils"
import axios from "axios"
@@ -8,7 +7,9 @@ import { ClineEnv } from "@/config"
import { ClineAccountService } from "@/services/account/ClineAccountService"
import { AuthService } from "@/services/auth/AuthService"
import { buildClineExtraHeaders } from "@/services/EnvUtils"
import { Logger } from "@/services/logging/Logger"
import { CLINE_ACCOUNT_AUTH_ERROR_MESSAGE } from "@/shared/ClineAccount"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch, getAxiosSettings } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -26,6 +27,7 @@ interface ClineHandlerOptions extends CommonApiHandlerOptions {
openRouterModelId?: string
openRouterModelInfo?: ModelInfo
clineAccountId?: string
geminiThinkingLevel?: string
}
export class ClineHandler implements ApiHandler {
@@ -96,7 +98,7 @@ export class ClineHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
try {
const client = await this.ensureClient()
@@ -114,11 +116,13 @@ export class ClineHandler implements ApiHandler {
this.options.thinkingBudgetTokens,
this.options.openRouterProviderSorting,
tools,
this.options.geminiThinkingLevel,
)
const toolCallProcessor = new ToolCallProcessor()
for await (const chunk of stream) {
Logger.debug("ClineHandler chunk:" + JSON.stringify(chunk))
// openrouter returns an error object instead of the openai sdk throwing an error
if ("error" in chunk) {
const error = chunk.error as OpenRouterErrorResponse["error"]
@@ -149,6 +153,7 @@ export class ClineHandler implements ApiHandler {
}
const delta = choice?.delta
if (delta?.content) {
yield {
type: "text",
@@ -165,8 +170,7 @@ export class ClineHandler implements ApiHandler {
if ("reasoning" in delta && delta.reasoning && !shouldSkipReasoningForModel(this.options.openRouterModelId)) {
yield {
type: "reasoning",
// @ts-ignore-next-line
reasoning: delta.reasoning,
reasoning: typeof delta.reasoning === "string" ? delta.reasoning : JSON.stringify(delta.reasoning),
}
}
@@ -181,20 +185,23 @@ export class ClineHandler implements ApiHandler {
"reasoning_details" in delta &&
delta.reasoning_details &&
// @ts-ignore-next-line
delta.reasoning_details.length && // exists and non-0
delta?.reasoning_details?.length && // exists and non-0
!shouldSkipReasoningForModel(this.options.openRouterModelId)
) {
yield {
type: "reasoning_details",
reasoning_details: delta.reasoning_details,
type: "reasoning",
reasoning: "",
details: delta.reasoning_details,
}
}
console.log("didOutputUsage", didOutputUsage, chunk.usage)
if (!didOutputUsage && chunk.usage) {
// @ts-ignore-next-line
let totalCost = (chunk.usage.cost || 0) + (chunk.usage.cost_details?.upstream_inference_cost || 0)
if (this.getModel().id === "x-ai/grok-code-fast-1") {
if (this.getModel().id === "x-ai/grok-code-fast-1" || this.getModel().id === "minimax/minimax-m2") {
totalCost = 0
}
+2 -2
View File
@@ -1,8 +1,8 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { DeepSeekModelId, deepSeekDefaultModelId, deepSeekModels, ModelInfo } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -75,7 +75,7 @@ export class DeepSeekHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
+3 -3
View File
@@ -1,4 +1,4 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ModelInfo } from "../../../shared/api"
import { ApiHandler } from "../index"
@@ -97,7 +97,7 @@ export class DifyHandler implements ApiHandler {
}
}
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
console.log("[DIFY DEBUG] createMessage called with:", {
systemPromptLength: systemPrompt?.length || 0,
messagesCount: messages?.length || 0,
@@ -384,7 +384,7 @@ export class DifyHandler implements ApiHandler {
}
}
private convertMessagesToQuery(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): string {
private convertMessagesToQuery(systemPrompt: string, messages: ClineStorageMessage[]): string {
// Dify's context is managed by `conversation_id`. The `query` should be the last user message.
// The system prompt is typically configured in the Dify App itself.
const lastUserMessage = messages.filter((m) => m.role === "user").pop()
+2 -2
View File
@@ -1,6 +1,6 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { DoubaoModelId, doubaoDefaultModelId, doubaoModels, ModelInfo } from "@shared/api"
import OpenAI from "openai"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from ".."
import { withRetry } from "../retry"
@@ -50,7 +50,7 @@ export class DoubaoHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
+2 -2
View File
@@ -1,6 +1,6 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { FireworksModelId, fireworksDefaultModelId, fireworksModels, ModelInfo } from "@shared/api"
import OpenAI from "openai"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from ".."
import { withRetry } from "../retry"
@@ -41,7 +41,7 @@ export class FireworksHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
const client = this.ensureClient()
const modelId = this.options.fireworksModelId ?? ""
+54 -47
View File
@@ -1,4 +1,3 @@
import type { Anthropic } from "@anthropic-ai/sdk"
// Restore GenerateContentConfig import and add GenerateContentResponseUsageMetadata
import {
ApiError,
@@ -7,10 +6,11 @@ import {
type GenerateContentResponseUsageMetadata,
GoogleGenAI,
FunctionDeclaration as GoogleTool,
Part,
ThinkingLevel,
} from "@google/genai"
import { GeminiModelId, geminiDefaultModelId, geminiModels, ModelInfo } from "@shared/api"
import { telemetryService } from "@/services/telemetry"
import { ClineStorageMessage } from "@/shared/messages/content"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { RetriableError, withRetry } from "../retry"
import { convertAnthropicMessageToGemini } from "../transform/gemini-format"
@@ -28,6 +28,7 @@ interface GeminiHandlerOptions extends CommonApiHandlerOptions {
geminiApiKey?: string
geminiBaseUrl?: string
thinkingBudgetTokens?: number
thinkingLevel?: string
apiModelId?: string
ulid?: string
}
@@ -110,34 +111,49 @@ export class GeminiHandler implements ApiHandler {
baseDelay: 2000,
maxDelay: 15000,
})
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: GoogleTool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: GoogleTool[]): ApiStream {
const client = this.ensureClient()
const { id: modelId, info } = this.getModel()
const contents = messages.map(convertAnthropicMessageToGemini)
// Configure thinking budget if supported
const thinkingBudget = this.options.thinkingBudgetTokens ?? 0
const _maxBudget = info.thinkingConfig?.maxBudget ?? 0
const _thinkingBudget = this.options.thinkingBudgetTokens ?? 0
const maxBudget = info.thinkingConfig?.maxBudget ?? 24576
const thinkingBudget = Math.min(_thinkingBudget, maxBudget)
// When ThinkingLevel is defineded, thinking budget cannot be zero
// and only level is used to control thinking behavior.
let thinkingLevel: ThinkingLevel | undefined
if (this.options.thinkingLevel === "low") {
thinkingLevel = ThinkingLevel.LOW
} else if (this.options.thinkingLevel === "high") {
thinkingLevel = ThinkingLevel.HIGH
}
// Set up base generation config
const requestConfig: GenerateContentConfig = {
// Add base URL if configured
httpOptions: this.options.geminiBaseUrl ? { baseUrl: this.options.geminiBaseUrl } : undefined,
...{ systemInstruction: systemPrompt },
systemInstruction: systemPrompt,
// Set temperature (default to 0)
temperature: 0,
// Gemini 3.0 recommends 1.0
temperature: info.temperature ?? 1,
}
// Add thinking config if the model supports it
if (thinkingBudget > 0) {
requestConfig.thinkingConfig = {
thinkingBudget: thinkingBudget,
includeThoughts: true,
}
requestConfig.thinkingConfig = {
// Turn off thinking:
// thinkingBudget: 0
// Turn on dynamic thinking:
// thinkingBudget: -1
// Turn on fixed thinking budget:
thinkingBudget: thinkingLevel ? undefined : thinkingBudget,
thinkingLevel,
includeThoughts: thinkingBudget > 0 || !!thinkingLevel,
}
// Generate content using the configured parameters
const sdkCallStartTime = Date.now()
let responseId: string | undefined
let sdkFirstChunkTime: number | undefined
let ttftSdkMs: number | undefined
let apiSuccess = false
@@ -148,7 +164,8 @@ export class GeminiHandler implements ApiHandler {
let thoughtsTokenCount = 0 // Initialize thought token counts
let lastUsageMetadata: GenerateContentResponseUsageMetadata | undefined
if (tools?.length) {
const isNativeToolCallsEnabled = tools?.length
if (isNativeToolCallsEnabled) {
requestConfig.tools = [{ functionDeclarations: tools }]
requestConfig.toolConfig = {
// Force the model to call 'any' function.
@@ -176,56 +193,45 @@ export class GeminiHandler implements ApiHandler {
}
// Handle thinking content from Gemini's response
const candidateForThoughts = chunk?.candidates?.[0]
const partsForThoughts = candidateForThoughts?.content?.parts
let thoughts = "" // Initialize as empty string
if (partsForThoughts) {
// This ensures partsForThoughts is a Part[] array
for (const part of partsForThoughts) {
const { thought, text } = part as Part
if (thought && text) {
// Ensure part.text exists
// Handle the thought part
thoughts += text + "\n" // Append thought and a newline
const parts = chunk?.candidates?.[0]?.content?.parts || []
for (const part of parts) {
if (part.thought && part.text) {
yield {
type: "reasoning",
id: chunk.responseId,
reasoning: part.text || "",
signature: part.thoughtSignature,
}
} else if (part.text) {
yield {
type: "text",
text: part.text,
id: chunk.responseId,
signature: part.thoughtSignature,
}
}
}
if (thoughts.trim() !== "") {
yield {
type: "reasoning",
reasoning: thoughts.trim(),
}
thoughts = "" // Reset thoughts after yielding
}
if (chunk.text) {
yield {
type: "text",
text: chunk.text,
}
}
if (tools && chunk.functionCalls && chunk.functionCalls?.length > 0) {
for (const functionCall of chunk.functionCalls) {
if (functionCall.args) {
console.log("[GeminiHandler] tool call received:", functionCall)
if (part.functionCall) {
const functionCall = part.functionCall
const args = Object.entries(functionCall.args || {}).filter(([_key, val]) => !!val)
if (functionCall.args && args.length > 0) {
yield {
type: "tool_calls",
id: chunk.responseId,
tool_call: {
function: {
id: functionCall.id || functionCall.name,
id: chunk.responseId,
name: functionCall.name,
arguments: JSON.stringify(functionCall.args),
},
},
signature: part.thoughtSignature,
}
}
}
}
if (chunk.usageMetadata) {
responseId = chunk.responseId
lastUsageMetadata = chunk.usageMetadata
promptTokens = lastUsageMetadata.promptTokenCount ?? promptTokens
outputTokens = lastUsageMetadata.candidatesTokenCount ?? outputTokens
@@ -251,6 +257,7 @@ export class GeminiHandler implements ApiHandler {
cacheReadTokens,
cacheWriteTokens: 0,
totalCost,
id: responseId,
}
}
} catch (error) {
+2 -2
View File
@@ -1,8 +1,8 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { GroqModelId, groqDefaultModelId, groqModels, ModelInfo } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -192,7 +192,7 @@ export class GroqHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const modelFamily = this.detectModelFamily(model.id)
+2 -2
View File
@@ -1,7 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { hicapModelInfoSaneDefaults, ModelInfo } from "@shared/api"
import OpenAI from "openai"
import type { ChatCompletionReasoningEffort } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
@@ -44,7 +44,7 @@ export class HicapHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
const client = this.ensureClient()
const modelId = this.options.hicapModelId ?? ""
+2 -2
View File
@@ -1,7 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { HuaweiCloudMaasModelId, huaweiCloudMaasDefaultModelId, huaweiCloudMaasModels, ModelInfo } from "@shared/api"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from ".."
import { withRetry } from "../retry"
@@ -62,7 +62,7 @@ export class HuaweiCloudMaaSHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
+2 -2
View File
@@ -1,8 +1,8 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { HuggingFaceModelId, huggingFaceDefaultModelId, huggingFaceModels, ModelInfo } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -69,7 +69,7 @@ export class HuggingFaceHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
try {
const client = this.ensureClient()
const model = this.getModel()
+2 -1
View File
@@ -1,6 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { LiteLLMModelInfo, liteLlmDefaultModelId, liteLlmModelInfoSaneDefaults } from "@shared/api"
import OpenAI from "openai"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { isAnthropicModelId } from "@/utils/model-utils"
import { ApiHandler, CommonApiHandlerOptions } from ".."
@@ -183,7 +184,7 @@ export class LiteLlmHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
const client = this.ensureClient()
const formattedMessages = convertToOpenAiMessages(messages)
const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam | Anthropic.Messages.TextBlockParam = {
+2 -2
View File
@@ -1,7 +1,7 @@
import type { Anthropic } from "@anthropic-ai/sdk"
import { type ModelInfo, openAiModelInfoSaneDefaults } from "@shared/api"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import type { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -40,7 +40,7 @@ export class LmStudioHandler implements ApiHandler {
}
@withRetry({ retryAllErrors: true })
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
+13 -18
View File
@@ -2,6 +2,7 @@ import { Anthropic } from "@anthropic-ai/sdk"
import { Tool as AnthropicTool } from "@anthropic-ai/sdk/resources/index"
import { Stream as AnthropicStream } from "@anthropic-ai/sdk/streaming"
import { MinimaxModelId, ModelInfo, minimaxDefaultModelId, minimaxModels } from "@/shared/api"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ClineTool } from "@/shared/tools"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
@@ -45,7 +46,7 @@ export class MinimaxHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: ClineTool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: ClineTool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
@@ -66,12 +67,11 @@ export class MinimaxHandler implements ApiHandler {
tool_choice: nativeToolsOn ? { type: "any" } : undefined,
})
let thinkingDeltaAccumulator = ""
const lastStartedToolCall = { id: "", name: "", arguments: "" }
for await (const chunk of stream) {
switch (chunk?.type) {
case "message_start":
case "message_start": {
// tells us cache reads/writes/input/output
const usage = chunk.message.usage
yield {
@@ -82,6 +82,7 @@ export class MinimaxHandler implements ApiHandler {
cacheReadTokens: usage.cache_read_input_tokens || undefined,
}
break
}
case "message_delta":
// tells us stop_reason, stop_sequence, and output tokens along the way and at the end of the message
yield {
@@ -100,13 +101,11 @@ export class MinimaxHandler implements ApiHandler {
type: "reasoning",
reasoning: chunk.content_block.thinking || "",
}
const thinking = chunk.content_block.thinking
const signature = chunk.content_block.signature
if (thinking && signature) {
if (chunk.content_block.thinking && chunk.content_block.signature) {
yield {
type: "ant_thinking",
thinking,
signature,
type: "reasoning",
reasoning: chunk.content_block.thinking,
signature: chunk.content_block.signature,
}
}
break
@@ -115,10 +114,7 @@ export class MinimaxHandler implements ApiHandler {
yield {
type: "reasoning",
reasoning: "[Redacted thinking block]",
}
yield {
type: "ant_redacted_thinking",
data: chunk.content_block.data,
redacted_data: chunk.content_block.data,
}
break
case "tool_use":
@@ -147,20 +143,19 @@ export class MinimaxHandler implements ApiHandler {
case "content_block_delta":
switch (chunk.delta.type) {
case "thinking_delta":
// 'reasoning' type just displays in the UI, but ant_thinking will be used to send the thinking traces back to the API
// 'reasoning' type just displays in the UI, but reasoning with signature will be used to send the thinking traces back to the API
yield {
type: "reasoning",
reasoning: chunk.delta.thinking,
}
thinkingDeltaAccumulator += chunk.delta.thinking
break
case "signature_delta":
// It's used when sending the thinking block back to the API
// API expects this in completed form, not as array of deltas
if (thinkingDeltaAccumulator && chunk.delta.signature) {
if (chunk.delta.signature) {
yield {
type: "ant_thinking",
thinking: thinkingDeltaAccumulator,
type: "reasoning",
reasoning: "",
signature: chunk.delta.signature,
}
}
+2 -2
View File
@@ -1,9 +1,9 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Mistral } from "@mistralai/mistralai"
import { HTTPClient } from "@mistralai/mistralai/lib/http"
import { Tool as MistralTool } from "@mistralai/mistralai/models/components/tool"
import { MistralModelId, ModelInfo, mistralDefaultModelId, mistralModels } from "@shared/api"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -48,7 +48,7 @@ export class MistralHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const stream = await client.chat
.stream({
+2 -2
View File
@@ -1,7 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ModelInfo, MoonshotModelId, moonshotDefaultModelId, moonshotModels } from "@/shared/api"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
@@ -40,7 +40,7 @@ export class MoonshotHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
+2 -2
View File
@@ -1,7 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { type ModelInfo, type NebiusModelId, nebiusDefaultModelId, nebiusModels } from "@shared/api"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
@@ -39,7 +39,7 @@ export class NebiusHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
+92
View File
@@ -0,0 +1,92 @@
import { ModelInfo, NousResearchModelId, nousResearchDefaultModelId, nousResearchModels } from "@shared/api"
import OpenAI from "openai"
import { ClineStorageMessage } from "@/shared/messages/content"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { ApiStream } from "../transform/stream"
interface NousResearchHandlerOptions extends CommonApiHandlerOptions {
nousResearchApiKey?: string
apiModelId?: string
}
export class NousResearchHandler implements ApiHandler {
private options: NousResearchHandlerOptions
private client: OpenAI | undefined
constructor(options: NousResearchHandlerOptions) {
this.options = options
}
private ensureClient(): OpenAI {
if (!this.client) {
if (!this.options.nousResearchApiKey) {
throw new Error("NousResearch API key is required")
}
try {
this.client = new OpenAI({
baseURL: "https://inference-api.nousResearch.com/v1",
apiKey: this.options.nousResearchApiKey,
})
} catch (error: any) {
throw new Error(`Error creating NousResearch client: ${error.message}`)
}
}
return this.client
}
@withRetry()
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages),
]
const stream = await client.chat.completions.create({
model: model.id,
messages: openAiMessages,
temperature: 0,
stream: true,
stream_options: { include_usage: true },
})
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta
if (delta?.content) {
yield {
type: "text",
text: delta.content,
}
}
if (delta && "reasoning_content" in delta && delta.reasoning_content) {
yield {
type: "reasoning",
reasoning: (delta.reasoning_content as string | undefined) || "",
}
}
if (chunk.usage) {
yield {
type: "usage",
inputTokens: chunk.usage.prompt_tokens || 0,
outputTokens: chunk.usage.completion_tokens || 0,
}
}
}
}
getModel(): { id: NousResearchModelId; info: ModelInfo } {
const modelId = this.options.apiModelId
if (modelId && modelId in nousResearchModels) {
const id = modelId as NousResearchModelId
return { id, info: nousResearchModels[id] }
}
return { id: nousResearchDefaultModelId, info: nousResearchModels[nousResearchDefaultModelId] }
}
}
+7 -7
View File
@@ -1,7 +1,5 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { LiteLLMModelInfo, liteLlmDefaultModelId, liteLlmModelInfoSaneDefaults } from "@shared/api"
import OpenAI, { APIError, OpenAIError } from "openai"
import type { FinalRequestOptions, Headers as OpenAIHeaders } from "openai/core"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { OcaAuthService } from "@/services/auth/oca/OcaAuthService"
import {
@@ -11,6 +9,7 @@ import {
} from "@/services/auth/oca/utils/constants"
import { createOcaHeaders } from "@/services/auth/oca/utils/utils"
import { Logger } from "@/services/logging/Logger"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, type CommonApiHandlerOptions } from ".."
import { withRetry } from "../retry"
@@ -38,7 +37,7 @@ export class OcaHandler implements ApiHandler {
protected initializeClient(options: OcaHandlerOptions) {
return new (class OCIOpenAI extends OpenAI {
protected override async prepareOptions(opts: FinalRequestOptions<unknown>): Promise<void> {
protected override async prepareOptions(opts: any): Promise<void> {
const token = await OcaAuthService.getInstance().getAuthToken()
if (!token) {
throw new OpenAIError("Unable to handle auth, Oracle Code Assist (OCA) access token is not available")
@@ -55,7 +54,7 @@ export class OcaHandler implements ApiHandler {
status: number | undefined,
error: Object | undefined,
message: string | undefined,
headers: OpenAIHeaders | undefined,
headers: any | undefined,
): APIError {
interface OciError {
code?: string
@@ -75,7 +74,8 @@ export class OcaHandler implements ApiHandler {
if (opcRequestId) {
ociErrorMessage += `\n(${OCI_HEADER_OPC_REQUEST_ID}: ${opcRequestId})`
}
return super.makeStatusError(status, error, ociErrorMessage, headers)
const statusCode = typeof status === "number" ? status : 500
return super.makeStatusError(statusCode, error ?? {}, ociErrorMessage, headers)
}
})({
baseURL:
@@ -139,7 +139,7 @@ export class OcaHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const formattedMessages = convertToOpenAiMessages(messages)
const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam = {
@@ -151,7 +151,7 @@ export class OcaHandler implements ApiHandler {
// Configuration for extended thinking
const budgetTokens = this.options.thinkingBudgetTokens || 0
const reasoningOn = budgetTokens !== 0 ? true : false
const reasoningOn = budgetTokens !== 0
const thinkingConfig = reasoningOn ? { type: "enabled", budget_tokens: budgetTokens } : undefined
let temperature: number | undefined = this.options.ocaModelInfo?.temperature ?? 0
+2 -2
View File
@@ -1,6 +1,6 @@
import type { Anthropic } from "@anthropic-ai/sdk"
import { type ModelInfo, openAiModelInfoSaneDefaults } from "@shared/api"
import { type Config, type Message, Ollama } from "ollama"
import { ClineStorageMessage } from "@/shared/messages/content"
import type { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToOllamaMessages } from "../transform/ollama-format"
@@ -48,7 +48,7 @@ export class OllamaHandler implements ApiHandler {
}
@withRetry({ retryAllErrors: true })
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
const client = this.ensureClient()
const ollamaMessages: Message[] = [{ role: "system", content: systemPrompt }, ...convertToOllamaMessages(messages)]
+223 -2
View File
@@ -1,12 +1,14 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, OpenAiNativeModelId, openAiNativeDefaultModelId, openAiNativeModels } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import OpenAI from "openai"
import type { ChatCompletionReasoningEffort, ChatCompletionTool } from "openai/resources/chat/completions"
import { Logger } from "@/services/logging/Logger"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
import { convertToOpenAiMessages } from "../transform/openai-format"
import { convertToOpenAIResponsesInput } from "../transform/openai-response-format"
import { ApiStream } from "../transform/stream"
import { getOpenAIToolParams, ToolCallProcessor } from "../transform/tool-call-processor"
@@ -61,7 +63,20 @@ export class OpenAiNativeHandler implements ApiHandler {
@withRetry()
async *createMessage(
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
messages: ClineStorageMessage[],
tools?: ChatCompletionTool[],
useResponseFormat = false,
): ApiStream {
if (useResponseFormat) {
yield* this.createResponseStream(systemPrompt, messages, tools)
} else {
yield* this.createCompletionStream(systemPrompt, messages, tools)
}
}
private async *createCompletionStream(
systemPrompt: string,
messages: ClineStorageMessage[],
tools?: ChatCompletionTool[],
): ApiStream {
const client = this.ensureClient()
@@ -115,6 +130,9 @@ export class OpenAiNativeHandler implements ApiHandler {
case "gpt-5-2025-08-07":
case "gpt-5-mini-2025-08-07":
case "gpt-5-nano-2025-08-07":
case "gpt-5.1-2025-11-13":
case "gpt-5.1-chat-latest":
case "gpt-5.1": {
const stream = await client.chat.completions.create({
model: model.id,
temperature: 1,
@@ -148,6 +166,7 @@ export class OpenAiNativeHandler implements ApiHandler {
}
}
break
}
default: {
const stream = await client.chat.completions.create({
model: model.id,
@@ -181,6 +200,208 @@ export class OpenAiNativeHandler implements ApiHandler {
}
}
private async *createResponseStream(
systemPrompt: string,
messages: ClineStorageMessage[],
tools?: ChatCompletionTool[],
): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
// Convert messages to Responses API input format
const input = convertToOpenAIResponsesInput(messages)
// Convert ChatCompletion tools to Responses API format if provided
const responseTools = tools
?.filter((tool) => tool.type === "function")
.map((tool: any) => ({
type: "function" as const,
name: tool.function.name,
description: tool.function.description,
parameters: tool.function.parameters,
strict: tool.function.strict ?? true, // Responses API defaults to strict mode
}))
Logger.debug("OpenAI Responses Input: " + JSON.stringify(input))
// const lastAssistantMessage = [...messages].reverse().find((msg) => msg.role === "assistant" && msg.id)
// const previous_response_id = lastAssistantMessage?.id
// Create the response using Responses API
const stream = await client.responses.create({
model: model.id,
instructions: systemPrompt,
input,
stream: true,
tools: responseTools,
// previous_response_id,
// store: true,
reasoning: { effort: "medium", summary: "auto" },
// include: ["reasoning.encrypted_content"],
})
// Process the response stream
for await (const chunk of stream) {
Logger.debug("OpenAI Responses Chunk: " + JSON.stringify(chunk))
// Handle different event types from Responses API
if (chunk.type === "response.output_item.added") {
const item = chunk.item
if (item.type === "function_call" && item.id) {
yield {
type: "tool_calls",
id: item.id,
tool_call: {
call_id: item.call_id,
function: {
id: item.id,
name: item.name,
arguments: item.arguments,
},
},
}
}
if (item.type === "reasoning" && item.encrypted_content && item.id) {
yield {
type: "reasoning",
id: item.id,
reasoning: "",
redacted_data: item.encrypted_content,
}
}
}
if (chunk.type === "response.output_item.done") {
const item = chunk.item
if (item.type === "function_call") {
yield {
type: "tool_calls",
id: item.id || item.call_id,
tool_call: {
call_id: item.call_id,
function: {
id: item.id,
name: item.name,
arguments: item.arguments,
},
},
}
}
if (item.type === "reasoning") {
yield {
type: "reasoning",
id: item.id,
details: item.summary,
reasoning: "",
}
}
}
if (chunk.type === "response.reasoning_summary_part.added") {
yield {
type: "reasoning",
id: chunk.item_id,
reasoning: chunk.part.text,
}
}
if (chunk.type === "response.reasoning_summary_text.delta") {
yield {
type: "reasoning",
id: chunk.item_id,
reasoning: chunk.delta,
}
}
if (chunk.type === "response.reasoning_summary_part.done") {
yield {
type: "reasoning",
id: chunk.item_id,
details: chunk.part,
reasoning: "",
}
}
if (chunk.type === "response.output_text.delta") {
// Handle text content deltas
if (chunk.delta) {
yield {
id: chunk.item_id,
type: "text",
text: chunk.delta,
}
}
}
if (chunk.type === "response.reasoning_text.delta") {
// Handle reasoning content deltas
if (chunk.delta) {
yield {
id: chunk.item_id,
type: "reasoning",
reasoning: chunk.delta,
}
}
}
if (chunk.type === "response.function_call_arguments.delta") {
yield {
type: "tool_calls",
tool_call: {
function: {
id: chunk.item_id,
name: chunk.item_id,
arguments: chunk.delta,
},
},
}
}
if (chunk.type === "response.function_call_arguments.done") {
// Handle completed function call
if (chunk.item_id && chunk.name && chunk.arguments) {
yield {
type: "tool_calls",
tool_call: {
function: {
id: chunk.item_id,
name: chunk.name,
arguments: chunk.arguments,
},
},
}
}
}
if (
chunk.type === "response.incomplete" &&
chunk.response?.status === "incomplete" &&
chunk.response?.incomplete_details?.reason === "max_output_tokens"
) {
console.log("Ran out of tokens")
if (chunk.response?.output_text?.length > 0) {
console.log("Partial output:", chunk.response.output_text)
} else {
console.log("Ran out of tokens during reasoning")
}
}
if (chunk.type === "response.completed" && chunk.response?.usage) {
// Handle usage information when response is complete
const usage = chunk.response.usage
const inputTokens = usage.input_tokens || 0
const outputTokens = usage.output_tokens || 0
const cacheReadTokens = usage.output_tokens_details?.reasoning_tokens || 0
const cacheWriteTokens = usage.input_tokens_details?.cached_tokens || 0
const totalTokens = usage.total_tokens || 0
Logger.log(`Total tokens from Responses API usage: ${totalTokens}`)
const totalCost = calculateApiCostOpenAI(model.info, inputTokens, outputTokens, cacheWriteTokens, cacheReadTokens)
const nonCachedInputTokens = Math.max(0, inputTokens - cacheReadTokens - cacheWriteTokens)
yield {
type: "usage",
inputTokens: nonCachedInputTokens,
outputTokens: outputTokens,
cacheWriteTokens: cacheWriteTokens,
cacheReadTokens: cacheReadTokens,
totalCost: totalCost,
id: chunk.response.id,
}
}
}
}
getModel(): { id: OpenAiNativeModelId; info: ModelInfo } {
const modelId = this.options.apiModelId
if (modelId && modelId in openAiNativeModels) {
+9 -7
View File
@@ -1,7 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { azureOpenAiDefaultApiVersion, ModelInfo, OpenAiCompatibleModelInfo, openAiModelInfoSaneDefaults } from "@shared/api"
import OpenAI, { AzureOpenAI } from "openai"
import type { ChatCompletionReasoningEffort, ChatCompletionTool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
@@ -65,11 +65,7 @@ export class OpenAiHandler implements ApiHandler {
}
@withRetry()
async *createMessage(
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
tools?: ChatCompletionTool[],
): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: ChatCompletionTool[]): ApiStream {
const client = this.ensureClient()
const modelId = this.options.openAiModelId ?? ""
const isDeepseekReasoner = modelId.includes("deepseek-reasoner")
@@ -81,7 +77,13 @@ export class OpenAiHandler implements ApiHandler {
{ role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages),
]
let temperature: number | undefined = this.options.openAiModelInfo?.temperature ?? openAiModelInfoSaneDefaults.temperature
let temperature: number | undefined
if (this.options.openAiModelInfo?.temperature !== undefined) {
const tempValue = Number(this.options.openAiModelInfo.temperature)
temperature = tempValue === 0 ? undefined : tempValue
} else {
temperature = openAiModelInfoSaneDefaults.temperature
}
let reasoningEffort: ChatCompletionReasoningEffort | undefined
let maxTokens: number | undefined
+14 -11
View File
@@ -1,10 +1,11 @@
import { setTimeout as setTimeoutPromise } from "node:timers/promises"
import { Anthropic } from "@anthropic-ai/sdk"
import { StateManager } from "@core/storage/StateManager"
import { ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo } from "@shared/api"
import { shouldSkipReasoningForModel } from "@utils/model-utils"
import axios from "axios"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch, getAxiosSettings } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -20,6 +21,7 @@ interface OpenRouterHandlerOptions extends CommonApiHandlerOptions {
openRouterProviderSorting?: string
reasoningEffort?: string
thinkingBudgetTokens?: number
geminiThinkingLevel?: string
}
export class OpenRouterHandler implements ApiHandler {
@@ -54,7 +56,7 @@ export class OpenRouterHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
this.lastGenerationId = undefined
@@ -67,6 +69,7 @@ export class OpenRouterHandler implements ApiHandler {
this.options.thinkingBudgetTokens,
this.options.openRouterProviderSorting,
tools,
this.options.geminiThinkingLevel,
)
let didOutputUsage: boolean = false
@@ -127,8 +130,7 @@ export class OpenRouterHandler implements ApiHandler {
if ("reasoning" in delta && delta.reasoning && !shouldSkipReasoningForModel(this.options.openRouterModelId)) {
yield {
type: "reasoning",
// @ts-ignore-next-line
reasoning: delta.reasoning,
reasoning: typeof delta.reasoning === "string" ? delta.reasoning : JSON.stringify(delta.reasoning),
}
}
@@ -142,8 +144,9 @@ export class OpenRouterHandler implements ApiHandler {
!shouldSkipReasoningForModel(this.options.openRouterModelId)
) {
yield {
type: "reasoning_details",
reasoning_details: delta.reasoning_details,
type: "reasoning",
reasoning: "",
details: delta.reasoning_details,
}
}
@@ -214,11 +217,11 @@ export class OpenRouterHandler implements ApiHandler {
}
getModel(): { id: string; info: ModelInfo } {
const modelId = this.options.openRouterModelId
const modelInfo = this.options.openRouterModelInfo
if (modelId && modelInfo) {
return { id: modelId, info: modelInfo }
const modelId = this.options.openRouterModelId || openRouterDefaultModelId
const cachedModelInfo = StateManager.get().getModelInfo("openRouter", modelId)
return {
id: modelId,
info: cachedModelInfo || openRouterDefaultModelInfo,
}
return { id: openRouterDefaultModelId, info: openRouterDefaultModelInfo }
}
}
+2 -2
View File
@@ -1,10 +1,10 @@
import { promises as fs } from "node:fs"
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, QwenCodeModelId, qwenCodeDefaultModelId, qwenCodeModels } from "@shared/api"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import * as os from "os"
import * as path from "path"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -177,7 +177,7 @@ export class QwenCodeHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
await this.ensureAuthenticated()
const client = this.ensureClient()
const model = this.getModel()
+2 -2
View File
@@ -1,4 +1,3 @@
import { Anthropic } from "@anthropic-ai/sdk"
import {
InternationalQwenModelId,
internationalQwenDefaultModelId,
@@ -11,6 +10,7 @@ import {
} from "@shared/api"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -81,7 +81,7 @@ export class QwenHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const isDeepseekReasoner = model.id.includes("deepseek-r1")
+2 -2
View File
@@ -1,8 +1,8 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, requestyDefaultModelId, requestyDefaultModelInfo } from "@shared/api"
import { calculateApiCostOpenAI } from "@utils/cost"
import OpenAI from "openai"
import { toRequestyServiceStringUrl } from "@/shared/clients/requesty"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
@@ -59,7 +59,7 @@ export class RequestyHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
+2 -2
View File
@@ -1,7 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, SambanovaModelId, sambanovaDefaultModelId, sambanovaModels } from "@shared/api"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
@@ -42,7 +42,7 @@ export class SambanovaHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
+26 -23
View File
@@ -4,10 +4,11 @@ import {
ConversationRole as BedrockConversationRole,
type Message as BedrockMessage,
} from "@aws-sdk/client-bedrock-runtime"
import { ChatMessages, LlmModuleConfig, OrchestrationClient, TemplatingModuleConfig } from "@sap-ai-sdk/orchestration"
import { ChatMessage, OrchestrationClient, OrchestrationModuleConfig } from "@sap-ai-sdk/orchestration"
import { ModelInfo, SapAiCoreModelId, sapAiCoreDefaultModelId, sapAiCoreModels } from "@shared/api"
import axios from "axios"
import OpenAI from "openai"
import { ClineStorageMessage } from "@/shared/messages/content"
import { getAxiosSettings } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -115,7 +116,7 @@ namespace Bedrock {
* Formats messages for models using the Converse API specification
* Used by both Anthropic and Nova models to avoid code duplication
*/
export function formatMessagesForConverseAPI(messages: Anthropic.Messages.MessageParam[]): BedrockMessage[] {
export function formatMessagesForConverseAPI(messages: ClineStorageMessage[]): BedrockMessage[] {
return messages.map((message) => {
// Determine role (user or assistant)
const role = message.role === "user" ? BedrockConversationRole.USER : BedrockConversationRole.ASSISTANT
@@ -315,7 +316,7 @@ namespace Gemini {
*/
export function prepareRequestPayload(
systemPrompt: string,
messages: Anthropic.Messages.MessageParam[],
messages: ClineStorageMessage[],
model: { id: SapAiCoreModelId; info: ModelInfo },
thinkingBudgetTokens?: number,
): any {
@@ -458,7 +459,7 @@ export class SapAiCoreHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
if (this.options.sapAiCoreUseOrchestrationMode) {
yield* this.createMessageWithOrchestration(systemPrompt, messages)
} else {
@@ -490,29 +491,31 @@ export class SapAiCoreHandler implements ApiHandler {
this.isAiCoreEnvSetup = true
}
private async *createMessageWithOrchestration(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
private async *createMessageWithOrchestration(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
try {
// Ensure AI Core environment variable is set up (only runs once)
this.ensureAiCoreEnvSetup()
const model = this.getModel()
// Define the LLM to be used by the Orchestration pipeline
const llm: LlmModuleConfig = {
model_name: model.id,
const orchestrationConfig: OrchestrationModuleConfig = {
promptTemplating: {
model: {
name: model.id,
},
prompt: {
template: [
{
role: "system",
content: systemPrompt,
},
],
},
},
}
const templating: TemplatingModuleConfig = {
template: [
{
role: "system",
content: systemPrompt,
},
],
}
const orchestrationClient = new OrchestrationClient(
{ llm, templating },
{ resourceGroup: this.options.sapAiResourceGroup || "default" },
)
const orchestrationClient = new OrchestrationClient(orchestrationConfig, {
resourceGroup: this.options.sapAiResourceGroup || "default",
})
const sapMessages = this.convertMessageParamToSAPMessages(messages)
@@ -538,7 +541,7 @@ export class SapAiCoreHandler implements ApiHandler {
}
}
private async *createMessageWithDeployments(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
private async *createMessageWithDeployments(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
const token = await this.getToken()
const headers = {
Authorization: `Bearer ${token}`,
@@ -1040,8 +1043,8 @@ export class SapAiCoreHandler implements ApiHandler {
}
return { id: sapAiCoreDefaultModelId, info: sapAiCoreModels[sapAiCoreDefaultModelId] }
}
private convertMessageParamToSAPMessages(messages: Anthropic.Messages.MessageParam[]): ChatMessages {
private convertMessageParamToSAPMessages(messages: ClineStorageMessage[]): ChatMessage[] {
// Use the existing OpenAI converter since the logic is identical
return convertToOpenAiMessages(messages) as ChatMessages
return convertToOpenAiMessages(messages) as ChatMessage[]
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, openAiModelInfoSaneDefaults } from "@shared/api"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
@@ -42,7 +42,7 @@ export class TogetherHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const modelId = this.options.togetherModelId ?? ""
const isDeepseekReasoner = modelId.includes("deepseek-reasoner")
+12 -18
View File
@@ -1,7 +1,7 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, openRouterDefaultModelId, openRouterDefaultModelInfo } from "@shared/api"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../index"
import { withRetry } from "../retry"
@@ -47,7 +47,7 @@ export class VercelAIGatewayHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const modelId = this.getModel().id
const modelInfo = this.getModel().info
@@ -82,8 +82,7 @@ export class VercelAIGatewayHandler implements ApiHandler {
if ("reasoning" in delta && delta.reasoning) {
yield {
type: "reasoning",
// @ts-ignore-next-line
reasoning: delta.reasoning,
reasoning: typeof delta.reasoning === "string" ? delta.reasoning : JSON.stringify(delta.reasoning),
}
}
@@ -95,28 +94,23 @@ export class VercelAIGatewayHandler implements ApiHandler {
delta.reasoning_details.length // exists and non-0
) {
yield {
type: "reasoning_details",
reasoning_details: delta.reasoning_details,
type: "reasoning",
reasoning: "",
details: delta.reasoning_details,
}
}
if (!didOutputUsage && chunk.usage) {
const inputTokens = chunk.usage.prompt_tokens || 0
const outputTokens =
(chunk.usage.completion_tokens || 0) + (chunk.usage.completion_tokens_details?.reasoning_tokens || 0)
const cacheReadTokens = chunk.usage.prompt_tokens_details?.cached_tokens || 0
// @ts-ignore - Vercel AI Gateway extends OpenAI types
const cacheWriteTokens = chunk.usage.cache_creation_input_tokens || 0
const totalCost = (chunk.usage.cost || 0) + (chunk.usage.cost_details?.upstream_inference_cost || 0)
yield {
type: "usage",
inputTokens: inputTokens,
outputTokens: outputTokens,
cacheWriteTokens: cacheWriteTokens,
cacheReadTokens: cacheReadTokens,
// @ts-expect-error - Vercel AI Gateway extends OpenAI types
totalCost: chunk.usage.cost || 0,
cacheWriteTokens: 0,
cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0,
inputTokens: (chunk.usage.prompt_tokens || 0) - (chunk.usage.prompt_tokens_details?.cached_tokens || 0),
outputTokens: chunk.usage.completion_tokens || 0,
totalCost,
}
didOutputUsage = true
}
+6 -12
View File
@@ -1,8 +1,8 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Tool as AnthropicTool } from "@anthropic-ai/sdk/resources/index"
import { AnthropicVertex } from "@anthropic-ai/vertex-sdk"
import { FunctionDeclaration as GoogleTool } from "@google/genai"
import { ModelInfo, VertexModelId, vertexDefaultModelId, vertexModels } from "@shared/api"
import { ClineStorageMessage } from "@/shared/messages/content"
import { ClineTool } from "@/shared/tools"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -67,7 +67,7 @@ export class VertexHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: ClineTool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: ClineTool[]): ApiStream {
const model = this.getModel()
const modelId = model.id
@@ -103,13 +103,6 @@ export class VertexHandler implements ApiHandler {
case "claude-3-5-haiku@20241022":
case "claude-3-opus@20240229":
case "claude-3-haiku@20240307": {
// Find indices of user messages for cache control
const userMsgIndices = messages.reduce(
(acc, msg, index) => (msg.role === "user" ? [...acc, index] : acc),
[] as number[],
)
const lastUserMsgIndex = userMsgIndices[userMsgIndices.length - 1] ?? -1
const secondLastMsgUserIndex = userMsgIndices[userMsgIndices.length - 2] ?? -1
stream = await clientAnthropic.beta.messages.create(
{
model: modelId,
@@ -123,7 +116,7 @@ export class VertexHandler implements ApiHandler {
cache_control: { type: "ephemeral" },
},
],
messages: sanitizeAnthropicMessages(messages, lastUserMsgIndex, secondLastMsgUserIndex),
messages: sanitizeAnthropicMessages(messages, true),
stream: true,
tools: tools?.length ? (tools as AnthropicTool[]) : undefined,
// tool_choice options:
@@ -149,7 +142,7 @@ export class VertexHandler implements ApiHandler {
type: "text",
},
],
messages: sanitizeAnthropicMessages(messages),
messages: sanitizeAnthropicMessages(messages, false),
stream: true,
tools: tools?.length ? (tools as AnthropicTool[]) : undefined,
// tool_choice options:
@@ -166,7 +159,7 @@ export class VertexHandler implements ApiHandler {
for await (const chunk of stream) {
switch (chunk?.type) {
case "message_start":
case "message_start": {
const usage = chunk.message.usage
yield {
type: "usage",
@@ -176,6 +169,7 @@ export class VertexHandler implements ApiHandler {
cacheReadTokens: usage.cache_read_input_tokens || undefined,
}
break
}
case "message_delta":
yield {
type: "usage",
+2 -2
View File
@@ -1,8 +1,8 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, openAiModelInfoSaneDefaults } from "@shared/api"
import { SELECTOR_SEPARATOR, stringifyVsCodeLmModelSelector } from "@shared/vsCodeSelectorUtils"
import { calculateApiCostAnthropic } from "@utils/cost"
import * as vscode from "vscode"
import { ClineStorageMessage } from "@/shared/messages/content"
import { ApiHandler, CommonApiHandlerOptions, SingleCompletionHandler } from "../"
import { withRetry } from "../retry"
import { ApiStream } from "../transform/stream"
@@ -366,7 +366,7 @@ export class VsCodeLmHandler implements ApiHandler, SingleCompletionHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[]): ApiStream {
// Ensure clean state before starting a new request
this.ensureCleanState()
const client: vscode.LanguageModelChat = await this.getClient()
+2 -2
View File
@@ -1,9 +1,9 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { ModelInfo, XAIModelId, xaiDefaultModelId, xaiModels } from "@shared/api"
import { shouldSkipReasoningForModel } from "@utils/model-utils"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ChatCompletionReasoningEffort } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { ApiHandler, CommonApiHandlerOptions } from "../"
import { withRetry } from "../retry"
@@ -44,7 +44,7 @@ export class XAIHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const modelId = this.getModel().id
// ensure reasoning effort is either "low" or "high" for grok-3-mini
+2 -2
View File
@@ -1,4 +1,3 @@
import { Anthropic } from "@anthropic-ai/sdk"
import {
internationalZAiDefaultModelId,
internationalZAiModelId,
@@ -10,6 +9,7 @@ import {
} from "@shared/api"
import OpenAI from "openai"
import type { ChatCompletionTool as OpenAITool } from "openai/resources/chat/completions"
import { ClineStorageMessage } from "@/shared/messages/content"
import { fetch } from "@/shared/net"
import { version as extensionVersion } from "../../../../package.json"
import { ApiHandler, CommonApiHandlerOptions } from ".."
@@ -76,7 +76,7 @@ export class ZAiHandler implements ApiHandler {
}
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[], tools?: OpenAITool[]): ApiStream {
async *createMessage(systemPrompt: string, messages: ClineStorageMessage[], tools?: OpenAITool[]): ApiStream {
const client = this.ensureClient()
const model = this.getModel()
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
+74 -61
View File
@@ -1,77 +1,90 @@
import { MessageParam } from "@anthropic-ai/sdk/resources/index"
import { Anthropic } from "@anthropic-ai/sdk"
import { ClineStorageMessage, convertClineStorageToAnthropicMessage } from "@/shared/messages/content"
/**
* Sanitize Anthropic messages by removing reasoning details and adding ephemeral cache control
* to the last two user messages to prevent them from being stored in Anthropic's cache.
* Converts Cline storage messages to Anthropic API format with optional cache control.
* Adds ephemeral cache control to the last two user messages to prevent them from being
* stored in Anthropic's cache.
*
* @param clineMessages - Array of Cline storage messages to convert
* @param lastUserMsgIndex - Optional index of the last user message
* @param secondLastMsgUserIndex - Optional index of the second-to-last user message
* @returns Array of Anthropic-compatible messages with cache control applied
*/
export function sanitizeAnthropicMessages(
messages: Array<MessageParam>,
lastUserMsgIndex?: number,
secondLastMsgUserIndex?: number,
): Array<MessageParam> {
return messages.map((_message, index) => {
const message = removeReasoningDetails(_message)
const addCacheControl = lastUserMsgIndex !== undefined && secondLastMsgUserIndex !== undefined
clineMessages: Array<ClineStorageMessage | Anthropic.MessageParam>,
supportCache: boolean,
): Array<Anthropic.MessageParam> {
// The latest message will be the new user message, one before will be the assistant message from a previous request,
// and the user message before that will be a previously cached user message. So we need to mark the latest user message
// as ephemeral to cache it for the next request, and mark the second to last user message as ephemeral to let the server
// know the last message to retrieve from the cache for the current request.
const userMsgIndices = clineMessages.reduce((acc, msg, index) => {
if (msg.role === "user") {
acc.push(index)
}
return acc
}, [] as number[])
// Set to -1 if there are no user messages so the indices are invalid
const indicesLength = userMsgIndices.length ?? -1
const lastUserMsgIndex = userMsgIndices[indicesLength - 1]
const secondLastMsgUserIndex = userMsgIndices[indicesLength - 2]
if (addCacheControl && (index === lastUserMsgIndex || index === secondLastMsgUserIndex)) {
return {
...message,
content:
typeof message.content === "string"
? [
{
type: "text",
text: message.content,
cache_control: {
type: "ephemeral",
},
},
]
: message.content.map((content, contentIndex) =>
contentIndex === message.content.length - 1
? {
...content,
cache_control: {
type: "ephemeral",
},
}
: content,
),
}
return clineMessages.map((msg, index) => {
const anthropicMsg = convertClineStorageToAnthropicMessage(msg)
// Add cache control to the last two user messages
if (supportCache && (index === lastUserMsgIndex || index === secondLastMsgUserIndex)) {
return addCacheControl(anthropicMsg)
}
return {
...message,
content:
typeof message.content === "string"
? [
{
type: "text",
text: message.content,
},
]
: message.content,
}
return anthropicMsg
})
}
const isThinkingBlock = (
block: Anthropic.ContentBlockParam,
): block is Anthropic.Messages.ThinkingBlockParam | Anthropic.Messages.RedactedThinkingBlockParam => {
return block.type === "thinking" || block.type === "redacted_thinking"
}
/**
* Remove reasoning details from a single Anthropic message parameter
* Adds ephemeral cache control to the last content block of a message.
* Returns a new message object without mutating the original.
*
* @param message - The Anthropic message to add cache control to
* @returns A new message with cache control added to the last content block
*/
function removeReasoningDetails(param: MessageParam): MessageParam {
if (Array.isArray(param.content)) {
function addCacheControl(message: Anthropic.MessageParam): Anthropic.MessageParam {
// Convert string content to array format
if (typeof message.content === "string") {
return {
...param,
content: param.content.map((item) => {
if (item.type === "text") {
return {
...item,
reasoning_details: undefined,
}
}
return item
}),
...message,
content: [
{
type: "text",
text: message.content,
cache_control: { type: "ephemeral" },
} satisfies Anthropic.TextBlockParam,
],
}
}
return param
// Handle array content - add cache control to the last block
const content = [...message.content]
const lastIndex = content.length - 1
if (lastIndex >= 0) {
const lastBlock = content[lastIndex]
// Only add cache_control to block types that support it (not ThinkingBlockParam)
if (!isThinkingBlock(lastBlock)) {
content[lastIndex] = {
...lastBlock,
cache_control: { type: "ephemeral" },
} satisfies Anthropic.ContentBlockParam
}
}
return { ...message, content }
}
+4 -2
View File
@@ -1,7 +1,8 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Content, GenerateContentResponse, Part } from "@google/genai"
import { ClineStorageMessage } from "@/shared/messages/content"
export function convertAnthropicContentToGemini(content: string | Anthropic.ContentBlockParam[]): Part[] {
export function convertAnthropicContentToGemini(content: string | ClineStorageMessage["content"]): Part[] {
if (typeof content === "string") {
return [{ text: content }]
}
@@ -9,7 +10,7 @@ export function convertAnthropicContentToGemini(content: string | Anthropic.Cont
.flatMap((block): Part | undefined => {
switch (block.type) {
case "text":
return { text: block.text }
return { text: block.text, thoughtSignature: block.signature }
case "image":
if (block.source.type !== "base64") {
throw new Error("Unsupported image source type")
@@ -26,6 +27,7 @@ export function convertAnthropicContentToGemini(content: string | Anthropic.Cont
name: block.name,
args: block.input as Record<string, unknown>,
},
thoughtSignature: block.signature,
}
case "tool_result":
return {
+12 -6
View File
@@ -1,7 +1,13 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Message } from "ollama"
import {
ClineAssistantToolUseBlock,
ClineImageContentBlock,
ClineStorageMessage,
ClineTextContentBlock,
ClineUserToolResultContentBlock,
} from "@/shared/messages/content"
export function convertToOllamaMessages(anthropicMessages: Anthropic.Messages.MessageParam[]): Message[] {
export function convertToOllamaMessages(anthropicMessages: Omit<ClineStorageMessage, "modelInfo">[]): Message[] {
const ollamaMessages: Message[] = []
for (const anthropicMessage of anthropicMessages) {
@@ -13,8 +19,8 @@ export function convertToOllamaMessages(anthropicMessages: Anthropic.Messages.Me
} else {
if (anthropicMessage.role === "user") {
const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{
nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[]
toolMessages: Anthropic.ToolResultBlockParam[]
nonToolMessages: (ClineTextContentBlock | ClineImageContentBlock)[]
toolMessages: ClineUserToolResultContentBlock[]
}>(
(acc, part) => {
if (part.type === "tool_result") {
@@ -70,8 +76,8 @@ export function convertToOllamaMessages(anthropicMessages: Anthropic.Messages.Me
}
} else if (anthropicMessage.role === "assistant") {
const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{
nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[]
toolMessages: Anthropic.ToolUseBlockParam[]
nonToolMessages: (ClineTextContentBlock | ClineImageContentBlock)[]
toolMessages: ClineAssistantToolUseBlock[]
}>(
(acc, part) => {
if (part.type === "tool_use") {
+70 -30
View File
@@ -1,8 +1,26 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import {
ClineAssistantRedactedThinkingBlock,
ClineAssistantThinkingBlock,
ClineAssistantToolUseBlock,
ClineImageContentBlock,
ClineStorageMessage,
ClineTextContentBlock,
ClineUserToolResultContentBlock,
} from "@/shared/messages/content"
/**
* Converts an array of ClineStorageMessage objects to OpenAI's Completions API format.
*
* Handles conversion of Cline-specific content types (tool uses, tool results, images, reasoning details)
* into OpenAI's expected message structure, including tool_calls and tool_call_id fields.
*
* @param anthropicMessages - Array of ClineStorageMessage objects to be converted
* @returns Array of OpenAI.Chat.ChatCompletionMessageParam objects
*/
export function convertToOpenAiMessages(
anthropicMessages: Anthropic.Messages.MessageParam[],
anthropicMessages: Omit<ClineStorageMessage, "modelInfo">[],
): OpenAI.Chat.ChatCompletionMessageParam[] {
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = []
@@ -23,8 +41,8 @@ export function convertToOpenAiMessages(
*/
if (anthropicMessage.role === "user") {
const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{
nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[]
toolMessages: Anthropic.ToolResultBlockParam[]
nonToolMessages: (ClineTextContentBlock | ClineImageContentBlock)[]
toolMessages: ClineUserToolResultContentBlock[]
}>(
(acc, part) => {
if (part.type === "tool_result") {
@@ -38,7 +56,7 @@ export function convertToOpenAiMessages(
)
// Process tool result messages FIRST since they must follow the tool use messages
const toolResultImages: Anthropic.Messages.ImageBlockParam[] = []
const toolResultImages: ClineImageContentBlock[] = []
toolMessages.forEach((toolMessage) => {
// The Anthropic SDK allows tool results to be a string or an array of text and image blocks, enabling rich and structured content. In contrast, the OpenAI SDK only supports tool results as a single string, so we map the Anthropic tool result parts into one concatenated string to maintain compatibility.
let content: string
@@ -102,8 +120,13 @@ export function convertToOpenAiMessages(
}
} else if (anthropicMessage.role === "assistant") {
const { nonToolMessages, toolMessages } = anthropicMessage.content.reduce<{
nonToolMessages: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[]
toolMessages: Anthropic.ToolUseBlockParam[]
nonToolMessages: (
| ClineTextContentBlock
| ClineImageContentBlock
| ClineAssistantThinkingBlock
| ClineAssistantRedactedThinkingBlock
)[]
toolMessages: ClineAssistantToolUseBlock[]
}>(
(acc, part) => {
if (part.type === "tool_use") {
@@ -119,6 +142,7 @@ export function convertToOpenAiMessages(
// Process non-tool messages
let content: string | undefined
const reasoningDetails: any[] = []
const thinkingBlock = []
if (nonToolMessages.length > 0) {
nonToolMessages.forEach((part) => {
// @ts-ignore-next-line
@@ -134,27 +158,42 @@ export function convertToOpenAiMessages(
// @ts-ignore-next-line
// delete part.reasoning_details
}
if (part.type === "thinking" && part.thinking) {
// Reasoning details should have been moved to the text block
thinkingBlock.push(part)
}
})
content = nonToolMessages
.map((part) => {
if (part.type === "image") {
return "" // impossible as the assistant cannot send images
if (part.type === "text" && part.text) {
return part.text
}
return part.text
return ""
})
.join("\n")
}
// Process tool use messages
const tool_calls: OpenAI.Chat.ChatCompletionMessageToolCall[] = toolMessages.map((toolMessage) => ({
id: toolMessage.id,
type: "function",
function: {
name: toolMessage.name,
// json string
arguments: JSON.stringify(toolMessage.input),
},
}))
const tool_calls: OpenAI.Chat.ChatCompletionMessageToolCall[] = toolMessages.map((toolMessage) => {
const toolDetails = toolMessage.reasoning_details
if (toolDetails?.length) {
if (Array.isArray(toolDetails)) {
reasoningDetails.push(...toolDetails)
} else {
reasoningDetails.push(toolDetails)
}
}
return {
id: toolMessage.id,
type: "function",
function: {
name: toolMessage.name,
// json string
arguments: JSON.stringify(toolMessage.input),
},
}
})
// Set content to blank when tool_calls are present but content has no text, per OpenAI API spec
const hasToolCalls = tool_calls.length > 0
@@ -321,29 +360,30 @@ export function convertToAnthropicMessage(completion: OpenAI.Chat.Completions.Ch
}
try {
if (openAiMessage?.tool_calls?.length) {
anthropicMessage.content.push(
...openAiMessage.tool_calls
.map((toolCall): Anthropic.ToolUseBlock => {
const parsedName = toolCall.type === "function" && toolCall.function.name
let parsedInput = toolCall.function.arguments
const functionCalls = openAiMessage.tool_calls.filter((tc: any) => tc?.type === "function" && tc.function)
if (functionCalls.length > 0) {
anthropicMessage.content.push(
...functionCalls.map((toolCall: any): Anthropic.ToolUseBlock => {
let parsedInput = {}
try {
parsedInput = JSON.parse(toolCall.function.arguments || "{}")
parsedInput = JSON.parse(toolCall.function?.arguments || "{}")
} catch (error) {
console.error("Failed to parse tool arguments:", error)
}
return {
type: "tool_use",
id: toolCall.id,
name: parsedName || UNIQUE_ERROR_TOOL_NAME,
name: toolCall.function?.name || UNIQUE_ERROR_TOOL_NAME,
input: parsedInput,
}
})
// Filter out any tool uses with the UNIQUE_ERROR_TOOL_NAME, which indicates a parsing error
.filter((toolUse) => toolUse.name !== UNIQUE_ERROR_TOOL_NAME),
)
}),
)
}
return anthropicMessage
}
} catch (error) {
console.error("Failed to process tool calls:", error)
console.error("Error converting OpenAI message to Anthropic format:", error)
}
return anthropicMessage
@@ -0,0 +1,217 @@
import { ResponseInput, ResponseInputMessageContentList, ResponseReasoningItem } from "openai/resources/responses/responses"
import { ClineStorageMessage } from "@/shared/messages/content"
/**
* Converts an array of ClineStorageMessage objects (extension of Anthropic format) to a ResponseInput array to use with OpenAI's Responses API.
*
* ## Key Differences from Chat Completions API
*
* The Responses API has stricter requirements than the Chat Completions API:
*
* ### Chat Completions API:
* - Messages are simple role/content pairs
* - System prompts are separate messages with role="system"
* - No explicit reasoning item structure
* - More forgiving about message ordering
*
* ### Responses API:
* - Uses an "input" array of heterogeneous items (messages, reasoning, function_calls, etc.)
* - System prompts go in an "instructions" field, not as messages
* - Reasoning items MUST be immediately followed by a message or function_call
* - Strict ordering requirements match training data distribution
*
* ## The Reasoning Item Constraint
*
* **THE CRITICAL ERROR:** "Item 'rs_...' of type 'reasoning' was provided without its required following item"
*
* This error occurs when reasoning items are orphaned or separated from their corresponding output.
*
* ### What Causes This Error:
* ```
* WRONG - Reasoning orphaned between turns:
* [
* { role: "user", content: [...] },
* { type: "reasoning", id: "rs_abc", summary: [...] }, // ← ORPHANED!
* { type: "message", role: "assistant", content: [...] },
* { role: "user", content: [...] }
* ]
* ```
*
* ### The Fix - Keep Complete Assistant Turns Together:
* ```
* CORRECT - Reasoning paired with its message:
* [
* { role: "user", content: [...] },
* { type: "reasoning", id: "rs_abc", summary: [...] },
* { type: "message", role: "assistant", content: [...] }, // ← Immediately follows reasoning
* { role: "user", content: [...] }
* ]
* ```
*
* **Per OpenAI Engineering Guidance:**
* - WRONG: `content += filter(lambda x: x.type == "reasoning", resp.output)`
* - CORRECT: `content += resp.output`
*
* Never extract only reasoning items - always include the complete output sequence
* (reasoning + message/function_call) as provided by the API.
*
* ## Implementation Strategy
*
* 1. **Separate processing for assistant vs user messages** - Assistant turns need special
* handling to maintain reasoning-message pairing
* 2. **Collect all assistant items together** - Gather reasoning, messages, and function_calls
* for the entire assistant turn before validating
* 3. **Validate pairing within each turn** - Ensure each reasoning item is immediately followed
* by a message or function_call, inserting placeholders if needed
* 4. **Flush complete turns atomically** - Add all items from an assistant turn together to
* maintain proper sequencing
*
* @link https://community.openai.com/t/openai-api-error-function-call-was-provided-without-its-required-reasoning-item-the-real-issue/1355347
*
* @param messages - Array of ClineStorageMessage objects to be converted
* @returns ResponseInput array containing the transformed messages with proper reasoning pairing
*/
export function convertToOpenAIResponsesInput(messages: ClineStorageMessage[]): ResponseInput {
const allItems: any[] = []
const toolUseIdToCallId = new Map<string, string>()
for (const m of messages) {
if (typeof m.content === "string") {
allItems.push({ role: m.role, content: [{ type: "input_text", text: m.content }] })
continue
}
if (m.role === "assistant") {
// For assistant messages, we must ensure reasoning items are IMMEDIATELY followed
// by their corresponding message or function_call. Process the entire assistant
// turn and ensure proper pairing.
const assistantItems: any[] = []
for (const part of m.content) {
switch (part.type) {
case "thinking":
// Include reasoning item if it has a call_id, even if thinking is empty
// This is required because the API expects reasoning items to be paired with
// their corresponding function_calls, and will error if a function_call
// references a reasoning item that wasn't sent
if (part.call_id && part.call_id.length > 0) {
assistantItems.push({
id: part.call_id,
type: "reasoning",
summary: part.thinking
? [
{
type: "summary_text",
text: part.thinking,
},
]
: [],
} as ResponseReasoningItem)
}
break
case "redacted_thinking":
// Include reasoning item with encrypted content if it has a call_id
// Even if data is missing, we need to maintain the reasoning-function_call pairing
if (part.call_id && part.call_id.length > 0) {
const reasoningItem: any = {
id: part.call_id,
type: "reasoning",
summary: [],
}
// Only include encrypted_content if data exists
if (part.data) {
reasoningItem.encrypted_content = part.data
}
assistantItems.push(reasoningItem as ResponseReasoningItem)
}
break
case "text":
assistantItems.push({
type: "message",
role: "assistant",
content: [{ type: "output_text", text: part.text }],
})
break
case "image":
assistantItems.push({
type: "message",
role: "assistant",
content: [{ type: "output_text", text: `[image:${part.source.media_type}]` }],
})
break
case "tool_use": {
const call_id = part.call_id || part.id
if (part.call_id) {
toolUseIdToCallId.set(part.id, part.call_id)
}
assistantItems.push({
type: "function_call",
call_id,
id: part.id,
name: part.name,
arguments: JSON.stringify(part.input ?? {}),
})
break
}
}
}
// Ensure every reasoning item is followed by a message or function_call
for (let i = 0; i < assistantItems.length; i++) {
const item = assistantItems[i]
if (item.type === "reasoning") {
const nextItem = assistantItems[i + 1]
if (!nextItem || (nextItem.type !== "message" && nextItem.type !== "function_call")) {
// Insert a placeholder message immediately after this reasoning item
assistantItems.splice(i + 1, 0, {
type: "message",
role: "assistant",
content: [{ type: "output_text", text: "" }],
})
}
}
}
allItems.push(...assistantItems)
} else {
// User messages - collect all content
const messageContent: ResponseInputMessageContentList = []
for (const part of m.content) {
switch (part.type) {
case "text":
messageContent.push({ type: "input_text", text: part.text })
break
case "image":
messageContent.push({
type: "input_image",
detail: "auto",
image_url: `data:${part.source.media_type};base64,${part.source.data}`,
})
break
case "tool_result": {
// Flush any pending message content before adding tool result
if (messageContent.length > 0) {
allItems.push({ role: m.role, content: [...messageContent] })
messageContent.length = 0
}
const call_id = part.call_id || toolUseIdToCallId.get(part.tool_use_id) || part.tool_use_id
allItems.push({
type: "function_call_output",
call_id,
output: typeof part.content === "string" ? part.content : JSON.stringify(part.content),
})
break
}
}
}
// Flush any remaining user message content
if (messageContent.length > 0) {
allItems.push({ role: m.role, content: [...messageContent] })
}
}
}
return allItems
}

Some files were not shown because too many files have changed in this diff Show More