@within-7/minto 0.3.10 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Tool.js.map +2 -2
- package/dist/commands/agents/AgentsCommand.js +2 -2
- package/dist/commands/agents/AgentsCommand.js.map +2 -2
- package/dist/commands/ctx_viz.js +1 -1
- package/dist/commands/effort.js +87 -0
- package/dist/commands/effort.js.map +7 -0
- package/dist/commands/export.js +19 -9
- package/dist/commands/export.js.map +2 -2
- package/dist/commands/ide.js +18 -0
- package/dist/commands/ide.js.map +7 -0
- package/dist/commands/mcp-interactive.js +14 -8
- package/dist/commands/mcp-interactive.js.map +2 -2
- package/dist/commands/memory.js +168 -0
- package/dist/commands/memory.js.map +7 -0
- package/dist/commands/model.js +45 -2
- package/dist/commands/model.js.map +2 -2
- package/dist/commands/outputStyle.js +64 -0
- package/dist/commands/outputStyle.js.map +7 -0
- package/dist/commands/plugin/utils.js +33 -1
- package/dist/commands/plugin/utils.js.map +2 -2
- package/dist/commands/plugin.js +10 -1
- package/dist/commands/plugin.js.map +2 -2
- package/dist/commands/refreshCommands.js +2 -0
- package/dist/commands/refreshCommands.js.map +2 -2
- package/dist/commands/review.js +51 -0
- package/dist/commands/review.js.map +7 -0
- package/dist/commands/terminalSetup.js +6 -0
- package/dist/commands/terminalSetup.js.map +2 -2
- package/dist/commands/undo.js +8 -0
- package/dist/commands/undo.js.map +2 -2
- package/dist/commands/vim.js +22 -0
- package/dist/commands/vim.js.map +7 -0
- package/dist/commands.js +12 -0
- package/dist/commands.js.map +2 -2
- package/dist/components/HighlightedCode.js +1 -0
- package/dist/components/HighlightedCode.js.map +2 -2
- package/dist/components/ModelSelector/ModelSelector.js +250 -143
- package/dist/components/ModelSelector/ModelSelector.js.map +2 -2
- package/dist/components/PromptInput.js +21 -6
- package/dist/components/PromptInput.js.map +2 -2
- package/dist/components/PulseLabel.js +44 -0
- package/dist/components/PulseLabel.js.map +7 -0
- package/dist/components/RequestStatusIndicator.js +1 -1
- package/dist/components/RequestStatusIndicator.js.map +1 -1
- package/dist/components/Spinner.js +12 -42
- package/dist/components/Spinner.js.map +3 -3
- package/dist/components/StartupStatus.js +57 -0
- package/dist/components/StartupStatus.js.map +7 -0
- package/dist/components/SubagentBlock.js +43 -6
- package/dist/components/SubagentBlock.js.map +2 -2
- package/dist/components/TabbedListView/TabBar.js +13 -8
- package/dist/components/TabbedListView/TabBar.js.map +2 -2
- package/dist/components/TabbedListView/TabbedListView.js +1 -1
- package/dist/components/TabbedListView/TabbedListView.js.map +2 -2
- package/dist/components/TodoPanel.js +1 -1
- package/dist/components/TodoPanel.js.map +1 -1
- package/dist/components/ToolUseLoader.js +5 -0
- package/dist/components/ToolUseLoader.js.map +2 -2
- package/dist/components/TrustDialog.js +0 -2
- package/dist/components/TrustDialog.js.map +2 -2
- package/dist/components/messages/TaskInModuleView.js +1 -1
- package/dist/components/messages/TaskInModuleView.js.map +2 -2
- package/dist/components/messages/TaskToolMessage.js +1 -1
- package/dist/components/messages/TaskToolMessage.js.map +2 -2
- package/dist/components/messages/UserPromptMessage.js +6 -1
- package/dist/components/messages/UserPromptMessage.js.map +2 -2
- package/dist/constants/modelCapabilities.js +103 -18
- package/dist/constants/modelCapabilities.js.map +2 -2
- package/dist/constants/product.js +2 -0
- package/dist/constants/product.js.map +2 -2
- package/dist/constants/prompts/agentPrompt.js +30 -0
- package/dist/constants/prompts/agentPrompt.js.map +7 -0
- package/dist/constants/prompts/codeConventions.js +27 -0
- package/dist/constants/prompts/codeConventions.js.map +7 -0
- package/dist/constants/prompts/doingTasks.js +15 -0
- package/dist/constants/prompts/doingTasks.js.map +7 -0
- package/dist/constants/prompts/envInfo.js +17 -0
- package/dist/constants/prompts/envInfo.js.map +7 -0
- package/dist/constants/prompts/executingWithCare.js +17 -0
- package/dist/constants/prompts/executingWithCare.js.map +7 -0
- package/dist/constants/prompts/identity.js +10 -0
- package/dist/constants/prompts/identity.js.map +7 -0
- package/dist/constants/prompts/index.js +78 -0
- package/dist/constants/prompts/index.js.map +7 -0
- package/dist/constants/prompts/taskManagement.js +60 -0
- package/dist/constants/prompts/taskManagement.js.map +7 -0
- package/dist/constants/prompts/toneAndStyle.js +62 -0
- package/dist/constants/prompts/toneAndStyle.js.map +7 -0
- package/dist/constants/prompts/toolUsagePolicy.js +38 -0
- package/dist/constants/prompts/toolUsagePolicy.js.map +7 -0
- package/dist/constants/prompts.js +5 -176
- package/dist/constants/prompts.js.map +2 -2
- package/dist/constants/providerRegistry.js +235 -0
- package/dist/constants/providerRegistry.js.map +7 -0
- package/dist/constants/providers.js +35 -0
- package/dist/constants/providers.js.map +7 -0
- package/dist/context/PermissionContext.js +0 -1
- package/dist/context/PermissionContext.js.map +2 -2
- package/dist/context.js +87 -31
- package/dist/context.js.map +2 -2
- package/dist/core/backupHook.js +2 -2
- package/dist/core/backupHook.js.map +2 -2
- package/dist/core/config/defaults.js +4 -1
- package/dist/core/config/defaults.js.map +2 -2
- package/dist/core/config/schema.js +7 -1
- package/dist/core/config/schema.js.map +2 -2
- package/dist/core/costTracker.js +18 -0
- package/dist/core/costTracker.js.map +2 -2
- package/dist/core/index.js +0 -1
- package/dist/core/index.js.map +2 -2
- package/dist/core/tokenStatsManager.js +22 -4
- package/dist/core/tokenStatsManager.js.map +2 -2
- package/dist/entrypoints/cli.js +65 -84
- package/dist/entrypoints/cli.js.map +2 -2
- package/dist/hooks/useAgentTokenStats.js +1 -1
- package/dist/hooks/useAgentTokenStats.js.map +2 -2
- package/dist/hooks/useAgentTranscripts.js +2 -1
- package/dist/hooks/useAgentTranscripts.js.map +2 -2
- package/dist/hooks/useBackgroundShells.js +29 -0
- package/dist/hooks/useBackgroundShells.js.map +7 -0
- package/dist/hooks/useCanUseTool.js +1 -1
- package/dist/hooks/useCanUseTool.js.map +2 -2
- package/dist/hooks/useDeferredLoading.js +64 -0
- package/dist/hooks/useDeferredLoading.js.map +7 -0
- package/dist/hooks/useHookStatus.js +1 -1
- package/dist/hooks/useHookStatus.js.map +2 -2
- package/dist/hooks/useSessionTracking.js +55 -0
- package/dist/hooks/useSessionTracking.js.map +7 -0
- package/dist/hooks/useTerminalSize.js +21 -0
- package/dist/hooks/useTerminalSize.js.map +2 -2
- package/dist/hooks/useTextInput.js +1 -0
- package/dist/hooks/useTextInput.js.map +2 -2
- package/dist/hooks/useUnifiedCompletion.js +3 -2
- package/dist/hooks/useUnifiedCompletion.js.map +2 -2
- package/dist/i18n/locales/en.js +8 -9
- package/dist/i18n/locales/en.js.map +2 -2
- package/dist/i18n/locales/zh-CN.js +8 -9
- package/dist/i18n/locales/zh-CN.js.map +2 -2
- package/dist/i18n/types.js.map +1 -1
- package/dist/messages.js +41 -17
- package/dist/messages.js.map +2 -2
- package/dist/permissions.js +94 -1
- package/dist/permissions.js.map +2 -2
- package/dist/query.js +27 -19
- package/dist/query.js.map +2 -2
- package/dist/screens/REPL.js +83 -74
- package/dist/screens/REPL.js.map +2 -2
- package/dist/services/adapters/responsesAPI.js +6 -0
- package/dist/services/adapters/responsesAPI.js.map +2 -2
- package/dist/services/agentTeams/index.js +35 -0
- package/dist/services/agentTeams/index.js.map +7 -0
- package/dist/services/agentTeams/mailbox.js +114 -0
- package/dist/services/agentTeams/mailbox.js.map +7 -0
- package/dist/services/agentTeams/teamManager.js +149 -0
- package/dist/services/agentTeams/teamManager.js.map +7 -0
- package/dist/services/agentTeams/teamTaskStore.js +114 -0
- package/dist/services/agentTeams/teamTaskStore.js.map +7 -0
- package/dist/services/agentTeams/teammateSpawner.js +80 -0
- package/dist/services/agentTeams/teammateSpawner.js.map +7 -0
- package/dist/services/checkpointManager.js +16 -3
- package/dist/services/checkpointManager.js.map +2 -2
- package/dist/services/claude.js +19 -1728
- package/dist/services/claude.js.map +3 -3
- package/dist/services/gpt5ConnectionTest.js +4 -2
- package/dist/services/gpt5ConnectionTest.js.map +2 -2
- package/dist/services/hookExecutor.js +411 -127
- package/dist/services/hookExecutor.js.map +2 -2
- package/dist/services/llm/anthropicProvider.js +807 -0
- package/dist/services/llm/anthropicProvider.js.map +7 -0
- package/dist/services/llm/dispatch.js +218 -0
- package/dist/services/llm/dispatch.js.map +7 -0
- package/dist/services/llm/index.js +44 -0
- package/dist/services/llm/index.js.map +7 -0
- package/dist/services/llm/mintoContext.js +69 -0
- package/dist/services/llm/mintoContext.js.map +7 -0
- package/dist/services/llm/openaiProvider.js +622 -0
- package/dist/services/llm/openaiProvider.js.map +7 -0
- package/dist/services/llm/types.js +157 -0
- package/dist/services/llm/types.js.map +7 -0
- package/dist/services/mcpClient.js +183 -33
- package/dist/services/mcpClient.js.map +2 -2
- package/dist/services/notifier.js +14 -0
- package/dist/services/notifier.js.map +2 -2
- package/dist/services/oauth.js +4 -2
- package/dist/services/oauth.js.map +2 -2
- package/dist/services/openai.js +66 -56
- package/dist/services/openai.js.map +3 -3
- package/dist/services/outputStyles.js +102 -21
- package/dist/services/outputStyles.js.map +2 -2
- package/dist/services/plugins/skillMarketplace.js +4 -1
- package/dist/services/plugins/skillMarketplace.js.map +2 -2
- package/dist/services/sentry.js +1 -1
- package/dist/services/sentry.js.map +2 -2
- package/dist/services/sessionMemory.js +16 -3
- package/dist/services/sessionMemory.js.map +2 -2
- package/dist/services/systemReminder.js +350 -3
- package/dist/services/systemReminder.js.map +2 -2
- package/dist/services/taskStore.js +19 -0
- package/dist/services/taskStore.js.map +2 -2
- package/dist/tools/ArchitectTool/ArchitectTool.js.map +1 -1
- package/dist/tools/AskUserQuestionTool/AskUserQuestionTool.js.map +1 -1
- package/dist/tools/BashOutputTool/BashOutputTool.js.map +1 -1
- package/dist/tools/BashTool/BashTool.js +28 -0
- package/dist/tools/BashTool/BashTool.js.map +2 -2
- package/dist/tools/FileEditTool/FileEditTool.js +1 -1
- package/dist/tools/FileEditTool/FileEditTool.js.map +2 -2
- package/dist/tools/FileReadTool/FileReadTool.js +14 -0
- package/dist/tools/FileReadTool/FileReadTool.js.map +2 -2
- package/dist/tools/FileWriteTool/FileWriteTool.js +3 -1
- package/dist/tools/FileWriteTool/FileWriteTool.js.map +2 -2
- package/dist/tools/GlobTool/GlobTool.js.map +1 -1
- package/dist/tools/GrepTool/GrepTool.js.map +1 -1
- package/dist/tools/KillShellTool/KillShellTool.js.map +1 -1
- package/dist/tools/ListMcpResourcesTool/ListMcpResourcesTool.js.map +2 -2
- package/dist/tools/LspTool/LspTool.js +11 -2
- package/dist/tools/LspTool/LspTool.js.map +2 -2
- package/dist/tools/MCPTool/MCPTool.js.map +1 -1
- package/dist/tools/MemoryReadTool/MemoryReadTool.js +2 -1
- package/dist/tools/MemoryReadTool/MemoryReadTool.js.map +2 -2
- package/dist/tools/MemoryWriteTool/MemoryWriteTool.js +2 -1
- package/dist/tools/MemoryWriteTool/MemoryWriteTool.js.map +2 -2
- package/dist/tools/MultiEditTool/MultiEditTool.js.map +1 -1
- package/dist/tools/NotebookEditTool/NotebookEditTool.js.map +1 -1
- package/dist/tools/NotebookReadTool/NotebookReadTool.js.map +1 -1
- package/dist/tools/PlanModeTool/EnterPlanModeTool.js +8 -2
- package/dist/tools/PlanModeTool/EnterPlanModeTool.js.map +2 -2
- package/dist/tools/PlanModeTool/ExitPlanModeTool.js +2 -0
- package/dist/tools/PlanModeTool/ExitPlanModeTool.js.map +2 -2
- package/dist/tools/ReadMcpResourceTool/ReadMcpResourceTool.js.map +1 -1
- package/dist/tools/SlashCommandTool/SlashCommandTool.js +174 -18
- package/dist/tools/SlashCommandTool/SlashCommandTool.js.map +3 -3
- package/dist/tools/TaskCreateTool/TaskCreateTool.js.map +1 -1
- package/dist/tools/TaskGetTool/TaskGetTool.js.map +1 -1
- package/dist/tools/TaskListTool/TaskListTool.js.map +1 -1
- package/dist/tools/TaskOutputTool/TaskOutputTool.js.map +1 -1
- package/dist/tools/TaskStopTool/TaskStopTool.js.map +1 -1
- package/dist/tools/TaskTool/TaskTool.js +75 -5
- package/dist/tools/TaskTool/TaskTool.js.map +2 -2
- package/dist/tools/TaskTool/prompt.js +12 -6
- package/dist/tools/TaskTool/prompt.js.map +2 -2
- package/dist/tools/TaskUpdateTool/TaskUpdateTool.js.map +1 -1
- package/dist/tools/ThinkTool/ThinkTool.js.map +1 -1
- package/dist/tools/TodoWriteTool/TodoWriteTool.js.map +1 -1
- package/dist/tools/URLFetcherTool/URLFetcherTool.js.map +1 -1
- package/dist/tools/WebSearchTool/WebSearchTool.js.map +1 -1
- package/dist/tools/WebSearchTool/searchProviders.js +2 -1
- package/dist/tools/WebSearchTool/searchProviders.js.map +2 -2
- package/dist/tools/lsTool/lsTool.js.map +2 -2
- package/dist/tools/lsTool/prompt.js.map +1 -1
- package/dist/tools.js +14 -3
- package/dist/tools.js.map +2 -2
- package/dist/types/PermissionMode.js +21 -1
- package/dist/types/PermissionMode.js.map +2 -2
- package/dist/types/agentTeams.js +1 -0
- package/dist/types/agentTeams.js.map +7 -0
- package/dist/types/hooks.js +8 -2
- package/dist/types/hooks.js.map +2 -2
- package/dist/types/plugin.js +1 -1
- package/dist/types/plugin.js.map +2 -2
- package/dist/utils/agentLoader.js +25 -3
- package/dist/utils/agentLoader.js.map +2 -2
- package/dist/utils/animationManager.js +1 -1
- package/dist/utils/animationManager.js.map +2 -2
- package/dist/utils/ask.js +1 -1
- package/dist/utils/async.js +5 -1
- package/dist/utils/async.js.map +2 -2
- package/dist/utils/autoCompactCore.js +60 -0
- package/dist/utils/autoCompactCore.js.map +2 -2
- package/dist/utils/config.js +26 -128
- package/dist/utils/config.js.map +2 -2
- package/dist/utils/configSchema.js +227 -0
- package/dist/utils/configSchema.js.map +7 -0
- package/dist/utils/debugLogger.js.map +2 -2
- package/dist/utils/env.js +4 -3
- package/dist/utils/env.js.map +2 -2
- package/dist/utils/envConfig.js +34 -0
- package/dist/utils/envConfig.js.map +3 -3
- package/dist/utils/gpt5.js +146 -0
- package/dist/utils/gpt5.js.map +7 -0
- package/dist/utils/hookManager.js +374 -140
- package/dist/utils/hookManager.js.map +2 -2
- package/dist/utils/markdown.js +47 -0
- package/dist/utils/markdown.js.map +2 -2
- package/dist/utils/memoizeWithTTL.js +25 -0
- package/dist/utils/memoizeWithTTL.js.map +7 -0
- package/dist/utils/model.js +34 -9
- package/dist/utils/model.js.map +2 -2
- package/dist/utils/pluginInstaller.js +34 -5
- package/dist/utils/pluginInstaller.js.map +2 -2
- package/dist/utils/pluginLoader.js +201 -32
- package/dist/utils/pluginLoader.js.map +2 -2
- package/dist/utils/safeFetch.js +45 -0
- package/dist/utils/safeFetch.js.map +7 -0
- package/dist/utils/skillLoader.js +59 -6
- package/dist/utils/skillLoader.js.map +2 -2
- package/dist/utils/streamingState.js +52 -0
- package/dist/utils/streamingState.js.map +7 -0
- package/dist/utils/style.js +6 -3
- package/dist/utils/style.js.map +2 -2
- package/dist/utils/teamConfig.js +9 -3
- package/dist/utils/teamConfig.js.map +2 -2
- package/dist/utils/toolRiskClassification.js +0 -6
- package/dist/utils/toolRiskClassification.js.map +2 -2
- package/dist/version.js +2 -2
- package/dist/version.js.map +1 -1
- package/package.json +7 -6
|
@@ -0,0 +1,807 @@
|
|
|
1
|
+
import "@anthropic-ai/sdk/shims/node";
|
|
2
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
3
|
+
import { AnthropicBedrock } from "@anthropic-ai/bedrock-sdk";
|
|
4
|
+
import { AnthropicVertex } from "@anthropic-ai/vertex-sdk";
|
|
5
|
+
import chalk from "chalk";
|
|
6
|
+
import { nanoid } from "nanoid";
|
|
7
|
+
import "dotenv/config";
|
|
8
|
+
import { getToolDescriptionAsync } from "../../Tool.js";
|
|
9
|
+
import {
|
|
10
|
+
getAnthropicApiKey,
|
|
11
|
+
getGlobalConfig
|
|
12
|
+
} from "../../utils/config.js";
|
|
13
|
+
import { USER_AGENT } from "../../utils/http.js";
|
|
14
|
+
import {
|
|
15
|
+
createAssistantAPIErrorMessage
|
|
16
|
+
} from "../../utils/messages.js";
|
|
17
|
+
import {
|
|
18
|
+
debug as debugLogger,
|
|
19
|
+
getCurrentRequest,
|
|
20
|
+
logLLMInteraction,
|
|
21
|
+
logSystemPromptConstruction
|
|
22
|
+
} from "../../utils/debugLogger.js";
|
|
23
|
+
import { getModelManager } from "../../utils/model.js";
|
|
24
|
+
import { USE_BEDROCK, USE_VERTEX, getVertexRegionForModel } from "../../utils/model.js";
|
|
25
|
+
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
26
|
+
import { getCLISyspromptPrefix } from "../../constants/prompts/index.js";
|
|
27
|
+
import { setStreamingState, getStreamingState } from "../../utils/streamingState.js";
|
|
28
|
+
import { addRetryEventToTranscript } from "../../utils/agentTranscripts.js";
|
|
29
|
+
import { generateMintoContext } from "./mintoContext.js";
|
|
30
|
+
import {
|
|
31
|
+
API_ERROR_MESSAGE_PREFIX,
|
|
32
|
+
PROMPT_TOO_LONG_ERROR_MESSAGE,
|
|
33
|
+
CREDIT_BALANCE_TOO_LOW_ERROR_MESSAGE,
|
|
34
|
+
INVALID_API_KEY_ERROR_MESSAGE,
|
|
35
|
+
PROMPT_CACHING_ENABLED,
|
|
36
|
+
MAIN_QUERY_TEMPERATURE,
|
|
37
|
+
getMetadata,
|
|
38
|
+
withRetry,
|
|
39
|
+
getMaxTokensFromProfile,
|
|
40
|
+
getModelInputTokenCostUSD,
|
|
41
|
+
getModelOutputTokenCostUSD,
|
|
42
|
+
addToTotalCost,
|
|
43
|
+
recordTokenUsage,
|
|
44
|
+
logError
|
|
45
|
+
} from "./types.js";
|
|
46
|
+
let anthropicClient = null;
|
|
47
|
+
function getAnthropicClient(model, overrideProfile) {
|
|
48
|
+
const config = getGlobalConfig();
|
|
49
|
+
const provider = config.primaryProvider;
|
|
50
|
+
if (overrideProfile) {
|
|
51
|
+
const overrideHeaders = {
|
|
52
|
+
"x-app": "cli",
|
|
53
|
+
"User-Agent": USER_AGENT
|
|
54
|
+
};
|
|
55
|
+
return new Anthropic({
|
|
56
|
+
apiKey: overrideProfile.apiKey || "",
|
|
57
|
+
dangerouslyAllowBrowser: true,
|
|
58
|
+
maxRetries: 0,
|
|
59
|
+
timeout: parseInt(process.env.API_TIMEOUT_MS || String(60 * 1e3), 10),
|
|
60
|
+
defaultHeaders: overrideHeaders,
|
|
61
|
+
...overrideProfile.baseURL && { baseURL: overrideProfile.baseURL }
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
if (anthropicClient && provider) {
|
|
65
|
+
anthropicClient = null;
|
|
66
|
+
}
|
|
67
|
+
if (anthropicClient) {
|
|
68
|
+
return anthropicClient;
|
|
69
|
+
}
|
|
70
|
+
const region = getVertexRegionForModel(model);
|
|
71
|
+
const defaultHeaders = {
|
|
72
|
+
"x-app": "cli",
|
|
73
|
+
"User-Agent": USER_AGENT
|
|
74
|
+
};
|
|
75
|
+
if (process.env.ANTHROPIC_AUTH_TOKEN) {
|
|
76
|
+
defaultHeaders["Authorization"] = `Bearer ${process.env.ANTHROPIC_AUTH_TOKEN}`;
|
|
77
|
+
}
|
|
78
|
+
const ARGS = {
|
|
79
|
+
defaultHeaders,
|
|
80
|
+
maxRetries: 0,
|
|
81
|
+
// Disabled auto-retry in favor of manual implementation
|
|
82
|
+
timeout: parseInt(process.env.API_TIMEOUT_MS || String(60 * 1e3), 10)
|
|
83
|
+
};
|
|
84
|
+
if (USE_BEDROCK) {
|
|
85
|
+
const client = new AnthropicBedrock(ARGS);
|
|
86
|
+
anthropicClient = client;
|
|
87
|
+
return client;
|
|
88
|
+
}
|
|
89
|
+
if (USE_VERTEX) {
|
|
90
|
+
const vertexArgs = {
|
|
91
|
+
...ARGS,
|
|
92
|
+
region: region || process.env.CLOUD_ML_REGION || "us-east5"
|
|
93
|
+
};
|
|
94
|
+
const client = new AnthropicVertex(vertexArgs);
|
|
95
|
+
anthropicClient = client;
|
|
96
|
+
return client;
|
|
97
|
+
}
|
|
98
|
+
const modelManager = getModelManager();
|
|
99
|
+
const modelProfile = modelManager.getModel("main");
|
|
100
|
+
let apiKey;
|
|
101
|
+
let baseURL;
|
|
102
|
+
if (modelProfile) {
|
|
103
|
+
apiKey = modelProfile.apiKey || "";
|
|
104
|
+
baseURL = modelProfile.baseURL;
|
|
105
|
+
} else {
|
|
106
|
+
apiKey = getAnthropicApiKey();
|
|
107
|
+
baseURL = void 0;
|
|
108
|
+
}
|
|
109
|
+
if (process.env.USER_TYPE === "ant" && !apiKey && provider === "anthropic") {
|
|
110
|
+
console.error(
|
|
111
|
+
chalk.red(
|
|
112
|
+
"[ANT-ONLY] Please set the ANTHROPIC_API_KEY environment variable to use the CLI. To create a new key, go to https://console.anthropic.com/settings/keys."
|
|
113
|
+
)
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
const clientConfig = {
|
|
117
|
+
apiKey,
|
|
118
|
+
dangerouslyAllowBrowser: true,
|
|
119
|
+
...ARGS,
|
|
120
|
+
...baseURL && { baseURL }
|
|
121
|
+
// Use baseURL directly, SDK will handle API versioning
|
|
122
|
+
};
|
|
123
|
+
anthropicClient = new Anthropic(clientConfig);
|
|
124
|
+
return anthropicClient;
|
|
125
|
+
}
|
|
126
|
+
function resetAnthropicClient() {
|
|
127
|
+
anthropicClient = null;
|
|
128
|
+
}
|
|
129
|
+
async function fetchAnthropicModels(baseURL, apiKey) {
|
|
130
|
+
try {
|
|
131
|
+
const modelsURL = baseURL ? `${baseURL.replace(/\/+$/, "")}/v1/models` : "https://api.anthropic.com/v1/models";
|
|
132
|
+
const response = await fetch(modelsURL, {
|
|
133
|
+
method: "GET",
|
|
134
|
+
headers: {
|
|
135
|
+
"x-api-key": apiKey,
|
|
136
|
+
"anthropic-version": "2023-06-01",
|
|
137
|
+
"User-Agent": USER_AGENT
|
|
138
|
+
},
|
|
139
|
+
signal: AbortSignal.timeout(3e4)
|
|
140
|
+
});
|
|
141
|
+
if (!response.ok) {
|
|
142
|
+
if (response.status === 401) {
|
|
143
|
+
throw new Error(
|
|
144
|
+
"Invalid API key. Please check your Anthropic API key and try again."
|
|
145
|
+
);
|
|
146
|
+
} else if (response.status === 403) {
|
|
147
|
+
throw new Error(
|
|
148
|
+
"API key does not have permission to access models. Please check your API key permissions."
|
|
149
|
+
);
|
|
150
|
+
} else if (response.status === 429) {
|
|
151
|
+
throw new Error(
|
|
152
|
+
"Too many requests. Please wait a moment and try again."
|
|
153
|
+
);
|
|
154
|
+
} else if (response.status >= 500) {
|
|
155
|
+
throw new Error(
|
|
156
|
+
"Anthropic service is temporarily unavailable. Please try again later."
|
|
157
|
+
);
|
|
158
|
+
} else {
|
|
159
|
+
throw new Error(
|
|
160
|
+
`Unable to connect to Anthropic API (${response.status}). Please check your internet connection and API key.`
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const data = await response.json();
|
|
165
|
+
return data.data || [];
|
|
166
|
+
} catch (error) {
|
|
167
|
+
if (error instanceof Error && error.message.includes("API key") || error instanceof Error && error.message.includes("Anthropic")) {
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
logError(error);
|
|
171
|
+
throw new Error(
|
|
172
|
+
"Unable to connect to Anthropic API. Please check your internet connection and try again."
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async function verifyApiKey(apiKey, baseURL, provider) {
|
|
177
|
+
if (!apiKey) {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
if (provider && provider !== "anthropic") {
|
|
181
|
+
try {
|
|
182
|
+
const headers = {
|
|
183
|
+
Authorization: `Bearer ${apiKey}`,
|
|
184
|
+
"Content-Type": "application/json"
|
|
185
|
+
};
|
|
186
|
+
if (!baseURL) {
|
|
187
|
+
debugLogger.warn("API_VERIFY", {
|
|
188
|
+
error: "No baseURL provided for non-Anthropic provider"
|
|
189
|
+
});
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
const modelsURL = `${baseURL.replace(/\/+$/, "")}/models`;
|
|
193
|
+
const response = await fetch(modelsURL, {
|
|
194
|
+
method: "GET",
|
|
195
|
+
headers,
|
|
196
|
+
signal: AbortSignal.timeout(3e4)
|
|
197
|
+
});
|
|
198
|
+
return response.ok;
|
|
199
|
+
} catch (error) {
|
|
200
|
+
debugLogger.warn("API_VERIFY", {
|
|
201
|
+
error: "non-Anthropic provider verification failed",
|
|
202
|
+
details: String(error)
|
|
203
|
+
});
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const clientConfig = {
|
|
208
|
+
apiKey,
|
|
209
|
+
dangerouslyAllowBrowser: true,
|
|
210
|
+
maxRetries: 3,
|
|
211
|
+
defaultHeaders: {
|
|
212
|
+
"User-Agent": USER_AGENT
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
if (baseURL && (provider === "anthropic" || provider === "bigdream" || provider === "opendev")) {
|
|
216
|
+
clientConfig.baseURL = baseURL;
|
|
217
|
+
}
|
|
218
|
+
const anthropic = new Anthropic(clientConfig);
|
|
219
|
+
try {
|
|
220
|
+
await withRetry(
|
|
221
|
+
async () => {
|
|
222
|
+
const model = "claude-sonnet-4-20250514";
|
|
223
|
+
const messages = [{ role: "user", content: "test" }];
|
|
224
|
+
await anthropic.messages.create({
|
|
225
|
+
model,
|
|
226
|
+
max_tokens: 1e3,
|
|
227
|
+
// Simple test token limit for API verification
|
|
228
|
+
messages,
|
|
229
|
+
temperature: 0,
|
|
230
|
+
metadata: getMetadata()
|
|
231
|
+
});
|
|
232
|
+
return true;
|
|
233
|
+
},
|
|
234
|
+
{ maxRetries: 2 }
|
|
235
|
+
// Use fewer retries for API key verification
|
|
236
|
+
);
|
|
237
|
+
return true;
|
|
238
|
+
} catch (error) {
|
|
239
|
+
logError(error);
|
|
240
|
+
if (error instanceof Error && error.message.includes(
|
|
241
|
+
'{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}'
|
|
242
|
+
)) {
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
function applyCacheControlWithLimits(systemBlocks, messageParams) {
|
|
249
|
+
if (!PROMPT_CACHING_ENABLED) {
|
|
250
|
+
return { systemBlocks, messageParams };
|
|
251
|
+
}
|
|
252
|
+
const maxCacheBlocks = 4;
|
|
253
|
+
let usedCacheBlocks = 0;
|
|
254
|
+
const processedSystemBlocks = systemBlocks.map((block, _index) => {
|
|
255
|
+
if (usedCacheBlocks < maxCacheBlocks && block.text.length > 1e3) {
|
|
256
|
+
usedCacheBlocks++;
|
|
257
|
+
return {
|
|
258
|
+
...block,
|
|
259
|
+
cache_control: { type: "ephemeral" }
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
const { cache_control, ...blockWithoutCache } = block;
|
|
263
|
+
return blockWithoutCache;
|
|
264
|
+
});
|
|
265
|
+
const processedMessageParams = messageParams.map((message, messageIndex) => {
|
|
266
|
+
if (Array.isArray(message.content)) {
|
|
267
|
+
const processedContent = message.content.map(
|
|
268
|
+
(contentBlock, blockIndex) => {
|
|
269
|
+
const shouldCache = usedCacheBlocks < maxCacheBlocks && contentBlock.type === "text" && typeof contentBlock.text === "string" && // Long documents (over 2000 characters)
|
|
270
|
+
(contentBlock.text.length > 2e3 || // Last content block of the last message (may be important context)
|
|
271
|
+
messageIndex === messageParams.length - 1 && blockIndex === message.content.length - 1 && contentBlock.text.length > 500);
|
|
272
|
+
if (shouldCache) {
|
|
273
|
+
usedCacheBlocks++;
|
|
274
|
+
return {
|
|
275
|
+
...contentBlock,
|
|
276
|
+
cache_control: { type: "ephemeral" }
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
const { cache_control, ...blockWithoutCache } = contentBlock;
|
|
280
|
+
return blockWithoutCache;
|
|
281
|
+
}
|
|
282
|
+
);
|
|
283
|
+
return {
|
|
284
|
+
...message,
|
|
285
|
+
content: processedContent
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
return message;
|
|
289
|
+
});
|
|
290
|
+
return {
|
|
291
|
+
systemBlocks: processedSystemBlocks,
|
|
292
|
+
messageParams: processedMessageParams
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
function userMessageToMessageParam(message, addCache = false) {
|
|
296
|
+
if (addCache) {
|
|
297
|
+
if (typeof message.message.content === "string") {
|
|
298
|
+
return {
|
|
299
|
+
role: "user",
|
|
300
|
+
content: [
|
|
301
|
+
{
|
|
302
|
+
type: "text",
|
|
303
|
+
text: message.message.content
|
|
304
|
+
}
|
|
305
|
+
]
|
|
306
|
+
};
|
|
307
|
+
} else {
|
|
308
|
+
return {
|
|
309
|
+
role: "user",
|
|
310
|
+
content: message.message.content.map((_) => ({ ..._ }))
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return {
|
|
315
|
+
role: "user",
|
|
316
|
+
content: message.message.content
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
function assistantMessageToMessageParam(message, addCache = false) {
|
|
320
|
+
if (addCache) {
|
|
321
|
+
if (typeof message.message.content === "string") {
|
|
322
|
+
return {
|
|
323
|
+
role: "assistant",
|
|
324
|
+
content: [
|
|
325
|
+
{
|
|
326
|
+
type: "text",
|
|
327
|
+
text: message.message.content
|
|
328
|
+
}
|
|
329
|
+
]
|
|
330
|
+
};
|
|
331
|
+
} else {
|
|
332
|
+
return {
|
|
333
|
+
role: "assistant",
|
|
334
|
+
content: message.message.content.map((_) => ({ ..._ }))
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return {
|
|
339
|
+
role: "assistant",
|
|
340
|
+
content: message.message.content
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
function splitSysPromptPrefix(systemPrompt) {
|
|
344
|
+
const systemPromptFirstBlock = systemPrompt[0] || "";
|
|
345
|
+
const systemPromptRest = systemPrompt.slice(1);
|
|
346
|
+
return [systemPromptFirstBlock, systemPromptRest.join("\n")].filter(Boolean);
|
|
347
|
+
}
|
|
348
|
+
function addCacheBreakpoints(messages) {
|
|
349
|
+
return messages.map((msg, index) => {
|
|
350
|
+
return msg.type === "user" ? userMessageToMessageParam(msg, index > messages.length - 3) : assistantMessageToMessageParam(msg, index > messages.length - 3);
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
function getAssistantMessageFromError(error) {
|
|
354
|
+
if (error instanceof Error && error.message.includes("prompt is too long")) {
|
|
355
|
+
return createAssistantAPIErrorMessage(PROMPT_TOO_LONG_ERROR_MESSAGE);
|
|
356
|
+
}
|
|
357
|
+
if (error instanceof Error && error.message.includes("Your credit balance is too low")) {
|
|
358
|
+
return createAssistantAPIErrorMessage(CREDIT_BALANCE_TOO_LOW_ERROR_MESSAGE);
|
|
359
|
+
}
|
|
360
|
+
if (error instanceof Error && error.message.toLowerCase().includes("x-api-key")) {
|
|
361
|
+
return createAssistantAPIErrorMessage(INVALID_API_KEY_ERROR_MESSAGE);
|
|
362
|
+
}
|
|
363
|
+
if (error instanceof Error) {
|
|
364
|
+
if (process.env.NODE_ENV === "development") {
|
|
365
|
+
debugLogger.error("ANTHROPIC_API_ERROR", {
|
|
366
|
+
message: error.message,
|
|
367
|
+
stack: error.stack
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
return createAssistantAPIErrorMessage(
|
|
371
|
+
`${API_ERROR_MESSAGE_PREFIX}: ${error.message}`
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
return createAssistantAPIErrorMessage(API_ERROR_MESSAGE_PREFIX);
|
|
375
|
+
}
|
|
376
|
+
async function queryAnthropicNative(messages, systemPrompt, maxThinkingTokens, tools, signal, options) {
|
|
377
|
+
const config = getGlobalConfig();
|
|
378
|
+
const modelManager = getModelManager();
|
|
379
|
+
const toolUseContext = options?.toolUseContext;
|
|
380
|
+
const modelProfile = options?.modelProfile || modelManager.getModel("main");
|
|
381
|
+
let anthropic;
|
|
382
|
+
let model;
|
|
383
|
+
let provider;
|
|
384
|
+
debugLogger.api("MODEL_CONFIG_ANTHROPIC", {
|
|
385
|
+
modelProfileFound: !!modelProfile,
|
|
386
|
+
modelProfileId: modelProfile?.modelName,
|
|
387
|
+
modelProfileName: modelProfile?.name,
|
|
388
|
+
modelProfileModelName: modelProfile?.modelName,
|
|
389
|
+
modelProfileProvider: modelProfile?.provider,
|
|
390
|
+
modelProfileBaseURL: modelProfile?.baseURL,
|
|
391
|
+
modelProfileApiKeyExists: !!modelProfile?.apiKey,
|
|
392
|
+
optionsModel: options?.model,
|
|
393
|
+
requestId: getCurrentRequest()?.id
|
|
394
|
+
});
|
|
395
|
+
if (modelProfile) {
|
|
396
|
+
model = modelProfile.modelName;
|
|
397
|
+
provider = modelProfile.provider || config.primaryProvider || "anthropic";
|
|
398
|
+
if (modelProfile.provider === "anthropic" || modelProfile.provider === "bigdream" || modelProfile.provider === "opendev") {
|
|
399
|
+
const clientConfig = {
|
|
400
|
+
apiKey: modelProfile.apiKey,
|
|
401
|
+
dangerouslyAllowBrowser: true,
|
|
402
|
+
maxRetries: 0,
|
|
403
|
+
timeout: parseInt(process.env.API_TIMEOUT_MS || String(60 * 1e3), 10),
|
|
404
|
+
defaultHeaders: {
|
|
405
|
+
"x-app": "cli",
|
|
406
|
+
"User-Agent": USER_AGENT
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
if (modelProfile.baseURL) {
|
|
410
|
+
clientConfig.baseURL = modelProfile.baseURL;
|
|
411
|
+
}
|
|
412
|
+
anthropic = new Anthropic(clientConfig);
|
|
413
|
+
} else {
|
|
414
|
+
anthropic = getAnthropicClient(model);
|
|
415
|
+
}
|
|
416
|
+
} else {
|
|
417
|
+
const errorDetails = {
|
|
418
|
+
modelProfileExists: !!modelProfile,
|
|
419
|
+
modelProfileModelName: modelProfile?.modelName,
|
|
420
|
+
requestedModel: options?.model,
|
|
421
|
+
requestId: getCurrentRequest()?.id
|
|
422
|
+
};
|
|
423
|
+
debugLogger.error("ANTHROPIC_FALLBACK_ERROR", errorDetails);
|
|
424
|
+
throw new Error(
|
|
425
|
+
`No valid ModelProfile available for Anthropic provider. Please configure model through /model command. Debug: ${JSON.stringify(errorDetails)}`
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
if (options?.prependCLISysprompt) {
|
|
429
|
+
const [firstSyspromptBlock] = splitSysPromptPrefix(systemPrompt);
|
|
430
|
+
systemPrompt = [getCLISyspromptPrefix(), ...systemPrompt];
|
|
431
|
+
}
|
|
432
|
+
const system = splitSysPromptPrefix(systemPrompt).map(
|
|
433
|
+
(_) => ({
|
|
434
|
+
text: _,
|
|
435
|
+
type: "text"
|
|
436
|
+
})
|
|
437
|
+
);
|
|
438
|
+
const toolSchemas = await Promise.all(
|
|
439
|
+
tools.map(
|
|
440
|
+
async (tool) => ({
|
|
441
|
+
name: tool.name,
|
|
442
|
+
description: await getToolDescriptionAsync(tool),
|
|
443
|
+
input_schema: "inputJSONSchema" in tool && tool.inputJSONSchema ? tool.inputJSONSchema : zodToJsonSchema(tool.inputSchema)
|
|
444
|
+
})
|
|
445
|
+
)
|
|
446
|
+
);
|
|
447
|
+
const anthropicMessages = addCacheBreakpoints(messages);
|
|
448
|
+
const { systemBlocks: processedSystem, messageParams: processedMessages } = applyCacheControlWithLimits(system, anthropicMessages);
|
|
449
|
+
const startIncludingRetries = Date.now();
|
|
450
|
+
logSystemPromptConstruction({
|
|
451
|
+
basePrompt: systemPrompt.join("\n"),
|
|
452
|
+
mintoContext: generateMintoContext() || "",
|
|
453
|
+
reminders: [],
|
|
454
|
+
finalPrompt: systemPrompt.join("\n")
|
|
455
|
+
});
|
|
456
|
+
let start = Date.now();
|
|
457
|
+
let attemptNumber = 0;
|
|
458
|
+
let response;
|
|
459
|
+
try {
|
|
460
|
+
response = await withRetry(
|
|
461
|
+
async (attempt) => {
|
|
462
|
+
attemptNumber = attempt;
|
|
463
|
+
start = Date.now();
|
|
464
|
+
const params = {
|
|
465
|
+
model,
|
|
466
|
+
max_tokens: getMaxTokensFromProfile(modelProfile),
|
|
467
|
+
messages: processedMessages,
|
|
468
|
+
system: processedSystem,
|
|
469
|
+
tools: toolSchemas.length > 0 ? toolSchemas : void 0,
|
|
470
|
+
tool_choice: toolSchemas.length > 0 ? { type: "auto" } : void 0
|
|
471
|
+
};
|
|
472
|
+
if (maxThinkingTokens > 0) {
|
|
473
|
+
;
|
|
474
|
+
params.extra_headers = {
|
|
475
|
+
"anthropic-beta": "max-tokens-3-5-sonnet-2024-07-15"
|
|
476
|
+
};
|
|
477
|
+
params.thinking = { max_tokens: maxThinkingTokens };
|
|
478
|
+
}
|
|
479
|
+
debugLogger.api("ANTHROPIC_API_CALL_START_STREAMING", {
|
|
480
|
+
endpoint: modelProfile?.baseURL || "DEFAULT_ANTHROPIC",
|
|
481
|
+
model,
|
|
482
|
+
provider,
|
|
483
|
+
apiKeyConfigured: !!modelProfile?.apiKey,
|
|
484
|
+
apiKeyPrefix: modelProfile?.apiKey ? modelProfile.apiKey.substring(0, 8) : null,
|
|
485
|
+
maxTokens: params.max_tokens,
|
|
486
|
+
temperature: MAIN_QUERY_TEMPERATURE,
|
|
487
|
+
params,
|
|
488
|
+
messageCount: params.messages?.length || 0,
|
|
489
|
+
streamMode: true,
|
|
490
|
+
toolsCount: toolSchemas.length,
|
|
491
|
+
thinkingTokens: maxThinkingTokens,
|
|
492
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
493
|
+
modelProfileId: modelProfile?.modelName,
|
|
494
|
+
modelProfileName: modelProfile?.name
|
|
495
|
+
});
|
|
496
|
+
if (config.stream) {
|
|
497
|
+
const stream = await anthropic.beta.messages.create(
|
|
498
|
+
{
|
|
499
|
+
...params,
|
|
500
|
+
stream: true
|
|
501
|
+
},
|
|
502
|
+
{
|
|
503
|
+
signal
|
|
504
|
+
}
|
|
505
|
+
);
|
|
506
|
+
let finalResponse = null;
|
|
507
|
+
let messageStartEvent = null;
|
|
508
|
+
const contentBlocks = [];
|
|
509
|
+
const inputJSONBuffers = /* @__PURE__ */ new Map();
|
|
510
|
+
let usage = null;
|
|
511
|
+
let stopReason = null;
|
|
512
|
+
let stopSequence = null;
|
|
513
|
+
for await (const event of stream) {
|
|
514
|
+
if (signal.aborted) {
|
|
515
|
+
debugLogger.flow("STREAM_ABORTED", {
|
|
516
|
+
eventType: event.type,
|
|
517
|
+
timestamp: Date.now()
|
|
518
|
+
});
|
|
519
|
+
throw new Error("Request was cancelled");
|
|
520
|
+
}
|
|
521
|
+
switch (event.type) {
|
|
522
|
+
case "message_start":
|
|
523
|
+
messageStartEvent = event;
|
|
524
|
+
finalResponse = {
|
|
525
|
+
...event.message,
|
|
526
|
+
content: []
|
|
527
|
+
};
|
|
528
|
+
setStreamingState({
|
|
529
|
+
inputTokens: event.message.usage?.input_tokens,
|
|
530
|
+
receivedChars: 0
|
|
531
|
+
});
|
|
532
|
+
break;
|
|
533
|
+
case "content_block_start":
|
|
534
|
+
contentBlocks[event.index] = { ...event.content_block };
|
|
535
|
+
if (event.content_block.type === "tool_use") {
|
|
536
|
+
inputJSONBuffers.set(event.index, "");
|
|
537
|
+
}
|
|
538
|
+
if (event.content_block.type === "thinking") {
|
|
539
|
+
const thinkingStartTime = Date.now();
|
|
540
|
+
setStreamingState({
|
|
541
|
+
phase: "deep_thinking",
|
|
542
|
+
tokenCount: 0,
|
|
543
|
+
thinkingMaxTokens: maxThinkingTokens,
|
|
544
|
+
thinkingStartTime
|
|
545
|
+
});
|
|
546
|
+
debugLogger.flow("THINKING_BLOCK_START", {
|
|
547
|
+
index: event.index,
|
|
548
|
+
maxTokens: maxThinkingTokens,
|
|
549
|
+
startTime: thinkingStartTime
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
break;
|
|
553
|
+
case "content_block_delta":
|
|
554
|
+
const blockIndex = event.index;
|
|
555
|
+
if (!contentBlocks[blockIndex]) {
|
|
556
|
+
contentBlocks[blockIndex] = {
|
|
557
|
+
type: event.delta.type === "text_delta" ? "text" : "tool_use",
|
|
558
|
+
text: event.delta.type === "text_delta" ? "" : void 0
|
|
559
|
+
};
|
|
560
|
+
if (event.delta.type === "input_json_delta") {
|
|
561
|
+
inputJSONBuffers.set(blockIndex, "");
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
if (event.delta.type === "text_delta") {
|
|
565
|
+
contentBlocks[blockIndex].text += event.delta.text;
|
|
566
|
+
const currentState = getStreamingState();
|
|
567
|
+
setStreamingState({
|
|
568
|
+
receivedChars: (currentState.receivedChars || 0) + event.delta.text.length
|
|
569
|
+
});
|
|
570
|
+
} else if (event.delta.type === "input_json_delta") {
|
|
571
|
+
const currentBuffer = inputJSONBuffers.get(blockIndex) || "";
|
|
572
|
+
inputJSONBuffers.set(
|
|
573
|
+
blockIndex,
|
|
574
|
+
currentBuffer + event.delta.partial_json
|
|
575
|
+
);
|
|
576
|
+
} else if (event.delta.type === "thinking_delta") {
|
|
577
|
+
const currentThinking = contentBlocks[blockIndex].thinking || "";
|
|
578
|
+
const updatedThinking = currentThinking + (event.delta.thinking || "");
|
|
579
|
+
contentBlocks[blockIndex] = {
|
|
580
|
+
...contentBlocks[blockIndex],
|
|
581
|
+
thinking: updatedThinking
|
|
582
|
+
};
|
|
583
|
+
setStreamingState({
|
|
584
|
+
phase: "deep_thinking",
|
|
585
|
+
tokenCount: updatedThinking.length,
|
|
586
|
+
thinkingMaxTokens: maxThinkingTokens
|
|
587
|
+
});
|
|
588
|
+
debugLogger.trace("THINKING_DELTA", {
|
|
589
|
+
index: blockIndex,
|
|
590
|
+
tokenCount: updatedThinking.length
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
break;
|
|
594
|
+
case "message_delta":
|
|
595
|
+
if (event.delta.stop_reason)
|
|
596
|
+
stopReason = event.delta.stop_reason;
|
|
597
|
+
if (event.delta.stop_sequence)
|
|
598
|
+
stopSequence = event.delta.stop_sequence;
|
|
599
|
+
if (event.usage) {
|
|
600
|
+
usage = { ...usage, ...event.usage };
|
|
601
|
+
setStreamingState({
|
|
602
|
+
outputTokens: event.usage.output_tokens
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
break;
|
|
606
|
+
case "content_block_stop":
|
|
607
|
+
const stopIndex = event.index;
|
|
608
|
+
const block = contentBlocks[stopIndex];
|
|
609
|
+
if (block?.type === "thinking") {
|
|
610
|
+
const streamState2 = getStreamingState();
|
|
611
|
+
const thinkingDurationMs = streamState2.thinkingStartTime ? Date.now() - streamState2.thinkingStartTime : 0;
|
|
612
|
+
setStreamingState({
|
|
613
|
+
phase: "generating",
|
|
614
|
+
thinkingDurationMs
|
|
615
|
+
});
|
|
616
|
+
debugLogger.flow("THINKING_BLOCK_COMPLETE", {
|
|
617
|
+
index: stopIndex,
|
|
618
|
+
finalTokenCount: block.thinking?.length || 0,
|
|
619
|
+
durationMs: thinkingDurationMs
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
if (block?.type === "tool_use" && inputJSONBuffers.has(stopIndex)) {
|
|
623
|
+
const jsonStr = inputJSONBuffers.get(stopIndex);
|
|
624
|
+
if (jsonStr) {
|
|
625
|
+
try {
|
|
626
|
+
block.input = JSON.parse(jsonStr);
|
|
627
|
+
} catch (error) {
|
|
628
|
+
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
629
|
+
debugLogger.error("JSON_PARSE_ERROR", {
|
|
630
|
+
blockIndex: stopIndex,
|
|
631
|
+
jsonStr: jsonStr.length > 500 ? jsonStr.slice(0, 500) + "..." : jsonStr,
|
|
632
|
+
error: errorMsg
|
|
633
|
+
});
|
|
634
|
+
block.input = {
|
|
635
|
+
__parse_error__: true,
|
|
636
|
+
__error_message__: `JSON parse failed: ${errorMsg}`,
|
|
637
|
+
__raw_json_preview__: jsonStr.length > 200 ? jsonStr.slice(0, 200) + "..." : jsonStr
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
inputJSONBuffers.delete(stopIndex);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
break;
|
|
644
|
+
case "message_stop":
|
|
645
|
+
inputJSONBuffers.clear();
|
|
646
|
+
break;
|
|
647
|
+
}
|
|
648
|
+
if (event.type === "message_stop") {
|
|
649
|
+
break;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
if (!finalResponse || !messageStartEvent) {
|
|
653
|
+
throw new Error("Stream ended without proper message structure");
|
|
654
|
+
}
|
|
655
|
+
finalResponse = {
|
|
656
|
+
...messageStartEvent.message,
|
|
657
|
+
content: contentBlocks.filter(Boolean),
|
|
658
|
+
stop_reason: stopReason,
|
|
659
|
+
stop_sequence: stopSequence,
|
|
660
|
+
usage: {
|
|
661
|
+
...messageStartEvent.message.usage,
|
|
662
|
+
...usage
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
return finalResponse;
|
|
666
|
+
} else {
|
|
667
|
+
debugLogger.api("ANTHROPIC_API_CALL_START_NON_STREAMING", {
|
|
668
|
+
endpoint: modelProfile?.baseURL || "DEFAULT_ANTHROPIC",
|
|
669
|
+
model,
|
|
670
|
+
provider,
|
|
671
|
+
apiKeyConfigured: !!modelProfile?.apiKey,
|
|
672
|
+
apiKeyPrefix: modelProfile?.apiKey ? modelProfile.apiKey.substring(0, 8) : null,
|
|
673
|
+
maxTokens: params.max_tokens,
|
|
674
|
+
temperature: MAIN_QUERY_TEMPERATURE,
|
|
675
|
+
messageCount: params.messages?.length || 0,
|
|
676
|
+
streamMode: false,
|
|
677
|
+
toolsCount: toolSchemas.length,
|
|
678
|
+
thinkingTokens: maxThinkingTokens,
|
|
679
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
680
|
+
modelProfileId: modelProfile?.modelName,
|
|
681
|
+
modelProfileName: modelProfile?.name
|
|
682
|
+
});
|
|
683
|
+
return await anthropic.beta.messages.create(params, {
|
|
684
|
+
signal
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
},
|
|
688
|
+
{
|
|
689
|
+
signal,
|
|
690
|
+
onRetry: toolUseContext?.agentId ? ({ attempt, maxRetries, error, delayMs }) => {
|
|
691
|
+
addRetryEventToTranscript(toolUseContext.agentId, {
|
|
692
|
+
attempt,
|
|
693
|
+
maxRetries,
|
|
694
|
+
errorMessage: error.message,
|
|
695
|
+
delayMs
|
|
696
|
+
});
|
|
697
|
+
} : void 0
|
|
698
|
+
}
|
|
699
|
+
);
|
|
700
|
+
debugLogger.api("ANTHROPIC_API_CALL_SUCCESS", {
|
|
701
|
+
content: response.content
|
|
702
|
+
});
|
|
703
|
+
const ttftMs = start - Date.now();
|
|
704
|
+
const durationMs = Date.now() - startIncludingRetries;
|
|
705
|
+
const content = response.content.map((block) => {
|
|
706
|
+
if (block.type === "text") {
|
|
707
|
+
return {
|
|
708
|
+
type: "text",
|
|
709
|
+
text: block.text
|
|
710
|
+
};
|
|
711
|
+
} else if (block.type === "tool_use") {
|
|
712
|
+
return {
|
|
713
|
+
type: "tool_use",
|
|
714
|
+
id: block.id,
|
|
715
|
+
name: block.name,
|
|
716
|
+
input: block.input
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
return block;
|
|
720
|
+
});
|
|
721
|
+
const thinkingBlocks = content.filter(
|
|
722
|
+
(block) => block.type === "thinking"
|
|
723
|
+
);
|
|
724
|
+
const streamState = getStreamingState();
|
|
725
|
+
const thinkingMetadata = thinkingBlocks.length > 0 ? {
|
|
726
|
+
charCount: thinkingBlocks.reduce(
|
|
727
|
+
(sum, b) => sum + (b.thinking?.length || 0),
|
|
728
|
+
0
|
|
729
|
+
),
|
|
730
|
+
durationMs: streamState.thinkingDurationMs || 0,
|
|
731
|
+
startTime: streamState.thinkingStartTime || Date.now(),
|
|
732
|
+
isComplete: true
|
|
733
|
+
} : void 0;
|
|
734
|
+
const assistantMessage = {
|
|
735
|
+
message: {
|
|
736
|
+
id: response.id,
|
|
737
|
+
content,
|
|
738
|
+
model: response.model,
|
|
739
|
+
role: "assistant",
|
|
740
|
+
stop_reason: response.stop_reason,
|
|
741
|
+
stop_sequence: response.stop_sequence,
|
|
742
|
+
type: "message",
|
|
743
|
+
usage: response.usage
|
|
744
|
+
},
|
|
745
|
+
type: "assistant",
|
|
746
|
+
uuid: nanoid(),
|
|
747
|
+
durationMs,
|
|
748
|
+
costUSD: 0,
|
|
749
|
+
// Will be calculated below
|
|
750
|
+
thinkingMetadata
|
|
751
|
+
};
|
|
752
|
+
const systemMessages = system.map((block) => ({
|
|
753
|
+
role: "system",
|
|
754
|
+
content: block.text
|
|
755
|
+
}));
|
|
756
|
+
logLLMInteraction({
|
|
757
|
+
systemPrompt: systemPrompt.join("\n"),
|
|
758
|
+
messages: [...systemMessages, ...anthropicMessages],
|
|
759
|
+
response,
|
|
760
|
+
usage: response.usage ? {
|
|
761
|
+
inputTokens: response.usage.input_tokens,
|
|
762
|
+
outputTokens: response.usage.output_tokens
|
|
763
|
+
} : void 0,
|
|
764
|
+
timing: {
|
|
765
|
+
start,
|
|
766
|
+
end: Date.now()
|
|
767
|
+
},
|
|
768
|
+
apiFormat: "anthropic"
|
|
769
|
+
});
|
|
770
|
+
const inputTokens = response.usage.input_tokens;
|
|
771
|
+
const outputTokens = response.usage.output_tokens;
|
|
772
|
+
const cacheCreationInputTokens = response.usage.cache_creation_input_tokens ?? 0;
|
|
773
|
+
const cacheReadInputTokens = response.usage.cache_read_input_tokens ?? 0;
|
|
774
|
+
const costUSD = inputTokens / 1e6 * getModelInputTokenCostUSD(model) + outputTokens / 1e6 * getModelOutputTokenCostUSD(model) + cacheCreationInputTokens / 1e6 * getModelInputTokenCostUSD(model) + cacheReadInputTokens / 1e6 * (getModelInputTokenCostUSD(model) * 0.1);
|
|
775
|
+
assistantMessage.costUSD = costUSD;
|
|
776
|
+
addToTotalCost(costUSD, durationMs);
|
|
777
|
+
recordTokenUsage(
|
|
778
|
+
{
|
|
779
|
+
inputTokens,
|
|
780
|
+
outputTokens,
|
|
781
|
+
cacheCreationTokens: cacheCreationInputTokens,
|
|
782
|
+
cacheReadTokens: cacheReadInputTokens
|
|
783
|
+
},
|
|
784
|
+
costUSD,
|
|
785
|
+
model,
|
|
786
|
+
toolUseContext ? {
|
|
787
|
+
agentId: toolUseContext.agentId,
|
|
788
|
+
toolUseId: toolUseContext.toolUseId,
|
|
789
|
+
model
|
|
790
|
+
} : void 0
|
|
791
|
+
);
|
|
792
|
+
return assistantMessage;
|
|
793
|
+
} catch (error) {
|
|
794
|
+
return getAssistantMessageFromError(error);
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
export {
|
|
798
|
+
assistantMessageToMessageParam,
|
|
799
|
+
fetchAnthropicModels,
|
|
800
|
+
getAnthropicClient,
|
|
801
|
+
queryAnthropicNative,
|
|
802
|
+
resetAnthropicClient,
|
|
803
|
+
splitSysPromptPrefix,
|
|
804
|
+
userMessageToMessageParam,
|
|
805
|
+
verifyApiKey
|
|
806
|
+
};
|
|
807
|
+
//# sourceMappingURL=anthropicProvider.js.map
|