Skip to content

Commit a2a0e48

Browse files
fix(cli): verify agent block exists before nesting tool calls
Prevents tool calls from attempting to nest under agent blocks that don't exist yet. Adds recursive search to confirm agent block presence before nesting, falling back to top-level placement when needed. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
1 parent aff0d3b commit a2a0e48

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

cli/src/hooks/use-send-message.ts

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,24 @@ const hiddenToolNames = new Set<ToolName | 'spawn_agent_inline'>([
2424
'spawn_agents',
2525
])
2626

27+
// Helper function to check if an agent block exists
28+
const findAgentBlock = (
29+
blocks: ContentBlock[],
30+
targetAgentId: string,
31+
): boolean => {
32+
for (const block of blocks) {
33+
if (block.type === 'agent' && block.agentId === targetAgentId) {
34+
return true
35+
}
36+
if (block.type === 'agent' && block.blocks) {
37+
if (findAgentBlock(block.blocks, targetAgentId)) {
38+
return true
39+
}
40+
}
41+
}
42+
return false
43+
}
44+
2745
// Helper function to recursively update blocks
2846
const updateBlocksRecursively = (
2947
blocks: ContentBlock[],
@@ -714,8 +732,22 @@ export const useSendMessage = ({
714732
agentId: agentId || 'none',
715733
})
716734

717-
// If this tool call belongs to a subagent, add it to that agent's blocks
718-
if (agentId) {
735+
// Check if this tool call should be nested in a subagent
736+
// Only nest if the agent block actually exists
737+
const shouldNestInAgent = agentId && setMessages.length > 0
738+
let agentBlockExists = false
739+
740+
if (shouldNestInAgent) {
741+
setMessages((prev) => {
742+
const msg = prev.find((m) => m.id === aiMessageId)
743+
if (msg?.blocks) {
744+
agentBlockExists = findAgentBlock(msg.blocks, agentId)
745+
}
746+
return prev
747+
})
748+
}
749+
750+
if (agentBlockExists) {
719751
logger.info('setMessages: tool_call for subagent', {
720752
agentId,
721753
toolName,
@@ -754,7 +786,7 @@ export const useSendMessage = ({
754786
}),
755787
)
756788
} else {
757-
// Top-level tool call
789+
// Top-level tool call (or agent block doesn't exist yet)
758790
setMessages((prev) =>
759791
prev.map((msg) => {
760792
if (msg.id !== aiMessageId) {

0 commit comments

Comments
 (0)