diff --git a/src/cli/print.ts b/src/cli/print.ts index 7a9ca405c..9873c7a21 100644 --- a/src/cli/print.ts +++ b/src/cli/print.ts @@ -377,9 +377,6 @@ const cronJitterConfigModule = require('../utils/cronJitterConfig.js') as typeof import('../utils/cronJitterConfig.js') const cronGate = require('@claude-code-best/builtin-tools/tools/ScheduleCronTool/prompt.js') as typeof import('@claude-code-best/builtin-tools/tools/ScheduleCronTool/prompt.js') -const extractMemoriesModule = feature('EXTRACT_MEMORIES') - ? (require('../services/extractMemories/extractMemories.js') as typeof import('../services/extractMemories/extractMemories.js')) - : null /* eslint-enable @typescript-eslint/no-require-imports */ const SHUTDOWN_TEAM_PROMPT = ` @@ -985,7 +982,14 @@ export async function runHeadless( // the forked agent mid-flight. Gated by isExtractModeActive so the // tengu_slate_thimble flag controls non-interactive extraction end-to-end. if (feature('EXTRACT_MEMORIES') && isExtractModeActive()) { - await extractMemoriesModule!.drainPendingExtraction() + try { + const { drainPendingExtraction } = await import( + '../services/extractMemories/extractMemories.js' + ) + await drainPendingExtraction() + } catch { + // Module load failure — non-critical at shutdown + } } gracefulShutdownSync( diff --git a/src/components/Spinner.tsx b/src/components/Spinner.tsx index 0ef3ab4d5..33a82a460 100644 --- a/src/components/Spinner.tsx +++ b/src/components/Spinner.tsx @@ -23,6 +23,7 @@ import { getDefaultCharacters, type SpinnerMode } from './Spinner/index.js'; import { SpinnerAnimationRow } from './Spinner/SpinnerAnimationRow.js'; import { useSettings } from '../hooks/useSettings.js'; import { isInProcessTeammateTask } from '../tasks/InProcessTeammateTask/types.js'; +import { isLocalAgentTask } from '../tasks/LocalAgentTask/LocalAgentTask.js'; import { isBackgroundTask } from '../tasks/types.js'; import { getAllInProcessTeammateTasks } from '../tasks/InProcessTeammateTask/InProcessTeammateTask.js'; import { getEffortSuffix } from '../utils/effort.js'; @@ -209,15 +210,22 @@ function SpinnerWithVerbInner({ const hasRunningTeammates = runningTeammates.length > 0; const allIdle = hasRunningTeammates && runningTeammates.every(t => t.isIdle); - // Gather aggregate token stats from all running swarm teammates - // In spinner-tree mode, skip aggregation (teammates have their own lines in the tree) + // Gather aggregate token stats from all running agents. + // In spinner-tree mode, skip in-process teammates (they have their own + // per-teammate lines in the tree) but still count local-agent tasks + // (background agents) which have no dedicated tree rows. let teammateTokens = 0; - if (!showSpinnerTree) { - for (const task of Object.values(tasks)) { - if (isInProcessTeammateTask(task) && task.status === 'running') { - if (task.progress?.tokenCount) { - teammateTokens += task.progress.tokenCount; - } + for (const task of Object.values(tasks)) { + if (task.status !== 'running') continue; + if (isInProcessTeammateTask(task)) { + if (!showSpinnerTree && task.progress?.tokenCount) { + teammateTokens += task.progress.tokenCount; + } + continue; + } + if (isLocalAgentTask(task)) { + if (task.progress?.tokenCount) { + teammateTokens += task.progress.tokenCount; } } } diff --git a/src/query/stopHooks.ts b/src/query/stopHooks.ts index a3b354c9a..f63f1ee0d 100644 --- a/src/query/stopHooks.ts +++ b/src/query/stopHooks.ts @@ -39,9 +39,6 @@ import { getTaskListId, listTasks } from '../utils/tasks.js' import { getAgentName, getTeamName, isTeammate } from '../utils/teammate.js' /* eslint-disable @typescript-eslint/no-require-imports */ -const extractMemoriesModule = feature('EXTRACT_MEMORIES') - ? (require('../services/extractMemories/extractMemories.js') as typeof import('../services/extractMemories/extractMemories.js')) - : null const jobClassifierModule = feature('TEMPLATES') ? (require('../jobs/classifier.js') as typeof import('../jobs/classifier.js')) : null @@ -154,12 +151,16 @@ export async function* handleStopHooks( // Fire-and-forget in both interactive and non-interactive. For -p/SDK, // print.ts drains the in-flight promise after flushing the response // but before gracefulShutdownSync (see drainPendingExtraction). - void extractMemoriesModule!.executeExtractMemories( - stopHookContext, - toolUseContext.appendSystemMessage as - | ((msg: import('../types/message.js').SystemMessage) => void) - | undefined, - ) + void import('../services/extractMemories/extractMemories.js') + .then(({ executeExtractMemories }) => + executeExtractMemories( + stopHookContext, + toolUseContext.appendSystemMessage as + | ((msg: import('../types/message.js').SystemMessage) => void) + | undefined, + ), + ) + .catch(() => {}) } if (!toolUseContext.agentId && !poorMode) { void executeAutoDream(stopHookContext, toolUseContext.appendSystemMessage) diff --git a/src/services/api/openai/__tests__/thinking.test.ts b/src/services/api/openai/__tests__/thinking.test.ts index a1f477a18..c147a8dc1 100644 --- a/src/services/api/openai/__tests__/thinking.test.ts +++ b/src/services/api/openai/__tests__/thinking.test.ts @@ -147,6 +147,22 @@ describe('isOpenAIThinkingEnabled', () => { expect(isOpenAIThinkingEnabled('deepseek-coder')).toBe(true) }) + test('returns true when model name is "mimo-v2-flash"', () => { + expect(isOpenAIThinkingEnabled('mimo-v2-flash')).toBe(true) + }) + + test('returns true when model name is "mimo-v2-pro"', () => { + expect(isOpenAIThinkingEnabled('mimo-v2-pro')).toBe(true) + }) + + test('returns true when model name is "mimo-v2.5-pro"', () => { + expect(isOpenAIThinkingEnabled('mimo-v2.5-pro')).toBe(true) + }) + + test('returns true when model name contains "mimo"', () => { + expect(isOpenAIThinkingEnabled('MiMo-V2-Omni')).toBe(true) + }) + test('returns false when model name is "gpt-4o"', () => { expect(isOpenAIThinkingEnabled('gpt-4o')).toBe(false) }) @@ -197,7 +213,10 @@ describe('buildOpenAIRequestBody — thinking params', () => { test('includes vLLM/self-hosted thinking format when enabled', () => { const body = buildOpenAIRequestBody({ ...baseParams, enableThinking: true }) expect(body.enable_thinking).toBe(true) - expect(body.chat_template_kwargs).toEqual({ thinking: true }) + expect(body.chat_template_kwargs).toEqual({ + thinking: true, + enable_thinking: true, + }) }) test('includes both formats simultaneously when enabled', () => { diff --git a/src/services/api/openai/requestBody.ts b/src/services/api/openai/requestBody.ts index 9de76752d..d47ccdfc8 100644 --- a/src/services/api/openai/requestBody.ts +++ b/src/services/api/openai/requestBody.ts @@ -7,11 +7,11 @@ import type { ChatCompletionCreateParamsStreaming } from 'openai/resources/chat/ import { isEnvTruthy, isEnvDefinedFalsy } from '../../../utils/envUtils.js' /** - * Detect whether DeepSeek-style thinking mode should be enabled. + * Detect whether thinking mode should be enabled for this model. * * Enabled when: * 1. OPENAI_ENABLE_THINKING=1 is set (explicit enable), OR - * 2. Model name contains "deepseek-reasoner" OR "DeepSeek-V3.2" (auto-detect, case-insensitive) + * 2. Model name contains "deepseek" or "mimo" (auto-detect, case-insensitive) * * Disabled when: * - OPENAI_ENABLE_THINKING=0/false/no/off is explicitly set (overrides model detection) @@ -23,9 +23,9 @@ export function isOpenAIThinkingEnabled(model: string): boolean { if (isEnvDefinedFalsy(process.env.OPENAI_ENABLE_THINKING)) return false // Explicit enable if (isEnvTruthy(process.env.OPENAI_ENABLE_THINKING)) return true - // Auto-detect from model name (all DeepSeek models support thinking mode) + // Auto-detect from model name (DeepSeek and MiMo models support thinking mode) const modelLower = model.toLowerCase() - return modelLower.includes('deepseek') + return modelLower.includes('deepseek') || modelLower.includes('mimo') } /** @@ -58,12 +58,12 @@ export function resolveOpenAIMaxTokens( * Build the request body for OpenAI chat.completions.create(). * Extracted for testability — the thinking mode params are injected here. * - * DeepSeek thinking mode: inject thinking params via request body. - * Two formats are added simultaneously to support different deployments: - * - Official DeepSeek API: `thinking: { type: 'enabled' }` - * - Self-hosted DeepSeek-V3.2: `enable_thinking: true` + `chat_template_kwargs: { thinking: true }` + * Three thinking-mode formats are sent simultaneously; each endpoint uses the + * format it recognizes and ignores the others: + * - Official DeepSeek API: `thinking: { type: 'enabled' }` + * - Self-hosted DeepSeek: `enable_thinking: true` + `chat_template_kwargs: { thinking: true }` + * - MiMo (Xiaomi): `chat_template_kwargs: { enable_thinking: true }` * OpenAI SDK passes unknown keys through to the HTTP body. - * Each endpoint will use the format it recognizes and ignore the others. */ export function buildOpenAIRequestBody(params: { model: string @@ -76,7 +76,7 @@ export function buildOpenAIRequestBody(params: { }): ChatCompletionCreateParamsStreaming & { thinking?: { type: string } enable_thinking?: boolean - chat_template_kwargs?: { thinking: boolean } + chat_template_kwargs?: { thinking: boolean; enable_thinking: boolean } } { const { model, @@ -97,14 +97,15 @@ export function buildOpenAIRequestBody(params: { }), stream: true, stream_options: { include_usage: true }, - // DeepSeek thinking mode: enable chain-of-thought output. - // When active, temperature/top_p/presence_penalty/frequency_penalty are ignored by DeepSeek. + // Enable chain-of-thought output for DeepSeek and MiMo models. + // When active, temperature/top_p/presence_penalty/frequency_penalty are ignored. ...(enableThinking && { // Official DeepSeek API format thinking: { type: 'enabled' }, // Self-hosted DeepSeek-V3.2 format enable_thinking: true, - chat_template_kwargs: { thinking: true }, + // Both DeepSeek self-hosted and MiMo formats in chat_template_kwargs + chat_template_kwargs: { thinking: true, enable_thinking: true }, }), // Only send temperature when thinking mode is off (DeepSeek ignores it anyway, // but other providers may respect it) diff --git a/src/utils/backgroundHousekeeping.ts b/src/utils/backgroundHousekeeping.ts index fa5672132..6312dd62b 100644 --- a/src/utils/backgroundHousekeeping.ts +++ b/src/utils/backgroundHousekeeping.ts @@ -4,9 +4,6 @@ import { initMagicDocs } from '../services/MagicDocs/magicDocs.js' import { initSkillImprovement } from './hooks/skillImprovement.js' /* eslint-disable @typescript-eslint/no-require-imports */ -const extractMemoriesModule = feature('EXTRACT_MEMORIES') - ? (require('../services/extractMemories/extractMemories.js') as typeof import('../services/extractMemories/extractMemories.js')) - : null const registerProtocolModule = feature('LODESTONE') ? (require('./deepLink/registerProtocol.js') as typeof import('./deepLink/registerProtocol.js')) : null @@ -32,7 +29,13 @@ export function startBackgroundHousekeeping(): void { void initMagicDocs() void initSkillImprovement() if (feature('EXTRACT_MEMORIES')) { - extractMemoriesModule!.initExtractMemories() + void import('../services/extractMemories/extractMemories.js') + .then(({ initExtractMemories }) => { + initExtractMemories() + }) + .catch(() => { + // Module load failure — non-critical, memory extraction just won't run + }) } initAutoDream() void autoUpdateMarketplacesAndPluginsInBackground() diff --git a/src/utils/cacheWarning.ts b/src/utils/cacheWarning.ts index 39ba5a599..2e193f9a4 100644 --- a/src/utils/cacheWarning.ts +++ b/src/utils/cacheWarning.ts @@ -24,6 +24,12 @@ interface CacheWarningState { // 模块级状态,每个 querySource 独立跟踪 const cacheWarningStateBySource = new Map() +// Limit the number of tracked sources to prevent unbounded Map growth. +// querySource strings are effectively unbounded (typed as `any`), so a +// long-running session that spawns many subagents could leak memory. +// Evict the oldest entry (by insertion order) when the limit is exceeded. +const MAX_SOURCE_ENTRIES = 50 + const DEFAULT_CACHE_THRESHOLD = 80 /** @@ -81,6 +87,13 @@ export function shouldShowCacheWarning( let state = cacheWarningStateBySource.get(querySource) if (!state) { state = { lastHitRate: null, lastTimestamp: null } + // Evict oldest entry when at capacity so the Map stays bounded + if (cacheWarningStateBySource.size >= MAX_SOURCE_ENTRIES) { + const oldestKey = cacheWarningStateBySource.keys().next().value + if (oldestKey !== undefined) { + cacheWarningStateBySource.delete(oldestKey) + } + } cacheWarningStateBySource.set(querySource, state) } @@ -132,3 +145,10 @@ export function createCacheWarningMessage(info: CacheHitRateInfo): Message { isMeta: false, } as Message } + +/** + * Reset the per-source tracking state — only used in tests. + */ +export function _resetCacheWarningStateForTest(): void { + cacheWarningStateBySource.clear() +} diff --git a/src/utils/swarm/inProcessRunner.ts b/src/utils/swarm/inProcessRunner.ts index bf2020248..4d2c7e605 100644 --- a/src/utils/swarm/inProcessRunner.ts +++ b/src/utils/swarm/inProcessRunner.ts @@ -47,6 +47,7 @@ import { import type { CustomAgentDefinition } from '@claude-code-best/builtin-tools/tools/AgentTool/loadAgentsDir.js' import { runAgent } from '@claude-code-best/builtin-tools/tools/AgentTool/runAgent.js' import { awaitClassifierAutoApproval } from '@claude-code-best/builtin-tools/tools/BashTool/bashPermissions.js' +import type { AgentToolResult } from '@claude-code-best/builtin-tools/tools/AgentTool/agentToolUtils.js' import { BASH_TOOL_NAME } from '@claude-code-best/builtin-tools/tools/BashTool/toolName.js' import { SEND_MESSAGE_TOOL_NAME } from '@claude-code-best/builtin-tools/tools/SendMessageTool/constants.js' import { TASK_CREATE_TOOL_NAME } from '@claude-code-best/builtin-tools/tools/TaskCreateTool/constants.js' @@ -63,7 +64,10 @@ import { } from '../../utils/messages.js' import { evictTaskOutput } from '../../utils/task/diskOutput.js' import { evictTerminalTask } from '../../utils/task/framework.js' -import { tokenCountWithEstimation } from '../../utils/tokens.js' +import { + tokenCountWithEstimation, + getTokenCountFromUsage, +} from '../../utils/tokens.js' import { createAbortController } from '../abortController.js' import { type AgentContext, runWithAgentContext } from '../agentContext.js' import { @@ -915,6 +919,7 @@ export async function runInProcessTeammate( invokingRequestId, } = config const { setAppState } = toolUseContext + const startTime = Date.now() logForDebugging( `[inProcessRunner] Starting agent loop for ${identity.agentId}`, @@ -1463,6 +1468,48 @@ export async function runInProcessTeammate( // Mark as completed when exiting the loop let alreadyTerminal = false let toolUseId: string | undefined + + // Compute result so the detail dialog can show token usage. + // Walk backwards for the last API usage (cumulative input_tokens from the + // Anthropic API already includes all prior context). + let completionTokens = 0 + let completionToolUseCount = 0 + let lastAssistantContent: AgentToolResult['content'] = [] + let lastUsage: AgentToolResult['usage'] | undefined + for (let i = allMessages.length - 1; i >= 0; i--) { + const m = allMessages[i]! + if (m.type === 'assistant') { + const blocks = (m.message?.content ?? []) as any[] + for (const b of blocks) { + if (b?.type === 'tool_use') completionToolUseCount++ + } + const textBlocks = blocks.filter((b: any) => b?.type === 'text') + if (textBlocks.length > 0 && lastAssistantContent.length === 0) { + lastAssistantContent = textBlocks.map((b: any) => ({ + type: 'text' as const, + text: b.text, + })) + } + if (!lastUsage && m.message?.usage) { + lastUsage = m.message.usage as AgentToolResult['usage'] + completionTokens = getTokenCountFromUsage( + m.message.usage as Parameters[0], + ) + } + if (completionTokens > 0 && lastAssistantContent.length > 0) break + } + } + + const teammateResult: AgentToolResult = { + agentId: identity.agentId, + agentType: 'teammate', + content: lastAssistantContent, + totalToolUseCount: completionToolUseCount, + totalDurationMs: Date.now() - startTime, + totalTokens: completionTokens, + usage: lastUsage as AgentToolResult['usage'], + } as unknown as AgentToolResult + updateTaskState( taskId, task => { @@ -1481,6 +1528,7 @@ export async function runInProcessTeammate( status: 'completed' as const, notified: true, endTime: Date.now(), + result: teammateResult, messages: task.messages?.length ? [task.messages.at(-1)!] : undefined, pendingUserMessages: [], inProgressToolUseIDs: undefined,