File size: 21,618 Bytes
e48a2d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
// shape.go 免费车道(OpenCode)的请求整形:官方系统提示 + 工具改名 + 官方工具集。
//
// 移植自 dsh-our-free-model 的 src/o2a/(opencode2api Go 实现的 JS 移植),
// 只保留 chat 线(本网关的免费层只暴露 /v1/chat/completions)。每条事实都有
// 实测依据,见 dsh 仓库 docs/free-lane-wire.md:
//   - 请求体必须带官方 CLI 系统提示(base + <env> + skills);
//   - 调用方工具必须全部改名成不透明的 clint_<sha256[:12]>;
//   - 必须补齐官方 13 个工具定义(read/shell 两个是闸门直接读的);
//   - 绝不下发 tool_choice:"none";流式补 stream_options.include_usage,
//     调用方没给上限时补 max_completion_tokens:32000。
package freemodel

import (
	"crypto/sha256"
	_ "embed"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"runtime"
	"strings"
	"time"
)

//go:embed assets/opencode_prompt_v2.txt
var openCodePromptBase string

//go:embed assets/opencode_tools.json
var openCodeToolsJSON []byte

const (
	officialPromptMarker = "You are opencode, an interactive CLI tool"
	clientToolPrefix     = "clint_"
	completionLimit      = 32000
)

const officialSkills = `Skills provide specialized instructions and workflows for specific tasks.
Use the skill tool to load a skill when a task matches its description.
<available_skills>
  <skill>
    <name>customize-opencode</name>
    <description>Use ONLY when the user is editing or creating opencode's own configuration: opencode.json, opencode.jsonc, files under .opencode/, or files under ~/.config/opencode/. Also use when creating or fixing opencode agents, subagents, skills, plugins, MCP servers, or permission rules. Do not use for the user's own application code, or for any project that is not configuring opencode itself.</description>
    <location>&lt;built-in&gt;</location>
  </skill>
</available_skills>`

// v2OfficialToolOrder 官方工具的固定顺序(JSON key 顺序不保证)。
var v2OfficialToolOrder = []string{
	"edit", "execute", "glob", "grep", "question", "read", "shell",
	"skill", "subagent", "webfetch", "websearch", "write", "patch",
}

// officialClientAliases 客户端常见工具名 → 官方工具名(折叠比较)。
var officialClientAliases = map[string]string{
	"edit": "edit", "glob": "glob", "grep": "grep",
	"question": "question", "askuserquestion": "question",
	"read": "read", "view": "read",
	"shell": "shell", "bash": "shell",
	"skill":    "skill",
	"subagent": "subagent", "agent": "subagent", "task": "subagent",
	"webfetch": "webfetch", "fetch": "webfetch",
	"websearch": "websearch", "write": "write",
	"patch": "patch", "applypatch": "patch",
}

var officialTools map[string]map[string]any

func init() {
	officialTools = map[string]map[string]any{}
	var parsed map[string]struct {
		Description string         `json:"description"`
		Parameters  map[string]any `json:"parameters"`
	}
	if json.Unmarshal(openCodeToolsJSON, &parsed) == nil {
		for name, def := range parsed {
			if def.Description == "" || def.Parameters == nil {
				continue
			}
			officialTools[name] = map[string]any{
				"description": def.Description,
				"parameters":  def.Parameters,
			}
		}
	}
}

// officialTool 渲染一个官方工具(chat 形状带 strict:false)。
func officialTool(name string) map[string]any {
	description := "Agent tool " + name
	parameters := map[string]any{"type": "object", "properties": map[string]any{}}
	if def, ok := officialTools[name]; ok {
		if d, ok := def["description"].(string); ok {
			description = d
		}
		if p, ok := def["parameters"].(map[string]any); ok {
			parameters = deepCopyMap(p)
		}
	}
	if name == "shell" && runtime.GOOS == "windows" {
		description = strings.ReplaceAll(description, "on Linux using bash", "on Windows using powershell")
	}
	return map[string]any{
		"type": "function",
		"function": map[string]any{
			"name":        name,
			"description": description,
			"parameters":  parameters,
			"strict":      false,
		},
	}
}

func deepCopyMap(in map[string]any) map[string]any {
	raw, _ := json.Marshal(in)
	var out map[string]any
	_ = json.Unmarshal(raw, &out)
	return out
}

// foldToolName 小写并去掉分隔符,用于别名比较。
func foldToolName(name string) string {
	var b strings.Builder
	for _, r := range strings.ToLower(name) {
		switch r {
		case '_', '.', '-', ' ', '\t', '\r', '\n':
			continue
		}
		b.WriteRune(r)
	}
	return b.String()
}

func officialForClientName(name string) string {
	return officialClientAliases[foldToolName(name)]
}

// clientToolWireName 生成不透明 wire 名:clint_ + sha256(name)[:12]。
func clientToolWireName(name string, used map[string]bool) string {
	sum := sha256.Sum256([]byte(name))
	base := clientToolPrefix + hex.EncodeToString(sum[:])[:12]
	if !used[base] {
		used[base] = true
		return base
	}
	for suffix := 2; ; suffix++ {
		tag := fmt.Sprintf("_%d", suffix)
		candidate := base
		if len(candidate)+len(tag) > 64 {
			candidate = candidate[:64-len(tag)]
		}
		candidate += tag
		if !used[candidate] {
			used[candidate] = true
			return candidate
		}
	}
}

// renameMap wire 名 → 客户端原名。
type renameMap struct {
	byClient map[string]string
	byWire   map[string]string
	byCase   map[string]string
	byShape  map[string]string
}

func newRenameMap() *renameMap {
	return &renameMap{
		byClient: map[string]string{},
		byWire:   map[string]string{},
		byCase:   map[string]string{},
		byShape:  map[string]string{},
	}
}

func (m *renameMap) add(client, wire string) {
	if client == "" || wire == "" || client == wire {
		return
	}
	if _, ok := m.byClient[client]; ok {
		return
	}
	if _, ok := m.byWire[wire]; ok {
		return
	}
	m.byClient[client] = wire
	m.byWire[wire] = client
	m.bindFolded(m.byCase, strings.ToLower(client), client)
	m.bindFolded(m.byShape, foldToolName(client), client)
}

func (m *renameMap) bindFolded(index map[string]string, key, client string) {
	if key == "" {
		return
	}
	if existing, ok := index[key]; !ok {
		index[key] = client
	} else if existing != client {
		index[key] = ""
	}
}

func (m *renameMap) wireOf(client string) (string, bool) {
	w, ok := m.byClient[client]
	return w, ok
}

// resolve 上游回来的名字 → 客户端原名。
func (m *renameMap) resolve(wire string) string {
	if m == nil || wire == "" {
		return wire
	}
	if exact, ok := m.byWire[wire]; ok {
		return exact
	}
	client := wire
	if strings.HasPrefix(client, clientToolPrefix) {
		client = strings.TrimPrefix(client, clientToolPrefix)
		if client == "" {
			return wire
		}
	}
	if _, ok := m.byClient[client]; ok {
		return client
	}
	if folded, ok := m.byCase[strings.ToLower(client)]; ok && folded != "" {
		return folded
	}
	if folded, ok := m.byShape[foldToolName(client)]; ok && folded != "" {
		return folded
	}
	return client
}

// applyFingerprint 对 chat 请求体做完整整形,返回改名表(响应侧还原用)。
func applyFingerprint(body map[string]any, model, session string) *renameMap {
	if body == nil {
		return newRenameMap()
	}
	if isTitleRequest(body) {
		return newRenameMap()
	}
	injectOfficialPrompt(body, model)
	renames, injected := shapeTools(body)
	if len(injected) > 0 {
		noteInjectedTools(body, injected)
	}
	if choice, ok := body["tool_choice"].(string); ok && choice == "none" {
		delete(body, "tool_choice")
	}
	if choice, ok := body["tool_choice"].(map[string]any); ok {
		if t, _ := choice["type"].(string); t == "none" {
			delete(body, "tool_choice")
		}
	}
	ensureChatUsage(body)
	ensureV2CompletionLimit(body)
	return renames
}

// isTitleRequest 与 dsh 同一判定:没有工具、1-3 轮纯 user/system、且带标题标记。
// 这类请求整形反而会被上游 403/429。
func isTitleRequest(body map[string]any) bool {
	if tools, ok := body["tools"].([]any); ok && len(tools) > 0 {
		return false
	}
	if functions, ok := body["functions"].([]any); ok && len(functions) > 0 {
		return false
	}
	if _, ok := body["tool_choice"]; ok {
		return false
	}
	messages, _ := body["messages"].([]any)
	if len(messages) == 0 || len(messages) > 3 {
		return false
	}
	var text strings.Builder
	for _, raw := range messages {
		msg, _ := raw.(map[string]any)
		if msg == nil {
			return false
		}
		role, _ := msg["role"].(string)
		if role != "user" && role != "system" && role != "developer" {
			return false
		}
		text.WriteString(textOf(msg["content"]))
		text.WriteString("\n")
	}
	lower := strings.ToLower(text.String())
	markers := []string{
		"generate a title", "write a title", "create a title", "come up with a title",
		"conversation title", "summarize this conversation", "summarize the conversation",
	}
	for _, marker := range markers {
		if strings.Contains(lower, marker) {
			return true
		}
	}
	return false
}

// injectOfficialPrompt 把官方 CLI 提示注入首条 system/developer 消息。
func injectOfficialPrompt(body map[string]any, model string) {
	prompt := officialSystemPrompt(model)
	if prompt == "" {
		return
	}
	messages, _ := body["messages"].([]any)
	anchor := -1
	for i, raw := range messages {
		msg, _ := raw.(map[string]any)
		if msg == nil {
			continue
		}
		role, _ := msg["role"].(string)
		if role != "system" && role != "developer" {
			continue
		}
		if carriesOpenCodePrompt(msg["content"]) {
			return
		}
		if anchor == -1 {
			anchor = i
		}
	}
	if anchor == -1 {
		body["messages"] = append([]any{map[string]any{"role": "system", "content": prompt}}, messages...)
		return
	}
	msg := messages[anchor].(map[string]any)
	switch content := msg["content"].(type) {
	case []any:
		msg["content"] = append([]any{map[string]any{"type": "text", "text": prompt}}, content...)
	case string:
		if strings.TrimSpace(content) == "" {
			msg["content"] = prompt
		} else {
			msg["content"] = prompt + "\n\n" + content
		}
	default:
		msg["content"] = prompt
	}
	messages[anchor] = msg
	body["messages"] = messages
}

func officialSystemPrompt(model string) string {
	if strings.TrimSpace(openCodePromptBase) == "" {
		return ""
	}
	return openCodePromptBase + officialEnvironment(model) + "\n" + officialSkills
}

func officialEnvironment(model string) string {
	apiModel := strings.TrimPrefix(strings.TrimSpace(model), "opencode/")
	if apiModel == "" {
		apiModel = "unknown"
	}
	platform := runtime.GOOS
	if platform == "windows" {
		platform = "win32"
	}
	now := time.Now().UTC()
	date := fmt.Sprintf("%s %s %02d %d", now.Format("Mon"), now.Format("Jan"), now.Day(), now.Year())
	return fmt.Sprintf("You are powered by the model named %s. The exact model ID is opencode/%s\n"+
		"Here is some useful information about the environment you are running in:\n"+
		"<env>\n  Working directory: /workspace\n  Workspace root folder: /workspace\n"+
		"  Is directory a git repo: yes\n  Platform: %s\n  Today's date: %s\n</env>",
		apiModel, apiModel, platform, date)
}

func textOf(value any) string {
	switch v := value.(type) {
	case string:
		return v
	case []any:
		var b strings.Builder
		for _, item := range v {
			b.WriteString(textOf(item))
		}
		return b.String()
	case map[string]any:
		if t, ok := v["text"].(string); ok {
			return t
		}
		if c, ok := v["content"]; ok {
			return textOf(c)
		}
	}
	return ""
}

func carriesOpenCodePrompt(value any) bool {
	switch v := value.(type) {
	case string:
		return strings.Contains(v, officialPromptMarker)
	case []any:
		for _, item := range v {
			if carriesOpenCodePrompt(item) {
				return true
			}
		}
	case map[string]any:
		if t, ok := v["text"].(string); ok && strings.Contains(t, officialPromptMarker) {
			return true
		}
		if c, ok := v["content"]; ok {
			return carriesOpenCodePrompt(c)
		}
	}
	return false
}

// shapeTools 改名调用方工具并补齐官方 13 工具集。
func shapeTools(body map[string]any) (*renameMap, []string) {
	renames := newRenameMap()
	used := map[string]bool{}
	officialUsed := map[string]bool{}

	items, _ := body["tools"].([]any)
	if functions, ok := body["functions"].([]any); ok {
		items = append(items, convertLegacyFunctions(functions, renames, used)...)
		delete(body, "functions")
	}
	// 已逐字带官方定义的声明视为官方声明,不重命名也不重复补。
	keep := map[string]bool{}
	for _, raw := range items {
		if name := renamableToolName(raw); name != "" && carriesOfficialDefinition(raw, name) {
			keep[name] = true
			officialUsed[name] = true
		}
	}
	declaredClientTools := 0
	for _, raw := range items {
		if renamableToolName(raw) != "" {
			declaredClientTools++
		}
	}
	shaped := make([]any, 0, len(items)+len(v2OfficialToolOrder))
	for _, raw := range items {
		name := renamableToolName(raw)
		if name == "" {
			shaped = append(shaped, raw)
			continue
		}
		if keep[name] || strings.HasPrefix(name, clientToolPrefix) {
			shaped = append(shaped, raw)
			continue
		}
		if official := officialForClientName(name); official != "" && !officialUsed[official] {
			if _, exists := officialTools[official]; exists {
				officialUsed[official] = true
				renames.add(name, official)
				shaped = append(shaped, withToolName(raw, official))
				continue
			}
		}
		wireName, ok := renames.wireOf(name)
		if !ok {
			wireName = clientToolWireName(name, used)
			renames.add(name, wireName)
		}
		if wireName != name {
			shaped = append(shaped, withToolName(raw, wireName))
		} else {
			shaped = append(shaped, raw)
		}
	}
	injected := make([]string, 0)
	for _, name := range v2OfficialToolOrder {
		if officialUsed[name] {
			continue
		}
		shaped = append(shaped, officialTool(name))
		injected = append(injected, name)
		officialUsed[name] = true
	}
	body["tools"] = shaped
	rewriteToolReferences(body, renames)
	if declaredClientTools > 0 {
		known := map[string]bool{}
		for name := range officialUsed {
			known[name] = true
		}
		for wire := range renames.byWire {
			known[wire] = true
		}
		sanitizeToolHistory(body, known)
		dropDanglingToolChoice(body, known)
	}
	return renames, injected
}

func renamableToolName(entry any) string {
	tool, _ := entry.(map[string]any)
	if tool == nil {
		return ""
	}
	fn, _ := tool["function"].(map[string]any)
	if fn == nil {
		return ""
	}
	name, _ := fn["name"].(string)
	return strings.TrimSpace(name)
}

func carriesOfficialDefinition(entry any, name string) bool {
	tool, _ := entry.(map[string]any)
	fn, _ := tool["function"].(map[string]any)
	official := officialTool(name)
	ofn, _ := official["function"].(map[string]any)
	if fn == nil || ofn == nil {
		return false
	}
	if fn["description"] != ofn["description"] {
		return false
	}
	a, _ := json.Marshal(fn["parameters"])
	b, _ := json.Marshal(ofn["parameters"])
	return string(a) == string(b)
}

func withToolName(entry any, name string) any {
	tool, _ := entry.(map[string]any)
	if tool == nil {
		return entry
	}
	clone := make(map[string]any, len(tool))
	for k, v := range tool {
		clone[k] = v
	}
	fn, _ := clone["function"].(map[string]any)
	fnClone := make(map[string]any, len(fn)+1)
	for k, v := range fn {
		fnClone[k] = v
	}
	fnClone["name"] = name
	clone["function"] = fnClone
	return clone
}

func convertLegacyFunctions(functions []any, renames *renameMap, used map[string]bool) []any {
	out := make([]any, 0, len(functions))
	for _, raw := range functions {
		fn, _ := raw.(map[string]any)
		if fn == nil {
			continue
		}
		name, _ := fn["name"].(string)
		if name == "" {
			continue
		}
		wireName, ok := renames.wireOf(name)
		if !ok {
			wireName = clientToolWireName(name, used)
			renames.add(name, wireName)
		}
		params := fn["parameters"]
		if params == nil {
			params = map[string]any{"type": "object", "properties": map[string]any{}}
		}
		converted := map[string]any{
			"type": "function",
			"function": map[string]any{
				"name":        wireName,
				"description": fn["description"],
				"parameters":  params,
			},
		}
		if strict, ok := fn["strict"]; ok {
			converted["function"].(map[string]any)["strict"] = strict
		}
		out = append(out, converted)
	}
	return out
}

func rewriteToolReferences(body map[string]any, renames *renameMap) {
	if len(renames.byClient) == 0 {
		return
	}
	resolve := func(container map[string]any) (string, bool) {
		name, _ := container["name"].(string)
		if name == "" {
			return "", false
		}
		wire, ok := renames.wireOf(name)
		if !ok || wire == name {
			return "", false
		}
		return wire, true
	}
	if choice, ok := body["tool_choice"].(map[string]any); ok {
		if fn, ok := choice["function"].(map[string]any); ok {
			if wire, ok := resolve(fn); ok {
				fn["name"] = wire
			}
		} else if wire, ok := resolve(choice); ok {
			choice["name"] = wire
		}
	}
	if fc, ok := body["function_call"].(map[string]any); ok {
		if wire, ok := resolve(fc); ok {
			fc["name"] = wire
		}
	}
	messages, _ := body["messages"].([]any)
	for _, raw := range messages {
		msg, _ := raw.(map[string]any)
		if msg == nil {
			continue
		}
		if fc, ok := msg["function_call"].(map[string]any); ok {
			if wire, ok := resolve(fc); ok {
				fc["name"] = wire
			}
		}
		calls, _ := msg["tool_calls"].([]any)
		for _, rawCall := range calls {
			call, _ := rawCall.(map[string]any)
			fn, _ := call["function"].(map[string]any)
			if fn == nil {
				continue
			}
			if wire, ok := resolve(fn); ok {
				fn["name"] = wire
			}
		}
	}
}

// sanitizeToolHistory 丢掉历史里「本轮 wire 不提供」的工具调用及其配对结果。
func sanitizeToolHistory(body map[string]any, known map[string]bool) {
	messages, _ := body["messages"].([]any)
	if messages == nil {
		return
	}
	droppedCalls := map[string]bool{}
	droppedFunctions := map[string]bool{}
	out := make([]any, 0, len(messages))
	for _, raw := range messages {
		msg, _ := raw.(map[string]any)
		if msg == nil {
			out = append(out, raw)
			continue
		}
		drop := false
		if role, _ := msg["role"].(string); role == "tool" {
			if id, _ := msg["tool_call_id"].(string); droppedCalls[id] {
				continue
			}
		}
		if role, _ := msg["role"].(string); role == "function" {
			if name, _ := msg["name"].(string); droppedFunctions[name] {
				continue
			}
		}
		if calls, ok := msg["tool_calls"].([]any); ok {
			kept := make([]any, 0, len(calls))
			for _, rawCall := range calls {
				call, _ := rawCall.(map[string]any)
				fn, _ := call["function"].(map[string]any)
				name, _ := fn["name"].(string)
				if name == "" {
					continue
				}
				if known[name] {
					kept = append(kept, call)
					continue
				}
				if official := officialForClientName(name); official != "" && known[official] {
					fn["name"] = official
					kept = append(kept, call)
					continue
				}
				if id, _ := call["id"].(string); id != "" {
					droppedCalls[id] = true
				}
			}
			if len(kept) == 0 {
				delete(msg, "tool_calls")
				if !rowHasContent(msg) {
					drop = true
				}
			} else if len(kept) != len(calls) {
				msg["tool_calls"] = kept
			}
		}
		if fc, ok := msg["function_call"].(map[string]any); ok {
			name, _ := fc["name"].(string)
			if official := officialForClientName(name); official != "" && known[official] {
				fc["name"] = official
			} else if !known[name] {
				if name != "" {
					droppedFunctions[name] = true
				}
				delete(msg, "function_call")
				if !rowHasContent(msg) {
					drop = true
				}
			}
		}
		if !drop {
			out = append(out, msg)
		}
	}
	body["messages"] = out
}

func rowHasContent(msg map[string]any) bool {
	for _, key := range []string{"content", "reasoning_content", "reasoning"} {
		switch v := msg[key].(type) {
		case string:
			if v != "" {
				return true
			}
		case []any:
			if len(v) > 0 {
				return true
			}
		case map[string]any:
			if len(v) > 0 {
				return true
			}
		case nil:
		default:
			return true
		}
	}
	return false
}

func dropDanglingToolChoice(body map[string]any, known map[string]bool) {
	choice, ok := body["tool_choice"].(map[string]any)
	if !ok {
		return
	}
	name := ""
	if fn, ok := choice["function"].(map[string]any); ok {
		name, _ = fn["name"].(string)
	} else {
		name, _ = choice["name"].(string)
	}
	if name != "" && !known[name] {
		delete(body, "tool_choice")
	}
}

func noteInjectedTools(body map[string]any, names []string) {
	quoted := make([]string, len(names))
	for i, name := range names {
		quoted[i] = "`" + name + "`"
	}
	note := "The tools " + strings.Join(quoted, ", ") +
		" are part of the host CLI's own toolset and are placeholders in this session; they do nothing here. Use the other tools you have been given instead."
	appendSystemContext(body, note)
}

func appendSystemContext(body map[string]any, note string) {
	messages, _ := body["messages"].([]any)
	if len(messages) > 0 {
		if first, ok := messages[0].(map[string]any); ok {
			if role, _ := first["role"].(string); role == "system" || role == "developer" {
				switch content := first["content"].(type) {
				case string:
					first["content"] = content + "\n\n" + note
					return
				case []any:
					first["content"] = append(content, map[string]any{"type": "text", "text": note})
					return
				}
				first["content"] = note
				return
			}
		}
	}
	body["messages"] = append([]any{map[string]any{"role": "system", "content": note}}, messages...)
}

func ensureChatUsage(body map[string]any) {
	if stream, _ := body["stream"].(bool); !stream {
		return
	}
	if opts, ok := body["stream_options"].(map[string]any); ok {
		if include, _ := opts["include_usage"].(bool); !include {
			opts["include_usage"] = true
		}
		return
	}
	body["stream_options"] = map[string]any{"include_usage": true}
}

func ensureV2CompletionLimit(body map[string]any) {
	if _, ok := body["max_completion_tokens"]; ok {
		return
	}
	if _, ok := body["max_tokens"]; ok {
		return
	}
	body["max_completion_tokens"] = completionLimit
}