6312
Ga
go-opencode-ai-zen-sdk / files
go-opencode-ai-zen-sdk / tool_calls.go
2.6 KB
1package zen 2 3import ( 4 "encoding/json" 5 "fmt" 6 "strings" 7) 8 9// StreamToolCall is a fully assembled tool call extracted from a stream. 10type StreamToolCall struct { 11 ID string 12 Name string 13 Arguments json.RawMessage 14 ThoughtSignature string 15} 16 17// ToolCallAccumulator stitches streaming tool call deltas into complete calls. 18// Call Apply for every NormalizedDelta, then call CompleteCalls at the end. 19type ToolCallAccumulator struct { 20 calls map[int]*toolCallState 21 order []int 22} 23 24type toolCallState struct { 25 index int 26 id string 27 name string 28 sig string 29 args strings.Builder 30 full string 31} 32 33// NewToolCallAccumulator creates a new accumulator for streaming tool calls. 34func NewToolCallAccumulator() *ToolCallAccumulator { 35 return &ToolCallAccumulator{calls: map[int]*toolCallState{}} 36} 37 38// Apply ingests a single delta. It returns true if the delta affected tool state. 39func (a *ToolCallAccumulator) Apply(delta NormalizedDelta) bool { 40 switch delta.Type { 41 case DeltaToolCallBegin, DeltaToolCallArgumentsDelta, DeltaToolCallDone: 42 // continue 43 default: 44 return false 45 } 46 47 call := a.ensure(delta.ToolCallIndex) 48 switch delta.Type { 49 case DeltaToolCallBegin: 50 if call.id == "" { 51 call.id = delta.ToolCallID 52 } 53 if call.name == "" { 54 call.name = delta.ToolCallName 55 } 56 if call.sig == "" { 57 call.sig = delta.ToolCallSignature 58 } 59 case DeltaToolCallArgumentsDelta: 60 call.args.WriteString(delta.ArgumentsDelta) 61 case DeltaToolCallDone: 62 if call.id == "" { 63 call.id = delta.ToolCallID 64 } 65 if call.name == "" { 66 call.name = delta.ToolCallName 67 } 68 if call.sig == "" { 69 call.sig = delta.ToolCallSignature 70 } 71 if delta.ArgumentsFull != "" { 72 call.full = delta.ArgumentsFull 73 } 74 } 75 76 return true 77} 78 79// CompleteCalls returns fully assembled tool calls in their original order. 80// Any missing IDs are filled with stable synthetic IDs. 81func (a *ToolCallAccumulator) CompleteCalls() []StreamToolCall { 82 if len(a.order) == 0 { 83 return nil 84 } 85 out := make([]StreamToolCall, 0, len(a.order)) 86 for _, idx := range a.order { 87 call := a.calls[idx] 88 if call == nil { 89 continue 90 } 91 id := call.id 92 if id == "" { 93 id = fmt.Sprintf("tool-%d", call.index) 94 } 95 full := call.full 96 if full == "" { 97 full = call.args.String() 98 } 99 out = append(out, StreamToolCall{ 100 ID: id, 101 Name: call.name, 102 Arguments: json.RawMessage(full), 103 ThoughtSignature: call.sig, 104 }) 105 } 106 return out 107} 108 109func (a *ToolCallAccumulator) ensure(index int) *toolCallState { 110 call := a.calls[index] 111 if call != nil { 112 return call 113 } 114 call = &toolCallState{index: index} 115 a.calls[index] = call 116 a.order = append(a.order, index) 117 return call 118}