Skip to content

Commit 8267250

Browse files
author
Zoo (VP)
committed
fix: clear stale native tool-call parse failures on new API request
parseErrors/parseFailures static maps accumulated an entry per malformed tool call and were never cleared in production (the consume* APIs have no production callers), slowly leaking for the extension-host lifetime. Add NativeToolCallParser.clearParseFailures() and call it in Task.recursivelyMakeClineRequests alongside clearAllStreamingToolCalls()/ clearRawChunkState(), where other per-stream state is reset. The consume* APIs keep working for tests.
1 parent 280da35 commit 8267250

3 files changed

Lines changed: 190 additions & 102 deletions

File tree

‎src/core/assistant-message/NativeToolCallParser.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,22 @@ export class NativeToolCallParser {
195195
return NativeToolCallParser.parseErrors.has(toolCallId)
196196
}
197197

198+
/**
199+
* Clear all recorded parse failures — both the typed {@link parseFailures}
200+
* descriptors and the legacy {@link parseErrors} strings.
201+
*
202+
* Called alongside {@link clearAllStreamingToolCalls} /
203+
* {@link clearRawChunkState} when a new API request starts (see
204+
* Task.recursivelyMakeClineRequests), so failures recorded by an
205+
* interrupted or completed stream do not accumulate for the lifetime of
206+
* the extension host. The consume* APIs keep working for per-call
207+
* retrieval; this clears everything still unconsumed.
208+
*/
209+
public static clearParseFailures(): void {
210+
NativeToolCallParser.parseFailures.clear()
211+
NativeToolCallParser.parseErrors.clear()
212+
}
213+
198214
private static coerceOptionalBoolean(value: unknown): boolean | undefined {
199215
if (typeof value === "boolean") {
200216
return value

‎src/core/assistant-message/__tests__/NativeToolCallParser.spec.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ describe("NativeToolCallParser", () => {
44
beforeEach(() => {
55
NativeToolCallParser.clearAllStreamingToolCalls()
66
NativeToolCallParser.clearRawChunkState()
7+
NativeToolCallParser.clearParseFailures()
78
})
89

910
describe("parseToolCall", () => {
@@ -343,4 +344,70 @@ describe("NativeToolCallParser", () => {
343344
})
344345
})
345346
})
347+
348+
describe("parse failure lifecycle", () => {
349+
it("records a failure on malformed JSON and empties both maps via clearParseFailures", () => {
350+
const result = NativeToolCallParser.parseToolCall({
351+
id: "call_bad_json",
352+
name: "read_file",
353+
arguments: "{not valid json",
354+
})
355+
356+
expect(result).toBeNull()
357+
expect(NativeToolCallParser.hasParseError("call_bad_json")).toBe(true)
358+
359+
// This is what Task.recursivelyMakeClineRequests invokes when a new
360+
// API request starts — the maps must not outlive the stream.
361+
NativeToolCallParser.clearParseFailures()
362+
363+
expect(NativeToolCallParser.hasParseError("call_bad_json")).toBe(false)
364+
expect(NativeToolCallParser.consumeParseError("call_bad_json")).toBeUndefined()
365+
expect(NativeToolCallParser.consumeParseFailure("call_bad_json")).toBeUndefined()
366+
})
367+
368+
it("clears structural failures (not just JSON syntax failures) via clearParseFailures", () => {
369+
// Valid JSON, but missing the required "path" argument.
370+
const result = NativeToolCallParser.parseToolCall({
371+
id: "call_missing_args",
372+
name: "read_file",
373+
arguments: "{}",
374+
})
375+
376+
expect(result).toBeNull()
377+
expect(NativeToolCallParser.consumeParseFailure("call_missing_args")).toBeDefined()
378+
379+
// Record another failure and clear everything unconsumed.
380+
NativeToolCallParser.parseToolCall({
381+
id: "call_missing_args_2",
382+
name: "write_to_file",
383+
arguments: "{}",
384+
})
385+
386+
NativeToolCallParser.clearParseFailures()
387+
388+
expect(NativeToolCallParser.hasParseError("call_missing_args")).toBe(false)
389+
expect(NativeToolCallParser.hasParseError("call_missing_args_2")).toBe(false)
390+
expect(NativeToolCallParser.consumeParseFailure("call_missing_args_2")).toBeUndefined()
391+
})
392+
393+
it("keeps the consume* API working for recorded failures", () => {
394+
NativeToolCallParser.parseToolCall({
395+
id: "call_consume",
396+
name: "read_file",
397+
arguments: "{}",
398+
})
399+
400+
const failure = NativeToolCallParser.consumeParseFailure("call_consume")
401+
expect(failure).toBeDefined()
402+
expect(failure?.kind).toBe("missing_required_arguments")
403+
expect(failure?.missingParameters).toEqual(["path"])
404+
405+
// Consume is atomic — a second read returns undefined.
406+
expect(NativeToolCallParser.consumeParseFailure("call_consume")).toBeUndefined()
407+
408+
// The legacy string side channel is independent and still available.
409+
expect(NativeToolCallParser.consumeParseError("call_consume")).toBeDefined()
410+
expect(NativeToolCallParser.consumeParseError("call_consume")).toBeUndefined()
411+
})
412+
})
346413
})

‎src/core/task/Task.ts‎

Lines changed: 107 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -2761,6 +2761,9 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
27612761
// Clear any leftover streaming tool call state from previous interrupted streams
27622762
NativeToolCallParser.clearAllStreamingToolCalls()
27632763
NativeToolCallParser.clearRawChunkState()
2764+
// Clear recorded parse failures from previous streams so they
2765+
// don't accumulate for the extension-host lifetime.
2766+
NativeToolCallParser.clearParseFailures()
27642767

27652768
await this.diffViewProvider.reset()
27662769

@@ -2942,7 +2945,9 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
29422945
// it is a malformed named call that must receive a
29432946
// tool_result. A call with any argument bytes is NOT a
29442947
// ghost — it carries partial model intent.
2945-
const preFinalizeState = NativeToolCallParser.getStreamingToolCallState(event.id)
2948+
const preFinalizeState = NativeToolCallParser.getStreamingToolCallState(
2949+
event.id,
2950+
)
29462951
const ghostDisposition = preFinalizeState
29472952
? classifyStreamedCall({
29482953
callId: event.id,
@@ -3063,7 +3068,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
30633068
argumentsAccumulator: chunk.arguments ?? "",
30643069
streamEnded: true,
30653070
})
3066-
3071+
30673072
if (isProvablyEmptyGhost(legacyDisposition)) {
30683073
// Silently drop the ghost. Do not push to
30693074
// assistantMessageContent, do not present.
@@ -3089,29 +3094,29 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
30893094
})
30903095
break
30913096
}
3092-
3097+
30933098
// Convert native tool call to ToolUse format
30943099
const toolUse = NativeToolCallParser.parseToolCall({
30953100
id: chunk.id,
30963101
name: chunk.name as ToolName,
30973102
arguments: chunk.arguments,
30983103
})
3099-
3104+
31003105
if (!toolUse) {
31013106
console.error(`Failed to parse tool call for task ${this.taskId}:`, chunk)
31023107
break
31033108
}
3104-
3109+
31053110
// Store the tool call ID on the ToolUse object for later reference
31063111
// This is needed to create tool_result blocks that reference the correct tool_use_id
31073112
toolUse.id = chunk.id
3108-
3113+
31093114
// Add the tool use to assistant message content
31103115
this.assistantMessageContent.push(toolUse)
3111-
3116+
31123117
// Mark that we have new content to process
31133118
this.userMessageContentReady = false
3114-
3119+
31153120
// Present the tool call to user - presentAssistantMessage will execute
31163121
// tools sequentially and accumulate all results in userMessageContent
31173122
/* v8 ignore next -- streaming presenter; .catch lives in presentAssistantMessageSafe (covered) */
@@ -3438,106 +3443,106 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
34383443
// This is critical for MCP tools which need tool_call_end events to be properly
34393444
// converted from ToolUse to McpToolUse via finalizeStreamingToolCall()
34403445
const finalizeEvents = NativeToolCallParser.finalizeRawChunks()
3441-
for (const event of finalizeEvents) {
3442-
if (event.type === "tool_call_end") {
3443-
// Ghost quarantine (same logic as the streaming tool_call_end
3444-
// handler above): inspect streaming state BEFORE
3445-
// finalizeStreamingToolCall() deletes it.
3446-
const preFinalizeState = NativeToolCallParser.getStreamingToolCallState(event.id)
3447-
const ghostDisposition = preFinalizeState
3448-
? classifyStreamedCall({
3449-
callId: event.id,
3450-
toolName: preFinalizeState.name,
3451-
argumentsAccumulator: preFinalizeState.argumentsAccumulator,
3452-
streamEnded: true,
3453-
})
3454-
: undefined
3455-
3456-
if (ghostDisposition && isProvablyEmptyGhost(ghostDisposition)) {
3457-
// Silently drop the ghost: remove its partial block
3458-
// from assistantMessageContent and discard streaming
3459-
// state. It will NOT receive a tool_result.
3460-
const ghostIndex = this.streamingToolCallIndices.get(event.id)
3461-
if (ghostIndex !== undefined) {
3462-
this.assistantMessageContent.splice(ghostIndex, 1)
3463-
for (const [cid, idx] of this.streamingToolCallIndices.entries()) {
3464-
if (idx > ghostIndex) {
3465-
this.streamingToolCallIndices.set(cid, idx - 1)
3466-
}
3467-
}
3468-
this.streamingToolCallIndices.delete(event.id)
3469-
}
3470-
NativeToolCallParser.discardStreamingToolCall(event.id)
3471-
// Emit telemetry for the ghost drop. Only counts and
3472-
// metadata are sent — no call ID, tool name, or args.
3473-
const ghostPolicy3 = resolveToolCallPolicy(
3474-
this.api.getModel().info,
3475-
this.apiConfiguration.apiProvider,
3476-
)
3477-
emitGhostDropTelemetry({
3478-
taskId: this.taskId,
3479-
provider: this.apiConfiguration.apiProvider ?? "unknown",
3480-
model: this.api.getModel().id,
3481-
policySource: ghostPolicy3.source,
3482-
maxCallsPerTurn: ghostPolicy3.maxCallsPerTurn,
3483-
enforcement: ghostPolicy3.enforcement,
3484-
callCount: this.assistantMessageContent.filter(
3485-
(b: AssistantMessageContent): b is ToolUse => b.type === "tool_use",
3486-
).length,
3487-
ghostDroppedCount: 1,
3488-
errorResultCount: 0,
3489-
parallelToolCallsRequested: ghostPolicy3.generation === "parallel",
3446+
for (const event of finalizeEvents) {
3447+
if (event.type === "tool_call_end") {
3448+
// Ghost quarantine (same logic as the streaming tool_call_end
3449+
// handler above): inspect streaming state BEFORE
3450+
// finalizeStreamingToolCall() deletes it.
3451+
const preFinalizeState = NativeToolCallParser.getStreamingToolCallState(event.id)
3452+
const ghostDisposition = preFinalizeState
3453+
? classifyStreamedCall({
3454+
callId: event.id,
3455+
toolName: preFinalizeState.name,
3456+
argumentsAccumulator: preFinalizeState.argumentsAccumulator,
3457+
streamEnded: true,
34903458
})
3491-
continue
3492-
}
3493-
3494-
// Finalize the streaming tool call
3495-
const finalToolUse = NativeToolCallParser.finalizeStreamingToolCall(event.id)
3496-
3497-
// Get the index for this tool call
3498-
const toolUseIndex = this.streamingToolCallIndices.get(event.id)
3499-
3500-
if (finalToolUse) {
3501-
// Store the tool call ID
3502-
;(finalToolUse as any).id = event.id
3503-
3504-
// Get the index and replace partial with final
3505-
if (toolUseIndex !== undefined) {
3506-
this.assistantMessageContent[toolUseIndex] = finalToolUse
3507-
}
3508-
3509-
// Clean up tracking
3510-
this.streamingToolCallIndices.delete(event.id)
3511-
3512-
// Mark that we have new content to process
3513-
this.userMessageContentReady = false
3514-
3515-
// Present the finalized tool call
3516-
/* v8 ignore next -- streaming presenter; .catch lives in presentAssistantMessageSafe (covered) */
3517-
this.presentAssistantMessageSafe()
3518-
} else if (toolUseIndex !== undefined) {
3519-
// finalizeStreamingToolCall returned null (malformed JSON or missing args)
3520-
// We still need to mark the tool as non-partial so it gets executed
3521-
// The tool's validation will catch any missing required parameters
3522-
const existingToolUse = this.assistantMessageContent[toolUseIndex]
3523-
if (existingToolUse && existingToolUse.type === "tool_use") {
3524-
existingToolUse.partial = false
3525-
// Ensure it has the ID for native protocol
3526-
;(existingToolUse as any).id = event.id
3459+
: undefined
3460+
3461+
if (ghostDisposition && isProvablyEmptyGhost(ghostDisposition)) {
3462+
// Silently drop the ghost: remove its partial block
3463+
// from assistantMessageContent and discard streaming
3464+
// state. It will NOT receive a tool_result.
3465+
const ghostIndex = this.streamingToolCallIndices.get(event.id)
3466+
if (ghostIndex !== undefined) {
3467+
this.assistantMessageContent.splice(ghostIndex, 1)
3468+
for (const [cid, idx] of this.streamingToolCallIndices.entries()) {
3469+
if (idx > ghostIndex) {
3470+
this.streamingToolCallIndices.set(cid, idx - 1)
3471+
}
35273472
}
3528-
3529-
// Clean up tracking
35303473
this.streamingToolCallIndices.delete(event.id)
3531-
3532-
// Mark that we have new content to process
3533-
this.userMessageContentReady = false
3534-
3535-
// Present the tool call - validation will handle missing params
3536-
/* v8 ignore next -- streaming presenter; .catch lives in presentAssistantMessageSafe (covered) */
3537-
this.presentAssistantMessageSafe()
35383474
}
3475+
NativeToolCallParser.discardStreamingToolCall(event.id)
3476+
// Emit telemetry for the ghost drop. Only counts and
3477+
// metadata are sent — no call ID, tool name, or args.
3478+
const ghostPolicy3 = resolveToolCallPolicy(
3479+
this.api.getModel().info,
3480+
this.apiConfiguration.apiProvider,
3481+
)
3482+
emitGhostDropTelemetry({
3483+
taskId: this.taskId,
3484+
provider: this.apiConfiguration.apiProvider ?? "unknown",
3485+
model: this.api.getModel().id,
3486+
policySource: ghostPolicy3.source,
3487+
maxCallsPerTurn: ghostPolicy3.maxCallsPerTurn,
3488+
enforcement: ghostPolicy3.enforcement,
3489+
callCount: this.assistantMessageContent.filter(
3490+
(b: AssistantMessageContent): b is ToolUse => b.type === "tool_use",
3491+
).length,
3492+
ghostDroppedCount: 1,
3493+
errorResultCount: 0,
3494+
parallelToolCallsRequested: ghostPolicy3.generation === "parallel",
3495+
})
3496+
continue
3497+
}
3498+
3499+
// Finalize the streaming tool call
3500+
const finalToolUse = NativeToolCallParser.finalizeStreamingToolCall(event.id)
3501+
3502+
// Get the index for this tool call
3503+
const toolUseIndex = this.streamingToolCallIndices.get(event.id)
3504+
3505+
if (finalToolUse) {
3506+
// Store the tool call ID
3507+
;(finalToolUse as any).id = event.id
3508+
3509+
// Get the index and replace partial with final
3510+
if (toolUseIndex !== undefined) {
3511+
this.assistantMessageContent[toolUseIndex] = finalToolUse
3512+
}
3513+
3514+
// Clean up tracking
3515+
this.streamingToolCallIndices.delete(event.id)
3516+
3517+
// Mark that we have new content to process
3518+
this.userMessageContentReady = false
3519+
3520+
// Present the finalized tool call
3521+
/* v8 ignore next -- streaming presenter; .catch lives in presentAssistantMessageSafe (covered) */
3522+
this.presentAssistantMessageSafe()
3523+
} else if (toolUseIndex !== undefined) {
3524+
// finalizeStreamingToolCall returned null (malformed JSON or missing args)
3525+
// We still need to mark the tool as non-partial so it gets executed
3526+
// The tool's validation will catch any missing required parameters
3527+
const existingToolUse = this.assistantMessageContent[toolUseIndex]
3528+
if (existingToolUse && existingToolUse.type === "tool_use") {
3529+
existingToolUse.partial = false
3530+
// Ensure it has the ID for native protocol
3531+
;(existingToolUse as any).id = event.id
3532+
}
3533+
3534+
// Clean up tracking
3535+
this.streamingToolCallIndices.delete(event.id)
3536+
3537+
// Mark that we have new content to process
3538+
this.userMessageContentReady = false
3539+
3540+
// Present the tool call - validation will handle missing params
3541+
/* v8 ignore next -- streaming presenter; .catch lives in presentAssistantMessageSafe (covered) */
3542+
this.presentAssistantMessageSafe()
35393543
}
35403544
}
3545+
}
35413546

35423547
// IMPORTANT: Capture partialBlocks AFTER finalizeRawChunks() to avoid double-presentation.
35433548
// Tools finalized above are already presented, so we only want blocks still partial after finalization.

0 commit comments

Comments
 (0)