diff --git a/.github/workflows/stable-release.yml b/.github/workflows/stable-release.yml index 13adec1c9..53b8eb17f 100644 --- a/.github/workflows/stable-release.yml +++ b/.github/workflows/stable-release.yml @@ -24,6 +24,7 @@ permissions: contents: write issues: write pull-requests: write + id-token: write # Required for OIDC jobs: stable-release: @@ -67,8 +68,6 @@ jobs: if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }} id: find_beta working-directory: extensions/cli - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} run: | if [[ -n "${{ inputs.beta_version }}" ]]; then # Manual input provided @@ -117,8 +116,6 @@ jobs: - name: Download and verify beta package if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }} working-directory: extensions/cli - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} run: | # Download the specific beta version npm pack @continuedev/cli@${{ steps.find_beta.outputs.beta_version }} @@ -189,8 +186,6 @@ jobs: - name: Publish stable to npm working-directory: extensions/cli - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} run: | npm publish --tag latest echo "Published stable version: ${{ steps.final_version.outputs.stable_version }}" diff --git a/extensions/cli/src/permissions/defaultPolicies.ts b/extensions/cli/src/permissions/defaultPolicies.ts index 0fce539b3..8bc4bdf75 100644 --- a/extensions/cli/src/permissions/defaultPolicies.ts +++ b/extensions/cli/src/permissions/defaultPolicies.ts @@ -12,8 +12,8 @@ export function getDefaultToolPolicies( { tool: "Edit", permission: "ask" }, { tool: "MultiEdit", permission: "ask" }, { tool: "Write", permission: "ask" }, - { tool: "CheckBackgroundJob", permission: "allow" }, + { tool: "AskQuestion", permission: "allow" }, { tool: "Checklist", permission: "allow" }, { tool: "Diff", permission: "allow" }, { tool: "Exit", permission: "allow" }, // Exit tool is generally safe (headless mode only) @@ -46,8 +46,8 @@ export const PLAN_MODE_POLICIES: ToolPermissionPolicy[] = [ // TODO address bash read only concerns, maybe make permissions more granular { tool: "Bash", permission: "allow" }, - { tool: "CheckBackgroundJob", permission: "allow" }, + { tool: "AskQuestion", permission: "allow" }, { tool: "Checklist", permission: "allow" }, { tool: "Diff", permission: "allow" }, { tool: "Exit", permission: "allow" }, diff --git a/extensions/cli/src/services/QuizService.ts b/extensions/cli/src/services/QuizService.ts new file mode 100644 index 000000000..df424d850 --- /dev/null +++ b/extensions/cli/src/services/QuizService.ts @@ -0,0 +1,112 @@ +import { EventEmitter } from "events"; + +/**Types */ +export interface QuizQuestion { + question: string; + options?: string[]; + defaultAnswer?: string; +} + +export interface PendingQuestion extends QuizQuestion { + requestId: string; + timestamp: number; +} + +export interface QuizAnswer { + requestId: string; + answer: string; + isCustomAnswer: boolean; +} + +export interface QuizServiceState { + pendingQuestion: PendingQuestion | null; +} + +export interface QuestionRequestedEvent { + requestId: string; + question: QuizQuestion; +} + +export interface QuestionAnsweredEvent { + requestId: string; + answer: string; + isCustomAnswer: boolean; +} + +/**Quiz service */ +export class QuizService extends EventEmitter { + private pendingRequests = new Map< + string, + { + question: QuizQuestion; + resolve: (answer: string) => void; + } + >(); + + private currentState: QuizServiceState = { + pendingQuestion: null, + }; + + /**set a pending question to be answered and return a promise that resolves when the question is answered */ + async askQuestion(question: QuizQuestion): Promise { + const requestId = `quiz-${Date.now()}`; + + return new Promise((resolve) => { + const pendingQuestion: PendingQuestion = { + ...question, + requestId, + timestamp: Date.now(), + }; + + this.pendingRequests.set(requestId, { + question, + resolve, + }); + + this.currentState.pendingQuestion = pendingQuestion; + + const event: QuestionRequestedEvent = { + requestId, + question, + }; + + this.emit("questionRequested", event); + }); + } + + /**answer the pending question request and resolve the answer */ + answerQuestion( + requestId: string, + answer: string, + isCustomAnswer = false, + ): boolean { + const pending = this.pendingRequests.get(requestId); + if (!pending) { + return false; + } + + this.pendingRequests.delete(requestId); + this.currentState.pendingQuestion = null; + + const event: QuestionAnsweredEvent = { + requestId, + answer, + isCustomAnswer, + }; + + this.emit("questionAnswered", event); + pending.resolve(answer); + + return true; + } + + async initialize(): Promise { + this.currentState = { + pendingQuestion: null, + }; + this.pendingRequests.clear(); + return this.currentState; + } +} + +export const quizService = new QuizService(); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index c1807e55c..ffb7cba2c 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -17,6 +17,7 @@ import { FileIndexService } from "./FileIndexService.js"; import { GitAiIntegrationService } from "./GitAiIntegrationService.js"; import { MCPService } from "./MCPService.js"; import { ModelService } from "./ModelService.js"; +import { quizService } from "./QuizService.js"; import { ResourceMonitoringService } from "./ResourceMonitoringService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { StorageSyncService } from "./StorageSyncService.js"; @@ -325,6 +326,12 @@ export async function initializeServices(initOptions: ServiceInitOptions = {}) { [], // No dependencies ); + serviceContainer.register( + SERVICE_NAMES.QUIZ, + () => quizService.initialize(), + [], // No dependencies + ); + // Eagerly initialize all services to ensure they're ready when needed // This avoids race conditions and "service not ready" errors await serviceContainer.initializeAll(); @@ -389,6 +396,7 @@ export const services = { artifactUpload: artifactUploadService, gitAiIntegration: gitAiIntegrationService, backgroundJobs: backgroundJobService, + quiz: quizService, } as const; export type ServicesType = typeof services; diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index 6011bbd5c..3b3776883 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -158,6 +158,7 @@ export const SERVICE_NAMES = { ARTIFACT_UPLOAD: "artifactUpload", GIT_AI_INTEGRATION: "gitAiIntegration", BACKGROUND_JOBS: "backgroundJobs", + QUIZ: "quiz", } as const; /** diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts index 205a76fe8..743cedc34 100644 --- a/extensions/cli/src/stream/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -377,6 +377,28 @@ export function recordStreamTelemetry(options: { }); } catch {} + // Report prompt cache metrics to PostHog + if (fullUsage?.prompt_tokens_details) { + const cacheReadTokens = + fullUsage.prompt_tokens_details.cache_read_tokens ?? 0; + const cacheWriteTokens = + fullUsage.prompt_tokens_details.cache_write_tokens ?? 0; + const totalPromptTokens = fullUsage.prompt_tokens ?? 0; + const cacheHitRate = + totalPromptTokens > 0 ? cacheReadTokens / totalPromptTokens : 0; + + try { + void posthogService.capture("prompt_cache_metrics", { + model: model.model, + cache_read_tokens: cacheReadTokens, + cache_write_tokens: cacheWriteTokens, + total_prompt_tokens: totalPromptTokens, + cache_hit_rate: cacheHitRate, + tool_count: tools?.length ?? 0, + }); + } catch {} + } + return cost; } diff --git a/extensions/cli/src/tools/allBuiltIns.ts b/extensions/cli/src/tools/allBuiltIns.ts index c5d054e6f..a7a501c71 100644 --- a/extensions/cli/src/tools/allBuiltIns.ts +++ b/extensions/cli/src/tools/allBuiltIns.ts @@ -1,5 +1,6 @@ import { SUBAGENT_TOOL_META } from "../subagent/index.js"; +import { askQuestionTool } from "./askQuestion.js"; import { editTool } from "./edit.js"; import { exitTool } from "./exit.js"; import { fetchTool } from "./fetch.js"; @@ -18,6 +19,7 @@ import { writeFileTool } from "./writeFile.js"; // putting in here for circular import issue export const ALL_BUILT_IN_TOOLS = [ + askQuestionTool, editTool, exitTool, fetchTool, diff --git a/extensions/cli/src/tools/askQuestion.ts b/extensions/cli/src/tools/askQuestion.ts new file mode 100644 index 000000000..beb3f81fb --- /dev/null +++ b/extensions/cli/src/tools/askQuestion.ts @@ -0,0 +1,61 @@ +import { quizService } from "../services/QuizService.js"; + +import { Tool } from "./types.js"; + +export const askQuestionTool: Tool = { + name: "AskQuestion", + displayName: "Ask Question", + description: `Ask the user a clarifying question to gather requirements, preferences, or implementation details before proceeding. +Guidelines: +- You should use this tool **whenever you want to clarify your assumption or need answers to build your plan**. +- DO NOT supply "other" or "none of the above" or similar as an option. User can always provide a free-form answer when needed. +`, + parameters: { + type: "object", + required: ["question", "options"], + properties: { + question: { + type: "string", + description: "The question to ask the user", + }, + options: { + type: "array", + description: + "The list of choices. Leave as empty array if user should provide a free-form answer.", + items: { + type: "string", + }, + }, + defaultAnswer: { + type: "string", + description: + "Default answer if user presses Enter without providing input", + }, + }, + }, + readonly: true, + isBuiltIn: true, + run: async (args: { + question: string; + options?: string[]; + defaultAnswer?: string; + }): Promise => { + const { question, options, defaultAnswer } = args; + + const answer = await quizService.askQuestion({ + question, + options, + defaultAnswer, + }); + + if (options && options.length > 0) { + const selectedIndex = options.indexOf(answer); + if (selectedIndex !== -1) { + return `User selected option ${selectedIndex + 1}: "${answer}"`; + } + return `User provided custom answer: "${answer}"`; + } + + return `User answered: "${answer}"`; + }, +}; diff --git a/extensions/cli/src/tools/builtInToolNames.ts b/extensions/cli/src/tools/builtInToolNames.ts index 274b19e7f..a19753276 100644 --- a/extensions/cli/src/tools/builtInToolNames.ts +++ b/extensions/cli/src/tools/builtInToolNames.ts @@ -6,6 +6,7 @@ * When adding a new built-in tool, update both this list and ALL_BUILT_IN_TOOLS in allBuiltIns.ts. */ export const BUILT_IN_TOOL_NAMES = [ + "AskQuestion", "Edit", "Exit", "Fetch", diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index eb10d870d..fb43739f8 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -19,6 +19,7 @@ import { telemetryService } from "../telemetry/telemetryService.js"; import { logger } from "../util/logger.js"; import { ALL_BUILT_IN_TOOLS } from "./allBuiltIns.js"; +import { askQuestionTool } from "./askQuestion.js"; import { checkBackgroundJobTool } from "./checkBackgroundJob.js"; import { editTool } from "./edit.js"; import { exitTool } from "./exit.js"; @@ -70,6 +71,7 @@ const BASE_BUILTIN_TOOLS: Tool[] = [ fetchTool, writeChecklistTool, checkBackgroundJobTool, + askQuestionTool, ]; const BUILTIN_SEARCH_TOOLS: Tool[] = [searchCodeTool]; diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index bedad8b38..62174cead 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -184,6 +184,7 @@ function useChatHandlers( }; } +// eslint-disable-next-line complexity const TUIChat: React.FC = ({ remoteUrl, configPath, @@ -261,6 +262,7 @@ const TUIChat: React.FC = ({ compactionStartTime, inputMode, activePermissionRequest, + activeQuizQuestion, wasInterrupted, queuedMessages, handleUserMessage, @@ -269,6 +271,7 @@ const TUIChat: React.FC = ({ resetChatHistory, handleEditMessage, handleToolPermissionResponse, + handleQuizAnswer, } = useChat({ assistant: services.config?.config || undefined, model: services.model?.model || undefined, @@ -332,7 +335,9 @@ const TUIChat: React.FC = ({ // Determine if input should be disabled // Allow input even when services are loading, but disable for UI overlays const isInputDisabled = - navState.currentScreen !== "chat" || !!activePermissionRequest; + navState.currentScreen !== "chat" || + !!activePermissionRequest || + !!activeQuizQuestion; // Check if verbose mode is enabled for resource debugging const isVerboseMode = useMemo(() => process.argv.includes("--verbose"), []); @@ -430,7 +435,9 @@ const TUIChat: React.FC = ({ handleReload={handleReload} closeCurrentScreen={closeCurrentScreen} activePermissionRequest={activePermissionRequest} + activeQuizQuestion={activeQuizQuestion} handleToolPermissionResponse={handleToolPermissionResponse} + handleQuizAnswer={handleQuizAnswer} handleUserMessage={handleUserMessage} isWaitingForResponse={isWaitingForResponse} isCompacting={isCompacting} diff --git a/extensions/cli/src/ui/components/ChatScreenContent.tsx b/extensions/cli/src/ui/components/ChatScreenContent.tsx index 7c3225da6..49eed4058 100644 --- a/extensions/cli/src/ui/components/ChatScreenContent.tsx +++ b/extensions/cli/src/ui/components/ChatScreenContent.tsx @@ -1,19 +1,25 @@ import type { AssistantConfig } from "@continuedev/sdk"; import React from "react"; -import type { ActivePermissionRequest } from "../hooks/useChat.types.js"; +import type { + ActivePermissionRequest, + ActiveQuizQuestion, +} from "../hooks/useChat.types.js"; import { UserInput } from "../UserInput.js"; +import { QuizPrompt } from "./QuizPrompt.js"; import { ToolPermissionSelector } from "./ToolPermissionSelector.js"; interface ChatScreenContentProps { activePermissionRequest: ActivePermissionRequest | null; + activeQuizQuestion: ActiveQuizQuestion | null; handleToolPermissionResponse: ( requestId: string, approved: boolean, createPolicy?: boolean, stopStream?: boolean, ) => void; + handleQuizAnswer: (requestId: string, answer: string) => void; handleUserMessage: (message: string, imageMap?: Map) => void; isWaitingForResponse: boolean; isCompacting: boolean; @@ -30,7 +36,9 @@ interface ChatScreenContentProps { export const ChatScreenContent: React.FC = ({ activePermissionRequest, + activeQuizQuestion, handleToolPermissionResponse, + handleQuizAnswer, handleUserMessage, isWaitingForResponse, isCompacting, @@ -44,6 +52,18 @@ export const ChatScreenContent: React.FC = ({ onImageInClipboardChange, onShowEditSelector, }) => { + if (activeQuizQuestion) { + return ( + + ); + } + if (activePermissionRequest) { return ( void; +} + +/**Quiz prompt component for answering for the AskQuestion tool and QuizService */ +export const QuizPrompt: React.FC = ({ + question, + options: rawOptions, + defaultAnswer, + requestId, + onAnswer, +}) => { + const options = Array.isArray(rawOptions) ? rawOptions : undefined; + const [selectedIndex, setSelectedIndex] = useState(0); + const [isCustomMode, setIsCustomMode] = useState( + !options || options.length === 0, + ); // allows typing out an answer even when there are options + const [customInput, setCustomInput] = useState(""); + const [submitted, setSubmitted] = useState(false); + + const hasOptions = options && options.length > 0; + + useInput((input, key) => { + if (submitted) return; + + if (isCustomMode) { + // submit the typed answer + if (key.return) { + const answer = customInput.trim() || defaultAnswer || ""; + if (answer) { + setSubmitted(true); + onAnswer(requestId, answer, true); + } + return; + } + + if (key.backspace || key.delete) { + setCustomInput((prev) => prev.slice(0, -1)); + return; + } + + if (hasOptions && key.upArrow && customInput === "") { + // exit out of typing a custom answer + setIsCustomMode(false); + setSelectedIndex(options.length - 1); + return; + } + + if (input && !key.ctrl && !key.meta) { + // handle typing a custom answer + setCustomInput((prev) => prev + input); + } + return; + } + + if (key.return) { + // submit the selected option + if (hasOptions && options[selectedIndex]) { + setSubmitted(true); + onAnswer(requestId, options[selectedIndex], false); + } + return; + } + + // navigate between options + if (key.upArrow) { + setSelectedIndex((prev) => + prev === 0 ? (hasOptions ? options.length - 1 : 0) : prev - 1, + ); + } else if (key.downArrow) { + if (hasOptions) { + if (selectedIndex === options.length - 1) { + setIsCustomMode(true); + setSelectedIndex(0); + } else { + setSelectedIndex((prev) => + prev === options.length - 1 ? 0 : prev + 1, + ); + } + } + } + + if (input && !key.ctrl && !key.meta && !key.upArrow && !key.downArrow) { + setIsCustomMode(true); + setCustomInput(input); + } + }); + + if (submitted) { + return null; + } + + return ( + + + + ?{" "} + + {question} + + + {hasOptions && !isCustomMode && ( + + {options.map((option, index) => { + const isSelected = index === selectedIndex; + return ( + + + {isSelected ? "❯ " : " "} + {option} + + + ); + })} + + + {" "}(or start typing for custom answer) + + + + )} + + {isCustomMode && ( + + + ❯ + {customInput} + ▊ + + {defaultAnswer && !customInput && ( + + + (Press Enter for default: {defaultAnswer}) + + + )} + + )} + + + + {hasOptions && !isCustomMode + ? "↑/↓ navigate, Enter select" + : "Type answer, Enter submit"} + + + + ); +}; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index aff68f1ce..516cb7811 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -9,7 +9,10 @@ import type { NavigationScreen } from "../context/NavigationContext.js"; import { DiffViewer } from "../DiffViewer.js"; import { EditMessageSelector } from "../EditMessageSelector.js"; import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js"; -import type { ActivePermissionRequest } from "../hooks/useChat.types.js"; +import type { + ActivePermissionRequest, + ActiveQuizQuestion, +} from "../hooks/useChat.types.js"; import { JobsSelector } from "../JobsSelector.js"; import { MCPSelector } from "../MCPSelector.js"; import { ModelSelector } from "../ModelSelector.js"; @@ -31,12 +34,14 @@ interface ScreenContentProps { handleReload: () => Promise; closeCurrentScreen: () => void; activePermissionRequest: ActivePermissionRequest | null; + activeQuizQuestion: ActiveQuizQuestion | null; handleToolPermissionResponse: ( requestId: string, approved: boolean, createPolicy?: boolean, stopStream?: boolean, ) => void; + handleQuizAnswer: (requestId: string, answer: string) => void; handleUserMessage: (message: string, imageMap?: Map) => void; isWaitingForResponse: boolean; isCompacting: boolean; @@ -72,7 +77,9 @@ export const ScreenContent: React.FC = ({ handleReload, closeCurrentScreen, activePermissionRequest, + activeQuizQuestion, handleToolPermissionResponse, + handleQuizAnswer, handleUserMessage, isWaitingForResponse, isCompacting, @@ -198,7 +205,9 @@ export const ScreenContent: React.FC = ({ return ( ([]); const [activePermissionRequest, setActivePermissionRequest] = useState(null); + const [activeQuizQuestion, setActiveQuizQuestion] = + useState(null); const [compactionIndex, setCompactionIndex] = useState(() => { // When resuming or forking, check for compaction markers in the loaded history if ((resume || fork) && currentSession.history.length > 0) { @@ -195,6 +198,27 @@ export function useChat({ }; }, []); + // Set up quiz service listeners + useEffect(() => { + const quizSvc = services.quiz; + + const onQuestionRequested = (pending: ActiveQuizQuestion) => { + setActiveQuizQuestion(pending); + }; + + const onQuestionAnswered = () => { + setActiveQuizQuestion(null); + }; + + quizSvc.on("questionRequested", onQuestionRequested); + quizSvc.on("questionAnswered", onQuestionAnswered); + + return () => { + quizSvc.off("questionRequested", onQuestionRequested); + quizSvc.off("questionAnswered", onQuestionAnswered); + }; + }, []); + // Clean up abort controller on unmount useEffect(() => { return () => { @@ -829,6 +853,11 @@ export function useChat({ } }; + const handleQuizAnswer = (requestId: string, answer: string) => { + setActiveQuizQuestion(null); + services.quiz.answerQuestion(requestId, answer); + }; + return { chatHistory, setChatHistory: setChatHistory, @@ -839,6 +868,7 @@ export function useChat({ inputMode, attachedFiles, activePermissionRequest, + activeQuizQuestion, wasInterrupted, queuedMessages, handleUserMessage, @@ -847,5 +877,6 @@ export function useChat({ resetChatHistory, handleEditMessage, handleToolPermissionResponse, + handleQuizAnswer, }; } diff --git a/extensions/cli/src/ui/hooks/useChat.types.ts b/extensions/cli/src/ui/hooks/useChat.types.ts index ac2ecc5c6..0e2887c6a 100644 --- a/extensions/cli/src/ui/hooks/useChat.types.ts +++ b/extensions/cli/src/ui/hooks/useChat.types.ts @@ -2,6 +2,7 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { Session } from "core/index.js"; +import { QuestionRequestedEvent } from "../../services/QuizService.js"; import { ToolCallPreview } from "../../tools/types.js"; export interface UseChatProps { @@ -42,6 +43,8 @@ export interface ActivePermissionRequest { hasDynamicEvaluation?: boolean; } +export type ActiveQuizQuestion = QuestionRequestedEvent; + export interface RemoteServerState { session: Session; isProcessing: boolean; diff --git a/package-lock.json b/package-lock.json index c77b2c5c0..acd1174ed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,6 +5,9 @@ "packages": { "": { "name": "continue", + "dependencies": { + "@ai-sdk/deepseek": "^2.0.20" + }, "devDependencies": { "@typescript-eslint/parser": "^8.40.0", "concurrently": "^9.1.2", @@ -17,6 +20,51 @@ "typescript": "^5.6.3" } }, + "node_modules/@ai-sdk/deepseek": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/@ai-sdk/deepseek/-/deepseek-2.0.20.tgz", + "integrity": "sha512-MAL04sDTOWUiBjAGWaVgyeE4bYRb9QpKYRlIeCTZFga6I8yQs50XakhWEssrmvVihdpHGkqpDtCHsFqCydsWLA==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "3.0.8", + "@ai-sdk/provider-utils": "4.0.15" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.25.76 || ^4.1.8" + } + }, + "node_modules/@ai-sdk/provider": { + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-3.0.8.tgz", + "integrity": "sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ==", + "license": "Apache-2.0", + "dependencies": { + "json-schema": "^0.4.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@ai-sdk/provider-utils": { + "version": "4.0.15", + "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-4.0.15.tgz", + "integrity": "sha512-8XiKWbemmCbvNN0CLR9u3PQiet4gtEVIrX4zzLxnCj06AwsEDJwJVBbKrEI4t6qE8XRSIvU2irka0dcpziKW6w==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "3.0.8", + "@standard-schema/spec": "^1.1.0", + "eventsource-parser": "^3.0.6" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.25.76 || ^4.1.8" + } + }, "node_modules/@eslint-community/eslint-utils": { "version": "4.9.0", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.0.tgz", @@ -224,6 +272,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, "node_modules/@types/json5": { "version": "0.0.29", "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", @@ -1601,6 +1655,15 @@ "dev": true, "license": "MIT" }, + "node_modules/eventsource-parser": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz", + "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/execa": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", @@ -2667,6 +2730,12 @@ "dev": true, "license": "MIT" }, + "node_modules/json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==", + "license": "(AFL-2.1 OR BSD-3-Clause)" + }, "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", @@ -4650,6 +4719,16 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "node_modules/zod": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", + "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } } } } diff --git a/package.json b/package.json index dd1a5f381..e23a05fc2 100644 --- a/package.json +++ b/package.json @@ -23,5 +23,8 @@ "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8", "typescript": "^5.6.3" + }, + "dependencies": { + "@ai-sdk/deepseek": "^2.0.20" } } diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 4a6cc731c..cc2b07d94 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -10,7 +10,9 @@ "license": "Apache-2.0", "dependencies": { "@ai-sdk/anthropic": "^3.0.44", + "@ai-sdk/deepseek": "^2.0.20", "@ai-sdk/openai": "^3.0.29", + "@ai-sdk/xai": "^3.0.57", "@anthropic-ai/sdk": "^0.67.0", "@aws-sdk/client-bedrock-runtime": "^3.931.0", "@aws-sdk/credential-providers": "^3.974.0", @@ -61,6 +63,22 @@ "zod": "^3.25.76 || ^4.1.8" } }, + "node_modules/@ai-sdk/deepseek": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/@ai-sdk/deepseek/-/deepseek-2.0.20.tgz", + "integrity": "sha512-MAL04sDTOWUiBjAGWaVgyeE4bYRb9QpKYRlIeCTZFga6I8yQs50XakhWEssrmvVihdpHGkqpDtCHsFqCydsWLA==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "3.0.8", + "@ai-sdk/provider-utils": "4.0.15" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.25.76 || ^4.1.8" + } + }, "node_modules/@ai-sdk/gateway": { "version": "3.0.50", "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-3.0.50.tgz", @@ -94,6 +112,22 @@ "zod": "^3.25.76 || ^4.1.8" } }, + "node_modules/@ai-sdk/openai-compatible": { + "version": "2.0.30", + "resolved": "https://registry.npmjs.org/@ai-sdk/openai-compatible/-/openai-compatible-2.0.30.tgz", + "integrity": "sha512-iTjumHf1/u4NhjXYFn/aONM2GId3/o7J1Lp5ql8FCbgIMyRwrmanR5xy1S3aaVkfTscuDvLTzWiy1mAbGzK3nQ==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/provider": "3.0.8", + "@ai-sdk/provider-utils": "4.0.15" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.25.76 || ^4.1.8" + } + }, "node_modules/@ai-sdk/provider": { "version": "3.0.8", "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-3.0.8.tgz", @@ -123,6 +157,23 @@ "zod": "^3.25.76 || ^4.1.8" } }, + "node_modules/@ai-sdk/xai": { + "version": "3.0.57", + "resolved": "https://registry.npmjs.org/@ai-sdk/xai/-/xai-3.0.57.tgz", + "integrity": "sha512-fY8MpcU1akfQStB/vDAAjJqJRWWGfHpRsNa31GNMlLLwHvwdyNhQVW8NtmIMrHDE+38pz/b0aMENJ4cb75qGPA==", + "license": "Apache-2.0", + "dependencies": { + "@ai-sdk/openai-compatible": "2.0.30", + "@ai-sdk/provider": "3.0.8", + "@ai-sdk/provider-utils": "4.0.15" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "zod": "^3.25.76 || ^4.1.8" + } + }, "node_modules/@anthropic-ai/sdk": { "version": "0.67.1", "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.67.1.tgz", diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index a94c64e92..6bef85dff 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -13,7 +13,9 @@ "license": "Apache-2.0", "dependencies": { "@ai-sdk/anthropic": "^3.0.44", + "@ai-sdk/deepseek": "^2.0.20", "@ai-sdk/openai": "^3.0.29", + "@ai-sdk/xai": "^3.0.57", "@anthropic-ai/sdk": "^0.67.0", "@aws-sdk/client-bedrock-runtime": "^3.931.0", "@aws-sdk/credential-providers": "^3.974.0", diff --git a/packages/openai-adapters/src/apis/AiSdk.ts b/packages/openai-adapters/src/apis/AiSdk.ts index 79cbb8686..6edfbbe41 100644 --- a/packages/openai-adapters/src/apis/AiSdk.ts +++ b/packages/openai-adapters/src/apis/AiSdk.ts @@ -1,5 +1,7 @@ import { createAnthropic } from "@ai-sdk/anthropic"; +import { createDeepSeek } from "@ai-sdk/deepseek"; import { createOpenAI } from "@ai-sdk/openai"; +import { createXai } from "@ai-sdk/xai"; import { ChatCompletion, ChatCompletionChunk, @@ -30,6 +32,8 @@ type AiSdkProviderCreator = (options: { const PROVIDER_MAP: Record = { openai: createOpenAI, anthropic: createAnthropic, + xai: createXai, + deepseek: createDeepSeek, openrouter: (options) => createOpenAI({ ...options, diff --git a/packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts b/packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts index 263c1f2d2..36a600f44 100644 --- a/packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts +++ b/packages/openai-adapters/src/apis/AnthropicCachingStrategies.test.ts @@ -210,6 +210,146 @@ describe("AnthropicCachingStrategies", () => { expect(result.messages).toEqual(body.messages); }); + it("should add cache_control to last two user messages for turn-level caching", () => { + const body: MessageCreateParams = { + system: [{ type: "text", text: "system message" }], + tools: [makeTool("tool1")], + messages: [ + { + role: "user", + content: [{ type: "text", text: "first user message" }], + }, + { + role: "assistant", + content: [{ type: "text", text: "assistant reply" }], + }, + { + role: "user", + content: [{ type: "text", text: "second user message" }], + }, + { + role: "assistant", + content: [{ type: "text", text: "another assistant reply" }], + }, + { + role: "user", + content: [{ type: "text", text: "third user message" }], + }, + ], + ...body_params, + }; + + const result = CACHING_STRATEGIES.systemAndTools(body); + + // System and tools should still be cached + expect(result.system).toEqual([ + { + type: "text", + text: "system message", + cache_control: { type: "ephemeral" }, + }, + ]); + expect(result.tools).toEqual([ + { + name: "tool1", + input_schema: { type: "object" }, + cache_control: { type: "ephemeral" }, + }, + ]); + + // Last two user messages should have cache_control + // First user message (index 0) should NOT have cache_control + expect(result.messages[0]).toEqual({ + role: "user", + content: [{ type: "text", text: "first user message" }], + }); + + // Second user message (index 2) should have cache_control (second-to-last user msg) + expect(result.messages[2]).toEqual({ + role: "user", + content: [ + { + type: "text", + text: "second user message", + cache_control: { type: "ephemeral" }, + }, + ], + }); + + // Third user message (index 4) should have cache_control (last user msg) + expect(result.messages[4]).toEqual({ + role: "user", + content: [ + { + type: "text", + text: "third user message", + cache_control: { type: "ephemeral" }, + }, + ], + }); + }); + + it("should not add cache_control to string content user messages", () => { + const body: MessageCreateParams = { + system: [{ type: "text", text: "system message" }], + messages: [ + { role: "user", content: "string content message" }, + { + role: "assistant", + content: [{ type: "text", text: "reply" }], + }, + { + role: "user", + content: [{ type: "text", text: "array content message" }], + }, + ], + ...body_params, + }; + + const result = CACHING_STRATEGIES.systemAndTools(body); + + // String content user message is skipped by addCacheControlToLastTwoUserMessages + expect(result.messages[0]).toEqual({ + role: "user", + content: "string content message", + }); + + // Array content user message gets cache_control + expect(result.messages[2]).toEqual({ + role: "user", + content: [ + { + type: "text", + text: "array content message", + cache_control: { type: "ephemeral" }, + }, + ], + }); + }); + + it("should not mutate the original input body", () => { + const body: MessageCreateParams = { + system: [{ type: "text", text: "system message" }], + tools: [makeTool("tool1")], + messages: [ + { + role: "user", + content: [{ type: "text", text: "user message" }], + }, + ], + ...body_params, + }; + + // Deep-check original content block before strategy + const originalContentBlock = (body.messages[0].content as any[])[0]; + expect(originalContentBlock.cache_control).toBeUndefined(); + + CACHING_STRATEGIES.systemAndTools(body); + + // Original content block should still NOT have cache_control + expect(originalContentBlock.cache_control).toBeUndefined(); + }); + it("should add only 4 cache controls in total to both system and tools", () => { const body: MessageCreateParams = { system: [ diff --git a/packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts b/packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts index b9a690d0d..ce9e2766a 100644 --- a/packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts +++ b/packages/openai-adapters/src/apis/AnthropicCachingStrategies.ts @@ -1,5 +1,7 @@ import { MessageCreateParams } from "@anthropic-ai/sdk/resources"; +import { addCacheControlToLastTwoUserMessages } from "./AnthropicUtils.js"; + const MAX_CACHING_MESSAGES = 4; // Caching strategy type - transforms a clean Anthropic body by adding cache_control @@ -67,6 +69,17 @@ const systemAndToolsStrategy: CachingStrategy = (body) => { }); } + // Cache last two user messages for turn-level caching. + // Uses the remaining 2 breakpoints (system=1, last tool=1, 2 user messages=2, total=4). + // Clone messages to avoid mutating the original input. + result.messages = result.messages.map((msg) => ({ + ...msg, + content: Array.isArray(msg.content) + ? msg.content.map((block) => ({ ...block })) + : msg.content, + })); + addCacheControlToLastTwoUserMessages(result.messages); + return result; }; diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index acb0c580e..a00b95b81 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -63,7 +63,35 @@ function isHuggingFaceOpenAICompatible(url: string): boolean { return openAIPatterns.some((pattern) => normalizedUrl.includes(pattern)); } +function createAiSdkApiForProvider( + config: LLMConfig & { model?: string }, + provider: string, +): AiSdkApi | undefined { + if (!config.model) { + return undefined; + } + return new AiSdkApi({ + provider: "ai-sdk", + model: `${provider}/${config.model}`, + apiKey: config.apiKey, + apiBase: config.apiBase, + requestOptions: config.requestOptions, + }); +} + export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined { + if (process.env.CONTINUE_USE_AI_SDK) { + if (["openai", "anthropic"].includes(config.provider)) { + const aiSdkApi = createAiSdkApiForProvider( + config as LLMConfig & { model?: string }, + config.provider, + ); + if (aiSdkApi) { + return aiSdkApi; + } + } + } + switch (config.provider) { case "openai": return new OpenAIApi(config); diff --git a/packages/openai-adapters/src/test/anthropic-adapter.vitest.ts b/packages/openai-adapters/src/test/anthropic-adapter.vitest.ts index dba75137c..7df5219cd 100644 --- a/packages/openai-adapters/src/test/anthropic-adapter.vitest.ts +++ b/packages/openai-adapters/src/test/anthropic-adapter.vitest.ts @@ -55,6 +55,7 @@ describe("Anthropic Adapter Tests", () => { role: "user", content: [ { + cache_control: { type: "ephemeral" }, type: "text", text: "hello", }, @@ -119,6 +120,7 @@ describe("Anthropic Adapter Tests", () => { role: "user", content: [ { + cache_control: { type: "ephemeral" }, type: "text", text: "hello", }, @@ -184,6 +186,7 @@ describe("Anthropic Adapter Tests", () => { role: "user", content: [ { + cache_control: { type: "ephemeral" }, type: "text", text: "hello", }, diff --git a/packages/openai-adapters/src/test/anthropic-caching-scenarios.live.test.ts b/packages/openai-adapters/src/test/anthropic-caching-scenarios.live.test.ts new file mode 100644 index 000000000..26b1af25d --- /dev/null +++ b/packages/openai-adapters/src/test/anthropic-caching-scenarios.live.test.ts @@ -0,0 +1,1405 @@ +/** + * Battle test suite for Anthropic prompt caching. + * + * Tests diverse real-world scenarios to validate caching works correctly + * across tool use, long conversations, large payloads, and edge cases. + * + * Guarded by ANTHROPIC_API_KEY env var — skipped if not set. + * Uses claude-haiku-4-5-20251001 to minimize cost. + * + * IMPORTANT: Haiku 4.5 requires a minimum of 4096 tokens for caching. + * + * Run: ANTHROPIC_API_KEY=sk-ant-... npx vitest packages/openai-adapters/src/test/anthropic-caching-scenarios.live.test.ts + */ +import { describe, expect, test } from "vitest"; + +import { constructLlmApi } from "../index.js"; + +const API_KEY = process.env.ANTHROPIC_API_KEY; +const MODEL = "claude-haiku-4-5-20251001"; + +// ─── Shared fixtures ──────────────────────────────────────────────── + +const TOOLS = [ + { + type: "function" as const, + function: { + name: "read_file", + description: + "Read the contents of a file at the given path. Use this when you need to examine existing files in the project. The output includes line numbers prefixed to each line (e.g., '1 | const x = 1'). When reading large files, you may want to specify a line range using the start_line and end_line parameters.", + parameters: { + type: "object" as const, + required: ["path"], + properties: { + path: { + type: "string", + description: + "The path of the file to read, relative to the workspace root", + }, + start_line: { + type: "number", + description: + "The starting line number to read from (1-indexed, inclusive)", + }, + end_line: { + type: "number", + description: + "The ending line number to read to (1-indexed, inclusive)", + }, + }, + }, + }, + }, + { + type: "function" as const, + function: { + name: "write_file", + description: + "Write content to a file at the given path. If the file exists, it will be overwritten. If it doesn't exist, a new file will be created. Always provide the complete intended content of the file.", + parameters: { + type: "object" as const, + required: ["path", "content"], + properties: { + path: { + type: "string", + description: + "The path of the file to write to, relative to the workspace root", + }, + content: { + type: "string", + description: "The full content to write to the file", + }, + }, + }, + }, + }, + { + type: "function" as const, + function: { + name: "run_terminal_command", + description: + "Run a terminal command in the workspace directory. Use this for executing build commands, running tests, installing packages, or any other command-line operations.", + parameters: { + type: "object" as const, + required: ["command"], + properties: { + command: { + type: "string", + description: "The terminal command to execute", + }, + workingDir: { + type: "string", + description: "The working directory for the command", + }, + }, + }, + }, + }, + { + type: "function" as const, + function: { + name: "list_files", + description: + "List files and directories at the given path. If the path is a directory, lists all files and subdirectories within it.", + parameters: { + type: "object" as const, + required: [], + properties: { + path: { + type: "string", + description: + "The path to list files from, relative to the workspace root", + }, + recursive: { + type: "boolean", + description: "Whether to list files recursively in subdirectories", + }, + }, + }, + }, + }, + { + type: "function" as const, + function: { + name: "search_code", + description: + "Search for a pattern across all files in the project. Returns matching lines with file paths and line numbers. Supports regex patterns.", + parameters: { + type: "object" as const, + required: ["pattern"], + properties: { + pattern: { + type: "string", + description: "The search pattern (supports regex)", + }, + file_glob: { + type: "string", + description: "Optional glob pattern to filter files", + }, + max_results: { + type: "number", + description: "Maximum number of results to return", + }, + }, + }, + }, + }, +]; + +// System message large enough to exceed Haiku 4.5's 4096-token minimum +// when combined with the tool definitions above. +const SYSTEM_MESSAGE = `You are an AI coding assistant integrated into a developer's IDE. You help with software engineering tasks including writing code, debugging, explaining code, and more. + +# Environment + +- Operating System: macOS 14.0 +- Shell: zsh +- IDE: VS Code 1.95.0 +- Working Directory: /Users/developer/projects/my-app +- Git Branch: feature/user-management +- Node.js: v20.11.0 +- npm: 10.2.4 +- TypeScript: 5.3.3 +- Docker: 24.0.6 +- PostgreSQL: 16.1 + +# Project Context + +This is a full-stack TypeScript monorepo using pnpm workspaces. The project is a team collaboration platform with the following packages: + +- packages/core: Shared business logic, database models, and services +- packages/api: Express.js REST API with WebSocket support +- packages/web: Next.js frontend with React components +- packages/shared: Shared types, constants, and validators + +# Directory Listing + +\`\`\` +my-app/ +├── .github/ +│ ├── workflows/ +│ │ ├── ci.yml +│ │ ├── deploy.yml +│ │ ├── release.yml +│ │ ├── codeql-analysis.yml +│ │ └── dependency-review.yml +│ ├── CODEOWNERS +│ ├── pull_request_template.md +│ └── ISSUE_TEMPLATE/ +│ ├── bug_report.md +│ ├── feature_request.md +│ └── config.yml +├── packages/ +│ ├── core/ +│ │ ├── src/ +│ │ │ ├── auth/ +│ │ │ │ ├── index.ts +│ │ │ │ ├── jwt.ts +│ │ │ │ ├── oauth.ts +│ │ │ │ ├── middleware.ts +│ │ │ │ ├── rbac.ts +│ │ │ │ ├── session.ts +│ │ │ │ └── types.ts +│ │ │ ├── database/ +│ │ │ │ ├── index.ts +│ │ │ │ ├── connection.ts +│ │ │ │ ├── migrations/ +│ │ │ │ │ ├── 001_create_users.ts +│ │ │ │ │ ├── 002_create_projects.ts +│ │ │ │ │ ├── 003_create_teams.ts +│ │ │ │ │ ├── 004_create_notifications.ts +│ │ │ │ │ └── 005_create_audit_log.ts +│ │ │ │ ├── models/ +│ │ │ │ │ ├── User.ts +│ │ │ │ │ ├── Project.ts +│ │ │ │ │ ├── Team.ts +│ │ │ │ │ ├── TeamMember.ts +│ │ │ │ │ ├── Notification.ts +│ │ │ │ │ ├── AuditLog.ts +│ │ │ │ │ └── index.ts +│ │ │ │ └── seeds/ +│ │ │ │ ├── development.ts +│ │ │ │ └── test.ts +│ │ │ ├── services/ +│ │ │ │ ├── user.service.ts +│ │ │ │ ├── project.service.ts +│ │ │ │ ├── team.service.ts +│ │ │ │ ├── notification.service.ts +│ │ │ │ ├── analytics.service.ts +│ │ │ │ ├── email.service.ts +│ │ │ │ ├── cache.service.ts +│ │ │ │ └── search.service.ts +│ │ │ ├── events/ +│ │ │ │ ├── index.ts +│ │ │ │ ├── emitter.ts +│ │ │ │ ├── handlers/ +│ │ │ │ │ ├── user.handler.ts +│ │ │ │ │ ├── project.handler.ts +│ │ │ │ │ └── notification.handler.ts +│ │ │ │ └── types.ts +│ │ │ ├── queue/ +│ │ │ │ ├── index.ts +│ │ │ │ ├── workers/ +│ │ │ │ │ ├── email.worker.ts +│ │ │ │ │ ├── analytics.worker.ts +│ │ │ │ │ └── cleanup.worker.ts +│ │ │ │ └── types.ts +│ │ │ └── utils/ +│ │ │ ├── logger.ts +│ │ │ ├── errors.ts +│ │ │ ├── validation.ts +│ │ │ ├── crypto.ts +│ │ │ ├── date.ts +│ │ │ └── retry.ts +│ │ ├── tests/ +│ │ │ ├── auth.test.ts +│ │ │ ├── services.test.ts +│ │ │ ├── events.test.ts +│ │ │ ├── queue.test.ts +│ │ │ └── utils.test.ts +│ │ ├── package.json +│ │ └── tsconfig.json +│ ├── api/ +│ │ ├── src/ +│ │ │ ├── routes/ +│ │ │ │ ├── users.ts +│ │ │ │ ├── projects.ts +│ │ │ │ ├── teams.ts +│ │ │ │ ├── webhooks.ts +│ │ │ │ ├── health.ts +│ │ │ │ ├── search.ts +│ │ │ │ └── admin.ts +│ │ │ ├── middleware/ +│ │ │ │ ├── auth.ts +│ │ │ │ ├── rateLimit.ts +│ │ │ │ ├── cors.ts +│ │ │ │ ├── requestId.ts +│ │ │ │ ├── logging.ts +│ │ │ │ └── validation.ts +│ │ │ ├── websocket/ +│ │ │ │ ├── index.ts +│ │ │ │ ├── handlers.ts +│ │ │ │ └── types.ts +│ │ │ └── index.ts +│ │ ├── tests/ +│ │ ├── package.json +│ │ └── tsconfig.json +│ ├── web/ +│ │ ├── src/ +│ │ │ ├── components/ +│ │ │ │ ├── common/ +│ │ │ │ │ ├── Button.tsx +│ │ │ │ │ ├── Input.tsx +│ │ │ │ │ ├── Modal.tsx +│ │ │ │ │ ├── Table.tsx +│ │ │ │ │ └── Loading.tsx +│ │ │ │ ├── layout/ +│ │ │ │ │ ├── Header.tsx +│ │ │ │ │ ├── Footer.tsx +│ │ │ │ │ ├── Sidebar.tsx +│ │ │ │ │ └── Layout.tsx +│ │ │ │ ├── dashboard/ +│ │ │ │ │ ├── Dashboard.tsx +│ │ │ │ │ ├── ProjectCard.tsx +│ │ │ │ │ ├── ActivityFeed.tsx +│ │ │ │ │ └── Stats.tsx +│ │ │ │ ├── settings/ +│ │ │ │ │ ├── Settings.tsx +│ │ │ │ │ ├── ProfileForm.tsx +│ │ │ │ │ ├── SecuritySettings.tsx +│ │ │ │ │ └── NotificationPrefs.tsx +│ │ │ │ └── team/ +│ │ │ │ ├── TeamList.tsx +│ │ │ │ ├── TeamDetail.tsx +│ │ │ │ ├── MemberList.tsx +│ │ │ │ └── InviteForm.tsx +│ │ │ ├── hooks/ +│ │ │ │ ├── useAuth.ts +│ │ │ │ ├── useApi.ts +│ │ │ │ ├── useTheme.ts +│ │ │ │ ├── useWebSocket.ts +│ │ │ │ ├── useDebounce.ts +│ │ │ │ └── usePagination.ts +│ │ │ ├── pages/ +│ │ │ │ ├── index.tsx +│ │ │ │ ├── login.tsx +│ │ │ │ ├── register.tsx +│ │ │ │ ├── dashboard.tsx +│ │ │ │ ├── settings.tsx +│ │ │ │ ├── project/[id].tsx +│ │ │ │ └── team/[id].tsx +│ │ │ ├── store/ +│ │ │ │ ├── index.ts +│ │ │ │ ├── authSlice.ts +│ │ │ │ ├── projectSlice.ts +│ │ │ │ └── uiSlice.ts +│ │ │ ├── styles/ +│ │ │ │ ├── globals.css +│ │ │ │ └── theme.ts +│ │ │ ├── lib/ +│ │ │ │ ├── api.ts +│ │ │ │ ├── auth.ts +│ │ │ │ └── utils.ts +│ │ │ └── App.tsx +│ │ ├── public/ +│ │ ├── tests/ +│ │ ├── package.json +│ │ └── tsconfig.json +│ └── shared/ +│ ├── src/ +│ │ ├── types/ +│ │ │ ├── user.ts +│ │ │ ├── project.ts +│ │ │ ├── team.ts +│ │ │ ├── api.ts +│ │ │ └── index.ts +│ │ ├── constants/ +│ │ │ ├── permissions.ts +│ │ │ ├── errors.ts +│ │ │ └── config.ts +│ │ └── validators/ +│ │ ├── user.ts +│ │ ├── project.ts +│ │ └── team.ts +│ ├── package.json +│ └── tsconfig.json +├── infrastructure/ +│ ├── terraform/ +│ │ ├── main.tf +│ │ ├── variables.tf +│ │ ├── outputs.tf +│ │ └── modules/ +│ │ ├── vpc/ +│ │ ├── ecs/ +│ │ ├── rds/ +│ │ └── redis/ +│ ├── docker/ +│ │ ├── Dockerfile.api +│ │ ├── Dockerfile.web +│ │ └── docker-compose.prod.yml +│ └── k8s/ +│ ├── deployment.yaml +│ ├── service.yaml +│ ├── ingress.yaml +│ └── configmap.yaml +├── scripts/ +│ ├── deploy.sh +│ ├── setup.sh +│ ├── seed-db.ts +│ ├── migrate.ts +│ └── health-check.sh +├── .env.example +├── .eslintrc.js +├── .gitignore +├── .prettierrc +├── docker-compose.yml +├── package.json +├── pnpm-workspace.yaml +├── README.md +└── tsconfig.base.json +\`\`\` + +# Code Style + +- Use 2-space indentation for TypeScript/JavaScript +- Use single quotes for strings, prefer const over let +- Strict TypeScript with no implicit any +- PascalCase for types/interfaces/classes/components, camelCase for variables/functions +- Named exports over default exports +- async/await over raw promises +- Add JSDoc comments for public API functions +- Prefer functional patterns and early returns +- Template literals over string concatenation +- Explicit error handling, never swallow exceptions + +# Testing + +- Unit tests for all business logic, integration tests for API routes +- describe/it blocks with descriptive names, AAA pattern +- Mock external dependencies, 80% coverage minimum on new code +- Test error cases and edge cases, not just happy paths`; + +// ─── Helpers ──────────────────────────────────────────────────────── + +/** Total input tokens = cache_read + cache_write + uncached (prompt_tokens) */ +function totalInputTokens(usage: any): number { + const details = usage.prompt_tokens_details; + return ( + (details?.cache_read_tokens ?? 0) + + (details?.cache_write_tokens ?? 0) + + usage.prompt_tokens + ); +} + +function cacheHitRate(usage: any): number { + const total = totalInputTokens(usage); + const read = usage.prompt_tokens_details?.cache_read_tokens ?? 0; + return total > 0 ? read / total : 0; +} + +function makeApi() { + return constructLlmApi({ + provider: "anthropic", + apiKey: API_KEY!, + })!; +} + +const signal = new AbortController().signal; + +// ─── Tests ────────────────────────────────────────────────────────── + +describe.skipIf(!API_KEY)( + "Anthropic Prompt Caching - Battle Test Scenarios", + () => { + // ── Scenario 1: Tool use round-trip ────────────────────────── + // Simulates: user asks to read a file → assistant calls read_file → + // tool result with file content → assistant explains → user follow-up. + // Validates caching with tool_use and tool_result blocks in conversation. + describe("Scenario 1: Tool use round-trip", () => { + const api = makeApi(); + let turn1Content = ""; + + test( + "Turn 1: initial request with tool use history creates cache", + { timeout: 30_000 }, + async () => { + // Simulate a conversation where the assistant already called a tool + // and we're continuing with the tool result + follow-up + const response = await api.chatCompletionNonStream( + { + model: MODEL, + messages: [ + { role: "system", content: SYSTEM_MESSAGE }, + { + role: "user", + content: "Can you read the user service file?", + }, + { + role: "assistant", + content: null, + tool_calls: [ + { + id: "toolu_01abc", + type: "function", + function: { + name: "read_file", + arguments: JSON.stringify({ + path: "packages/core/src/services/user.service.ts", + }), + }, + }, + ], + }, + { + role: "tool", + tool_call_id: "toolu_01abc", + content: [ + "1 | import { db } from '../database';", + "2 | import { User, CreateUserInput } from '../database/models/User';", + "3 | import { hashPassword, verifyPassword } from '../utils/crypto';", + "4 | import { logger } from '../utils/logger';", + "5 | import { AppError } from '../utils/errors';", + "6 |", + "7 | export class UserService {", + "8 | async createUser(input: CreateUserInput): Promise {", + "9 | const existing = await db.users.findByEmail(input.email);", + "10| if (existing) throw new AppError('EMAIL_EXISTS', 'Email already registered');", + "11| const hashedPassword = await hashPassword(input.password);", + "12| return db.users.create({ ...input, password: hashedPassword });", + "13| }", + "14|", + "15| async getUserById(id: string): Promise {", + "16| return db.users.findById(id);", + "17| }", + "18|", + "19| async updateUser(id: string, updates: Partial): Promise {", + "20| const user = await this.getUserById(id);", + "21| if (!user) throw new AppError('NOT_FOUND', 'User not found');", + "22| return db.users.update(id, updates);", + "23| }", + "24|", + "25| async deleteUser(id: string): Promise {", + "26| await db.users.delete(id);", + "27| }", + "28|", + "29| async authenticateUser(email: string, password: string): Promise {", + "30| const user = await db.users.findByEmail(email);", + "31| if (!user) throw new AppError('AUTH_FAILED', 'Invalid credentials');", + "32| const valid = await verifyPassword(password, user.password);", + "33| if (!valid) throw new AppError('AUTH_FAILED', 'Invalid credentials');", + "34| return user;", + "35| }", + "36| }", + ].join("\n"), + }, + { + role: "user", + content: + "I see the user service. Can you add a method to search users by name?", + }, + ], + tools: TOOLS, + max_tokens: 256, + }, + signal, + ); + + const usage = response.usage!; + const details = usage.prompt_tokens_details as any; + turn1Content = + response.choices[0].message.content ?? "Here's the method."; + + expect(details?.cache_write_tokens).toBeGreaterThan(0); + + console.log("Scenario 1 Turn 1:", { + cache_write: details?.cache_write_tokens, + cache_read: details?.cache_read_tokens, + total: totalInputTokens(usage), + }); + }, + ); + + test( + "Turn 2: follow-up after tool use hits cache", + { timeout: 30_000 }, + async () => { + const response = await api.chatCompletionNonStream( + { + model: MODEL, + messages: [ + { role: "system", content: SYSTEM_MESSAGE }, + { + role: "user", + content: "Can you read the user service file?", + }, + { + role: "assistant", + content: null, + tool_calls: [ + { + id: "toolu_01abc", + type: "function", + function: { + name: "read_file", + arguments: JSON.stringify({ + path: "packages/core/src/services/user.service.ts", + }), + }, + }, + ], + }, + { + role: "tool", + tool_call_id: "toolu_01abc", + content: [ + "1 | import { db } from '../database';", + "2 | import { User, CreateUserInput } from '../database/models/User';", + "3 | import { hashPassword, verifyPassword } from '../utils/crypto';", + "4 | import { logger } from '../utils/logger';", + "5 | import { AppError } from '../utils/errors';", + "6 |", + "7 | export class UserService {", + "8 | async createUser(input: CreateUserInput): Promise {", + "9 | const existing = await db.users.findByEmail(input.email);", + "10| if (existing) throw new AppError('EMAIL_EXISTS', 'Email already registered');", + "11| const hashedPassword = await hashPassword(input.password);", + "12| return db.users.create({ ...input, password: hashedPassword });", + "13| }", + "14|", + "15| async getUserById(id: string): Promise {", + "16| return db.users.findById(id);", + "17| }", + "18|", + "19| async updateUser(id: string, updates: Partial): Promise {", + "20| const user = await this.getUserById(id);", + "21| if (!user) throw new AppError('NOT_FOUND', 'User not found');", + "22| return db.users.update(id, updates);", + "23| }", + "24|", + "25| async deleteUser(id: string): Promise {", + "26| await db.users.delete(id);", + "27| }", + "28|", + "29| async authenticateUser(email: string, password: string): Promise {", + "30| const user = await db.users.findByEmail(email);", + "31| if (!user) throw new AppError('AUTH_FAILED', 'Invalid credentials');", + "32| const valid = await verifyPassword(password, user.password);", + "33| if (!valid) throw new AppError('AUTH_FAILED', 'Invalid credentials');", + "34| return user;", + "35| }", + "36| }", + ].join("\n"), + }, + { + role: "user", + content: + "I see the user service. Can you add a method to search users by name?", + }, + { role: "assistant", content: turn1Content }, + { + role: "user", + content: + "Good. Now also add pagination support to that search method.", + }, + ], + tools: TOOLS, + max_tokens: 256, + }, + signal, + ); + + const usage = response.usage!; + const details = usage.prompt_tokens_details as any; + const rate = cacheHitRate(usage); + + expect(details?.cache_read_tokens).toBeGreaterThan(0); + expect(rate).toBeGreaterThan(0.5); + + console.log("Scenario 1 Turn 2:", { + cache_write: details?.cache_write_tokens, + cache_read: details?.cache_read_tokens, + hit_rate: rate.toFixed(3), + }); + }, + ); + }); + + // ── Scenario 2: Parallel tool calls ────────────────────────── + // Simulates: assistant calls multiple tools at once (read_file + + // list_files), both return results, then user asks follow-up. + // Validates caching with multiple tool_use + tool_result blocks. + describe("Scenario 2: Parallel tool calls", () => { + const api = makeApi(); + + test( + "Turn 1: conversation with parallel tool calls creates cache", + { timeout: 30_000 }, + async () => { + const response = await api.chatCompletionNonStream( + { + model: MODEL, + messages: [ + { role: "system", content: SYSTEM_MESSAGE }, + { + role: "user", + content: + "Show me the team routes and list the test files for the API package.", + }, + { + role: "assistant", + content: null, + tool_calls: [ + { + id: "toolu_read1", + type: "function", + function: { + name: "read_file", + arguments: JSON.stringify({ + path: "packages/api/src/routes/teams.ts", + }), + }, + }, + { + id: "toolu_list1", + type: "function", + function: { + name: "list_files", + arguments: JSON.stringify({ + path: "packages/api/tests", + recursive: true, + }), + }, + }, + ], + }, + { + role: "tool", + tool_call_id: "toolu_read1", + content: [ + "1 | import { Router } from 'express';", + "2 | import { TeamService } from '@my-app/core';", + "3 | import { authMiddleware } from '../middleware/auth';", + "4 | import { validateBody } from '../middleware/validation';", + "5 |", + "6 | const router = Router();", + "7 | const teamService = new TeamService();", + "8 |", + "9 | router.get('/', authMiddleware, async (req, res) => {", + "10| const teams = await teamService.listTeams(req.user.id);", + "11| res.json({ teams });", + "12| });", + "13|", + "14| router.post('/', authMiddleware, validateBody('createTeam'), async (req, res) => {", + "15| const team = await teamService.createTeam(req.body, req.user.id);", + "16| res.status(201).json({ team });", + "17| });", + "18|", + "19| export { router as teamRoutes };", + ].join("\n"), + }, + { + role: "tool", + tool_call_id: "toolu_list1", + content: + "routes/\n users.test.ts\n projects.test.ts\n teams.test.ts\nmiddleware/\n auth.test.ts\n rateLimit.test.ts", + }, + { + role: "user", + content: + "Good. The team routes look basic. Can you add CRUD endpoints for team members?", + }, + ], + tools: TOOLS, + max_tokens: 256, + }, + signal, + ); + + const usage = response.usage!; + const details = usage.prompt_tokens_details as any; + expect(details?.cache_write_tokens).toBeGreaterThan(0); + + console.log("Scenario 2 Turn 1:", { + cache_write: details?.cache_write_tokens, + total: totalInputTokens(usage), + }); + }, + ); + + test( + "Turn 2: follow-up after parallel tool calls hits cache", + { timeout: 30_000 }, + async () => { + const response = await api.chatCompletionNonStream( + { + model: MODEL, + messages: [ + { role: "system", content: SYSTEM_MESSAGE }, + { + role: "user", + content: + "Show me the team routes and list the test files for the API package.", + }, + { + role: "assistant", + content: null, + tool_calls: [ + { + id: "toolu_read1", + type: "function", + function: { + name: "read_file", + arguments: JSON.stringify({ + path: "packages/api/src/routes/teams.ts", + }), + }, + }, + { + id: "toolu_list1", + type: "function", + function: { + name: "list_files", + arguments: JSON.stringify({ + path: "packages/api/tests", + recursive: true, + }), + }, + }, + ], + }, + { + role: "tool", + tool_call_id: "toolu_read1", + content: [ + "1 | import { Router } from 'express';", + "2 | import { TeamService } from '@my-app/core';", + "3 | import { authMiddleware } from '../middleware/auth';", + "4 | import { validateBody } from '../middleware/validation';", + "5 |", + "6 | const router = Router();", + "7 | const teamService = new TeamService();", + "8 |", + "9 | router.get('/', authMiddleware, async (req, res) => {", + "10| const teams = await teamService.listTeams(req.user.id);", + "11| res.json({ teams });", + "12| });", + "13|", + "14| router.post('/', authMiddleware, validateBody('createTeam'), async (req, res) => {", + "15| const team = await teamService.createTeam(req.body, req.user.id);", + "16| res.status(201).json({ team });", + "17| });", + "18|", + "19| export { router as teamRoutes };", + ].join("\n"), + }, + { + role: "tool", + tool_call_id: "toolu_list1", + content: + "routes/\n users.test.ts\n projects.test.ts\n teams.test.ts\nmiddleware/\n auth.test.ts\n rateLimit.test.ts", + }, + { + role: "user", + content: + "Good. The team routes look basic. Can you add CRUD endpoints for team members?", + }, + { + role: "assistant", + content: + "I'll add the team member CRUD endpoints to the routes file.", + }, + { + role: "user", + content: "Also add appropriate validation middleware.", + }, + ], + tools: TOOLS, + max_tokens: 256, + }, + signal, + ); + + const usage = response.usage!; + const rate = cacheHitRate(usage); + expect(rate).toBeGreaterThan(0.5); + + console.log("Scenario 2 Turn 2:", { + cache_read: (usage.prompt_tokens_details as any)?.cache_read_tokens, + hit_rate: rate.toFixed(3), + }); + }, + ); + }); + + // ── Scenario 3: Long conversation (8 turns) ───────────────── + // Simulates an extended debugging session with many back-and-forth + // exchanges. Validates cache accumulates over many turns. + test( + "Scenario 3: Long 8-turn conversation maintains high cache rate", + { timeout: 60_000 }, + async () => { + const api = makeApi(); + const messages: any[] = [ + { role: "system", content: SYSTEM_MESSAGE }, + { + role: "user", + content: + "I'm getting a TypeScript error in the auth middleware. The error is: Type 'string | undefined' is not assignable to type 'string'. How do I fix it?", + }, + ]; + + const exchanges = [ + "The error suggests that `req.headers.authorization` might be undefined. You need to add a null check before using it.", + "Can you show me what the fix would look like in code?", + "Here's the fix:\n```typescript\nconst authHeader = req.headers.authorization;\nif (!authHeader) {\n return res.status(401).json({ error: 'Missing authorization header' });\n}\nconst token = authHeader.split(' ')[1];\n```", + "That works but now I'm getting a different error: jwt.verify is throwing 'TokenExpiredError'. How should I handle that?", + "You should wrap the jwt.verify call in a try-catch and handle TokenExpiredError specifically:\n```typescript\ntry {\n const decoded = jwt.verify(token, SECRET);\n req.user = decoded;\n} catch (err) {\n if (err instanceof jwt.TokenExpiredError) {\n return res.status(401).json({ error: 'Token expired', code: 'TOKEN_EXPIRED' });\n }\n return res.status(401).json({ error: 'Invalid token' });\n}\n```", + "Should I also handle the refresh token flow here or in a separate middleware?", + "I'd recommend a separate middleware for refresh tokens. Keep the auth middleware focused on validating access tokens. Create a new `refreshToken.ts` middleware that handles the refresh flow, checks the refresh token's validity, and issues a new access token pair.", + "Makes sense. One more thing - should I add rate limiting specifically to the refresh endpoint?", + ]; + + let lastRate = 0; + + for (let i = 0; i < exchanges.length; i++) { + const isAssistant = i % 2 === 0; + + if (isAssistant) { + // For the first assistant turn (i=0), push the pre-written response. + // For subsequent assistant turns, skip — we already pushed the real + // API response after the previous user turn. + if (i === 0) { + messages.push({ + role: "assistant", + content: exchanges[i], + }); + } + continue; + } + + // Push user message + messages.push({ + role: "user", + content: exchanges[i], + }); + + const response = await api.chatCompletionNonStream( + { + model: MODEL, + messages: [...messages], + tools: TOOLS, + max_tokens: 256, + }, + signal, + ); + + const usage = response.usage!; + const rate = cacheHitRate(usage); + const details = usage.prompt_tokens_details as any; + + console.log(`Scenario 3 turn ${Math.ceil((i + 1) / 2)}:`, { + cache_read: details?.cache_read_tokens, + cache_write: details?.cache_write_tokens, + hit_rate: rate.toFixed(3), + total: totalInputTokens(usage), + }); + + // After the first user turn creates cache, subsequent turns should read + if (i > 1) { + expect(details?.cache_read_tokens).toBeGreaterThan(0); + lastRate = rate; + } + + // Use actual response as next assistant message + messages.push({ + role: "assistant", + content: response.choices[0].message.content ?? "Done.", + }); + } + + // Final turn should have high hit rate + expect(lastRate).toBeGreaterThan(0.5); + }, + ); + + // ── Scenario 4: Large tool result (simulating file read) ───── + // Simulates reading a large file that returns ~500 lines of code. + // Validates caching works with large tool_result content blocks. + describe("Scenario 4: Large tool result payload", () => { + const api = makeApi(); + + // Generate a realistic large file (~200 lines of TypeScript) + const largeFileContent = Array.from({ length: 200 }, (_, i) => { + const line = i + 1; + if (line === 1) + return `${line} | import { Injectable } from '@nestjs/common';`; + if (line === 2) + return `${line} | import { InjectRepository } from '@nestjs/typeorm';`; + if (line === 3) + return `${line} | import { Repository, Like, In } from 'typeorm';`; + if (line <= 5) + return `${line} | import { ${["Logger", "HttpException", "HttpStatus"][line - 4]} } from '@nestjs/common';`; + if (line === 6) return `${line} |`; + if (line === 7) return `${line} | @Injectable()`; + if (line === 8) return `${line} | export class ProjectService {`; + if (line === 9) + return `${line} | private readonly logger = new Logger(ProjectService.name);`; + if (line === 10) return `${line} |`; + // Generate method stubs every ~20 lines + if (line % 20 === 0) + return `${line} | async method${line / 20}(args: Record): Promise {`; + if (line % 20 === 1) + return `${line} | this.logger.log('Executing method${Math.floor(line / 20)}');`; + if (line % 20 === 2) + return `${line} | const result = await this.repository.findOne({ where: args });`; + if (line % 20 === 3) + return `${line} | if (!result) throw new HttpException('Not found', HttpStatus.NOT_FOUND);`; + if (line % 20 === 4) return `${line} | return result;`; + if (line % 20 === 5) return `${line} | }`; + if (line % 20 === 6) return `${line} |`; + return `${line} | // ${["validate input", "transform data", "check permissions", "audit log", "notify subscribers", "update cache", "emit event", "retry on failure", "parse response", "handle error", "sanitize output", "rate limit check", "circuit breaker"][line % 13]}`; + }).join("\n"); + + test( + "Turn 1: request with large tool result creates cache", + { timeout: 30_000 }, + async () => { + const response = await api.chatCompletionNonStream( + { + model: MODEL, + messages: [ + { role: "system", content: SYSTEM_MESSAGE }, + { + role: "user", + content: "Read the project service file, it's quite long.", + }, + { + role: "assistant", + content: null, + tool_calls: [ + { + id: "toolu_bigfile", + type: "function", + function: { + name: "read_file", + arguments: JSON.stringify({ + path: "packages/core/src/services/project.service.ts", + }), + }, + }, + ], + }, + { + role: "tool", + tool_call_id: "toolu_bigfile", + content: largeFileContent, + }, + { + role: "user", + content: + "That's a big file. Can you summarize the main methods?", + }, + ], + tools: TOOLS, + max_tokens: 256, + }, + signal, + ); + + const usage = response.usage!; + const details = usage.prompt_tokens_details as any; + const total = totalInputTokens(usage); + + expect(details?.cache_write_tokens).toBeGreaterThan(0); + expect(total).toBeGreaterThan(5000); // Should be a substantial request + + console.log("Scenario 4 Turn 1:", { + cache_write: details?.cache_write_tokens, + total, + }); + }, + ); + + test( + "Turn 2: follow-up on large file hits cache", + { timeout: 30_000 }, + async () => { + const response = await api.chatCompletionNonStream( + { + model: MODEL, + messages: [ + { role: "system", content: SYSTEM_MESSAGE }, + { + role: "user", + content: "Read the project service file, it's quite long.", + }, + { + role: "assistant", + content: null, + tool_calls: [ + { + id: "toolu_bigfile", + type: "function", + function: { + name: "read_file", + arguments: JSON.stringify({ + path: "packages/core/src/services/project.service.ts", + }), + }, + }, + ], + }, + { + role: "tool", + tool_call_id: "toolu_bigfile", + content: largeFileContent, + }, + { + role: "user", + content: + "That's a big file. Can you summarize the main methods?", + }, + { + role: "assistant", + content: + "The file contains a ProjectService class with 10 methods covering standard CRUD operations.", + }, + { + role: "user", + content: + "Can you refactor method5 to use a transaction instead of a raw query?", + }, + ], + tools: TOOLS, + max_tokens: 256, + }, + signal, + ); + + const usage = response.usage!; + const rate = cacheHitRate(usage); + expect(rate).toBeGreaterThan(0.5); + + console.log("Scenario 4 Turn 2:", { + cache_read: (usage.prompt_tokens_details as any)?.cache_read_tokens, + hit_rate: rate.toFixed(3), + }); + }, + ); + }); + + // ── Scenario 5: Cache invalidation on system message change ── + // Same conversation but with a modified system message. + // Should get a cache miss (everything re-written). + test( + "Scenario 5: Modified system message invalidates cache", + { timeout: 30_000 }, + async () => { + const api = makeApi(); + + // First request with original system message + const resp1 = await api.chatCompletionNonStream( + { + model: MODEL, + messages: [ + { role: "system", content: SYSTEM_MESSAGE }, + { + role: "user", + content: "Explain the project architecture briefly.", + }, + ], + tools: TOOLS, + max_tokens: 128, + }, + signal, + ); + + const usage1 = resp1.usage!; + const details1 = usage1.prompt_tokens_details as any; + const writeTokens1 = details1?.cache_write_tokens ?? 0; + + // Second request with MODIFIED system message (added a line) + const modifiedSystem = + SYSTEM_MESSAGE + "\n\n# Additional Context\n- DEBUG MODE: enabled"; + + const resp2 = await api.chatCompletionNonStream( + { + model: MODEL, + messages: [ + { role: "system", content: modifiedSystem }, + { + role: "user", + content: "Explain the project architecture briefly.", + }, + ], + tools: TOOLS, + max_tokens: 128, + }, + signal, + ); + + const usage2 = resp2.usage!; + const details2 = usage2.prompt_tokens_details as any; + + // Modified system message should cause a cache miss — new write, no read + // (or minimal read if only the tail changed and prefix still matches) + const read2 = details2?.cache_read_tokens ?? 0; + const write2 = details2?.cache_write_tokens ?? 0; + + // The key assertion: when system message changes, we should see new + // cache writes and minimal/no cache reads from the FIRST request's cache + expect(write2).toBeGreaterThan(0); + // The read from the modified request should be less than the original write, + // because the system message prefix changed + expect(read2).toBeLessThan(writeTokens1); + + console.log("Scenario 5:", { + original_write: writeTokens1, + modified_write: write2, + modified_read: read2, + }); + }, + ); + + // ── Scenario 6: Identical request replay (100% cache hit) ──── + // Send the exact same request twice. Second should be a full cache hit. + test( + "Scenario 6: Identical request replay gets full cache hit", + { timeout: 30_000 }, + async () => { + const api = makeApi(); + const request = { + model: MODEL, + messages: [ + { role: "system" as const, content: SYSTEM_MESSAGE }, + { + role: "user" as const, + content: + "List all the database migration files and explain what each one does.", + }, + ], + tools: TOOLS, + max_tokens: 256, + }; + + // First request + const resp1 = await api.chatCompletionNonStream(request, signal); + const usage1 = resp1.usage!; + const details1 = usage1.prompt_tokens_details as any; + const write1 = details1?.cache_write_tokens ?? 0; + + expect(write1).toBeGreaterThan(0); + + // Identical second request + const resp2 = await api.chatCompletionNonStream(request, signal); + const usage2 = resp2.usage!; + const details2 = usage2.prompt_tokens_details as any; + const read2 = details2?.cache_read_tokens ?? 0; + const rate = cacheHitRate(usage2); + + // Should read back approximately what was written + expect(read2).toBeGreaterThan(0); + // Hit rate should be very high (>90%) since it's identical + expect(rate).toBeGreaterThan(0.9); + + console.log("Scenario 6:", { + first_write: write1, + second_read: read2, + hit_rate: rate.toFixed(3), + }); + }, + ); + + // ── Scenario 7: Multi-step tool chain ──────────────────────── + // Simulates: user asks to fix a bug → assistant reads file → assistant + // runs tests → assistant writes fix. Tests caching across a realistic + // multi-step agentic workflow with interleaved tool calls. + test( + "Scenario 7: Multi-step agentic workflow with chained tool calls", + { timeout: 60_000 }, + async () => { + const api = makeApi(); + + // Step 1: user reports bug, assistant reads the file + const messages1: any[] = [ + { role: "system", content: SYSTEM_MESSAGE }, + { + role: "user", + content: + "There's a bug in the team service - when you delete a team, it doesn't clean up the team members. Can you investigate and fix it?", + }, + { + role: "assistant", + content: null, + tool_calls: [ + { + id: "tc_step1", + type: "function", + function: { + name: "read_file", + arguments: JSON.stringify({ + path: "packages/core/src/services/team.service.ts", + }), + }, + }, + ], + }, + { + role: "tool", + tool_call_id: "tc_step1", + content: [ + "1 | import { db } from '../database';", + "2 | import { Team } from '../database/models/Team';", + "3 |", + "4 | export class TeamService {", + "5 | async deleteTeam(teamId: string): Promise {", + "6 | await db.teams.delete(teamId);", + "7 | // BUG: doesn't clean up team members!", + "8 | }", + "9 | }", + ].join("\n"), + }, + { + role: "user", + content: + "I see the file. Can you also check the test file to see if there's a test for this?", + }, + ]; + + const resp1 = await api.chatCompletionNonStream( + { model: MODEL, messages: messages1, tools: TOOLS, max_tokens: 256 }, + signal, + ); + const usage1 = resp1.usage!; + const details1 = usage1.prompt_tokens_details as any; + expect(details1?.cache_write_tokens).toBeGreaterThan(0); + + // Step 2: assistant reads the test file (builds on step 1's cache) + const messages2: any[] = [ + ...messages1, + { + role: "assistant", + content: null, + tool_calls: [ + { + id: "tc_step2", + type: "function", + function: { + name: "read_file", + arguments: JSON.stringify({ + path: "packages/core/tests/services.test.ts", + }), + }, + }, + ], + }, + { + role: "tool", + tool_call_id: "tc_step2", + content: [ + "1 | describe('TeamService', () => {", + "2 | it('should create a team', async () => { /* ... */ });", + "3 | it('should delete a team', async () => {", + "4 | await teamService.deleteTeam('team-1');", + "5 | // Only checks team is deleted, not members", + "6 | expect(await db.teams.findById('team-1')).toBeNull();", + "7 | });", + "8 | });", + ].join("\n"), + }, + { + role: "user", + content: + "Alright, I see the problem. Please write the fix and update the test.", + }, + ]; + + const resp2 = await api.chatCompletionNonStream( + { model: MODEL, messages: messages2, tools: TOOLS, max_tokens: 256 }, + signal, + ); + const usage2 = resp2.usage!; + const rate2 = cacheHitRate(usage2); + + // Step 2 should have a cache hit from step 1's prefix + expect( + (usage2.prompt_tokens_details as any)?.cache_read_tokens, + ).toBeGreaterThan(0); + + // Step 3: another follow-up (builds further on the cache) + const messages3: any[] = [ + ...messages2, + { + role: "assistant", + content: + resp2.choices[0].message.content ?? + "I'll fix the deleteTeam method to also delete team members.", + }, + { + role: "user", + content: + "Good fix. Now run the tests to make sure everything passes.", + }, + ]; + + const resp3 = await api.chatCompletionNonStream( + { model: MODEL, messages: messages3, tools: TOOLS, max_tokens: 256 }, + signal, + ); + const usage3 = resp3.usage!; + const rate3 = cacheHitRate(usage3); + + expect( + (usage3.prompt_tokens_details as any)?.cache_read_tokens, + ).toBeGreaterThan(0); + expect(rate3).toBeGreaterThan(0.4); + + console.log("Scenario 7:", { + step1_write: details1?.cache_write_tokens, + step2_rate: rate2.toFixed(3), + step3_rate: rate3.toFixed(3), + }); + }, + ); + }, +); diff --git a/packages/openai-adapters/src/test/anthropic-caching.live.test.ts b/packages/openai-adapters/src/test/anthropic-caching.live.test.ts new file mode 100644 index 000000000..c0dfe1ebc --- /dev/null +++ b/packages/openai-adapters/src/test/anthropic-caching.live.test.ts @@ -0,0 +1,724 @@ +/** + * Live API test for Anthropic prompt caching. + * + * Validates that the systemAndTools caching strategy produces real cache hits + * when making sequential requests with the same prefix to the Anthropic API. + * + * Guarded by ANTHROPIC_API_KEY env var — skipped if not set. + * Uses claude-haiku-4-5-20251001 to minimize cost. + * + * IMPORTANT: Haiku 4.5 requires a minimum of 4096 tokens for caching. + * The system message + tools in this test are sized to exceed that threshold. + * + * Run: ANTHROPIC_API_KEY=sk-ant-... npx vitest packages/openai-adapters/src/test/anthropic-caching.live.test.ts + */ +import { describe, expect, test } from "vitest"; + +import { constructLlmApi } from "../index.js"; + +const API_KEY = process.env.ANTHROPIC_API_KEY; +const MODEL = "claude-haiku-4-5-20251001"; + +// Realistic tool definitions mimicking CLI's builtin tools +const REALISTIC_TOOLS = [ + { + type: "function" as const, + function: { + name: "read_file", + description: + "Read the contents of a file at the given path. Use this when you need to examine existing files in the project. The output includes line numbers prefixed to each line (e.g., '1 | const x = 1'). When reading large files, you may want to specify a line range using the start_line and end_line parameters.", + parameters: { + type: "object" as const, + required: ["path"], + properties: { + path: { + type: "string", + description: + "The path of the file to read, relative to the workspace root", + }, + start_line: { + type: "number", + description: + "The starting line number to read from (1-indexed, inclusive)", + }, + end_line: { + type: "number", + description: + "The ending line number to read to (1-indexed, inclusive)", + }, + }, + }, + }, + }, + { + type: "function" as const, + function: { + name: "write_file", + description: + "Write content to a file at the given path. If the file exists, it will be overwritten. If it doesn't exist, a new file will be created. Always provide the complete intended content of the file. Avoid writing partial content that requires manual additions.", + parameters: { + type: "object" as const, + required: ["path", "content"], + properties: { + path: { + type: "string", + description: + "The path of the file to write to, relative to the workspace root", + }, + content: { + type: "string", + description: "The full content to write to the file", + }, + }, + }, + }, + }, + { + type: "function" as const, + function: { + name: "list_files", + description: + "List files and directories at the given path. If the path is a directory, lists all files and subdirectories within it. If no path is provided, lists files in the current working directory. Results include file type indicators.", + parameters: { + type: "object" as const, + required: [], + properties: { + path: { + type: "string", + description: + "The path to list files from, relative to the workspace root", + }, + recursive: { + type: "boolean", + description: "Whether to list files recursively in subdirectories", + }, + }, + }, + }, + }, + { + type: "function" as const, + function: { + name: "run_terminal_command", + description: + "Run a terminal command in the workspace directory. Use this for executing build commands, running tests, installing packages, or any other command-line operations. The command runs in a shell environment with access to standard tools.", + parameters: { + type: "object" as const, + required: ["command"], + properties: { + command: { + type: "string", + description: "The terminal command to execute", + }, + workingDir: { + type: "string", + description: "The working directory for the command", + }, + }, + }, + }, + }, + { + type: "function" as const, + function: { + name: "fetch_url", + description: + "Fetch the content of a URL. Use this to retrieve documentation, API responses, or any web content that might be needed for the task at hand.", + parameters: { + type: "object" as const, + required: ["url"], + properties: { + url: { + type: "string", + description: "The URL to fetch content from", + }, + }, + }, + }, + }, + { + type: "function" as const, + function: { + name: "write_checklist", + description: + "Write or update a checklist for tracking progress on complex tasks. Checklists help organize multi-step work and provide visibility into what has been completed.", + parameters: { + type: "object" as const, + required: ["items"], + properties: { + items: { + type: "array", + description: "Array of checklist items with status", + items: { + type: "object", + properties: { + text: { type: "string" }, + checked: { type: "boolean" }, + }, + }, + }, + }, + }, + }, + }, + { + type: "function" as const, + function: { + name: "check_background_job", + description: + "Check the status of a background job that was previously started. Returns the current output and status of the job.", + parameters: { + type: "object" as const, + required: ["jobId"], + properties: { + jobId: { + type: "string", + description: "The ID of the background job to check", + }, + }, + }, + }, + }, +]; + +// System message sized to exceed Haiku 4.5's 4096-token caching minimum. +// The system message + tools together must be > 4096 tokens. +// This realistic message mimics the CLI's baseSystemMessage with extensive +// directory listings and detailed instructions. +const REALISTIC_SYSTEM_MESSAGE = `You are an AI coding assistant integrated into a developer's IDE. You help with software engineering tasks including writing code, debugging, explaining code, and more. + +# Environment + +- Operating System: macOS 14.0 +- Shell: zsh +- IDE: VS Code 1.95.0 +- Working Directory: /Users/developer/projects/my-app +- Git Branch: main +- Node.js: v20.11.0 +- npm: 10.2.4 +- TypeScript: 5.3.3 +- Python: 3.12.0 +- Docker: 24.0.6 +- PostgreSQL: 16.1 +- Redis: 7.2.3 + +# Directory Listing + +The following is the full directory structure of the workspace: + +\`\`\` +my-app/ +├── .github/ +│ ├── workflows/ +│ │ ├── ci.yml +│ │ ├── deploy.yml +│ │ ├── release.yml +│ │ ├── codeql-analysis.yml +│ │ └── dependency-review.yml +│ ├── CODEOWNERS +│ ├── pull_request_template.md +│ ├── ISSUE_TEMPLATE/ +│ │ ├── bug_report.md +│ │ ├── feature_request.md +│ │ └── config.yml +│ └── dependabot.yml +├── .vscode/ +│ ├── settings.json +│ ├── extensions.json +│ ├── launch.json +│ └── tasks.json +├── docs/ +│ ├── api/ +│ │ ├── authentication.md +│ │ ├── endpoints.md +│ │ ├── rate-limiting.md +│ │ ├── websockets.md +│ │ ├── pagination.md +│ │ └── error-codes.md +│ ├── architecture/ +│ │ ├── overview.md +│ │ ├── database-schema.md +│ │ ├── deployment.md +│ │ ├── caching-strategy.md +│ │ ├── event-sourcing.md +│ │ └── microservices.md +│ ├── guides/ +│ │ ├── getting-started.md +│ │ ├── contributing.md +│ │ ├── code-review.md +│ │ ├── testing.md +│ │ └── debugging.md +│ └── adr/ +│ ├── 001-use-typescript.md +│ ├── 002-monorepo-structure.md +│ ├── 003-database-choice.md +│ ├── 004-auth-strategy.md +│ └── 005-api-versioning.md +├── packages/ +│ ├── core/ +│ │ ├── src/ +│ │ │ ├── auth/ +│ │ │ │ ├── index.ts +│ │ │ │ ├── jwt.ts +│ │ │ │ ├── oauth.ts +│ │ │ │ ├── middleware.ts +│ │ │ │ ├── rbac.ts +│ │ │ │ ├── session.ts +│ │ │ │ └── types.ts +│ │ │ ├── database/ +│ │ │ │ ├── index.ts +│ │ │ │ ├── connection.ts +│ │ │ │ ├── migrations/ +│ │ │ │ │ ├── 001_create_users.ts +│ │ │ │ │ ├── 002_create_projects.ts +│ │ │ │ │ ├── 003_create_teams.ts +│ │ │ │ │ ├── 004_create_notifications.ts +│ │ │ │ │ └── 005_create_audit_log.ts +│ │ │ │ ├── models/ +│ │ │ │ │ ├── User.ts +│ │ │ │ │ ├── Project.ts +│ │ │ │ │ ├── Team.ts +│ │ │ │ │ ├── TeamMember.ts +│ │ │ │ │ ├── Notification.ts +│ │ │ │ │ ├── AuditLog.ts +│ │ │ │ │ └── index.ts +│ │ │ │ └── seeds/ +│ │ │ │ ├── development.ts +│ │ │ │ └── test.ts +│ │ │ ├── services/ +│ │ │ │ ├── user.service.ts +│ │ │ │ ├── project.service.ts +│ │ │ │ ├── team.service.ts +│ │ │ │ ├── notification.service.ts +│ │ │ │ ├── analytics.service.ts +│ │ │ │ ├── email.service.ts +│ │ │ │ ├── cache.service.ts +│ │ │ │ └── search.service.ts +│ │ │ ├── events/ +│ │ │ │ ├── index.ts +│ │ │ │ ├── emitter.ts +│ │ │ │ ├── handlers/ +│ │ │ │ │ ├── user.handler.ts +│ │ │ │ │ ├── project.handler.ts +│ │ │ │ │ └── notification.handler.ts +│ │ │ │ └── types.ts +│ │ │ ├── queue/ +│ │ │ │ ├── index.ts +│ │ │ │ ├── workers/ +│ │ │ │ │ ├── email.worker.ts +│ │ │ │ │ ├── analytics.worker.ts +│ │ │ │ │ └── cleanup.worker.ts +│ │ │ │ └── types.ts +│ │ │ └── utils/ +│ │ │ ├── logger.ts +│ │ │ ├── errors.ts +│ │ │ ├── validation.ts +│ │ │ ├── crypto.ts +│ │ │ ├── date.ts +│ │ │ └── retry.ts +│ │ ├── tests/ +│ │ │ ├── auth.test.ts +│ │ │ ├── services.test.ts +│ │ │ ├── events.test.ts +│ │ │ ├── queue.test.ts +│ │ │ └── utils.test.ts +│ │ ├── package.json +│ │ └── tsconfig.json +│ ├── api/ +│ │ ├── src/ +│ │ │ ├── routes/ +│ │ │ │ ├── users.ts +│ │ │ │ ├── projects.ts +│ │ │ │ ├── teams.ts +│ │ │ │ ├── webhooks.ts +│ │ │ │ ├── health.ts +│ │ │ │ ├── search.ts +│ │ │ │ └── admin.ts +│ │ │ ├── middleware/ +│ │ │ │ ├── auth.ts +│ │ │ │ ├── rateLimit.ts +│ │ │ │ ├── cors.ts +│ │ │ │ ├── requestId.ts +│ │ │ │ ├── logging.ts +│ │ │ │ └── validation.ts +│ │ │ ├── websocket/ +│ │ │ │ ├── index.ts +│ │ │ │ ├── handlers.ts +│ │ │ │ └── types.ts +│ │ │ └── index.ts +│ │ ├── tests/ +│ │ │ ├── routes/ +│ │ │ │ ├── users.test.ts +│ │ │ │ ├── projects.test.ts +│ │ │ │ └── teams.test.ts +│ │ │ └── middleware/ +│ │ │ ├── auth.test.ts +│ │ │ └── rateLimit.test.ts +│ │ ├── package.json +│ │ └── tsconfig.json +│ ├── web/ +│ │ ├── src/ +│ │ │ ├── components/ +│ │ │ │ ├── common/ +│ │ │ │ │ ├── Button.tsx +│ │ │ │ │ ├── Input.tsx +│ │ │ │ │ ├── Modal.tsx +│ │ │ │ │ ├── Table.tsx +│ │ │ │ │ ├── Toast.tsx +│ │ │ │ │ └── Loading.tsx +│ │ │ │ ├── layout/ +│ │ │ │ │ ├── Header.tsx +│ │ │ │ │ ├── Footer.tsx +│ │ │ │ │ ├── Sidebar.tsx +│ │ │ │ │ └── Layout.tsx +│ │ │ │ ├── dashboard/ +│ │ │ │ │ ├── Dashboard.tsx +│ │ │ │ │ ├── ProjectCard.tsx +│ │ │ │ │ ├── ActivityFeed.tsx +│ │ │ │ │ └── Stats.tsx +│ │ │ │ ├── settings/ +│ │ │ │ │ ├── Settings.tsx +│ │ │ │ │ ├── ProfileForm.tsx +│ │ │ │ │ ├── SecuritySettings.tsx +│ │ │ │ │ └── NotificationPrefs.tsx +│ │ │ │ └── team/ +│ │ │ │ ├── TeamList.tsx +│ │ │ │ ├── TeamDetail.tsx +│ │ │ │ ├── MemberList.tsx +│ │ │ │ └── InviteForm.tsx +│ │ │ ├── hooks/ +│ │ │ │ ├── useAuth.ts +│ │ │ │ ├── useApi.ts +│ │ │ │ ├── useTheme.ts +│ │ │ │ ├── useWebSocket.ts +│ │ │ │ ├── useDebounce.ts +│ │ │ │ └── usePagination.ts +│ │ │ ├── pages/ +│ │ │ │ ├── index.tsx +│ │ │ │ ├── login.tsx +│ │ │ │ ├── register.tsx +│ │ │ │ ├── dashboard.tsx +│ │ │ │ ├── settings.tsx +│ │ │ │ ├── project/[id].tsx +│ │ │ │ └── team/[id].tsx +│ │ │ ├── store/ +│ │ │ │ ├── index.ts +│ │ │ │ ├── authSlice.ts +│ │ │ │ ├── projectSlice.ts +│ │ │ │ └── uiSlice.ts +│ │ │ ├── styles/ +│ │ │ │ ├── globals.css +│ │ │ │ ├── theme.ts +│ │ │ │ └── animations.css +│ │ │ ├── lib/ +│ │ │ │ ├── api.ts +│ │ │ │ ├── auth.ts +│ │ │ │ └── utils.ts +│ │ │ └── App.tsx +│ │ ├── public/ +│ │ │ ├── favicon.ico +│ │ │ └── manifest.json +│ │ ├── tests/ +│ │ │ ├── components/ +│ │ │ └── pages/ +│ │ ├── package.json +│ │ └── tsconfig.json +│ └── shared/ +│ ├── src/ +│ │ ├── types/ +│ │ │ ├── user.ts +│ │ │ ├── project.ts +│ │ │ ├── team.ts +│ │ │ ├── api.ts +│ │ │ └── index.ts +│ │ ├── constants/ +│ │ │ ├── permissions.ts +│ │ │ ├── errors.ts +│ │ │ └── config.ts +│ │ └── validators/ +│ │ ├── user.ts +│ │ ├── project.ts +│ │ └── team.ts +│ ├── package.json +│ └── tsconfig.json +├── infrastructure/ +│ ├── terraform/ +│ │ ├── main.tf +│ │ ├── variables.tf +│ │ ├── outputs.tf +│ │ └── modules/ +│ │ ├── vpc/ +│ │ ├── ecs/ +│ │ ├── rds/ +│ │ └── redis/ +│ ├── docker/ +│ │ ├── Dockerfile.api +│ │ ├── Dockerfile.web +│ │ └── docker-compose.prod.yml +│ └── k8s/ +│ ├── deployment.yaml +│ ├── service.yaml +│ ├── ingress.yaml +│ └── configmap.yaml +├── scripts/ +│ ├── deploy.sh +│ ├── setup.sh +│ ├── seed-db.ts +│ ├── migrate.ts +│ ├── generate-api-docs.ts +│ └── health-check.sh +├── .env.example +├── .eslintrc.js +├── .gitignore +├── .prettierrc +├── docker-compose.yml +├── docker-compose.test.yml +├── Dockerfile +├── Makefile +├── package.json +├── pnpm-workspace.yaml +├── README.md +├── CHANGELOG.md +├── LICENSE +└── tsconfig.base.json +\`\`\` + +# Instructions + +You are a helpful AI coding assistant. Follow these guidelines: + +1. Always provide complete, working code solutions +2. Follow the project's existing coding style and conventions +3. Write clean, maintainable code with appropriate error handling +4. Use TypeScript types and interfaces where applicable +5. Consider edge cases and potential issues +6. Explain your reasoning when making architectural decisions +7. Prefer editing existing files over creating new ones +8. Run tests after making changes to ensure nothing is broken +9. Use the available tools to explore the codebase before making changes +10. Keep changes focused and minimal - don't over-engineer solutions + +When using tools, prefer: +- read_file to understand existing code before modifying +- list_files to explore project structure +- run_terminal_command for builds, tests, and git operations +- write_file only when you need to create or fully rewrite a file + +# Code Style + +- Use 2-space indentation for TypeScript and JavaScript files +- Use single quotes for string literals +- Always use strict TypeScript with no implicit any +- Prefer const over let, never use var +- Use async/await instead of raw promises +- Use named exports instead of default exports +- Use descriptive variable and function names following camelCase +- Use PascalCase for types, interfaces, classes, and React components +- Add JSDoc comments for public API functions +- Use early returns to reduce nesting +- Prefer functional programming patterns where appropriate +- Use template literals instead of string concatenation +- Always handle errors explicitly - never swallow exceptions +- Use optional chaining and nullish coalescing operators +- Destructure objects and arrays when it improves readability + +# Testing Guidelines + +- Write unit tests for all business logic in services +- Write integration tests for API routes +- Use describe/it blocks with descriptive test names +- Follow the AAA pattern: Arrange, Act, Assert +- Mock external dependencies (database, APIs, file system) +- Aim for 80% code coverage minimum on new code +- Test error cases and edge cases, not just happy paths +- Use factories for test data generation +- Keep test files colocated with source files +- Run the full test suite before committing changes + +Always think step by step and explain your approach before making changes.`; + +/** + * Helper to compute total input tokens from Anthropic's split usage fields. + * When caching is active, `prompt_tokens` only counts uncached tokens. + * Total = cache_read + cache_write + prompt_tokens (uncached). + */ +function totalInputTokens(usage: any): number { + const details = usage.prompt_tokens_details; + const cacheRead = details?.cache_read_tokens ?? 0; + const cacheWrite = details?.cache_write_tokens ?? 0; + return cacheRead + cacheWrite + usage.prompt_tokens; +} + +describe.skipIf(!API_KEY)("Anthropic Prompt Caching - Live API", () => { + const api = constructLlmApi({ + provider: "anthropic", + apiKey: API_KEY!, + // Default cachingStrategy is "systemAndTools" + })!; + + const signal = new AbortController().signal; + + // Shared conversation state across sequential tests + let turn1AssistantContent = ""; + let turn2AssistantContent = ""; + + test("Turn 1: first request creates cache", { timeout: 30_000 }, async () => { + const response = await api.chatCompletionNonStream( + { + model: MODEL, + messages: [ + { + role: "system", + content: REALISTIC_SYSTEM_MESSAGE, + }, + { + role: "user", + content: + "What is the project structure of this workspace? Give a brief summary.", + }, + ], + tools: REALISTIC_TOOLS, + max_tokens: 256, + }, + signal, + ); + + expect(response.choices.length).toBeGreaterThan(0); + turn1AssistantContent = + response.choices[0].message.content ?? "I can see the project structure."; + + const usage = response.usage!; + const details = usage.prompt_tokens_details as any; + const total = totalInputTokens(usage); + + // First request should write to cache + expect(details?.cache_write_tokens).toBeGreaterThan(0); + // First request should have no cache reads + expect(details?.cache_read_tokens ?? 0).toBe(0); + + console.log("Turn 1 usage:", { + prompt_tokens: usage.prompt_tokens, + cache_write_tokens: details?.cache_write_tokens, + cache_read_tokens: details?.cache_read_tokens, + total_input_tokens: total, + }); + }); + + test( + "Turn 2: second request hits cache on shared prefix", + { timeout: 30_000 }, + async () => { + const response = await api.chatCompletionNonStream( + { + model: MODEL, + messages: [ + { + role: "system", + content: REALISTIC_SYSTEM_MESSAGE, + }, + { + role: "user", + content: + "What is the project structure of this workspace? Give a brief summary.", + }, + { + role: "assistant", + content: turn1AssistantContent, + }, + { + role: "user", + content: + "Now explain the authentication system in the core package.", + }, + ], + tools: REALISTIC_TOOLS, + max_tokens: 256, + }, + signal, + ); + + expect(response.choices.length).toBeGreaterThan(0); + turn2AssistantContent = + response.choices[0].message.content ?? "The auth system uses JWT."; + + const usage = response.usage!; + const details = usage.prompt_tokens_details as any; + const cacheReadTokens = details?.cache_read_tokens ?? 0; + const total = totalInputTokens(usage); + + // Second request should read from cache + expect(cacheReadTokens).toBeGreaterThan(0); + + console.log("Turn 2 usage:", { + prompt_tokens: usage.prompt_tokens, + cache_write_tokens: details?.cache_write_tokens, + cache_read_tokens: cacheReadTokens, + total_input_tokens: total, + cache_hit_rate: total > 0 ? (cacheReadTokens / total).toFixed(3) : 0, + }); + }, + ); + + test( + "Turn 3: cache hit rate stays high with growing conversation", + { timeout: 30_000 }, + async () => { + const response = await api.chatCompletionNonStream( + { + model: MODEL, + messages: [ + { + role: "system", + content: REALISTIC_SYSTEM_MESSAGE, + }, + { + role: "user", + content: + "What is the project structure of this workspace? Give a brief summary.", + }, + { + role: "assistant", + content: turn1AssistantContent, + }, + { + role: "user", + content: + "Now explain the authentication system in the core package.", + }, + { + role: "assistant", + content: turn2AssistantContent, + }, + { + role: "user", + content: + "How would you add a new API route for managing team memberships? Walk me through the steps.", + }, + ], + tools: REALISTIC_TOOLS, + max_tokens: 256, + }, + signal, + ); + + expect(response.choices.length).toBeGreaterThan(0); + + const usage = response.usage!; + const details = usage.prompt_tokens_details as any; + const cacheReadTokens = details?.cache_read_tokens ?? 0; + const total = totalInputTokens(usage); + const hitRate = total > 0 ? cacheReadTokens / total : 0; + + // At least 30% of total input tokens should come from cache + expect(hitRate).toBeGreaterThan(0.3); + + console.log("Turn 3 usage:", { + prompt_tokens: usage.prompt_tokens, + cache_write_tokens: details?.cache_write_tokens, + cache_read_tokens: cacheReadTokens, + total_input_tokens: total, + cache_hit_rate: hitRate.toFixed(3), + }); + }, + ); +}); diff --git a/packages/openai-adapters/vitest.config.ts b/packages/openai-adapters/vitest.config.ts index 2185afe65..bb5429db5 100644 --- a/packages/openai-adapters/vitest.config.ts +++ b/packages/openai-adapters/vitest.config.ts @@ -1,4 +1,4 @@ -import { defineConfig } from "vitest/config"; +import { configDefaults, defineConfig } from "vitest/config"; export default defineConfig({ test: { @@ -6,6 +6,7 @@ export default defineConfig({ globals: true, testTimeout: 10000, include: ["src/**/*.test.{ts,tsx}", "src/**/*.vitest.{ts,tsx}"], + exclude: [...configDefaults.exclude, "src/**/*.live.test.{ts,tsx}"], }, resolve: { alias: {