Spaces:
Sleeping
Sleeping
File size: 17,887 Bytes
98c9143 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 | import type { Model } from "~/services/copilot/get-models"
import {
COMPACT_AUTO_CONTINUE,
COMPACT_REQUEST,
compactAutoContinuePromptStarts,
compactMessageSections,
compactSummaryPromptStart,
compactSystemPromptStarts,
compactTextOnlyGuard,
type CompactType,
} from "~/lib/compact"
import { getReasoningEffortForModel } from "~/lib/config"
import type {
AnthropicAssistantContentBlock,
AnthropicCacheControl,
AnthropicDocumentBlock,
AnthropicImageBlock,
AnthropicMessage,
AnthropicMessagesPayload,
AnthropicTextBlock,
AnthropicToolResultBlock,
AnthropicToolResultContentBlock,
AnthropicUserContentBlock,
} from "./anthropic-types"
export const TOOL_REFERENCE_TURN_BOUNDARY = "Tool loaded."
const IDE_EXECUTE_CODE_TOOL = "mcp__ide__executeCode"
const IDE_GET_DIAGNOSTICS_TOOL = "mcp__ide__getDiagnostics"
const IDE_GET_DIAGNOSTICS_DESCRIPTION =
"Get language diagnostics from VS Code. Returns errors, warnings, information, and hints for files in the workspace."
const PDF_FILE_READ_PREFIX = "PDF file read:"
type AnthropicAttachmentBlock = AnthropicImageBlock | AnthropicDocumentBlock
type AnthropicMessageContentBlock =
| AnthropicUserContentBlock
| AnthropicAssistantContentBlock
type IndexedAttachment = {
attachment: AnthropicAttachmentBlock
order: number
}
const getBlockCacheControl = (
block: AnthropicMessageContentBlock | undefined,
): AnthropicCacheControl | undefined => {
if (!block || block.type === "thinking") {
return undefined
}
const cacheControl = block.cache_control
if (!cacheControl || typeof cacheControl !== "object") {
return
}
return cacheControl
}
export const getLastMessageContentCacheControl = (
lastMessage: AnthropicMessage | undefined,
): AnthropicCacheControl | undefined => {
if (!lastMessage || !Array.isArray(lastMessage.content)) {
return undefined
}
const cacheControl = getBlockCacheControl(lastMessage.content.at(-1))
return cacheControl ? { ...cacheControl } : undefined
}
// Apply the original last message tail's cache_control to the rewritten tail. If
// the original tail was not marked, fall back to a default ephemeral marker.
export const applyLastMessageCacheControl = (
anthropicPayload: AnthropicMessagesPayload,
lastMessageCacheControl: AnthropicCacheControl | undefined,
): void => {
const cacheControl = lastMessageCacheControl ?? {
type: "ephemeral",
}
const lastMessage = anthropicPayload.messages.at(-1)
if (!lastMessage || !Array.isArray(lastMessage.content)) {
return
}
const lastBlock = lastMessage.content.at(-1)
if (!lastBlock || lastBlock.type === "thinking" || lastBlock.cache_control) {
return
}
lastBlock.cache_control = { ...cacheControl }
}
const getCompactCandidateText = (message: AnthropicMessage): string => {
if (message.role !== "user") {
return ""
}
if (typeof message.content === "string") {
return message.content
}
return message.content
.filter((block): block is AnthropicTextBlock => block.type === "text")
.map((block) =>
block.text.startsWith("<system-reminder>") ? "" : block.text,
)
.filter((text) => text.length > 0)
.join("\n\n")
}
const isCompactMessage = (lastMessage: AnthropicMessage): boolean => {
const text = getCompactCandidateText(lastMessage)
if (!text) {
return false
}
return (
text.includes(compactTextOnlyGuard)
&& text.includes(compactSummaryPromptStart)
&& compactMessageSections.some((section) => text.includes(section))
)
}
const isCompactAutoContinueMessage = (
lastMessage: AnthropicMessage,
): boolean => {
const text = getCompactCandidateText(lastMessage)
return (
Boolean(text)
&& compactAutoContinuePromptStarts.some((promptStart) =>
text.startsWith(promptStart),
)
)
}
export const getCompactType = (
anthropicPayload: AnthropicMessagesPayload,
): CompactType => {
const lastMessage = anthropicPayload.messages.at(-1)
if (lastMessage && isCompactMessage(lastMessage)) {
return COMPACT_REQUEST
}
if (lastMessage && isCompactAutoContinueMessage(lastMessage)) {
return COMPACT_AUTO_CONTINUE
}
const system = anthropicPayload.system
if (typeof system === "string") {
const hasCompactSystemPrompt = compactSystemPromptStarts.some(
(promptStart) => system.startsWith(promptStart),
)
return hasCompactSystemPrompt ? COMPACT_REQUEST : 0
}
if (!Array.isArray(system)) return 0
const hasCompactSystemPrompt = system.some(
(msg) =>
typeof msg.text === "string"
&& compactSystemPromptStarts.some((promptStart) =>
msg.text.startsWith(promptStart),
),
)
if (hasCompactSystemPrompt) {
return COMPACT_REQUEST
}
return 0
}
const mergeContentWithText = (
tr: AnthropicToolResultBlock,
textBlock: AnthropicTextBlock,
): AnthropicToolResultBlock => {
if (typeof tr.content === "string") {
return { ...tr, content: `${tr.content}\n\n${textBlock.text}` }
}
// Unable to merge, discard other text blocks, wait for the next round of re-request
if (hasToolRef(tr)) {
return tr
}
return {
...tr,
content: [...tr.content, stripContentBlockCacheControl(textBlock)],
}
}
const mergeContentWithTexts = (
tr: AnthropicToolResultBlock,
textBlocks: Array<AnthropicTextBlock>,
): AnthropicToolResultBlock => {
if (typeof tr.content === "string") {
const appendedTexts = textBlocks.map((tb) => tb.text).join("\n\n")
return { ...tr, content: `${tr.content}\n\n${appendedTexts}` }
}
// Unable to merge, discard other text blocks, wait for the next round of re-request
if (hasToolRef(tr)) {
return tr
}
return {
...tr,
content: [...tr.content, ...textBlocks.map(stripContentBlockCacheControl)],
}
}
const mergeContentWithAttachments = (
tr: AnthropicToolResultBlock,
attachments: Array<AnthropicAttachmentBlock>,
): AnthropicToolResultBlock => {
const cleanAttachments = attachments.map(stripContentBlockCacheControl)
if (typeof tr.content === "string") {
return {
...tr,
content: [{ type: "text", text: tr.content }, ...cleanAttachments],
}
}
return {
...tr,
content: [...tr.content, ...cleanAttachments],
}
}
const stripContentBlockCacheControl = <
T extends AnthropicToolResultContentBlock,
>(
block: T,
): T => {
if (!Object.hasOwn(block, "cache_control")) {
return block
}
const copy = { ...block }
delete copy.cache_control
return copy
}
const isAttachmentBlock = (
block: AnthropicUserContentBlock,
): block is AnthropicAttachmentBlock => {
return block.type === "image" || block.type === "document"
}
const getMergeableToolResultIndices = (
toolResults: Array<AnthropicToolResultBlock>,
): Array<number> => {
return toolResults.flatMap((block, index) =>
block.is_error || hasToolRef(block) ? [] : [index],
)
}
const mergeAttachmentsIntoToolResults = (
toolResults: Array<AnthropicToolResultBlock>,
attachmentsByToolResultIndex: Map<number, Array<IndexedAttachment>>,
): Array<AnthropicToolResultBlock> => {
if (attachmentsByToolResultIndex.size === 0) {
return toolResults
}
return toolResults.map((block, index) => {
const matchedAttachments = attachmentsByToolResultIndex.get(index)
if (!matchedAttachments) {
return block
}
const orderedAttachments = [...matchedAttachments]
.sort((left, right) => left.order - right.order)
.map(({ attachment }) => attachment)
return mergeContentWithAttachments(block, orderedAttachments)
})
}
const assignAttachmentsToToolResults = (
target: Map<number, Array<IndexedAttachment>>,
attachments: Array<IndexedAttachment>,
options: {
toolResultIndices: Array<number>
fallbackToolResultIndices?: Array<number>
},
): void => {
const { toolResultIndices } = options
const fallbackToolResultIndices =
options.fallbackToolResultIndices ?? toolResultIndices
if (attachments.length === 0) {
return
}
if (
toolResultIndices.length > 0
&& toolResultIndices.length === attachments.length
) {
for (const [index, toolResultIndex] of toolResultIndices.entries()) {
const currentAttachments = target.get(toolResultIndex)
if (currentAttachments) {
currentAttachments.push(attachments[index])
continue
}
target.set(toolResultIndex, [attachments[index]])
}
return
}
const lastToolResultIndex = fallbackToolResultIndices.at(-1)
if (lastToolResultIndex === undefined) {
return
}
const currentAttachments = target.get(lastToolResultIndex)
if (currentAttachments) {
currentAttachments.push(...attachments)
return
}
target.set(lastToolResultIndex, [...attachments])
}
const startsWithPdfFileRead = (
toolResult: AnthropicToolResultBlock,
): boolean => {
if (typeof toolResult.content === "string") {
return toolResult.content.startsWith(PDF_FILE_READ_PREFIX)
}
if (toolResult.content.some((block) => block.type === "document")) {
return false
}
if (toolResult.content.length === 0) {
return false
}
const firstBlock = toolResult.content[0]
if (firstBlock.type !== "text") {
return false
}
return firstBlock.text.startsWith(PDF_FILE_READ_PREFIX)
}
const collectMergeableUserContent = (
content: Array<AnthropicUserContentBlock>,
): {
toolResults: Array<AnthropicToolResultBlock>
textBlocks: Array<AnthropicTextBlock>
attachments: Array<IndexedAttachment>
} | null => {
const toolResults: Array<AnthropicToolResultBlock> = []
const textBlocks: Array<AnthropicTextBlock> = []
const attachments: Array<IndexedAttachment> = []
for (const [order, block] of content.entries()) {
if (block.type === "tool_result") {
toolResults.push(block)
continue
}
if (block.type === "text") {
textBlocks.push(block)
continue
}
if (isAttachmentBlock(block)) {
attachments.push({ attachment: block, order })
continue
}
return null
}
return {
toolResults,
textBlocks,
attachments,
}
}
const mergeAttachmentsForToolResults = (
toolResults: Array<AnthropicToolResultBlock>,
attachments: Array<IndexedAttachment>,
): Array<AnthropicToolResultBlock> => {
if (attachments.length === 0) {
return toolResults
}
const documentBlocks = attachments.filter(
({ attachment }) => attachment.type === "document",
)
const mergeableToolResultIndices = getMergeableToolResultIndices(toolResults)
const pdfReadToolResultIndices = mergeableToolResultIndices.filter((index) =>
startsWithPdfFileRead(toolResults[index]),
)
const attachmentsByToolResultIndex = new Map<
number,
Array<IndexedAttachment>
>()
let remainingAttachments = attachments
let countMatchToolResultIndices = mergeableToolResultIndices
// Match PDF read tool results and documents in order first, then leave any
// unmatched documents to the generic fallback path below.
if (documentBlocks.length > 0 && pdfReadToolResultIndices.length > 0) {
const matchedDocumentCount = Math.min(
pdfReadToolResultIndices.length,
documentBlocks.length,
)
const matchedDocuments = documentBlocks.slice(0, matchedDocumentCount)
const matchedDocumentOrders = new Set(
matchedDocuments.map(({ order }) => order),
)
const matchedPdfToolResultIndices = pdfReadToolResultIndices.slice(
0,
matchedDocumentCount,
)
const matchedPdfToolResultIndexSet = new Set(matchedPdfToolResultIndices)
assignAttachmentsToToolResults(
attachmentsByToolResultIndex,
matchedDocuments,
{
toolResultIndices: matchedPdfToolResultIndices,
},
)
countMatchToolResultIndices = mergeableToolResultIndices.filter(
(index) => !matchedPdfToolResultIndexSet.has(index),
)
remainingAttachments = attachments.filter(
({ attachment, order }) =>
attachment.type !== "document" || !matchedDocumentOrders.has(order),
)
}
// Everything else keeps the existing count-match / last-tool-result fallback.
assignAttachmentsToToolResults(
attachmentsByToolResultIndex,
remainingAttachments,
{
toolResultIndices: countMatchToolResultIndices,
fallbackToolResultIndices: mergeableToolResultIndices,
},
)
return mergeAttachmentsIntoToolResults(
toolResults,
attachmentsByToolResultIndex,
)
}
const mergeUserMessageContent = (
content: Array<AnthropicUserContentBlock>,
): Array<AnthropicUserContentBlock> | null => {
const mergeableContent = collectMergeableUserContent(content)
if (!mergeableContent) {
return null
}
const { toolResults, textBlocks, attachments } = mergeableContent
if (
toolResults.length === 0
|| (textBlocks.length === 0 && attachments.length === 0)
) {
return null
}
const mergedToolResults =
textBlocks.length === 0 ?
toolResults
: mergeToolResult(toolResults, textBlocks)
return mergeAttachmentsForToolResults(mergedToolResults, attachments)
}
const mergeToolResult = (
toolResults: Array<AnthropicToolResultBlock>,
textBlocks: Array<AnthropicTextBlock>,
): Array<AnthropicToolResultBlock> => {
if (toolResults.length === textBlocks.length) {
return toolResults.map((tr, i) => mergeContentWithText(tr, textBlocks[i]))
}
const lastIndex = toolResults.length - 1
return toolResults.map((tr, i) =>
i === lastIndex ? mergeContentWithTexts(tr, textBlocks) : tr,
)
}
export const stripToolReferenceTurnBoundary = (
anthropicPayload: AnthropicMessagesPayload,
): void => {
for (const msg of anthropicPayload.messages) {
if (msg.role !== "user" || !Array.isArray(msg.content)) continue
const hasToolReference = msg.content.some(
(block) => block.type === "tool_result" && hasToolRef(block),
)
if (!hasToolReference) continue
msg.content = msg.content.filter(
(block) =>
block.type !== "text"
|| block.text.trim() !== TOOL_REFERENCE_TURN_BOUNDARY,
)
}
}
export const mergeToolResultForClaude = (
anthropicPayload: AnthropicMessagesPayload,
options?: {
skipLastMessage?: boolean
},
): void => {
const lastMessageIndex = anthropicPayload.messages.length - 1
for (const [index, msg] of anthropicPayload.messages.entries()) {
if (options?.skipLastMessage && index === lastMessageIndex) continue
if (msg.role !== "user" || !Array.isArray(msg.content)) continue
const mergedContent = mergeUserMessageContent(msg.content)
if (mergedContent) {
msg.content = mergedContent
}
}
}
// align with vscode copilot claude agent tools
export const sanitizeIdeTools = (payload: AnthropicMessagesPayload): void => {
if (!payload.tools || payload.tools.length === 0) {
return
}
payload.tools = payload.tools.flatMap((tool) => {
if (tool.name === IDE_EXECUTE_CODE_TOOL && !tool.defer_loading) {
return []
}
if (tool.name === IDE_GET_DIAGNOSTICS_TOOL) {
return [
{
...tool,
description: IDE_GET_DIAGNOSTICS_DESCRIPTION,
},
]
}
return [tool]
})
}
const hasToolRef = (block: AnthropicToolResultBlock) => {
return (
Array.isArray(block.content)
&& block.content.some((c) => c.type === "tool_reference")
)
}
// Strip cache_control from system content blocks as the
// Copilot Messages API does not support them (rejects extra fields like scope).
// commit by nicktogo
const stripCacheControl = (payload: AnthropicMessagesPayload): void => {
if (Array.isArray(payload.system)) {
for (const block of payload.system) {
const cacheControl = block.cache_control
if (cacheControl && typeof cacheControl === "object") {
const { scope, ...rest } = cacheControl
block.cache_control = rest
}
}
}
}
// Pre-request processing: filter thinking blocks for Claude models so only
// valid thinking blocks are sent to the Copilot Messages API.
const filterAssistantThinkingBlocks = (
payload: AnthropicMessagesPayload,
): void => {
for (const msg of payload.messages) {
if (msg.role === "assistant" && Array.isArray(msg.content)) {
msg.content = msg.content.filter((block) => {
if (block.type !== "thinking") return true
return (
block.thinking
&& block.thinking !== "Thinking..."
&& block.signature
&& !block.signature.includes("@")
)
})
}
}
}
export const prepareMessagesApiPayload = (
payload: AnthropicMessagesPayload,
selectedModel?: Model,
): void => {
stripCacheControl(payload)
filterAssistantThinkingBlocks(payload)
const hasThinking = Boolean(payload.thinking)
// https://platform.claude.com/docs/en/build-with-claude/extended-thinking#extended-thinking-with-tool-use
// Using tool_choice: {"type": "any"} or tool_choice: {"type": "tool", "name": "..."} will result in an error because these options force tool use, which is incompatible with extended thinking.
const toolChoice = payload.tool_choice
const disableThink = toolChoice?.type === "any" || toolChoice?.type === "tool"
if (selectedModel?.capabilities.supports.adaptive_thinking && !disableThink) {
payload.thinking = {
type: "adaptive",
}
// align with vscode copilot
if (!hasThinking) {
payload.thinking.display = "summarized"
}
if (payload.model === "claude-opus-4.7") {
payload.thinking.display = "summarized"
}
let effort = getReasoningEffortForModel(payload.model)
if (effort === "none" || effort === "minimal") {
effort = "low"
}
const reasoningEffort = selectedModel.capabilities.supports.reasoning_effort
if (reasoningEffort && !reasoningEffort.includes(effort)) {
effort = reasoningEffort.at(-1) as "low" | "medium" | "high"
}
payload.output_config = {
effort: effort,
}
}
}
|