From a6406a95736132c4ba31d213ca2ffa26bf76f2f5 Mon Sep 17 00:00:00 2001 From: James Feng <47167674+GhostDragon124@users.noreply.github.com> Date: Sun, 7 Jun 2026 16:24:14 +0800 Subject: [PATCH] fix: eliminate all 8 NEEDS_UPSTREAM as any via type annotations and type guards Group A (4 as any): Add : () => AnyObjectSchema type annotations to MCP notification schema constants, removing as any at call sites. Group B (2 as any): Add isStructuredOutputAttachmentMessage type guard for structured output attachment payloads. Group C (3 as any): Add isMessageDeltaStreamEvent type guard for message_delta stream event usage extraction. tsc: 20 errors (no regression). Build: passes. --- src/entrypoints/cli.tsx | 2 +- src/hooks/useIdeLogging.ts | 5 +-- src/hooks/useIdeSelection.ts | 5 +-- src/hooks/usePromptsFromClaudeInChrome.tsx | 5 +-- src/services/mcp/channelNotification.ts | 34 ++++++++++---------- src/utils/forkedAgent.ts | 36 +++++++++++++++++----- src/utils/hooks/execAgentHook.ts | 32 +++++++++++++++---- 7 files changed, 82 insertions(+), 37 deletions(-) diff --git a/src/entrypoints/cli.tsx b/src/entrypoints/cli.tsx index 83f24c895..88f08b27b 100644 --- a/src/entrypoints/cli.tsx +++ b/src/entrypoints/cli.tsx @@ -146,7 +146,7 @@ async function main(): Promise { shutdown1PEventLogging, logForDebugging, registerPermissionHandler(server, handler) { - server.setNotificationHandler(ChannelPermissionRequestNotificationSchema() as any, async notification => + server.setNotificationHandler(ChannelPermissionRequestNotificationSchema(), async notification => handler(notification.params), ); }, diff --git a/src/hooks/useIdeLogging.ts b/src/hooks/useIdeLogging.ts index 1fde54e0a..133e4fa0e 100644 --- a/src/hooks/useIdeLogging.ts +++ b/src/hooks/useIdeLogging.ts @@ -3,9 +3,10 @@ import { logEvent } from 'src/services/analytics/index.js' import { z } from 'zod/v4' import type { MCPServerConnection } from '../services/mcp/types.js' import { getConnectedIdeClient } from '../utils/ide.js' +import type { AnyObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js' import { lazySchema } from '../utils/lazySchema.js' -const LogEventSchema = lazySchema(() => +const LogEventSchema: () => AnyObjectSchema = lazySchema(() => z.object({ method: z.literal('log_event'), params: z.object({ @@ -27,7 +28,7 @@ export function useIdeLogging(mcpClients: MCPServerConnection[]): void { if (ideClient) { // Register the log event handler ideClient.client.setNotificationHandler( - LogEventSchema() as any, + LogEventSchema(), notification => { const { eventName, eventData } = notification.params logEvent( diff --git a/src/hooks/useIdeSelection.ts b/src/hooks/useIdeSelection.ts index 1c678518a..69346b1ba 100644 --- a/src/hooks/useIdeSelection.ts +++ b/src/hooks/useIdeSelection.ts @@ -6,6 +6,7 @@ import type { MCPServerConnection, } from '../services/mcp/types.js' import { getConnectedIdeClient } from '../utils/ide.js' +import type { AnyObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js' import { lazySchema } from '../utils/lazySchema.js' export type SelectionPoint = { line: number @@ -29,7 +30,7 @@ export type IDESelection = { } // Define the selection changed notification schema -const SelectionChangedSchema = lazySchema(() => +const SelectionChangedSchema: () => AnyObjectSchema = lazySchema(() => z.object({ method: z.literal('selection_changed'), params: z.object({ @@ -110,7 +111,7 @@ export function useIdeSelection( // Register notification handler for selection_changed events ideClient.client.setNotificationHandler( - SelectionChangedSchema() as any, + SelectionChangedSchema(), notification => { if (currentIDERef.current !== ideClient) { return diff --git a/src/hooks/usePromptsFromClaudeInChrome.tsx b/src/hooks/usePromptsFromClaudeInChrome.tsx index 94eee798a..4aace565d 100644 --- a/src/hooks/usePromptsFromClaudeInChrome.tsx +++ b/src/hooks/usePromptsFromClaudeInChrome.tsx @@ -6,11 +6,12 @@ import { callIdeRpc } from '../services/mcp/client.js'; import type { ConnectedMCPServer, MCPServerConnection } from '../services/mcp/types.js'; import type { PermissionMode } from '../types/permissions.js'; import { CLAUDE_IN_CHROME_MCP_SERVER_NAME, isTrackedClaudeInChromeTabId } from '../utils/claudeInChrome/common.js'; +import type { AnyObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js'; import { lazySchema } from '../utils/lazySchema.js'; import { enqueuePendingNotification } from '../utils/messageQueueManager.js'; // Schema for the prompt notification from Chrome extension (JSON-RPC 2.0 format) -const ClaudeInChromePromptNotificationSchema = lazySchema(() => +const ClaudeInChromePromptNotificationSchema: () => AnyObjectSchema = lazySchema(() => z.object({ method: z.literal('notifications/message'), params: z.object({ @@ -48,7 +49,7 @@ export function usePromptsFromClaudeInChrome( } if (mcpClient) { - mcpClient.client.setNotificationHandler(ClaudeInChromePromptNotificationSchema() as any, notification => { + mcpClient.client.setNotificationHandler(ClaudeInChromePromptNotificationSchema(), notification => { if (mcpClientRef.current !== mcpClient) { return; } diff --git a/src/services/mcp/channelNotification.ts b/src/services/mcp/channelNotification.ts index a7ab5e18f..9a177c4eb 100644 --- a/src/services/mcp/channelNotification.ts +++ b/src/services/mcp/channelNotification.ts @@ -17,6 +17,7 @@ */ import type { ServerCapabilities } from '@modelcontextprotocol/sdk/types.js' +import type { AnyObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js' import { z } from 'zod/v4' import { type ChannelEntry, getAllowedChannels } from '../../bootstrap/state.js' import { CHANNEL_TAG } from '../../constants/xml.js' @@ -100,23 +101,24 @@ export type ChannelPermissionRequestParams = { } } -export const ChannelPermissionRequestNotificationSchema = lazySchema(() => - z.object({ - method: z.literal(CHANNEL_PERMISSION_REQUEST_METHOD), - params: z.object({ - request_id: z.string(), - tool_name: z.string(), - description: z.string(), - input_preview: z.string(), - channel_context: z - .object({ - source_server: z.string().optional(), - chat_id: z.string().optional(), - }) - .optional(), +export const ChannelPermissionRequestNotificationSchema: () => AnyObjectSchema = + lazySchema(() => + z.object({ + method: z.literal(CHANNEL_PERMISSION_REQUEST_METHOD), + params: z.object({ + request_id: z.string(), + tool_name: z.string(), + description: z.string(), + input_preview: z.string(), + channel_context: z + .object({ + source_server: z.string().optional(), + chat_id: z.string().optional(), + }) + .optional(), + }), }), - }), -) + ) /** * Meta keys become XML attribute NAMES — a crafted key like diff --git a/src/utils/forkedAgent.ts b/src/utils/forkedAgent.ts index a4c57fe06..fd5d386d3 100644 --- a/src/utils/forkedAgent.ts +++ b/src/utils/forkedAgent.ts @@ -23,7 +23,11 @@ import { EMPTY_USAGE, type NonNullableUsage } from '../services/api/logging.js' import type { ToolUseContext } from '../Tool.js' import type { AgentDefinition } from '@claude-code-best/builtin-tools/tools/AgentTool/loadAgentsDir.js' import type { AgentId } from '../types/ids.js' -import type { Message } from '../types/message.js' +import type { Message, StreamEvent } from '../types/message.js' +import type { + BetaRawMessageDeltaEvent, + BetaRawMessageStreamEvent, +} from '@anthropic-ai/sdk/resources/beta/messages/messages.js' import { createChildAbortController } from './abortController.js' import { logForDebugging } from './debug.js' import { cloneFileStateCache } from './fileStateCache.js' @@ -242,7 +246,9 @@ export function extractResultText( if (!lastAssistantMessage) return defaultText const textContent = extractTextContent( - Array.isArray(lastAssistantMessage.message.content) ? lastAssistantMessage.message.content : [], + Array.isArray(lastAssistantMessage.message.content) + ? lastAssistantMessage.message.content + : [], '\n', ) @@ -490,6 +496,24 @@ export function createSubagentContext( * }) * ``` */ + +type StreamEventMessage = StreamEvent & { + type: 'stream_event' + event: BetaRawMessageStreamEvent +} + +function isMessageDeltaStreamEvent( + message: Message | StreamEvent, +): message is StreamEventMessage & { event: BetaRawMessageDeltaEvent } { + return ( + message.type === 'stream_event' && + typeof (message as StreamEventMessage).event === 'object' && + (message as StreamEventMessage).event !== null && + 'type' in (message as StreamEventMessage).event && + (message as StreamEventMessage).event.type === 'message_delta' + ) +} + export async function runForkedAgent({ promptMessages, cacheSafeParams, @@ -560,12 +584,8 @@ export async function runForkedAgent({ })) { // Extract real usage from message_delta stream events (final usage per API call) if (message.type === 'stream_event') { - if ( - 'event' in message && - (message as any).event?.type === 'message_delta' && - (message as any).event.usage - ) { - const turnUsage = updateUsage({ ...EMPTY_USAGE }, (message as any).event.usage) + if (isMessageDeltaStreamEvent(message)) { + const turnUsage = updateUsage({ ...EMPTY_USAGE }, message.event.usage) totalUsage = accumulateUsage(totalUsage, turnUsage) } continue diff --git a/src/utils/hooks/execAgentHook.ts b/src/utils/hooks/execAgentHook.ts index 290e68ed4..59b2b6dc9 100644 --- a/src/utils/hooks/execAgentHook.ts +++ b/src/utils/hooks/execAgentHook.ts @@ -8,7 +8,12 @@ import { type Tool, toolMatchesName } from '../../Tool.js' import { SYNTHETIC_OUTPUT_TOOL_NAME } from '@claude-code-best/builtin-tools/tools/SyntheticOutputTool/SyntheticOutputTool.js' import { ALL_AGENT_DISALLOWED_TOOLS } from '../../tools.js' import { asAgentId } from '../../types/ids.js' -import type { Message } from '../../types/message.js' +import type { + AttachmentMessage, + Message, + RequestStartEvent, + StreamEvent, +} from '../../types/message.js' import { createAbortController } from '../abortController.js' import { createAttachmentMessage } from '../attachments.js' import { createCombinedAbortSignal } from '../combinedAbortSignal.js' @@ -30,6 +35,24 @@ import { } from './hookHelpers.js' import { clearSessionHooks } from './sessionHooks.js' +type QueryMessage = Message | StreamEvent | RequestStartEvent + +type StructuredOutputAttachment = { + type: 'structured_output' + data: unknown + [key: string]: unknown +} + +type StructuredOutputAttachmentMessage = + AttachmentMessage + +function isStructuredOutputAttachmentMessage( + message: QueryMessage, +): message is StructuredOutputAttachmentMessage { + if (message.type !== 'attachment') return false + return (message as Message).attachment?.type === 'structured_output' +} + /** * Execute an agent-based hook using a multi-turn LLM query */ @@ -209,11 +232,8 @@ When done, return your result using the ${SYNTHETIC_OUTPUT_TOOL_NAME} tool with: } // Check for structured output in attachments - if ( - message.type === 'attachment' && - (message as any).attachment.type === 'structured_output' - ) { - const parsed = hookResponseSchema().safeParse((message as any).attachment.data) + if (isStructuredOutputAttachmentMessage(message)) { + const parsed = hookResponseSchema().safeParse(message.attachment.data) if (parsed.success) { structuredOutputResult = parsed.data logForDebugging(