Merge branch 'main' into back-job-perm
This commit is contained in:
commit
4c0f3b66ca
28 changed files with 2901 additions and 12 deletions
7
.github/workflows/stable-release.yml
vendored
7
.github/workflows/stable-release.yml
vendored
|
|
@ -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 }}"
|
||||
|
|
|
|||
|
|
@ -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" },
|
||||
|
|
|
|||
112
extensions/cli/src/services/QuizService.ts
Normal file
112
extensions/cli/src/services/QuizService.ts
Normal file
|
|
@ -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<string> {
|
||||
const requestId = `quiz-${Date.now()}`;
|
||||
|
||||
return new Promise<string>((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<QuizServiceState> {
|
||||
this.currentState = {
|
||||
pendingQuestion: null,
|
||||
};
|
||||
this.pendingRequests.clear();
|
||||
return this.currentState;
|
||||
}
|
||||
}
|
||||
|
||||
export const quizService = new QuizService();
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -158,6 +158,7 @@ export const SERVICE_NAMES = {
|
|||
ARTIFACT_UPLOAD: "artifactUpload",
|
||||
GIT_AI_INTEGRATION: "gitAiIntegration",
|
||||
BACKGROUND_JOBS: "backgroundJobs",
|
||||
QUIZ: "quiz",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
61
extensions/cli/src/tools/askQuestion.ts
Normal file
61
extensions/cli/src/tools/askQuestion.ts
Normal file
|
|
@ -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<string> => {
|
||||
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}"`;
|
||||
},
|
||||
};
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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];
|
||||
|
|
|
|||
|
|
@ -184,6 +184,7 @@ function useChatHandlers(
|
|||
};
|
||||
}
|
||||
|
||||
// eslint-disable-next-line complexity
|
||||
const TUIChat: React.FC<TUIChatProps> = ({
|
||||
remoteUrl,
|
||||
configPath,
|
||||
|
|
@ -261,6 +262,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
compactionStartTime,
|
||||
inputMode,
|
||||
activePermissionRequest,
|
||||
activeQuizQuestion,
|
||||
wasInterrupted,
|
||||
queuedMessages,
|
||||
handleUserMessage,
|
||||
|
|
@ -269,6 +271,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
resetChatHistory,
|
||||
handleEditMessage,
|
||||
handleToolPermissionResponse,
|
||||
handleQuizAnswer,
|
||||
} = useChat({
|
||||
assistant: services.config?.config || undefined,
|
||||
model: services.model?.model || undefined,
|
||||
|
|
@ -332,7 +335,9 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
// 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<TUIChatProps> = ({
|
|||
handleReload={handleReload}
|
||||
closeCurrentScreen={closeCurrentScreen}
|
||||
activePermissionRequest={activePermissionRequest}
|
||||
activeQuizQuestion={activeQuizQuestion}
|
||||
handleToolPermissionResponse={handleToolPermissionResponse}
|
||||
handleQuizAnswer={handleQuizAnswer}
|
||||
handleUserMessage={handleUserMessage}
|
||||
isWaitingForResponse={isWaitingForResponse}
|
||||
isCompacting={isCompacting}
|
||||
|
|
|
|||
|
|
@ -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<string, Buffer>) => void;
|
||||
isWaitingForResponse: boolean;
|
||||
isCompacting: boolean;
|
||||
|
|
@ -30,7 +36,9 @@ interface ChatScreenContentProps {
|
|||
|
||||
export const ChatScreenContent: React.FC<ChatScreenContentProps> = ({
|
||||
activePermissionRequest,
|
||||
activeQuizQuestion,
|
||||
handleToolPermissionResponse,
|
||||
handleQuizAnswer,
|
||||
handleUserMessage,
|
||||
isWaitingForResponse,
|
||||
isCompacting,
|
||||
|
|
@ -44,6 +52,18 @@ export const ChatScreenContent: React.FC<ChatScreenContentProps> = ({
|
|||
onImageInClipboardChange,
|
||||
onShowEditSelector,
|
||||
}) => {
|
||||
if (activeQuizQuestion) {
|
||||
return (
|
||||
<QuizPrompt
|
||||
question={activeQuizQuestion.question.question}
|
||||
options={activeQuizQuestion.question.options}
|
||||
defaultAnswer={activeQuizQuestion.question.defaultAnswer}
|
||||
requestId={activeQuizQuestion.requestId}
|
||||
onAnswer={handleQuizAnswer}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (activePermissionRequest) {
|
||||
return (
|
||||
<ToolPermissionSelector
|
||||
|
|
|
|||
162
extensions/cli/src/ui/components/QuizPrompt.tsx
Normal file
162
extensions/cli/src/ui/components/QuizPrompt.tsx
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
import { Box, Text, useInput } from "ink";
|
||||
import React, { useState } from "react";
|
||||
|
||||
import { defaultBoxStyles } from "../styles.js";
|
||||
|
||||
interface QuizPromptProps {
|
||||
question: string;
|
||||
options?: string[];
|
||||
defaultAnswer?: string;
|
||||
requestId: string;
|
||||
onAnswer: (
|
||||
requestId: string,
|
||||
answer: string,
|
||||
isCustomAnswer: boolean,
|
||||
) => void;
|
||||
}
|
||||
|
||||
/**Quiz prompt component for answering for the AskQuestion tool and QuizService */
|
||||
export const QuizPrompt: React.FC<QuizPromptProps> = ({
|
||||
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 (
|
||||
<Box {...defaultBoxStyles("magenta")} marginBottom={1}>
|
||||
<Box marginBottom={1}>
|
||||
<Text color="magenta" bold>
|
||||
?{" "}
|
||||
</Text>
|
||||
<Text bold>{question}</Text>
|
||||
</Box>
|
||||
|
||||
{hasOptions && !isCustomMode && (
|
||||
<Box flexDirection="column" marginLeft={2}>
|
||||
{options.map((option, index) => {
|
||||
const isSelected = index === selectedIndex;
|
||||
return (
|
||||
<Box key={index}>
|
||||
<Text color={isSelected ? "cyan" : "white"} bold={isSelected}>
|
||||
{isSelected ? "❯ " : " "}
|
||||
{option}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
<Box>
|
||||
<Text color="gray" dimColor>
|
||||
{" "}(or start typing for custom answer)
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{isCustomMode && (
|
||||
<Box marginLeft={2} flexDirection="column">
|
||||
<Box>
|
||||
<Text color="cyan">❯ </Text>
|
||||
<Text>{customInput}</Text>
|
||||
<Text color="gray">▊</Text>
|
||||
</Box>
|
||||
{defaultAnswer && !customInput && (
|
||||
<Box marginTop={1}>
|
||||
<Text color="gray" dimColor>
|
||||
(Press Enter for default: {defaultAnswer})
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text color="gray" dimColor>
|
||||
{hasOptions && !isCustomMode
|
||||
? "↑/↓ navigate, Enter select"
|
||||
: "Type answer, Enter submit"}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
|
@ -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<void>;
|
||||
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<string, Buffer>) => void;
|
||||
isWaitingForResponse: boolean;
|
||||
isCompacting: boolean;
|
||||
|
|
@ -72,7 +77,9 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
|
|||
handleReload,
|
||||
closeCurrentScreen,
|
||||
activePermissionRequest,
|
||||
activeQuizQuestion,
|
||||
handleToolPermissionResponse,
|
||||
handleQuizAnswer,
|
||||
handleUserMessage,
|
||||
isWaitingForResponse,
|
||||
isCompacting,
|
||||
|
|
@ -198,7 +205,9 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
|
|||
return (
|
||||
<ChatScreenContent
|
||||
activePermissionRequest={activePermissionRequest}
|
||||
activeQuizQuestion={activeQuizQuestion}
|
||||
handleToolPermissionResponse={handleToolPermissionResponse}
|
||||
handleQuizAnswer={handleQuizAnswer}
|
||||
handleUserMessage={handleUserMessage}
|
||||
isWaitingForResponse={isWaitingForResponse}
|
||||
isCompacting={isCompacting}
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ import {
|
|||
} from "./useChat.stream.helpers.js";
|
||||
import {
|
||||
ActivePermissionRequest,
|
||||
ActiveQuizQuestion,
|
||||
AttachedFile,
|
||||
UseChatProps,
|
||||
} from "./useChat.types.js";
|
||||
|
|
@ -168,6 +169,8 @@ export function useChat({
|
|||
const [attachedFiles, setAttachedFiles] = useState<AttachedFile[]>([]);
|
||||
const [activePermissionRequest, setActivePermissionRequest] =
|
||||
useState<ActivePermissionRequest | null>(null);
|
||||
const [activeQuizQuestion, setActiveQuizQuestion] =
|
||||
useState<ActiveQuizQuestion | null>(null);
|
||||
const [compactionIndex, setCompactionIndex] = useState<number | null>(() => {
|
||||
// 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,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
79
package-lock.json
generated
79
package-lock.json
generated
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
51
packages/openai-adapters/package-lock.json
generated
51
packages/openai-adapters/package-lock.json
generated
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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<string, AiSdkProviderCreator> = {
|
||||
openai: createOpenAI,
|
||||
anthropic: createAnthropic,
|
||||
xai: createXai,
|
||||
deepseek: createDeepSeek,
|
||||
openrouter: (options) =>
|
||||
createOpenAI({
|
||||
...options,
|
||||
|
|
|
|||
|
|
@ -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: [
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
},
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
724
packages/openai-adapters/src/test/anthropic-caching.live.test.ts
Normal file
724
packages/openai-adapters/src/test/anthropic-caching.live.test.ts
Normal file
|
|
@ -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),
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
|
@ -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: {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue