(scope: ToolScope)
| 9 | } from './types' |
| 10 | |
| 11 | export function handleTextEvent(scope: ToolScope): StreamHandler { |
| 12 | return (event, context) => { |
| 13 | if (event.type !== 'text') { |
| 14 | return |
| 15 | } |
| 16 | |
| 17 | const chunk = event.payload.text |
| 18 | if (!chunk) { |
| 19 | return |
| 20 | } |
| 21 | |
| 22 | if (scope === 'subagent') { |
| 23 | const parentToolCallId = getScopedParentToolCallId(event, context) |
| 24 | if (!parentToolCallId) return |
| 25 | const spanIdentity = getScopedSpanIdentity(event) |
| 26 | if (event.payload.channel === MothershipStreamV1TextChannel.thinking) { |
| 27 | // Per-lane thinking: each concurrent subagent accumulates into its own |
| 28 | // block keyed by parentToolCallId, so interleaved chunks from a sibling |
| 29 | // subagent never flush or corrupt this lane's reasoning. |
| 30 | let block = context.subagentThinkingBlocks.get(parentToolCallId) |
| 31 | if (!block) { |
| 32 | block = { |
| 33 | type: 'subagent_thinking', |
| 34 | content: '', |
| 35 | parentToolCallId, |
| 36 | ...spanIdentity, |
| 37 | timestamp: Date.now(), |
| 38 | } |
| 39 | context.subagentThinkingBlocks.set(parentToolCallId, block) |
| 40 | } |
| 41 | block.content = `${block.content || ''}${chunk}` |
| 42 | return |
| 43 | } |
| 44 | // Real text for this lane: close this lane's thinking block first so the |
| 45 | // persisted order is [thinking, text] within the lane. |
| 46 | flushSubagentThinkingBlock(context, parentToolCallId) |
| 47 | if (context.isInThinkingBlock) { |
| 48 | flushThinkingBlock(context) |
| 49 | } |
| 50 | context.subAgentContent[parentToolCallId] = |
| 51 | (context.subAgentContent[parentToolCallId] || '') + chunk |
| 52 | addContentBlock(context, { |
| 53 | type: 'subagent_text', |
| 54 | content: chunk, |
| 55 | parentToolCallId, |
| 56 | ...spanIdentity, |
| 57 | }) |
| 58 | return |
| 59 | } |
| 60 | |
| 61 | if (event.payload.channel === MothershipStreamV1TextChannel.thinking) { |
| 62 | if (!context.currentThinkingBlock) { |
| 63 | context.currentThinkingBlock = { |
| 64 | type: 'thinking', |
| 65 | content: '', |
| 66 | timestamp: Date.now(), |
| 67 | } |
| 68 | context.isInThinkingBlock = true |
no test coverage detected