Repository navigation
Expand file tree
/
Copy pathhandoff.go
More file actions
600 lines (546 loc) · 20.5 KB
/
Copy pathhandoff.go
File metadata and controls
600 lines (546 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
// Copyright (c) 2026 Matthew Winter
//
// This source code is licensed under the MIT license found in the LICENSE file
// in the root directory of this source tree.
package sigma
import (
"fmt"
"strconv"
"strings"
)
const (
defaultHandoffThinkingStartDelimiter = "<thinking>"
defaultHandoffThinkingEndDelimiter = "</thinking>"
)
// HandoffChangeKind identifies one request adaptation made during handoff.
type HandoffChangeKind string
const (
// HandoffChangeThinkingConverted indicates a thinking block was converted
// to text for a target that cannot safely replay it natively.
HandoffChangeThinkingConverted HandoffChangeKind = "thinking-converted"
// HandoffChangeDeveloperRoleConverted indicates a developer message was
// converted to a user message for target compatibility.
HandoffChangeDeveloperRoleConverted HandoffChangeKind = "developer-role-converted"
// HandoffChangeToolResultNameRepaired indicates a missing tool result name
// was filled from a prior assistant tool call.
HandoffChangeToolResultNameRepaired HandoffChangeKind = "tool-result-name-repaired"
// HandoffChangeUnansweredToolCallDropped indicates an assistant tool call
// without a matching tool result before the next user/developer turn was
// removed.
HandoffChangeUnansweredToolCallDropped HandoffChangeKind = "unanswered-tool-call-dropped"
// HandoffChangeRepairMessageInserted indicates an assistant bridge message
// was inserted between a tool result and following user turn.
HandoffChangeRepairMessageInserted HandoffChangeKind = "repair-message-inserted"
// HandoffChangeToolResultSynthesized indicates a missing tool result was
// synthesized for an unanswered assistant tool call.
HandoffChangeToolResultSynthesized HandoffChangeKind = "tool-result-synthesized"
// HandoffChangeUnsupportedImageReplaced indicates an image block was
// replaced with caller-supplied text for a non-vision target.
HandoffChangeUnsupportedImageReplaced HandoffChangeKind = "unsupported-image-replaced"
)
// HandoffChange describes one source-neutral transformation.
type HandoffChange struct {
Kind HandoffChangeKind `json:"kind"`
MessageIndex int `json:"messageIndex"`
OutputMessageIndex *int `json:"outputMessageIndex,omitempty"`
ContentIndex *int `json:"contentIndex,omitempty"`
Detail string `json:"detail,omitempty"`
}
// HandoffReport summarizes adaptations made for a target model.
type HandoffReport struct {
ConvertedThinkingBlocks int `json:"convertedThinkingBlocks,omitempty"`
ConvertedDeveloperMessages int `json:"convertedDeveloperMessages,omitempty"`
RepairedToolResultNames int `json:"repairedToolResultNames,omitempty"`
DroppedUnansweredToolCalls int `json:"droppedUnansweredToolCalls,omitempty"`
InsertedRepairMessages int `json:"insertedRepairMessages,omitempty"`
SynthesizedToolResults int `json:"synthesizedToolResults,omitempty"`
ReplacedUnsupportedImages int `json:"replacedUnsupportedImages,omitempty"`
Changes []HandoffChange `json:"changes,omitempty"`
}
// HandoffResult is a transformed request and its adaptation report.
type HandoffResult struct {
Request Request `json:"request"`
Report HandoffReport `json:"report,omitempty"`
}
// HandoffMessagesResult is a transformed message list and its adaptation report.
type HandoffMessagesResult struct {
Messages []Message `json:"messages,omitempty"`
Report HandoffReport `json:"report,omitempty"`
}
// HandoffOption configures public cross-provider request adaptation.
type HandoffOption func(*handoffConfig)
// WithHandoffThinkingDelimiters configures the text wrappers used when
// provider-native thinking blocks are converted to text.
func WithHandoffThinkingDelimiters(start string, end string) HandoffOption {
return func(config *handoffConfig) {
config.thinkingStartDelimiter = start
config.thinkingEndDelimiter = end
}
}
// WithHandoffUnsupportedImageReplacement replaces unsupported image blocks
// with the supplied text instead of returning an unsupported-content error.
func WithHandoffUnsupportedImageReplacement(text string) HandoffOption {
return func(config *handoffConfig) {
config.unsupportedImageReplacement = &text
}
}
// TransformRequestForModel adapts a request for replay against target. The
// helper is opt-in and does not mutate the caller's request.
func TransformRequestForModel(target Model, req Request, opts ...HandoffOption) (HandoffResult, error) {
if err := ValidateModelRef(ModelRef{Provider: target.Provider, ID: target.ID}); err != nil {
return HandoffResult{}, err
}
config := newHandoffConfig(opts...)
compat := handoffCompatibilityForModel(target)
report := HandoffReport{}
output := Request{
SystemPrompt: req.SystemPrompt,
Tools: cloneHandoffTools(req.Tools),
}
sourceIndexes := make([]int, len(req.Messages))
for index := range sourceIndexes {
sourceIndexes[index] = index
}
messages := req.Messages
if compat.dropUnansweredToolCalls {
messages, sourceIndexes = dropUnansweredHandoffToolCalls(messages, sourceIndexes, len(req.Messages), &report)
}
toolNamesByID := make(map[string]string)
for index, message := range messages {
transformed, err := transformHandoffMessage(message, handoffMessageContext{
target: target,
compat: compat,
config: config,
toolNames: toolNamesByID,
messageIndex: sourceIndexes[index],
report: &report,
})
if err != nil {
return HandoffResult{}, err
}
output.Messages = append(output.Messages, transformed)
recordHandoffToolCalls(toolNamesByID, transformed)
}
if compat.assistantAfterToolResultRepair {
output.Messages = insertHandoffRepairMessages(output.Messages, sourceIndexes, &report)
}
return HandoffResult{Request: output, Report: report}, nil
}
// TransformMessagesForModel adapts a message list for replay against target.
// It is equivalent to TransformRequestForModel with only Request.Messages set.
func TransformMessagesForModel(target Model, messages []Message, opts ...HandoffOption) (HandoffMessagesResult, error) {
result, err := TransformRequestForModel(target, Request{Messages: messages}, opts...)
if err != nil {
return HandoffMessagesResult{}, err
}
return HandoffMessagesResult{Messages: result.Request.Messages, Report: result.Report}, nil
}
type handoffConfig struct {
thinkingStartDelimiter string
thinkingEndDelimiter string
unsupportedImageReplacement *string
}
func newHandoffConfig(opts ...HandoffOption) handoffConfig {
config := handoffConfig{
thinkingStartDelimiter: defaultHandoffThinkingStartDelimiter,
thinkingEndDelimiter: defaultHandoffThinkingEndDelimiter,
}
for _, opt := range opts {
if opt != nil {
opt(&config)
}
}
if config.thinkingStartDelimiter == "" {
config.thinkingStartDelimiter = defaultHandoffThinkingStartDelimiter
}
if config.thinkingEndDelimiter == "" {
config.thinkingEndDelimiter = defaultHandoffThinkingEndDelimiter
}
return config
}
type handoffCompatibility struct {
assistantAfterToolResultRepair bool
requireToolResultName bool
convertDeveloperRole bool
dropUnansweredToolCalls bool
normalizeToolCallID func(string) string
}
func handoffCompatibilityForModel(model Model) handoffCompatibility {
compat := handoffCompatibility{dropUnansweredToolCalls: true}
if model.API == APIOpenAICompletions && model.OpenAICompletionsCompat != nil {
compat.requireToolResultName = model.OpenAICompletionsCompat.RequiresToolResultName == OpenAICompatSupported
compat.assistantAfterToolResultRepair = model.OpenAICompletionsCompat.RequiresAssistantAfterToolResult == OpenAICompatSupported
compat.convertDeveloperRole = model.OpenAICompletionsCompat.SupportsDeveloperRole == OpenAICompatUnsupported
}
if model.API == APIAnthropicMessages || model.API == APIBedrockConverseStream {
compat.normalizeToolCallID = newHandoffToolCallIDNormalizer(64)
}
return compat
}
type handoffMessageContext struct {
target Model
compat handoffCompatibility
config handoffConfig
toolNames map[string]string
messageIndex int
report *HandoffReport
}
func transformHandoffMessage(message Message, ctx handoffMessageContext) (Message, error) {
transformed := cloneHandoffMessage(message)
if ctx.compat.convertDeveloperRole && transformed.Role == RoleDeveloper {
transformed.Role = RoleUser
ctx.report.record(HandoffChangeDeveloperRoleConverted, ctx.messageIndex, nil, "converted developer message to user message")
}
content := make([]ContentBlock, 0, len(message.Content))
for index, block := range message.Content {
if block.Type == ContentBlockImage && !ctx.target.SupportsImages() {
if ctx.config.unsupportedImageReplacement == nil {
return Message{}, handoffError(ctx, "target model does not support image content")
}
content = append(content, Text(*ctx.config.unsupportedImageReplacement))
ctx.report.record(HandoffChangeUnsupportedImageReplaced, ctx.messageIndex, intPtr(index), "replaced image block with text")
continue
}
if transformed.Role == RoleAssistant && block.Type == ContentBlockThinking && shouldConvertHandoffThinking(message, ctx) {
if strings.TrimSpace(block.ThinkingText) == "" || block.Redacted {
continue
}
content = append(content, Text(wrapHandoffThinking(block.ThinkingText, ctx.config)))
ctx.report.record(HandoffChangeThinkingConverted, ctx.messageIndex, intPtr(index), "converted thinking block to text")
continue
}
cloned := block.Clone()
if cloned.Type == ContentBlockToolCall && isHandoffClientToolCall(cloned) && ctx.compat.normalizeToolCallID != nil {
cloned.ToolCallID = ctx.compat.normalizeToolCallID(cloned.ToolCallID)
}
content = append(content, cloned)
}
transformed.Content = content
if transformed.Role == RoleTool && ctx.compat.normalizeToolCallID != nil {
transformed.ToolCallID = ctx.compat.normalizeToolCallID(transformed.ToolCallID)
}
if transformed.Role == RoleTool && ctx.compat.requireToolResultName && transformed.ToolName == "" {
toolName, ok := ctx.toolNames[transformed.ToolCallID]
if !ok {
return Message{}, handoffError(ctx, "tool result requires a tool name but no matching assistant tool call was found")
}
transformed.ToolName = toolName
ctx.report.record(HandoffChangeToolResultNameRepaired, ctx.messageIndex, nil, "filled tool result name from assistant tool call")
}
return transformed, nil
}
func shouldConvertHandoffThinking(message Message, ctx handoffMessageContext) bool {
// Keep interrupted reasoning distinguishable until provider request preparation
// removes it. Converting it to text here would make it appear user-visible.
if message.StopReason == StopReasonError || message.StopReason == StopReasonAborted {
return false
}
if !ctx.target.SupportsReasoning() {
return true
}
if message.Provider != "" && message.Provider != ctx.target.Provider {
return true
}
if message.API != "" && ctx.target.API != "" && message.API != ctx.target.API {
return true
}
return message.Model != "" && ctx.target.ID != "" && message.Model != ctx.target.ID
}
func wrapHandoffThinking(text string, config handoffConfig) string {
return config.thinkingStartDelimiter + "\n" + text + "\n" + config.thinkingEndDelimiter
}
func recordHandoffToolCalls(toolNamesByID map[string]string, message Message) {
if message.Role != RoleAssistant {
return
}
for _, block := range message.Content {
if block.Type == ContentBlockToolCall && block.ToolCallID != "" && block.ToolName != "" {
toolNamesByID[block.ToolCallID] = block.ToolName
}
}
}
func handoffRepairMessage() Message {
return Message{
Role: RoleAssistant,
Content: []ContentBlock{Text("I have processed the tool results.")},
}
}
func dropUnansweredHandoffToolCalls(messages []Message, sourceIndexes []int, endSourceIndex int, report *HandoffReport) ([]Message, []int) {
if len(messages) == 0 {
return nil, nil
}
priorChanges := len(report.Changes)
indexMap := make([]int, len(messages))
repaired := make([]Message, 0, len(messages))
repairedSourceIndexes := make([]int, 0, len(messages))
var pending []ContentBlock
var held []int
answered := make(map[string]struct{})
insertMissing := func(sourceIndex int) {
for _, call := range pending {
if _, ok := answered[call.ToolCallID]; ok {
continue
}
outputIndex := len(repaired)
repaired = append(repaired, syntheticHandoffToolResult(call))
repairedSourceIndexes = append(repairedSourceIndexes, sourceIndex)
report.recordOutput(HandoffChangeToolResultSynthesized, sourceIndex, outputIndex, nil, "synthesized missing tool result")
}
for _, index := range held {
indexMap[index] = len(repaired)
repaired = append(repaired, messages[index])
repairedSourceIndexes = append(repairedSourceIndexes, handoffSourceIndex(sourceIndexes, index, endSourceIndex))
}
held = nil
pending = nil
answered = make(map[string]struct{})
}
for index, message := range messages {
sourceIndex := handoffSourceIndex(sourceIndexes, index, endSourceIndex)
switch message.Role {
case RoleAssistant:
insertMissing(sourceIndex)
pending = handoffAssistantToolCalls(message)
case RoleDeveloper:
if len(pending) > 0 {
held = append(held, index)
continue
}
case RoleUser:
insertMissing(sourceIndex)
case RoleTool:
if hasPendingHandoffToolCall(pending, message.ToolCallID) {
answered[message.ToolCallID] = struct{}{}
}
}
indexMap[index] = len(repaired)
repaired = append(repaired, message)
repairedSourceIndexes = append(repairedSourceIndexes, sourceIndex)
}
insertMissing(endSourceIndex)
remapHandoffOutputIndexes(report, priorChanges, indexMap)
return repaired, repairedSourceIndexes
}
func handoffAssistantToolCalls(message Message) []ContentBlock {
var calls []ContentBlock
for _, block := range message.Content {
if isHandoffClientToolCall(block) {
calls = append(calls, block)
}
}
return calls
}
func hasPendingHandoffToolCall(calls []ContentBlock, id string) bool {
for _, call := range calls {
if call.ToolCallID == id {
return true
}
}
return false
}
func syntheticHandoffToolResult(call ContentBlock) Message {
return Message{
Role: RoleTool,
ToolCallID: call.ToolCallID,
ToolName: call.ToolName,
IsError: true,
Content: []ContentBlock{Text("No result provided")},
}
}
func insertHandoffRepairMessages(messages []Message, sourceIndexes []int, report *HandoffReport) []Message {
if len(messages) == 0 {
return nil
}
priorChanges := len(report.Changes)
indexMap := make([]int, len(messages))
repaired := make([]Message, 0, len(messages)+1)
for index, message := range messages {
if (message.Role == RoleUser || message.Role == RoleDeveloper) &&
len(repaired) > 0 &&
repaired[len(repaired)-1].Role == RoleTool {
sourceIndex := handoffSourceIndex(sourceIndexes, index, index)
outputIndex := len(repaired)
repaired = append(repaired, handoffRepairMessage())
report.recordOutput(HandoffChangeRepairMessageInserted, sourceIndex, outputIndex, nil, "inserted assistant bridge before user message")
}
indexMap[index] = len(repaired)
repaired = append(repaired, message)
}
remapHandoffOutputIndexes(report, priorChanges, indexMap)
return repaired
}
func handoffSourceIndex(sourceIndexes []int, outputIndex int, fallback int) int {
if outputIndex >= 0 && outputIndex < len(sourceIndexes) {
return sourceIndexes[outputIndex]
}
return fallback
}
// remapHandoffOutputIndexes rewrites OutputMessageIndex values recorded before
// a rebuild pass so they keep pointing at the same messages after the pass
// inserted synthetic messages. indexMap maps each pre-pass output position to
// its post-pass position; only the first priorChanges entries predate the pass.
func remapHandoffOutputIndexes(report *HandoffReport, priorChanges int, indexMap []int) {
for i := range min(priorChanges, len(report.Changes)) {
change := &report.Changes[i]
if change.OutputMessageIndex == nil {
continue
}
if old := *change.OutputMessageIndex; old >= 0 && old < len(indexMap) {
change.OutputMessageIndex = intPtr(indexMap[old])
}
}
}
func isHandoffClientToolCall(block ContentBlock) bool {
if block.Type != ContentBlockToolCall {
return false
}
metadataType, _ := block.ProviderMetadata["type"].(string)
return metadataType != "server_tool_use"
}
func handoffError(ctx handoffMessageContext, message string) error {
return &Error{
Code: ErrorUnsupported,
Message: fmt.Sprintf("handoff message %d: %s", ctx.messageIndex, message),
Provider: ctx.target.Provider,
Model: ctx.target.ID,
}
}
func (report *HandoffReport) record(kind HandoffChangeKind, messageIndex int, contentIndex *int, detail string) {
report.recordChange(kind, messageIndex, nil, contentIndex, detail)
}
func (report *HandoffReport) recordOutput(kind HandoffChangeKind, messageIndex int, outputIndex int, contentIndex *int, detail string) {
report.recordChange(kind, messageIndex, intPtr(outputIndex), contentIndex, detail)
}
func (report *HandoffReport) recordChange(kind HandoffChangeKind, messageIndex int, outputIndex *int, contentIndex *int, detail string) {
switch kind {
case HandoffChangeThinkingConverted:
report.ConvertedThinkingBlocks++
case HandoffChangeDeveloperRoleConverted:
report.ConvertedDeveloperMessages++
case HandoffChangeToolResultNameRepaired:
report.RepairedToolResultNames++
case HandoffChangeUnansweredToolCallDropped:
report.DroppedUnansweredToolCalls++
case HandoffChangeRepairMessageInserted:
report.InsertedRepairMessages++
case HandoffChangeToolResultSynthesized:
report.SynthesizedToolResults++
case HandoffChangeUnsupportedImageReplaced:
report.ReplacedUnsupportedImages++
}
report.Changes = append(report.Changes, HandoffChange{
Kind: kind,
MessageIndex: messageIndex,
OutputMessageIndex: outputIndex,
ContentIndex: contentIndex,
Detail: detail,
})
}
func newHandoffToolCallIDNormalizer(limit int) func(string) string {
mapped := make(map[string]string)
used := make(map[string]string)
return func(id string) string {
if id == "" {
return id
}
if normalized := mapped[id]; normalized != "" {
return normalized
}
base := safeHandoffToolCallID(id, limit)
for attempt := 0; ; attempt++ {
candidate := base
if attempt > 0 {
suffix := "_" + strconv.Itoa(attempt)
candidate = strings.TrimRight(base[:min(len(base), max(1, limit-len(suffix)))], "_") + suffix
}
if owner := used[candidate]; owner == "" || owner == id {
mapped[id] = candidate
used[candidate] = id
return candidate
}
}
}
}
func safeHandoffToolCallID(id string, limit int) string {
var out strings.Builder
for _, r := range id {
switch {
case r >= 'a' && r <= 'z',
r >= 'A' && r <= 'Z',
r >= '0' && r <= '9',
r == '_',
r == '-':
out.WriteRune(r)
default:
out.WriteByte('_')
}
if out.Len() == limit {
break
}
}
if out.Len() == 0 {
return "_"
}
return out.String()
}
func cloneHandoffMessage(message Message) Message {
message.Content = cloneHandoffContentBlocks(message.Content)
message.AddedToolNames = append([]string(nil), message.AddedToolNames...)
return message
}
func cloneHandoffContentBlocks(blocks []ContentBlock) []ContentBlock {
if len(blocks) == 0 {
return nil
}
cloned := make([]ContentBlock, len(blocks))
for index, block := range blocks {
cloned[index] = block.Clone()
}
return cloned
}
func cloneHandoffTool(tool Tool) Tool {
tool.InputSchema = cloneHandoffAny(tool.InputSchema)
tool.ProviderDefinedOptions = cloneHandoffProviderDefinedOptions(tool.ProviderDefinedOptions)
tool.ProviderMetadata = cloneHandoffStringAnyMap(tool.ProviderMetadata)
if tool.OpenAIGrammar != nil {
grammar := *tool.OpenAIGrammar
tool.OpenAIGrammar = &grammar
}
return tool
}
func cloneHandoffTools(tools []Tool) []Tool {
if len(tools) == 0 {
return nil
}
cloned := make([]Tool, len(tools))
for index, tool := range tools {
cloned[index] = cloneHandoffTool(tool)
}
return cloned
}
func cloneHandoffStringAnyMap(values map[string]any) map[string]any {
if len(values) == 0 {
return nil
}
cloned := make(map[string]any, len(values))
for key, value := range values {
cloned[key] = cloneHandoffAny(value)
}
return cloned
}
func cloneHandoffProviderDefinedOptions(values map[string]any) map[string]any {
if values == nil {
return nil
}
cloned := make(map[string]any, len(values))
for key, value := range values {
cloned[key] = cloneHandoffProviderDefinedOption(value)
}
return cloned
}
func cloneHandoffProviderDefinedOption(value any) any {
return cloneJSONValue(value, cloneProviderOptions)
}
func cloneHandoffAny(value any) any {
return cloneJSONValue(value, cloneContent)
}