magpie-gemini-web 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
1
  diff --git a/internal/app/argon.go b/internal/app/argon.go
2
2
  new file mode 100644
3
- index 0000000..94c7aca
3
+ index 0000000..366b005
4
4
  --- /dev/null
5
5
  +++ b/internal/app/argon.go
6
- @@ -0,0 +1,81 @@
6
+ @@ -0,0 +1,152 @@
7
7
  +package app
8
8
  +
9
9
  +import (
@@ -14,77 +14,148 @@ index 0000000..94c7aca
14
14
  + "time"
15
15
  +)
16
16
  +
17
- +func validateArgonIdentity(raw []byte) error {
18
- + found := false
19
- + for _, line := range strings.Split(string(raw), "\n") {
20
- + var rows [][]json.RawMessage
21
- + if json.Unmarshal([]byte(line), &rows) != nil {
17
+ +// argonIdentityInLine 检查单行 wrb.fr 帧里的模型身份。
18
+ +// 返回 found=true 表示这行带有正确的 Argon 身份;err 非 nil 表示这行报的是别的模型。
19
+ +func argonIdentityInLine(line string) (found bool, err error) {
20
+ + var rows [][]json.RawMessage
21
+ + if json.Unmarshal([]byte(line), &rows) != nil {
22
+ + return false, nil
23
+ + }
24
+ + for _, row := range rows {
25
+ + if len(row) < 3 {
26
+ + continue
27
+ + }
28
+ + var kind, payload string
29
+ + if json.Unmarshal(row[0], &kind) != nil || kind != "wrb.fr" || json.Unmarshal(row[2], &payload) != nil {
22
30
  + continue
23
31
  + }
24
- + for _, row := range rows {
25
- + if len(row) < 3 {
32
+ + var fields []any
33
+ + if json.Unmarshal([]byte(payload), &fields) != nil {
34
+ + continue
35
+ + }
36
+ + // Upstream reports model identity as consecutive top-level slots hex,null,null,name.
37
+ + for i := 0; i+3 < len(fields); i++ {
38
+ + id, ok := fields[i].(string)
39
+ + if !ok || len(id) != 16 || fields[i+1] != nil || fields[i+2] != nil {
26
40
  + continue
27
41
  + }
28
- + var kind, payload string
29
- + if json.Unmarshal(row[0], &kind) != nil || kind != "wrb.fr" || json.Unmarshal(row[2], &payload) != nil {
30
- + continue
42
+ + validHex := true
43
+ + for _, c := range id {
44
+ + if !strings.ContainsRune("0123456789abcdef", c) {
45
+ + validHex = false
46
+ + break
47
+ + }
31
48
  + }
32
- + var fields []any
33
- + if json.Unmarshal([]byte(payload), &fields) != nil {
49
+ + name, ok := fields[i+3].(string)
50
+ + if !validHex || !ok {
34
51
  + continue
35
52
  + }
36
- + // Upstream reports model identity as consecutive top-level slots hex,null,null,name.
37
- + for i := 0; i+3 < len(fields); i++ {
38
- + id, ok := fields[i].(string)
39
- + if !ok || len(id) != 16 || fields[i+1] != nil || fields[i+2] != nil {
40
- + continue
41
- + }
42
- + validHex := true
43
- + for _, c := range id {
44
- + if !strings.ContainsRune("0123456789abcdef", c) {
45
- + validHex = false
46
- + break
47
- + }
48
- + }
49
- + name, ok := fields[i+3].(string)
50
- + if !validHex || !ok {
51
- + continue
52
- + }
53
- + if id != hexArgon4 || (name != "4 Argon" && name != "Gemini 4 Argon") {
54
- + return fmt.Errorf("Argon model mismatch: upstream reported %q (%s)", name, id)
55
- + }
56
- + found = true
53
+ + if id != hexArgon4 || (name != "4 Argon" && name != "Gemini 4 Argon") {
54
+ + return false, fmt.Errorf("Argon model mismatch: upstream reported %q (%s)", name, id)
57
55
  + }
56
+ + found = true
57
+ + }
58
+ + }
59
+ + return found, nil
60
+ +}
61
+ +
62
+ +var errArgonIdentityMissing = fmt.Errorf("Argon identity missing in upstream response; refusing unverified model")
63
+ +
64
+ +func validateArgonIdentity(raw []byte) error {
65
+ + found := false
66
+ + for _, line := range strings.Split(string(raw), "\n") {
67
+ + ok, err := argonIdentityInLine(line)
68
+ + if err != nil {
69
+ + return err
58
70
  + }
71
+ + found = found || ok
59
72
  + }
60
73
  + if !found {
61
- + return fmt.Errorf("Argon identity missing in upstream response; refusing unverified model")
74
+ + return errArgonIdentityMissing
62
75
  + }
63
76
  + return nil
64
77
  +}
65
78
  +
79
+ +// readModelCheckedBody 对 Argon 请求逐帧校验模型身份后再转发。
80
+ +//
81
+ +// 身份确认之前的行先暂存、不回调;第一次在帧里确认是 Argon 时把暂存的行一次放行,
82
+ +// 之后边读边转发,同时继续检查每一帧。上游对未授权账号会静默降级成别的模型,
83
+ +// 所以:
84
+ +// - 身份始终没出现、或首次出现就不对:一个字都不放行,返回错误;
85
+ +// - 放行之后又报了别的模型:立刻停读并返回错误(调用方据此发流错误收尾)。
86
+ +// 已经发出去的内容收不回来,这是增量转发换首字延迟必须接受的代价。
87
+ +//
88
+ +// 实测身份跟首段正文在同一帧(Argon 探针:首帧 1.9s、身份与首字 9.5s、结束 14.6s),
89
+ +// 所以放行时机就是首字时机,不再要等上游整段生成完。
90
+ +//
91
+ +// onLine 为 nil(非流式)时没有转发,照旧读完整段再校验。
66
92
  +func readModelCheckedBody(r io.Reader, onLine func(string), start time.Time, status int, modelHeader string) ([]byte, int64, error) {
67
93
  + var h []any
68
94
  + isArgon := json.Unmarshal([]byte(modelHeader), &h) == nil && len(h) > 4 && h[4] == hexArgon4
69
95
  + if !isArgon {
70
96
  + return readBody(r, onLine, start)
71
97
  + }
72
- + raw, ttfb, err := readBody(r, nil, start)
73
- + if err != nil || status != 200 {
74
- + return raw, ttfb, err
75
- + }
76
- + if err = validateArgonIdentity(raw); err != nil {
77
- + return raw, ttfb, err
98
+ + if status != 200 || onLine == nil {
99
+ + raw, ttfb, err := readBody(r, nil, start)
100
+ + if err != nil || status != 200 {
101
+ + return raw, ttfb, err
102
+ + }
103
+ + return raw, ttfb, validateArgonIdentity(raw)
78
104
  + }
79
- + if onLine != nil {
80
- + for _, line := range strings.Split(string(raw), "\n") {
81
- + if line != "" {
82
- + onLine(line)
105
+ +
106
+ + var pending []string
107
+ + verified := false
108
+ + var identityErr error
109
+ + raw, ttfb, err := readBody(identityGuardReader{r, &identityErr}, func(line string) {
110
+ + if identityErr != nil {
111
+ + return
112
+ + }
113
+ + ok, lerr := argonIdentityInLine(line)
114
+ + if lerr != nil {
115
+ + identityErr = lerr
116
+ + return
117
+ + }
118
+ + if !verified {
119
+ + if !ok {
120
+ + if line != "" {
121
+ + pending = append(pending, line)
122
+ + }
123
+ + return
83
124
  + }
125
+ + verified = true
126
+ + for _, p := range pending {
127
+ + onLine(p)
128
+ + }
129
+ + pending = nil
130
+ + }
131
+ + if line != "" {
132
+ + onLine(line)
84
133
  + }
134
+ + }, start)
135
+ + if identityErr != nil {
136
+ + return raw, ttfb, identityErr
137
+ + }
138
+ + if err != nil {
139
+ + return raw, ttfb, err
140
+ + }
141
+ + if !verified {
142
+ + return raw, ttfb, errArgonIdentityMissing
85
143
  + }
86
144
  + return raw, ttfb, nil
87
145
  +}
146
+ +
147
+ +// identityGuardReader 在身份校验失败后让下一次 Read 返回 EOF,不再读上游。
148
+ +type identityGuardReader struct {
149
+ + r io.Reader
150
+ + err *error
151
+ +}
152
+ +
153
+ +func (g identityGuardReader) Read(p []byte) (int, error) {
154
+ + if *g.err != nil {
155
+ + return 0, io.EOF
156
+ + }
157
+ + return g.r.Read(p)
158
+ +}
88
159
  diff --git a/internal/app/argon_test.go b/internal/app/argon_test.go
89
160
  new file mode 100644
90
161
  index 0000000..4449c45
@@ -320,11 +391,292 @@ index 0000000..4449c45
320
391
  + t.Fatal("gemini-4-argon should be available when pool cookie exists")
321
392
  + }
322
393
  +}
394
+ diff --git a/internal/app/cancel_test.go b/internal/app/cancel_test.go
395
+ new file mode 100644
396
+ index 0000000..e5f1b6f
397
+ --- /dev/null
398
+ +++ b/internal/app/cancel_test.go
399
+ @@ -0,0 +1,105 @@
400
+ +package app
401
+ +
402
+ +import (
403
+ + "context"
404
+ + "errors"
405
+ + "net/http"
406
+ + "net/http/httptest"
407
+ + "strings"
408
+ + "testing"
409
+ + "time"
410
+ +)
411
+ +
412
+ +// 客户端断开后必须真的掐掉上游连接:上游那头要能看到连接断了,而不是一直生成到结束。
413
+ +//
414
+ +// 假上游挂在代理那条路上(stdlib 客户端 + 代理),http:// 目标会以绝对 URI 发给代理,
415
+ +// 所以 httptest 服务器本身就能当上游,不用碰真网络。
416
+ +func TestCancelAbortsUpstreamStream(t *testing.T) {
417
+ + upstreamGone := make(chan struct{})
418
+ + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
419
+ + w.WriteHeader(200)
420
+ + w.Write([]byte(")]}'\nfirst frame\n"))
421
+ + w.(http.Flusher).Flush()
422
+ + select {
423
+ + case <-r.Context().Done():
424
+ + close(upstreamGone)
425
+ + case <-time.After(10 * time.Second): // 模拟一个还要生成很久的上游
426
+ + }
427
+ + }))
428
+ + defer srv.Close()
429
+ +
430
+ + ctx, cancel := context.WithCancel(context.Background())
431
+ + defer cancel()
432
+ + start := time.Now()
433
+ + _, _, _, _, err := doGeminiRequestStop(ctx, "http://upstream.invalid/StreamGenerate", "f.req=x",
434
+ + map[string]string{}, srv.URL, func(line string) {
435
+ + if line == "first frame" {
436
+ + cancel() // 客户端在收到首帧后走了
437
+ + }
438
+ + }, nil)
439
+ + if err == nil {
440
+ + t.Fatal("取消后应返回错误")
441
+ + }
442
+ + if took := time.Since(start); took > 3*time.Second {
443
+ + t.Fatalf("取消后仍等了 %v 才返回", took)
444
+ + }
445
+ + select {
446
+ + case <-upstreamGone:
447
+ + case <-time.After(3 * time.Second):
448
+ + t.Fatal("上游连接没有被关闭")
449
+ + }
450
+ +}
451
+ +
452
+ +func TestSleepCtxCancels(t *testing.T) {
453
+ + ctx, cancel := context.WithCancel(context.Background())
454
+ + go func() { time.Sleep(20 * time.Millisecond); cancel() }()
455
+ + start := time.Now()
456
+ + if err := sleepCtx(ctx, 10*time.Second); !errors.Is(err, context.Canceled) {
457
+ + t.Fatalf("sleepCtx = %v", err)
458
+ + }
459
+ + if time.Since(start) > time.Second {
460
+ + t.Fatal("重试等待没有随取消提前结束")
461
+ + }
462
+ + if err := sleepCtx(context.Background(), time.Millisecond); err != nil {
463
+ + t.Fatal(err)
464
+ + }
465
+ +}
466
+ +
467
+ +// 已经断开的请求不能再去占限流 slot、挑号、发上游。
468
+ +func TestStreamGenerateSkipsWhenCancelled(t *testing.T) {
469
+ + ctx, cancel := context.WithCancel(context.Background())
470
+ + cancel()
471
+ + _, err := streamGenerateWithFiles(ctx, "hi", promptCtx{Latest: "hi"}, Models["gemini-3.5-flash-lite"], nil, nil, nil, nil)
472
+ + if !errors.Is(err, context.Canceled) {
473
+ + t.Fatalf("err = %v", err)
474
+ + }
475
+ +}
476
+ +
477
+ +// 客户端断开:不写响应(没人收),requests 表记 499 而不是 502。
478
+ +func TestChatCompletionsClientGoneRecords499(t *testing.T) {
479
+ + ctx, cancel := context.WithCancel(context.Background())
480
+ + cancel()
481
+ + body := `{"model":"gemini-3.5-flash-lite","messages":[{"role":"user","content":"cancel-probe-499"}]}`
482
+ + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body)).WithContext(ctx)
483
+ + rec := httptest.NewRecorder()
484
+ + handleChatCompletions(rec, req)
485
+ + if rec.Body.Len() != 0 {
486
+ + t.Fatalf("客户端已断开仍写了响应: %q", rec.Body.String())
487
+ + }
488
+ +
489
+ + deadline := time.Now().Add(3 * time.Second)
490
+ + for time.Now().Before(deadline) {
491
+ + var status int
492
+ + var errStr string
493
+ + row := getDB().QueryRow(`SELECT status, error FROM requests WHERE prompt_chars=? ORDER BY id DESC LIMIT 1`,
494
+ + len("cancel-probe-499"))
495
+ + if row.Scan(&status, &errStr) == nil {
496
+ + if status != statusClientClosed || errStr != "client disconnected" {
497
+ + t.Fatalf("记录 = %d %q,应为 499 client disconnected", status, errStr)
498
+ + }
499
+ + return
500
+ + }
501
+ + time.Sleep(20 * time.Millisecond)
502
+ + }
503
+ + t.Fatal("没有记录这次请求")
504
+ +}
505
+ diff --git a/internal/app/context_file.go b/internal/app/context_file.go
506
+ index bfc577b..cb60661 100644
507
+ --- a/internal/app/context_file.go
508
+ +++ b/internal/app/context_file.go
509
+ @@ -1,6 +1,7 @@
510
+ package app
511
+
512
+ import (
513
+ + "context"
514
+ "fmt"
515
+ "strings"
516
+ )
517
+ @@ -76,7 +77,11 @@ func contextFilePrompt(latest string, budget int) string {
518
+ //
519
+ // 上传失败**不静默回退到超长内联**:那样上游会把最新提问截掉,客户端拿到一个
520
+ // 答非所问的 200 却看不出问题。
521
+ -func prepareContextFile(prompt, latest string, budget int, cookie, proxyURL string) (
522
+ +//
523
+ +// 附件里只放对话历史,工具协议(pc.Head / pc.Tail)留在正文:agentic 客户端的
524
+ +// 请求动辄十几万字节,几乎每轮都走这条路,工具说明和末尾锚点一旦进了附件,模型
525
+ +// 就不再稳定地吐 ```tool_call```。工具说明本身就超预算时才退回整段进附件。
526
+ +func prepareContextFile(ctx context.Context, prompt string, pc promptCtx, budget int, cookie, proxyURL string) (
527
+ string, []fileRef, bool, error) {
528
+ if budget <= 0 || len(prompt) <= budget {
529
+ return prompt, nil, false, nil
530
+ @@ -84,11 +89,50 @@ func prepareContextFile(prompt, latest string, budget int, cookie, proxyURL stri
531
+ if cookie == "" {
532
+ return prompt, nil, false, nil // 匿名:引用会被回 1100,转了也没用
533
+ }
534
+ - ref, err := uploadBytes(cookie, proxyURL, []byte(prompt), contextFileName)
535
+ + history, inline := planContextFile(prompt, pc, budget)
536
+ + ref, err := uploadBytesCtx(ctx, cookie, proxyURL, []byte(history), contextFileName)
537
+ if err != nil {
538
+ return prompt, nil, false, fmt.Errorf("超长对话转附件失败: %w", err)
539
+ }
540
+ - logf("[context] prompt %d 字节超过 %d,已转成附件 %s", len(prompt), budget, contextFileName)
541
+ + logf("[context] prompt %d 字节超过 %d,已转成附件 %s(附件 %d 字节,内联 %d 字节)",
542
+ + len(prompt), budget, contextFileName, len(history), len(inline))
543
+ files := []fileRef{{Ref: ref, Name: contextFileName, Kind: 3, Mime: "text/plain"}}
544
+ - return contextFilePrompt(latest, budget), files, true, nil
545
+ + return inline, files, true, nil
546
+ +}
547
+ +
548
+ +// planContextFile 决定附件里放什么、正文里内联什么。
549
+ +func planContextFile(prompt string, pc promptCtx, budget int) (history, inline string) {
550
+ + history, inline = prompt, contextFilePrompt(pc.Latest, budget)
551
+ + if h, ok := stripToolProtocol(prompt, pc); ok {
552
+ + if withTools := joinPromptParts(pc.Head, inline, pc.Tail); len(withTools) <= budget {
553
+ + history, inline = h, withTools
554
+ + }
555
+ + }
556
+ + return history, inline
557
+ +}
558
+ +
559
+ +// stripToolProtocol 从拼好的 prompt 里去掉首尾的工具协议,只留对话历史。
560
+ +// 没有工具协议、或 prompt 不是按 pc 拼出来的,返回 ok=false。
561
+ +func stripToolProtocol(prompt string, pc promptCtx) (string, bool) {
562
+ + if pc.Head == "" && pc.Tail == "" {
563
+ + return prompt, false
564
+ + }
565
+ + body := prompt
566
+ + if pc.Head != "" {
567
+ + if !strings.HasPrefix(body, pc.Head) {
568
+ + return prompt, false
569
+ + }
570
+ + body = strings.TrimPrefix(body[len(pc.Head):], "\n\n")
571
+ + }
572
+ + if pc.Tail != "" {
573
+ + if !strings.HasSuffix(body, pc.Tail) {
574
+ + return prompt, false
575
+ + }
576
+ + body = strings.TrimSuffix(body[:len(body)-len(pc.Tail)], "\n\n")
577
+ + }
578
+ + return body, true
579
+ +}
580
+ +
581
+ +func joinPromptParts(parts ...string) string {
582
+ + return promptParts{body: parts}.join()
583
+ }
584
+ diff --git a/internal/app/conversation.go b/internal/app/conversation.go
585
+ index aef12eb..cbf1371 100644
586
+ --- a/internal/app/conversation.go
587
+ +++ b/internal/app/conversation.go
588
+ @@ -1,6 +1,7 @@
589
+ package app
590
+
591
+ import (
592
+ + "context"
593
+ "crypto/sha256"
594
+ "encoding/hex"
595
+ "encoding/json"
596
+ @@ -244,8 +245,11 @@ const webUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
597
+ // streamGenerateConv 发一路会话的一轮。turn==0 是首轮(建会话),>0 是续接(只发新消息)。
598
+ // 整条会话绑定 conv.cookie / conv.proxyID,中途不换号不换出口。成功后回填 conv 的
599
+ // cid/rid/rcid/tok26 和 turn+1,供下一轮续接。
600
+ -func streamGenerateConv(prompt string, mc ModelConfig, conv *convState,
601
+ +func streamGenerateConv(ctx context.Context, prompt string, mc ModelConfig, conv *convState,
602
+ onDelta, onReasoning func(string)) (*StreamResult, error) {
603
+ + if err := ctx.Err(); err != nil {
604
+ + return &StreamResult{}, err
605
+ + }
606
+ p, slotOK, slotErr := acquireSlot(conv.proxyID)
607
+ if !slotOK {
608
+ return &StreamResult{}, slotErr
609
+ @@ -365,13 +369,19 @@ func streamGenerateConv(prompt string, mc ModelConfig, conv *convState,
610
+ t0 := time.Now()
611
+ var lastErr error
612
+ for attempt := 0; attempt < rtCfg().RetryAttempts; attempt++ {
613
+ - statusCode, raw, ttfb, setCookie, err := doGeminiRequest(endpoint, body, geminiHeaders, proxyURL, lineCB)
614
+ + if cerr := ctx.Err(); cerr != nil {
615
+ + return &StreamResult{ProxyID: p.ID, ProxyName: p.Name, AccountID: conv.accountID}, cerr
616
+ + }
617
+ + statusCode, raw, ttfb, setCookie, err := doGeminiRequestStop(ctx, endpoint, body, geminiHeaders, proxyURL, lineCB, nil)
618
+ if len(setCookie) > 0 && conv.cookie != "" {
619
+ if merged := mergeSetCookie(conv.cookie, setCookie); merged != conv.cookie {
620
+ conv.cookie = merged
621
+ }
622
+ }
623
+ if err != nil || statusCode != 200 || !hasContentFrame(string(raw)) {
624
+ + if cerr := ctx.Err(); cerr != nil {
625
+ + return &StreamResult{ProxyID: p.ID, ProxyName: p.Name, AccountID: conv.accountID}, cerr
626
+ + }
627
+ if err == nil && statusCode == 200 {
628
+ lastErr = fmt.Errorf("续接无内容帧(会话可能已失效,raw %d 字节)", len(raw))
629
+ } else if err != nil {
630
+ @@ -386,7 +396,9 @@ func streamGenerateConv(prompt string, mc ModelConfig, conv *convState,
631
+ break
632
+ }
633
+ if attempt < rtCfg().RetryAttempts-1 {
634
+ - time.Sleep(time.Duration(rtCfg().RetryDelaySec) * time.Second)
635
+ + if werr := sleepCtx(ctx, time.Duration(rtCfg().RetryDelaySec)*time.Second); werr != nil {
636
+ + return &StreamResult{ProxyID: p.ID, ProxyName: p.Name, AccountID: conv.accountID}, werr
637
+ + }
638
+ }
639
+ continue
640
+ }
641
+ @@ -427,7 +439,7 @@ func streamGenerateConv(prompt string, mc ModelConfig, conv *convState,
642
+ // - 没命中 → 新建会话,首轮发全量拼接的历史(含 tools 指令,把当前上下文交给服务端)。
643
+ //
644
+ // 支持 tools(续接里也解析 ```tool_call``` 围栏);图片走原单轮路径(callGemini)。
645
+ -func callGeminiConv(messages []map[string]interface{}, mc ModelConfig,
646
+ +func callGeminiConv(ctx context.Context, messages []map[string]interface{}, mc ModelConfig,
647
+ tools []map[string]interface{}, toolChoice interface{},
648
+ onDelta, onReasoning func(string)) (string, []ToolCall, *StreamResult, error) {
649
+ parentKey := convParentKey(messages)
650
+ @@ -462,7 +474,7 @@ func callGeminiConv(messages []map[string]interface{}, mc ModelConfig,
651
+ logf("[conv] 续接命中 turn=%d,只发 %d 字节(历史留服务端)", conv.turn, len(prompt))
652
+ }
653
+
654
+ - res, err := streamGenerateConv(prompt, mc, conv, onDelta, onReasoning)
655
+ + res, err := streamGenerateConv(ctx, prompt, mc, conv, onDelta, onReasoning)
656
+ if err != nil {
657
+ if !fresh {
658
+ // 续接失败:这路会话作废,客户端重试时会当新会话全量重发。
323
659
  diff --git a/internal/app/gemini.go b/internal/app/gemini.go
324
- index 200c728..077a413 100644
660
+ index 200c728..83256f3 100644
325
661
  --- a/internal/app/gemini.go
326
662
  +++ b/internal/app/gemini.go
327
- @@ -27,6 +27,7 @@ const (
663
+ @@ -3,6 +3,7 @@ package app
664
+ import (
665
+ "bufio"
666
+ "bytes"
667
+ + "context"
668
+ "encoding/json"
669
+ "fmt"
670
+ "io"
671
+ @@ -10,6 +11,7 @@ import (
672
+ "net/url"
673
+ "regexp"
674
+ "strings"
675
+ + "sync/atomic"
676
+ "time"
677
+
678
+ fhttp "github.com/bogdanfinn/fhttp"
679
+ @@ -27,6 +29,7 @@ const (
328
680
  // "当前 Flash" 泛指针,老批次号发它拿到的是 3.6,会冒充 3.7。老批次号发这个主 hex
329
681
  // 会干净降级成 3.5 Flash-Lite(跟 3.1 Pro 一样),所以 gate 成要 cookie。
330
682
  hexFlash38 = "56fdd199312815e2" // 3.8 Flash(原记 3.7;Google 把这个 hex 原地升成 3.8,HAR 响应帧显示名已是 "3.8 Flash")
@@ -332,7 +684,7 @@ index 200c728..077a413 100644
332
684
  )
333
685
 
334
686
  // innerSlots 是 payload 里 inner 数组的长度。浏览器发 97-98 槽,我们原来只开 80,
335
- @@ -72,6 +73,7 @@ var Models = map[string]ModelConfig{
687
+ @@ -72,6 +75,7 @@ var Models = map[string]ModelConfig{
336
688
  "gemini-3.6-flash": {HexID: hexFlash36, Mode: 1, Desc: "Latest all-around model"},
337
689
  "gemini-3.5-flash-lite": {HexID: hexFlashLite, Mode: 6, Desc: "Fastest, lightweight"},
338
690
  "gemini-3.1-pro": {HexID: hexPro31, Mode: 3, Desc: "Most capable; needs a signed-in cookie (downgraded to Flash-Lite without one)"},
@@ -340,7 +692,7 @@ index 200c728..077a413 100644
340
692
  // 3.8 Flash:Google 把原 3.7 那个 hex 原地升级了(同 hex,服务端显示名从 3.7 变 3.8)。
341
693
  // 实测是**付费号专属**(不是灰度):只有付费 Gemini 账号有,免费号降级成 3.5 Flash-Lite。
342
694
  // gemini-3.7-flash 保留为别名(同 hex)。
343
- @@ -110,7 +112,7 @@ func hasCookie() bool {
695
+ @@ -110,7 +114,7 @@ func hasCookie() bool {
344
696
  // 逐模型核对等价:那三个正名的 HexID 就是 hexPro31 / hexFlash38,其余登录模型都被
345
697
  // Thinking 或 Tool 覆盖。
346
698
  func modelNeedsLogin(mc ModelConfig) bool {
@@ -349,21 +701,296 @@ index 200c728..077a413 100644
349
701
  }
350
702
 
351
703
  // anonFirstEligible 判断「匿名优先」开关下这次请求能不能走匿名(不占 cookie 账号):
352
- @@ -823,7 +825,7 @@ func doGeminiRequest(endpoint, body string, headers map[string]string, proxyURL
704
+ @@ -298,7 +302,7 @@ func (d *deltaTracker) Push(fullText string) string {
705
+ // 自己做。一旦已经吐过内容就不再重试——重试会让客户端收到重复文本。
706
+ func streamGenerate(prompt, latest string, mc ModelConfig,
707
+ onDelta, onReasoning func(string)) (*StreamResult, error) {
708
+ - return streamGenerateWithFiles(prompt, latest, mc, nil, onDelta, onReasoning)
709
+ + return streamGenerateWithFiles(context.Background(), prompt, promptCtx{Latest: latest}, mc, nil, onDelta, onReasoning, nil)
710
+ }
711
+
712
+ // fileRef 是一个已上传附件的引用。
713
+ @@ -313,8 +317,16 @@ type fileRef struct {
714
+ //
715
+ // 附件填 inner[0][3],形状 [[[ref, 1], "文件名"], …]。附件只在登录态可用:
716
+ // 匿名能把文件传上去,但对话里一引用就被服务端回 1100。
717
+ -func streamGenerateWithFiles(prompt, latest string, mc ModelConfig, pending []pendingUpload,
718
+ - onDelta, onReasoning func(string)) (*StreamResult, error) {
719
+ +//
720
+ +// stopWhen 非 nil 时,每帧拿当前累积正文问一次;返回 true 就不再读上游、按已收到
721
+ +// 的内容收尾。用于工具调用:围栏闭合时调用就已确定,上游最后一次改正文之后还要
722
+ +// 再推几秒收尾帧(Argon 实测约 2.3 秒),没必要让客户端干等。
723
+ +//
724
+ +// ctx 是客户端请求的 context:客户端断开后中止上游读取、上传和重试等待,不再替
725
+ +// 已经走掉的请求生成(否则账号照样被占用、重试还会再发一次,限流名额也一直占着)。
726
+ +// 取消导致的失败不记进代理 / cookie 健康度,那不是它们的错。
727
+ +func streamGenerateWithFiles(ctx context.Context, prompt string, pc promptCtx, mc ModelConfig, pending []pendingUpload,
728
+ + onDelta, onReasoning func(string), stopWhen func(string) bool) (*StreamResult, error) {
729
+ var files []fileRef
730
+
731
+ // 先挑号,再按它上次绑的出口挑代理 —— 同一个账号要尽量固定从同一个 IP 出去,
732
+ @@ -324,6 +336,9 @@ func streamGenerateWithFiles(prompt, latest string, mc ModelConfig, pending []pe
733
+ // 不发请求,真正发请求的是下面的 getXSRF,它在拿到 slot 之后。
734
+ // #20 匿名优先:不需要登录态能力时不占用 cookie 账号,走匿名省额度(见 anonFirstEligible)。
735
+ // 带附件(图/视频)时不能走匿名——下面 uploadBytes 那段会因 cookieStr=="" 直接报错。
736
+ + if err := ctx.Err(); err != nil {
737
+ + return nil, err
738
+ + }
739
+ var acct *CookieAccount
740
+ if !anonFirstEligible(mc, len(pending) > 0) {
741
+ if a, ok := pickCookieAccount(); ok {
742
+ @@ -379,6 +394,9 @@ func streamGenerateWithFiles(prompt, latest string, mc ModelConfig, pending []pe
743
+ // 每个号只给一次「轮转后重试」的机会,避免在一个请求里反复打 accounts.google.com
744
+ rotatedOnce := map[int64]bool{}
745
+ for acct != nil && len(tried) < maxCookieTries {
746
+ + if err := ctx.Err(); err != nil {
747
+ + return attrib(err)
748
+ + }
749
+ tried[acct.ID] = true
750
+ // 归属先记上:这一轮失败了也留痕,面板上看得出是哪个号在坏
751
+ cookieID, cookieLabel = acct.ID, accountDisplayName(acct)
752
+ @@ -406,6 +424,8 @@ func streamGenerateWithFiles(prompt, latest string, mc ModelConfig, pending []pe
753
+ rotatedOnce[acct.ID] = true
754
+ if _, _, rerr := rotateAccount(*acct); rerr == nil {
755
+ if fresh := accountByID(acct.ID); fresh != nil {
756
+ + // rotateAccount 成功改了 cookie 时已经用新 cookie 重取过 token
757
+ + // (失败则作废了缓存),所以这里命中的缓存就是刚验证过的。
758
+ if tok2, err2 := getXSRF(fresh.Cookie, proxyURL); err2 == nil {
759
+ logf("[cookie] 账号 #%d 轮转后恢复可用", acct.ID)
760
+ acct = fresh
761
+ @@ -445,7 +465,10 @@ func streamGenerateWithFiles(prompt, latest string, mc ModelConfig, pending []pe
762
+ }
763
+ nImg, nVid := 0, 0
764
+ for _, u := range pending {
765
+ - ref, uerr := uploadBytes(cookieStr, proxyURL, u.Data, u.Name)
766
+ + ref, uerr := uploadBytesCtx(ctx, cookieStr, proxyURL, u.Data, u.Name)
767
+ + if err := ctx.Err(); err != nil {
768
+ + return attrib(err)
769
+ + }
770
+ if uerr != nil {
771
+ return attrib(fmt.Errorf("上传附件 %s 失败: %w", u.Name, uerr))
772
+ }
773
+ @@ -462,7 +485,10 @@ func streamGenerateWithFiles(prompt, latest string, mc ModelConfig, pending []pe
774
+ // prompt 超长时转成文本附件。要等挑完号和出口才能做:上传要 cookie,
775
+ // 而且必须走跟正式请求同一个出口。
776
+ budget := rtCfg().MaxPromptBytes
777
+ - if p, f, used, ferr := prepareContextFile(prompt, latest, budget, cookieStr, proxyURL); ferr != nil {
778
+ + if p, f, used, ferr := prepareContextFile(ctx, prompt, pc, budget, cookieStr, proxyURL); ferr != nil {
779
+ + if err := ctx.Err(); err != nil {
780
+ + return attrib(err)
781
+ + }
782
+ return attrib(ferr)
783
+ } else if used {
784
+ prompt = p
785
+ @@ -583,32 +609,18 @@ func streamGenerateWithFiles(prompt, latest string, mc ModelConfig, pending []pe
786
+ xsrfRetried := false // XSRF 自愈只做一次,避免死循环
787
+ t0 := time.Now()
788
+
789
+ - tracker := &deltaTracker{}
790
+ - rtracker := &deltaTracker{}
791
+ - var lineCB func(string)
792
+ - if onDelta != nil || onReasoning != nil {
793
+ - lineCB = func(line string) {
794
+ - // 思考链先推完才轮到正文,所以先处理它,客户端拿到的顺序才对。
795
+ - if onReasoning != nil {
796
+ - if r := reasoningInLine(line); r != "" {
797
+ - if d := rtracker.Push(r); d != "" {
798
+ - onReasoning(d)
799
+ - }
800
+ - }
801
+ - }
802
+ - if onDelta == nil {
803
+ - return
804
+ - }
805
+ - for _, t := range textsInLine(line) {
806
+ - if d := tracker.Push(t); d != "" {
807
+ - onDelta(d)
808
+ - }
809
+ - }
810
+ - }
811
+ + lh := newLineHandler(onDelta, onReasoning, stopWhen)
812
+ + tracker, rtracker := lh.tracker, lh.rtracker
813
+ +
814
+ + retryWait := func() error {
815
+ + return sleepCtx(ctx, time.Duration(rtCfg().RetryDelaySec)*time.Second)
816
+ }
817
+
818
+ for attempt := 0; attempt < rtCfg().RetryAttempts; attempt++ {
819
+ - statusCode, raw, ttfb, setCookie, err := doGeminiRequest(endpoint, body, geminiHeaders, proxyURL, lineCB)
820
+ + if err := ctx.Err(); err != nil {
821
+ + return attrib(err)
822
+ + }
823
+ + statusCode, raw, ttfb, setCookie, err := doGeminiRequestStop(ctx, endpoint, body, geminiHeaders, proxyURL, lh.cb, &lh.stop)
824
+ if len(setCookie) > 0 && cookieID > 0 {
825
+ if merged := mergeSetCookie(cookieStr, setCookie); merged != cookieStr {
826
+ cookieStr = merged
827
+ @@ -616,6 +628,9 @@ func streamGenerateWithFiles(prompt, latest string, mc ModelConfig, pending []pe
828
+ }
829
+ }
830
+ if err != nil {
831
+ + if cerr := ctx.Err(); cerr != nil {
832
+ + return attrib(cerr) // 客户端断开,不是出口的错
833
+ + }
834
+ lastErr = err
835
+ if pickedOK {
836
+ recordProxyResult(picked.ID, false, err.Error())
837
+ @@ -626,7 +641,9 @@ func streamGenerateWithFiles(prompt, latest string, mc ModelConfig, pending []pe
838
+ }
839
+ if attempt < rtCfg().RetryAttempts-1 {
840
+ logf("retry %d/%d: %v", attempt+1, rtCfg().RetryAttempts, err)
841
+ - time.Sleep(time.Duration(rtCfg().RetryDelaySec) * time.Second)
842
+ + if werr := retryWait(); werr != nil {
843
+ + return attrib(werr)
844
+ + }
845
+ }
846
+ continue
847
+ }
848
+ @@ -654,7 +671,9 @@ func streamGenerateWithFiles(prompt, latest string, mc ModelConfig, pending []pe
849
+ break
850
+ }
851
+ if attempt < rtCfg().RetryAttempts-1 {
852
+ - time.Sleep(time.Duration(rtCfg().RetryDelaySec) * time.Second)
853
+ + if werr := retryWait(); werr != nil {
854
+ + return attrib(werr)
855
+ + }
856
+ }
857
+ continue
858
+ }
859
+ @@ -677,7 +696,9 @@ func streamGenerateWithFiles(prompt, latest string, mc ModelConfig, pending []pe
860
+ }
861
+ if attempt < rtCfg().RetryAttempts-1 {
862
+ logf("retry %d/%d: 空响应(无内容帧,%d 字节)", attempt+1, rtCfg().RetryAttempts, len(raw))
863
+ - time.Sleep(time.Duration(rtCfg().RetryDelaySec) * time.Second)
864
+ + if werr := retryWait(); werr != nil {
865
+ + return attrib(werr)
866
+ + }
867
+ }
868
+ continue
869
+ }
870
+ @@ -737,6 +758,54 @@ func streamGenerateWithFiles(prompt, latest string, mc ModelConfig, pending []pe
871
+ return attrib(lastErr)
872
+ }
873
+
874
+ +// lineHandler 是每读到一行上游数据时的处理:推思考链、推正文增量、判断能否提前收尾。
875
+ +//
876
+ +// tracker / rtracker 记的是**已经发给客户端的**正文 / 思考链,调用方据此决定还能
877
+ +// 不能重试(吐过内容就不能重试,否则重复)。非流式也要逐帧看正文才能判断能否提前
878
+ +// 收尾,所以没有 onDelta 时另用一份 watch 记,不污染 tracker。
879
+ +type lineHandler struct {
880
+ + tracker, rtracker *deltaTracker
881
+ + stop atomic.Bool
882
+ + cb func(string) // nil 表示不需要逐行处理
883
+ +}
884
+ +
885
+ +func newLineHandler(onDelta, onReasoning func(string), stopWhen func(string) bool) *lineHandler {
886
+ + lh := &lineHandler{tracker: &deltaTracker{}, rtracker: &deltaTracker{}}
887
+ + if onDelta == nil && onReasoning == nil && stopWhen == nil {
888
+ + return lh
889
+ + }
890
+ + watch := lh.tracker
891
+ + if onDelta == nil {
892
+ + watch = &deltaTracker{}
893
+ + }
894
+ + lh.cb = func(line string) {
895
+ + // 思考链先推完才轮到正文,所以先处理它,客户端拿到的顺序才对。
896
+ + if onReasoning != nil {
897
+ + if r := reasoningInLine(line); r != "" {
898
+ + if d := lh.rtracker.Push(r); d != "" {
899
+ + onReasoning(d)
900
+ + }
901
+ + }
902
+ + }
903
+ + if onDelta == nil && stopWhen == nil {
904
+ + return
905
+ + }
906
+ + grew := false
907
+ + for _, t := range textsInLine(line) {
908
+ + if d := watch.Push(t); d != "" {
909
+ + grew = true
910
+ + if onDelta != nil {
911
+ + onDelta(d)
912
+ + }
913
+ + }
914
+ + }
915
+ + if grew && stopWhen != nil && stopWhen(watch.emitted) {
916
+ + lh.stop.Store(true)
917
+ + }
918
+ + }
919
+ + return lh
920
+ +}
921
+ +
922
+ // upstreamModelRe 匹配响应帧里服务端自报的模型显示名(帧的 [42] 位)。
923
+ // 形如 ...,"fbb127bbb056c959",null,null,"3.6 Flash",true,...
924
+ var upstreamModelRe = regexp.MustCompile(`\\"[0-9a-f]{16}\\",null,null,\\"([^"\\]{1,40})\\"`)
925
+ @@ -806,10 +875,43 @@ func buildGeminiHeaders(cookieStr, sapisid, hexID string) map[string]string {
926
+ // 实测号活一两小时就失效 —— 所以这些必须收下来并写回账号。
927
+ func doGeminiRequest(endpoint, body string, headers map[string]string, proxyURL string,
928
+ onLine func(string)) (int, []byte, int64, []string, error) {
929
+ + return doGeminiRequestStop(context.Background(), endpoint, body, headers, proxyURL, onLine, nil)
930
+ +}
931
+ +
932
+ +// sleepCtx 等 d;ctx 先结束就提前返回它的错误。
933
+ +func sleepCtx(ctx context.Context, d time.Duration) error {
934
+ + t := time.NewTimer(d)
935
+ + defer t.Stop()
936
+ + select {
937
+ + case <-t.C:
938
+ + return nil
939
+ + case <-ctx.Done():
940
+ + return ctx.Err()
941
+ + }
942
+ +}
943
+ +
944
+ +// stopReader 在 stop 置位后让下一次 Read 直接返回 EOF:调用方已经拿到想要的内容,
945
+ +// 剩下的上游帧不再等。已经读进 Scanner 缓冲的行照常处理完。
946
+ +type stopReader struct {
947
+ + r io.Reader
948
+ + stop *atomic.Bool
949
+ +}
950
+ +
951
+ +func (s stopReader) Read(p []byte) (int, error) {
952
+ + if s.stop != nil && s.stop.Load() {
953
+ + return 0, io.EOF
954
+ + }
955
+ + return s.r.Read(p)
956
+ +}
957
+ +
958
+ +// doGeminiRequestStop 同 doGeminiRequest,stop 置位后提前结束读取(见 stopReader),
959
+ +// ctx 结束时中止连接和读取。
960
+ +func doGeminiRequestStop(ctx context.Context, endpoint, body string, headers map[string]string, proxyURL string,
961
+ + onLine func(string), stop *atomic.Bool) (int, []byte, int64, []string, error) {
962
+ sendAt := time.Now()
963
+ if proxyURL != "" {
964
+ // 走 stdlib 的 http.ProxyURL,已知能过 socks5/socks5h。
965
+ - req, err := http.NewRequest("POST", endpoint, strings.NewReader(body))
966
+ + req, err := http.NewRequestWithContext(ctx, "POST", endpoint, strings.NewReader(body))
967
+ if err != nil {
968
+ return 0, nil, 0, nil, err
969
+ }
970
+ @@ -823,7 +925,7 @@ func doGeminiRequest(endpoint, body string, headers map[string]string, proxyURL
353
971
  return 0, nil, 0, nil, err
354
972
  }
355
973
  defer resp.Body.Close()
356
974
  - raw, ttfb, err := readBody(resp.Body, onLine, sendAt)
357
- + raw, ttfb, err := readModelCheckedBody(resp.Body, onLine, sendAt, resp.StatusCode, headers["x-goog-ext-525001261-jspb"])
975
+ + raw, ttfb, err := readModelCheckedBody(stopReader{resp.Body, stop}, onLine, sendAt, resp.StatusCode, headers["x-goog-ext-525001261-jspb"])
358
976
  if err != nil {
359
977
  return resp.StatusCode, nil, ttfb, resp.Header.Values("Set-Cookie"), err
360
978
  }
361
- @@ -844,7 +846,7 @@ func doGeminiRequest(endpoint, body string, headers map[string]string, proxyURL
979
+ @@ -831,7 +933,7 @@ func doGeminiRequest(endpoint, body string, headers map[string]string, proxyURL
980
+ }
981
+
982
+ // 直连 → tls-client,保留 chrome146 TLS/HTTP2 真指纹
983
+ - req, err := fhttp.NewRequest("POST", endpoint, strings.NewReader(body))
984
+ + req, err := fhttp.NewRequestWithContext(ctx, "POST", endpoint, strings.NewReader(body))
985
+ if err != nil {
986
+ return 0, nil, 0, nil, err
987
+ }
988
+ @@ -844,7 +946,7 @@ func doGeminiRequest(endpoint, body string, headers map[string]string, proxyURL
362
989
  return 0, nil, 0, nil, err
363
990
  }
364
991
  defer resp.Body.Close()
365
992
  - raw, ttfb, err := readBody(resp.Body, onLine, sendAt)
366
- + raw, ttfb, err := readModelCheckedBody(resp.Body, onLine, sendAt, resp.StatusCode, headers["x-goog-ext-525001261-jspb"])
993
+ + raw, ttfb, err := readModelCheckedBody(stopReader{resp.Body, stop}, onLine, sendAt, resp.StatusCode, headers["x-goog-ext-525001261-jspb"])
367
994
  if err != nil {
368
995
  return resp.StatusCode, nil, ttfb, resp.Header.Values("Set-Cookie"), err
369
996
  }
@@ -396,16 +1023,850 @@ index 9dc2541..f709b15 100644
396
1023
  }
397
1024
  // 反过来:每个真 hex 都应该有一个 thinking 版
398
1025
  for _, base := range []string{hexFlash36, hexFlashLite, hexPro31, hexFlash38} {
1026
+ diff --git a/internal/app/latency_test.go b/internal/app/latency_test.go
1027
+ new file mode 100644
1028
+ index 0000000..9329309
1029
+ --- /dev/null
1030
+ +++ b/internal/app/latency_test.go
1031
+ @@ -0,0 +1,299 @@
1032
+ +package app
1033
+ +
1034
+ +import (
1035
+ + "bytes"
1036
+ + "encoding/json"
1037
+ + "fmt"
1038
+ + "io"
1039
+ + "strings"
1040
+ + "sync/atomic"
1041
+ + "testing"
1042
+ + "time"
1043
+ +)
1044
+ +
1045
+ +// SIDCC 每个响应都刷新,XSRF 缓存不能因此失效,否则每个登录态请求都多抓一次 /app。
1046
+ +func TestXSRFCacheSurvivesSIDCCRefresh(t *testing.T) {
1047
+ + cookie := "SAPISID=sap; __Secure-1PSID=psid; SIDCC=old; __Secure-1PSIDCC=old"
1048
+ + refreshed := mergeSetCookie(cookie, []string{"SIDCC=new; Path=/", "__Secure-1PSIDCC=new; Path=/"})
1049
+ + if refreshed == cookie {
1050
+ + t.Fatal("测试前提不成立:合并后 cookie 没变")
1051
+ + }
1052
+ + if cookieKey(cookie) != cookieKey(refreshed) {
1053
+ + t.Fatal("同一账号刷新 SIDCC 后缓存键变了")
1054
+ + }
1055
+ + if cookieKey(cookie) == cookieKey("SAPISID=other; __Secure-1PSID=psid2") {
1056
+ + t.Fatal("不同账号撞了缓存键")
1057
+ + }
1058
+ + if cookieKey("a=1") == cookieKey("a=2") {
1059
+ + t.Fatal("没有身份项时应退回按整串区分")
1060
+ + }
1061
+ +
1062
+ + key := cookieKey(cookie)
1063
+ + xsrfMu.Lock()
1064
+ + xsrfCache[key] = xsrfEntry{token: "tok", fetched: time.Now()}
1065
+ + xsrfMu.Unlock()
1066
+ + t.Cleanup(func() { invalidateXSRF(cookie) })
1067
+ +
1068
+ + // 命中缓存时不发网络请求;这里 proxyURL 指向不可达地址,真去抓会报错。
1069
+ + tok, err := getXSRF(refreshed, "http://127.0.0.1:1")
1070
+ + if err != nil || tok != "tok" {
1071
+ + t.Fatalf("刷新后的 cookie 没命中缓存: tok=%q err=%v", tok, err)
1072
+ + }
1073
+ +}
1074
+ +
1075
+ +func toolsFixture(names ...string) []map[string]interface{} {
1076
+ + var out []map[string]interface{}
1077
+ + for _, n := range names {
1078
+ + out = append(out, map[string]interface{}{
1079
+ + "type": "function",
1080
+ + "function": map[string]interface{}{
1081
+ + "name": n,
1082
+ + "description": "Run <cmd> & report",
1083
+ + "parameters": map[string]interface{}{
1084
+ + "type": "object",
1085
+ + "properties": map[string]interface{}{
1086
+ + "command": map[string]interface{}{"type": "string"},
1087
+ + },
1088
+ + "required": []interface{}{"command"},
1089
+ + },
1090
+ + },
1091
+ + })
1092
+ + }
1093
+ + return out
1094
+ +}
1095
+ +
1096
+ +func TestToolSchemaIsCompact(t *testing.T) {
1097
+ + msgs := []map[string]interface{}{{"role": "user", "content": "hi"}}
1098
+ + p, pc := messagesToPrompt(msgs, toolsFixture("bash"), nil)
1099
+ + if strings.Contains(pc.Head, "\n \"") {
1100
+ + t.Error("工具定义仍是缩进格式")
1101
+ + }
1102
+ + if strings.Contains(pc.Head, `\u00`) || !strings.Contains(pc.Head, "Run <cmd> & report") {
1103
+ + t.Error("工具描述里的 HTML 字符被转义了")
1104
+ + }
1105
+ + if pc.Tail == "" || !strings.HasPrefix(p, pc.Head) || !strings.HasSuffix(p, pc.Tail) {
1106
+ + t.Fatal("prompt 首尾应分别是工具说明和末尾锚点")
1107
+ + }
1108
+ + if p != buildPrompt(msgs, toolsFixture("bash"), nil) {
1109
+ + t.Fatal("messagesToPrompt 和 buildPrompt 结果不一致")
1110
+ + }
1111
+ +}
1112
+ +
1113
+ +// 超长转附件时,工具说明和末尾锚点留在正文,附件里只有历史。
1114
+ +func TestContextFileKeepsToolProtocolInline(t *testing.T) {
1115
+ + msgs := longConversation(300)
1116
+ + prompt, pc := messagesToPrompt(msgs, toolsFixture("bash", "read"), nil)
1117
+ + budget := len(prompt) / 2
1118
+ +
1119
+ + history, inline := planContextFile(prompt, pc, budget)
1120
+ + if strings.Contains(history, pc.Head) || strings.Contains(history, pc.Tail) {
1121
+ + t.Fatal("工具协议跟着历史进了附件")
1122
+ + }
1123
+ + if !strings.HasPrefix(inline, pc.Head) || !strings.HasSuffix(inline, pc.Tail) {
1124
+ + t.Fatal("正文里没保留工具协议")
1125
+ + }
1126
+ + if !strings.Contains(inline, contextFileName) || !strings.Contains(inline, "读取一下 task.md") {
1127
+ + t.Fatal("正文缺少附件指引或最新提问")
1128
+ + }
1129
+ + if !strings.Contains(history, "历史填充内容") || len(inline) > budget {
1130
+ + t.Fatalf("附件缺历史或正文超预算(%d > %d)", len(inline), budget)
1131
+ + }
1132
+ +
1133
+ + // 工具说明本身就超预算:退回整段进附件,至少不撞墙。
1134
+ + history, inline = planContextFile(prompt, pc, len(pc.Head)/2)
1135
+ + if history != prompt || strings.Contains(inline, pc.Head) {
1136
+ + t.Fatal("工具说明超预算时应整段进附件")
1137
+ + }
1138
+ +
1139
+ + // 没有工具:跟原来一样整段进附件。
1140
+ + plain, ppc := messagesToPrompt(msgs, nil, nil)
1141
+ + if history, _ := planContextFile(plain, ppc, len(plain)/2); history != plain {
1142
+ + t.Fatal("没有工具时附件内容变了")
1143
+ + }
1144
+ +}
1145
+ +
1146
+ +func TestToolCallComplete(t *testing.T) {
1147
+ + done := toolCallComplete(toolsFixture("bash"))
1148
+ + cases := []struct {
1149
+ + text string
1150
+ + want bool
1151
+ + }{
1152
+ + {"先说两句", false},
1153
+ + {"```tool_call\n{\"name\": \"bash\", \"arguments\": {\"command\": \"ls\"}}", false}, // 未闭合
1154
+ + {"```tool_call\n{\"name\": \"bash\", \"arguments\": {\"command\": \"ls\"}}\n``", false}, // 闭合到一半
1155
+ + {"```tool_call\n{\"name\": \"bash\", \"arguments\": {\"command\": \"ls\"}}\n```", true},
1156
+ + {"好的\n```tool_call {\"name\":\"bash\",\"arguments\":{}}```", true},
1157
+ + {"```tool_call\n{\"name\": \"rm_rf\", \"arguments\": {}}\n```", false}, // 不认识的函数
1158
+ + {"```tool_call\n{\"name\": \"bash\", \"arguments\": {\"command\": \"echo ```\"}}\n```", false}, // 参数里有围栏,解析不完整
1159
+ + }
1160
+ + for _, c := range cases {
1161
+ + if got := done(c.text); got != c.want {
1162
+ + t.Errorf("toolCallComplete(%q) = %v, want %v", c.text, got, c.want)
1163
+ + }
1164
+ + }
1165
+ + if toolCallComplete(nil) != nil {
1166
+ + t.Error("没有工具时不应做判定")
1167
+ + }
1168
+ +}
1169
+ +
1170
+ +// countingReader 按块吐数据并记录被读了几次。
1171
+ +type countingReader struct {
1172
+ + chunks [][]byte
1173
+ + reads int
1174
+ +}
1175
+ +
1176
+ +func (r *countingReader) Read(p []byte) (int, error) {
1177
+ + if r.reads >= len(r.chunks) {
1178
+ + return 0, io.EOF
1179
+ + }
1180
+ + n := copy(p, r.chunks[r.reads])
1181
+ + r.reads++
1182
+ + return n, nil
1183
+ +}
1184
+ +
1185
+ +func TestStopReaderEndsReadEarly(t *testing.T) {
1186
+ + src := &countingReader{chunks: [][]byte{[]byte("a\n"), []byte("b\n"), []byte("c\n"), []byte("d\n")}}
1187
+ + var stop atomic.Bool
1188
+ + var got []string
1189
+ + _, _, err := readBody(stopReader{src, &stop}, func(line string) {
1190
+ + got = append(got, line)
1191
+ + if line == "b" {
1192
+ + stop.Store(true)
1193
+ + }
1194
+ + }, time.Now())
1195
+ + if err != nil {
1196
+ + t.Fatal(err)
1197
+ + }
1198
+ + if strings.Join(got, ",") != "a,b" || src.reads != 2 {
1199
+ + t.Fatalf("置位后仍在读上游: lines=%v reads=%d", got, src.reads)
1200
+ + }
1201
+ +}
1202
+ +
1203
+ +func argonLine(hexID, name, answer string) []byte {
1204
+ + return makeSyntheticArgonFrame(hexID, name, answer)
1205
+ +}
1206
+ +
1207
+ +func TestArgonIncrementalForwarding(t *testing.T) {
1208
+ + header := fmt.Sprintf(`[1,null,null,null,"%s"]`, hexArgon4)
1209
+ + noID := argonLine("", "", "x")
1210
+ +
1211
+ + // 身份晚到:之前的帧先扣住,确认后按原顺序放行。
1212
+ + var got []string
1213
+ + body := bytes.Join([][]byte{[]byte(")]}'\n"), noID, argonLine(hexArgon4, "4 Argon", "ok")}, nil)
1214
+ + _, _, err := readModelCheckedBody(bytes.NewReader(body), func(l string) { got = append(got, l) }, time.Now(), 200, header)
1215
+ + if err != nil || len(got) != 3 || got[0] != ")]}'" {
1216
+ + t.Fatalf("晚到身份: err=%v lines=%d", err, len(got))
1217
+ + }
1218
+ +
1219
+ + // 确认之后增量转发:每读一块就要回调,不能攒到结尾。
1220
+ + calls := 0
1221
+ + inc := &incrementalReader{
1222
+ + chunks: [][]byte{argonLine(hexArgon4, "4 Argon", "a"), argonLine(hexArgon4, "4 Argon", "ab"), noID},
1223
+ + callbacksCalled: &calls,
1224
+ + }
1225
+ + if _, _, err := readModelCheckedBody(inc, func(string) { calls++ }, time.Now(), 200, header); err != nil || calls != 3 {
1226
+ + t.Fatalf("确认后未增量转发: err=%v calls=%d", err, calls)
1227
+ + }
1228
+ +
1229
+ + // 先对后错:已放行的收不回,但必须报错并停读。
1230
+ + got = nil
1231
+ + src := &countingReader{chunks: [][]byte{
1232
+ + argonLine(hexArgon4, "4 Argon", "a"),
1233
+ + argonLine(hexFlash36, "3.6 Flash", "b"),
1234
+ + argonLine(hexArgon4, "4 Argon", "c"),
1235
+ + }}
1236
+ + _, _, err = readModelCheckedBody(src, func(l string) { got = append(got, l) }, time.Now(), 200, header)
1237
+ + if err == nil || !strings.Contains(err.Error(), "mismatch") || len(got) != 1 || src.reads != 2 {
1238
+ + t.Fatalf("先对后错: err=%v lines=%d reads=%d", err, len(got), src.reads)
1239
+ + }
1240
+ +
1241
+ + // 始终没有身份:一行都不放行。
1242
+ + got = nil
1243
+ + _, _, err = readModelCheckedBody(bytes.NewReader(bytes.Repeat(noID, 3)), func(l string) { got = append(got, l) }, time.Now(), 200, header)
1244
+ + if err == nil || !strings.Contains(err.Error(), "identity missing") || len(got) != 0 {
1245
+ + t.Fatalf("无身份: err=%v lines=%d", err, len(got))
1246
+ + }
1247
+ +
1248
+ + // 非流式(onLine 为 nil)仍整段校验。
1249
+ + if _, _, err := readModelCheckedBody(bytes.NewReader(noID), nil, time.Now(), 200, header); err == nil {
1250
+ + t.Fatal("非流式无身份应报错")
1251
+ + }
1252
+ +}
1253
+ +
1254
+ +// 轮转后重取失败时必须作废缓存,否则失效的号会一直拿着旧 token 被当成可用。
1255
+ +func TestRefreshXSRFFailureDropsCache(t *testing.T) {
1256
+ + cookie := "SAPISID=sap2; __Secure-1PSID=psid2"
1257
+ + xsrfMu.Lock()
1258
+ + xsrfCache[cookieKey(cookie)] = xsrfEntry{token: "stale", fetched: time.Now()}
1259
+ + xsrfMu.Unlock()
1260
+ + t.Cleanup(func() { invalidateXSRF(cookie) })
1261
+ +
1262
+ + if err := refreshXSRF(cookie, "http://127.0.0.1:1"); err == nil {
1263
+ + t.Fatal("不可达出口应报错")
1264
+ + }
1265
+ + xsrfMu.Lock()
1266
+ + _, ok := xsrfCache[cookieKey(cookie)]
1267
+ + xsrfMu.Unlock()
1268
+ + if ok {
1269
+ + t.Fatal("重取失败后缓存仍在")
1270
+ + }
1271
+ +}
1272
+ +
1273
+ +// genFrame 造一行 StreamGenerate 帧:inner[4] 带累积正文,argon=true 时带上模型身份槽。
1274
+ +func genFrame(text string, argon bool) []byte {
1275
+ + inner := make([]any, 43)
1276
+ + inner[0] = "padding-to-pass-the-minimum-frame-length-checks-in-textsInLine"
1277
+ + inner[4] = []any{[]any{"rc_test", []any{text}}}
1278
+ + if argon {
1279
+ + inner[39], inner[40], inner[41], inner[42] = hexArgon4, nil, nil, "4 Argon"
1280
+ + }
1281
+ + ib, _ := json.Marshal(inner)
1282
+ + line, _ := json.Marshal([]any{[]any{"wrb.fr", nil, string(ib)}})
1283
+ + return append(line, '\n')
1284
+ +}
1285
+ +
1286
+ +// 端到端:工具块闭合那一帧之后不再读上游,客户端只收到围栏外的正文,最终能解析出调用。
1287
+ +func TestToolCallStopsUpstreamRead(t *testing.T) {
1288
+ + call := "```tool_call\n{\"name\": \"bash\", \"arguments\": {\"command\": \"ls\"}}\n```"
1289
+ + texts := []string{"好的", "好的\n```tool_call\n{\"name\": \"ba", "好的\n" + call, "好的\n" + call, "好的\n" + call}
1290
+ + for _, argon := range []bool{false, true} {
1291
+ + hexID := hexFlash36
1292
+ + if argon {
1293
+ + hexID = hexArgon4
1294
+ + }
1295
+ + var frames [][]byte
1296
+ + for _, tx := range texts {
1297
+ + frames = append(frames, genFrame(tx, argon))
1298
+ + }
1299
+ + src := &countingReader{chunks: frames}
1300
+ + var sent strings.Builder
1301
+ + gate := newToolFenceGate(func(s string) { sent.WriteString(s) })
1302
+ + lh := newLineHandler(gate.Push, nil, toolCallComplete(toolsFixture("bash")))
1303
+ +
1304
+ + raw, _, err := readModelCheckedBody(stopReader{src, &lh.stop}, lh.cb, time.Now(), 200,
1305
+ + fmt.Sprintf(`[1,null,null,null,"%s"]`, hexID))
1306
+ + if err != nil {
1307
+ + t.Fatalf("argon=%v: %v", argon, err)
1308
+ + }
1309
+ + if !lh.stop.Load() || src.reads != 3 {
1310
+ + t.Fatalf("argon=%v: 工具块闭合后仍在读上游(reads=%d,应为 3)", argon, src.reads)
1311
+ + }
1312
+ + if sent.String() != "好的\n" {
1313
+ + t.Fatalf("argon=%v: 围栏原文漏给了客户端: %q", argon, sent.String())
1314
+ + }
1315
+ + _, calls := parseToolCalls(extractResponseText(string(raw)))
1316
+ + if len(calls) != 1 || calls[0].Function.Name != "bash" || calls[0].Function.Arguments != `{"command":"ls"}` {
1317
+ + t.Fatalf("argon=%v: 提前收尾后解析不出调用: %+v", argon, calls)
1318
+ + }
1319
+ + }
1320
+ +
1321
+ + // 非流式(onDelta 为 nil)同样提前收尾,但不能把 tracker 记成「已发给客户端」,否则失败时不能重试。
1322
+ + src := &countingReader{chunks: [][]byte{genFrame("好的\n"+call, false), genFrame("好的\n"+call, false)}}
1323
+ + lh := newLineHandler(nil, nil, toolCallComplete(toolsFixture("bash")))
1324
+ + if _, _, err := readModelCheckedBody(stopReader{src, &lh.stop}, lh.cb, time.Now(), 200, `[1,null,null,null,"x"]`); err != nil {
1325
+ + t.Fatal(err)
1326
+ + }
1327
+ + if !lh.stop.Load() || src.reads != 1 || lh.tracker.emitted != "" {
1328
+ + t.Fatalf("非流式: stop=%v reads=%d tracker=%q", lh.stop.Load(), src.reads, lh.tracker.emitted)
1329
+ + }
1330
+ +}
1331
+ diff --git a/internal/app/messages.go b/internal/app/messages.go
1332
+ index 376171f..87b91fe 100644
1333
+ --- a/internal/app/messages.go
1334
+ +++ b/internal/app/messages.go
1335
+ @@ -46,8 +46,50 @@ type ToolCallFunction struct {
1336
+ // 出口才知道能不能做,所以判断放在 streamGenerate 里。最新那条消息单独返回,
1337
+ // 转附件时用来内联,好让模型不必去文件里找问题。
1338
+ func messagesToPrompt(messages []map[string]interface{}, tools []map[string]interface{},
1339
+ - toolChoice interface{}) (string, string) {
1340
+ - return buildPrompt(messages, tools, toolChoice), latestUserMessage(messages)
1341
+ + toolChoice interface{}) (string, promptCtx) {
1342
+ + pp := buildPromptParts(messages, tools, toolChoice)
1343
+ + return pp.join(), promptCtx{Latest: latestUserMessage(messages), Head: pp.head, Tail: pp.tail}
1344
+ +}
1345
+ +
1346
+ +// promptCtx 是拼好的 prompt 之外、超长转附件时仍要内联的部分。
1347
+ +//
1348
+ +// 工具协议(Head:格式说明 + schema;Tail:末尾锚点提醒)不能跟着历史一起进附件:
1349
+ +// 末尾锚点是模型肯吐 ```tool_call``` 的关键(见 buildPromptParts 里的判据),
1350
+ +// 整段塞进 message.txt 后正文只剩一句「去读附件」,锚点就失效了。
1351
+ +type promptCtx struct {
1352
+ + Latest string // 最新那条用户消息
1353
+ + Head string // 工具格式说明与定义,没有工具时为空
1354
+ + Tail string // 末尾的工具锚点提醒,没有工具时为空
1355
+ +}
1356
+ +
1357
+ +// promptParts 是 prompt 的三段:工具说明、对话历史、末尾提醒。
1358
+ +type promptParts struct {
1359
+ + head string
1360
+ + body []string
1361
+ + tail string
1362
+ +}
1363
+ +
1364
+ +func (pp promptParts) join() string {
1365
+ + var nonEmpty []string
1366
+ + for _, p := range append(append([]string{pp.head}, pp.body...), pp.tail) {
1367
+ + if p != "" {
1368
+ + nonEmpty = append(nonEmpty, p)
1369
+ + }
1370
+ + }
1371
+ + return strings.Join(nonEmpty, "\n\n")
1372
+ +}
1373
+ +
1374
+ +// compactJSON 不缩进、不转义 HTML 字符。工具 schema 原来用 MarshalIndent,
1375
+ +// 缩进空白和 \u003c 这类转义全算进 prompt 字节预算,agentic 客户端几十个工具时
1376
+ +// 很容易把请求推过转附件的门槛。
1377
+ +func compactJSON(v interface{}) string {
1378
+ + var b strings.Builder
1379
+ + enc := json.NewEncoder(&b)
1380
+ + enc.SetEscapeHTML(false)
1381
+ + if err := enc.Encode(v); err != nil {
1382
+ + return ""
1383
+ + }
1384
+ + return strings.TrimSuffix(b.String(), "\n")
1385
+ }
1386
+
1387
+ // latestUserMessage 取最后一条 user 消息的正文,没有则返回空串。
1388
+ @@ -65,6 +107,12 @@ func latestUserMessage(messages []map[string]interface{}) string {
1389
+
1390
+ func buildPrompt(messages []map[string]interface{}, tools []map[string]interface{},
1391
+ toolChoice interface{}) string {
1392
+ + return buildPromptParts(messages, tools, toolChoice).join()
1393
+ +}
1394
+ +
1395
+ +func buildPromptParts(messages []map[string]interface{}, tools []map[string]interface{},
1396
+ + toolChoice interface{}) promptParts {
1397
+ + var pp promptParts
1398
+ var parts []string
1399
+
1400
+ toolsInjected := false
1401
+ @@ -89,7 +137,7 @@ func buildPrompt(messages []map[string]interface{}, tools []map[string]interface
1402
+ })
1403
+ }
1404
+ if len(defs) > 0 {
1405
+ - defsJSON, _ := json.MarshalIndent(defs, "", " ")
1406
+ + defsJSON := compactJSON(defs)
1407
+ rule := "Only use tool_call blocks when needed."
1408
+ switch {
1409
+ case forced != "":
1410
+ @@ -102,13 +150,13 @@ func buildPrompt(messages []map[string]interface{}, tools []map[string]interface
1411
+ "and nothing else — do not answer the question yourself, even if you " +
1412
+ "know the answer."
1413
+ }
1414
+ - parts = append(parts, fmt.Sprintf(
1415
+ + pp.head = fmt.Sprintf(
1416
+ "[System instruction]: You have access to tools. "+
1417
+ "To call a tool, respond with:\n"+
1418
+ "```tool_call\n{\"name\": \"func_name\", \"arguments\": {...}}\n```\n"+
1419
+ "%s\n\n"+
1420
+ - "Available tools:\n%s", rule, string(defsJSON),
1421
+ - ))
1422
+ + "Available tools:\n%s", rule, defsJSON,
1423
+ + )
1424
+ toolsInjected = true
1425
+ }
1426
+ }
1427
+ @@ -165,33 +213,27 @@ func buildPrompt(messages []map[string]interface{}, tools []map[string]interface
1428
+ // 工具名(shell_command)0/4 抄假名 —— 示例教的是「动作」不是名字,故不必按客户端
1429
+ // 动态生成 schema。
1430
+ if toolsInjected {
1431
+ - parts = append(parts,
1432
+ - "[System instruction — highest priority]: To run a command or read a file you MUST "+
1433
+ - "output a ```tool_call``` block — this is the ONLY execution channel. A "+
1434
+ - "```powershell/```bash/```cmd/```python code block is NOT executed, it is only shown "+
1435
+ - "to the user; never use one to run anything, and never claim you lack tools.\n"+
1436
+ - "Act, do not explain: when the request needs a tool, your reply is ONE ```tool_call``` "+
1437
+ - "block and nothing else — do not list the commands you 'would' run, do not output more "+
1438
+ - "than one tool_call, do not add prose. If several steps are needed, do the FIRST one "+
1439
+ - "now; you will be called again with its result to continue.\n"+
1440
+ - "Know when to STOP: once a tool result shows a step succeeded (for example it exited "+
1441
+ - "with code 0, even with no printed output), that step is DONE — do not run it again and "+
1442
+ - "do not retry the same thing a different way. When the whole request is accomplished, "+
1443
+ - "stop calling tools and reply with a short final answer instead of another tool_call.\n"+
1444
+ - "Example of a correct turn — user asks \"list the files here and tell me the size of "+
1445
+ - "README.md\", you reply with exactly one block and nothing else:\n"+
1446
+ - "```tool_call\n{\"name\": \"run_command\", \"arguments\": {\"command\": \"ls -la\"}}\n```\n"+
1447
+ - "(In your block use one of the real tool names listed above with its own arguments.) "+
1448
+ - "When the request needs a tool, emit the tool_call block now.")
1449
+ + pp.tail = "[System instruction — highest priority]: To run a command or read a file you MUST " +
1450
+ + "output a ```tool_call``` block — this is the ONLY execution channel. A " +
1451
+ + "```powershell/```bash/```cmd/```python code block is NOT executed, it is only shown " +
1452
+ + "to the user; never use one to run anything, and never claim you lack tools.\n" +
1453
+ + "Act, do not explain: when the request needs a tool, your reply is ONE ```tool_call``` " +
1454
+ + "block and nothing else — do not list the commands you 'would' run, do not output more " +
1455
+ + "than one tool_call, do not add prose. If several steps are needed, do the FIRST one " +
1456
+ + "now; you will be called again with its result to continue.\n" +
1457
+ + "Know when to STOP: once a tool result shows a step succeeded (for example it exited " +
1458
+ + "with code 0, even with no printed output), that step is DONE — do not run it again and " +
1459
+ + "do not retry the same thing a different way. When the whole request is accomplished, " +
1460
+ + "stop calling tools and reply with a short final answer instead of another tool_call.\n" +
1461
+ + "Example of a correct turn — user asks \"list the files here and tell me the size of " +
1462
+ + "README.md\", you reply with exactly one block and nothing else:\n" +
1463
+ + "```tool_call\n{\"name\": \"run_command\", \"arguments\": {\"command\": \"ls -la\"}}\n```\n" +
1464
+ + "(In your block use one of the real tool names listed above with its own arguments.) " +
1465
+ + "When the request needs a tool, emit the tool_call block now."
1466
+ }
1467
+
1468
+ - var nonEmpty []string
1469
+ - for _, p := range parts {
1470
+ - if p != "" {
1471
+ - nonEmpty = append(nonEmpty, p)
1472
+ - }
1473
+ - }
1474
+ - return strings.Join(nonEmpty, "\n\n")
1475
+ + pp.body = parts
1476
+ + return pp
1477
+ }
1478
+
1479
+ func contentToString(content interface{}) string {
1480
+ @@ -392,6 +434,47 @@ func parseToolCalls(text string) (string, []ToolCall) {
1481
+ return strings.TrimSpace(clean), toolCalls
1482
+ }
1483
+
1484
+ +// toolCallComplete 返回一个判定函数:累积正文里出现了**闭合且能解析**、函数名在
1485
+ +// tools 里的 ```tool_call``` 块时为真,表示这一轮的工具调用已经确定,可以不等上游
1486
+ +// 收尾。没有工具时返回 nil(不做判定)。
1487
+ +//
1488
+ +// 提示词要求一轮只出一个 tool_call 块、不带别的正文(见 buildPromptParts 末尾锚点),
1489
+ +// 所以第一个合法块闭合就收尾。函数名不认识或 JSON 不完整时不收尾,照旧等上游
1490
+ +// 结束 —— 宁可慢,不把半截或错的调用当成结果。
1491
+ +func toolCallComplete(tools []map[string]interface{}) func(string) bool {
1492
+ + names := map[string]bool{}
1493
+ + for _, tool := range tools {
1494
+ + fn := tool
1495
+ + if f, ok := tool["function"].(map[string]interface{}); ok {
1496
+ + fn = f
1497
+ + }
1498
+ + if n := getStr(fn, "name"); n != "" {
1499
+ + names[n] = true
1500
+ + }
1501
+ + }
1502
+ + if len(names) == 0 {
1503
+ + return nil
1504
+ + }
1505
+ + return func(text string) bool {
1506
+ + i := strings.Index(text, toolFenceOpen)
1507
+ + if i < 0 {
1508
+ + return false
1509
+ + }
1510
+ + m := toolCallRe.FindStringSubmatch(text[i:])
1511
+ + if m == nil {
1512
+ + return false
1513
+ + }
1514
+ + var data struct {
1515
+ + Name string `json:"name"`
1516
+ + Arguments map[string]interface{} `json:"arguments"`
1517
+ + }
1518
+ + if json.Unmarshal([]byte(strings.TrimSpace(m[1])), &data) != nil {
1519
+ + return false
1520
+ + }
1521
+ + return names[data.Name]
1522
+ + }
1523
+ +}
1524
+ +
1525
+ // parseToolChoice 解析 OpenAI 的 tool_choice。
1526
+ // 返回 (mode, forcedName):mode ∈ {"auto","none","required"};
1527
+ // forcedName 非空表示客户端点名了某个函数。
1528
+ diff --git a/internal/app/rotate.go b/internal/app/rotate.go
1529
+ index e082b15..908a052 100644
1530
+ --- a/internal/app/rotate.go
1531
+ +++ b/internal/app/rotate.go
1532
+ @@ -95,7 +95,14 @@ func rotateAccount(a CookieAccount) (time.Duration, []string, error) {
1533
+ if cookie != a.Cookie {
1534
+ old := a.Cookie
1535
+ updateAccountCookie(a.ID, cookie)
1536
+ - invalidateXSRF(old)
1537
+ + // 轮转本身不在请求路径上,顺手用新 cookie 重取 token:既验证轮转结果,
1538
+ + // 又让下一个请求直接命中缓存。失败时缓存已作废,下个请求同步重取。
1539
+ + if err := refreshXSRF(cookie, proxyURL); err != nil {
1540
+ + logf("[rotate] 账号 #%d 轮转后取 XSRF 失败: %v", a.ID, err)
1541
+ + }
1542
+ + if cookieKey(old) != cookieKey(cookie) {
1543
+ + invalidateXSRF(old) // 身份项都变了(理论上不会):旧键别留着
1544
+ + }
1545
+ }
1546
+ if len(names) > 0 {
1547
+ logf("[rotate] 账号 #%d 刷新了 %s", a.ID, strings.Join(names, ", "))
399
1548
  diff --git a/internal/app/server.go b/internal/app/server.go
400
- index 2ce8d11..8f52a30 100644
1549
+ index 2ce8d11..4ae16b2 100644
401
1550
  --- a/internal/app/server.go
402
1551
  +++ b/internal/app/server.go
403
- @@ -9,7 +9,7 @@ import (
1552
+ @@ -1,6 +1,7 @@
1553
+ package app
1554
+
1555
+ import (
1556
+ + "context"
1557
+ "encoding/json"
1558
+ "fmt"
1559
+ "io"
1560
+ @@ -9,7 +10,7 @@ import (
404
1561
  "time"
405
1562
  )
406
1563
 
407
1564
  -const Version = "4.21.0"
408
- +const Version = "4.21.0-argon.1"
1565
+ +const Version = "4.21.0-argon.2"
409
1566
 
410
1567
  func writeJSON(w http.ResponseWriter, status int, data interface{}) {
411
1568
  body, _ := json.Marshal(data)
1569
+ @@ -129,9 +130,9 @@ func rejectUnsupported(req map[string]interface{}, messages []map[string]interfa
1570
+ return nil
1571
+ }
1572
+
1573
+ -func callGemini(prompt, latest string, mc ModelConfig, tools []map[string]interface{},
1574
+ +func callGemini(ctx context.Context, prompt string, pc promptCtx, mc ModelConfig, tools []map[string]interface{},
1575
+ images []pendingUpload, onDelta, onReasoning func(string)) (string, []ToolCall, *StreamResult, error) {
1576
+ - res, err := streamGenerateWithFiles(prompt, latest, mc, images, onDelta, onReasoning)
1577
+ + res, err := streamGenerateWithFiles(ctx, prompt, pc, mc, images, onDelta, onReasoning, toolCallComplete(tools))
1578
+ if err != nil {
1579
+ // res 非 nil:失败时它只带归属(哪个号 / 哪个出口),给 recordRequest 用
1580
+ return "", nil, res, err
1581
+ @@ -267,7 +268,7 @@ func handleChatCompletions(w http.ResponseWriter, r *http.Request) {
1582
+ return
1583
+ }
1584
+
1585
+ - prompt, latest := messagesToPrompt(messages, tools, req["tool_choice"])
1586
+ + prompt, pc := messagesToPrompt(messages, tools, req["tool_choice"])
1587
+ if strings.TrimSpace(prompt) == "" && len(images) == 0 {
1588
+ writeJSON(w, 400, map[string]interface{}{"error": map[string]string{"message": "empty prompt"}})
1589
+ return
1590
+ @@ -304,11 +305,14 @@ func handleChatCompletions(w http.ResponseWriter, r *http.Request) {
1591
+ var res *StreamResult
1592
+ if rtCfg().MultiTurn && len(images) == 0 && modelCfg.Tool == 0 {
1593
+ // 多轮:按历史前缀识别续接,命中就只发新消息、历史留服务端。带 tools 也走这条。
1594
+ - text, toolCalls, res, err = callGeminiConv(messages, modelCfg, tools, req["tool_choice"], onDelta, onReasoning)
1595
+ + text, toolCalls, res, err = callGeminiConv(r.Context(), messages, modelCfg, tools, req["tool_choice"], onDelta, onReasoning)
1596
+ } else {
1597
+ - text, toolCalls, res, err = callGemini(prompt, latest, modelCfg, tools, images, onDelta, onReasoning)
1598
+ + text, toolCalls, res, err = callGemini(r.Context(), prompt, pc, modelCfg, tools, images, onDelta, onReasoning)
1599
+ }
1600
+ if err != nil {
1601
+ + if clientGone(r, "chat.completions", modelName, prompt, res, stream) {
1602
+ + return
1603
+ + }
1604
+ recordRequest("chat.completions", modelName, prompt, "", res, 502, err.Error(), stream)
1605
+ if sse != nil && sse.Started() {
1606
+ sse.Fail(err) // 已经开流,HTTP 状态码改不了了
1607
+ @@ -390,6 +394,21 @@ func handleChatCompletions(w http.ResponseWriter, r *http.Request) {
1608
+ })
1609
+ }
1610
+
1611
+ +// statusClientClosed 是客户端先断开时记进 requests 表的状态码(沿用 nginx 的 499)。
1612
+ +const statusClientClosed = 499
1613
+ +
1614
+ +// clientGone 判断失败是不是因为客户端已经断开;是的话记一条 499 并返回 true。
1615
+ +//
1616
+ +// 这时连接已经没了,再写 502 / 流错误没人收。记成 502 会让「用户自己取消」看起来
1617
+ +// 像上游故障;499 + "client disconnected" 在面板的失败列表里一眼能分清。
1618
+ +func clientGone(r *http.Request, endpoint, model, prompt string, res *StreamResult, stream bool) bool {
1619
+ + if r.Context().Err() == nil {
1620
+ + return false
1621
+ + }
1622
+ + recordRequest(endpoint, model, prompt, "", res, statusClientClosed, "client disconnected", stream)
1623
+ + return true
1624
+ +}
1625
+ +
1626
+ // usageOf 是 buildUsageWithReasoning 的便捷包装,res 可能为 nil。
1627
+ func usageOf(prompt, text string, res *StreamResult) map[string]int {
1628
+ r := ""
1629
+ @@ -565,7 +584,7 @@ func handleResponses(w http.ResponseWriter, r *http.Request) {
1630
+ return
1631
+ }
1632
+
1633
+ - prompt, latest := messagesToPrompt(messages, tools, req["tool_choice"])
1634
+ + prompt, pc := messagesToPrompt(messages, tools, req["tool_choice"])
1635
+ if strings.TrimSpace(prompt) == "" && len(images) == 0 {
1636
+ writeJSON(w, 400, map[string]interface{}{"error": map[string]string{"message": "empty input"}})
1637
+ return
1638
+ @@ -659,11 +678,14 @@ func handleResponses(w http.ResponseWriter, r *http.Request) {
1639
+ var toolCalls []ToolCall
1640
+ var res *StreamResult
1641
+ if rtCfg().MultiTurn && len(images) == 0 && modelCfg.Tool == 0 {
1642
+ - text, toolCalls, res, err = callGeminiConv(messages, modelCfg, tools, req["tool_choice"], onDelta, nil)
1643
+ + text, toolCalls, res, err = callGeminiConv(r.Context(), messages, modelCfg, tools, req["tool_choice"], onDelta, nil)
1644
+ } else {
1645
+ - text, toolCalls, res, err = callGemini(prompt, latest, modelCfg, tools, images, onDelta, nil)
1646
+ + text, toolCalls, res, err = callGemini(r.Context(), prompt, pc, modelCfg, tools, images, onDelta, nil)
1647
+ }
1648
+ if err != nil {
1649
+ + if clientGone(r, "responses", modelName, prompt, res, stream) {
1650
+ + return
1651
+ + }
1652
+ recordRequest("responses", modelName, prompt, "", res, 502, err.Error(), stream)
1653
+ if stream {
1654
+ writeEvent("response.failed", map[string]interface{}{
1655
+ diff --git a/internal/app/upload.go b/internal/app/upload.go
1656
+ index 7747a72..09e8a04 100644
1657
+ --- a/internal/app/upload.go
1658
+ +++ b/internal/app/upload.go
1659
+ @@ -2,6 +2,7 @@ package app
1660
+
1661
+ import (
1662
+ "bytes"
1663
+ + "context"
1664
+ "fmt"
1665
+ "io"
1666
+ "net/http"
1667
+ @@ -20,6 +21,11 @@ const uploadHost = "https://push.clients6.google.com/upload/"
1668
+ // 匿名也能传成功,但传上去的文件在对话里引用会被回 1100,所以调用方要自己确保有 cookie。
1669
+ // proxyURL 必须跟正式请求同一出口,否则在 Google 眼里是两个会话共用文件。
1670
+ func uploadBytes(cookie, proxyURL string, data []byte, filename string) (string, error) {
1671
+ + return uploadBytesCtx(context.Background(), cookie, proxyURL, data, filename)
1672
+ +}
1673
+ +
1674
+ +// uploadBytesCtx 同 uploadBytes,ctx 取消(客户端断开)时中止上传。
1675
+ +func uploadBytesCtx(ctx context.Context, cookie, proxyURL string, data []byte, filename string) (string, error) {
1676
+ pushID, pctx, err := getUploadTokens(cookie, proxyURL)
1677
+ if err != nil {
1678
+ return "", fmt.Errorf("取上传页面参数失败: %w", err)
1679
+ @@ -63,7 +69,7 @@ func uploadBytes(cookie, proxyURL string, data []byte, filename string) (string,
1680
+ "X-Goog-Upload-Protocol": "resumable",
1681
+ "X-Goog-Upload-Header-Content-Length": strconv.Itoa(len(data)),
1682
+ })
1683
+ - status, respHead, body, err := uploadPost(uploadHost, startHeaders,
1684
+ + status, respHead, body, err := uploadPostCtx(ctx, uploadHost, startHeaders,
1685
+ []byte("File name: "+sanitizeUploadName(filename)), proxyURL)
1686
+ if err != nil {
1687
+ return "", fmt.Errorf("上传 start 失败: %w", err)
1688
+ @@ -82,7 +88,7 @@ func uploadBytes(cookie, proxyURL string, data []byte, filename string) (string,
1689
+ "X-Goog-Upload-Command": "upload, finalize",
1690
+ "X-Goog-Upload-Offset": "0",
1691
+ })
1692
+ - status, _, body, err = uploadPost(putURL, upHeaders, data, proxyURL)
1693
+ + status, _, body, err = uploadPostCtx(ctx, putURL, upHeaders, data, proxyURL)
1694
+ if err != nil {
1695
+ return "", fmt.Errorf("上传 finalize 失败: %w", err)
1696
+ }
1697
+ @@ -109,9 +115,14 @@ func sanitizeUploadName(name string) string {
1698
+
1699
+ // uploadPost 走跟主请求相同的出口发 POST,响应头一起带回(start 要取 x-goog-upload-url)。
1700
+ func uploadPost(url string, headers map[string]string, body []byte, proxyURL string) (
1701
+ + int, map[string]string, []byte, error) {
1702
+ + return uploadPostCtx(context.Background(), url, headers, body, proxyURL)
1703
+ +}
1704
+ +
1705
+ +func uploadPostCtx(ctx context.Context, url string, headers map[string]string, body []byte, proxyURL string) (
1706
+ int, map[string]string, []byte, error) {
1707
+ if proxyURL != "" {
1708
+ - req, err := http.NewRequest("POST", url, bytes.NewReader(body))
1709
+ + req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
1710
+ if err != nil {
1711
+ return 0, nil, nil, err
1712
+ }
1713
+ @@ -131,7 +142,7 @@ func uploadPost(url string, headers map[string]string, body []byte, proxyURL str
1714
+ }
1715
+ return resp.StatusCode, h, b, err
1716
+ }
1717
+ - req, err := fhttp.NewRequest("POST", url, bytes.NewReader(body))
1718
+ + req, err := fhttp.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
1719
+ if err != nil {
1720
+ return 0, nil, nil, err
1721
+ }
1722
+ diff --git a/internal/app/videos.go b/internal/app/videos.go
1723
+ index 390b580..0365a78 100644
1724
+ --- a/internal/app/videos.go
1725
+ +++ b/internal/app/videos.go
1726
+ @@ -10,6 +10,7 @@ package app
1727
+ // 只是把「阻塞等结果」挪到后台 goroutine,前台立即返 id。
1728
+
1729
+ import (
1730
+ + "context"
1731
+ "encoding/json"
1732
+ "net/http"
1733
+ "strings"
1734
+ @@ -105,7 +106,7 @@ func runVideoJob(j *videoJob) {
1735
+ finishVideoJob(j, nil, "", err.Error())
1736
+ return
1737
+ }
1738
+ - _, _, res, err := callGemini(j.Prompt, j.Prompt, mc, nil, nil, nil, nil)
1739
+ + _, _, res, err := callGemini(context.Background(), j.Prompt, promptCtx{Latest: j.Prompt}, mc, nil, nil, nil, nil)
1740
+ if err != nil {
1741
+ recordRequest("videos", j.Model, j.Prompt, "", res, 502, err.Error(), false)
1742
+ finishVideoJob(j, nil, "", err.Error())
1743
+ diff --git a/internal/app/xsrf.go b/internal/app/xsrf.go
1744
+ index c43b104..55634b6 100644
1745
+ --- a/internal/app/xsrf.go
1746
+ +++ b/internal/app/xsrf.go
1747
+ @@ -27,15 +27,23 @@ var (
1748
+ )
1749
+
1750
+ type xsrfEntry struct {
1751
+ - token string
1752
+ - pushID string // 上传文件用的 Push-ID 头
1753
+ - pctx string // 上传文件用的 X-Client-Pctx 头
1754
+ - fetched time.Time
1755
+ + token string
1756
+ + pushID string // 上传文件用的 Push-ID 头
1757
+ + pctx string // 上传文件用的 X-Client-Pctx 头
1758
+ + fetched time.Time
1759
+ + refreshing bool // 后台刷新正在飞,避免并发请求重复抓页面
1760
+ }
1761
+
1762
+ // 页面上的 token 没写明有效期,取个保守值定期重取。
1763
+ const xsrfTTL = 20 * time.Minute
1764
+
1765
+ +// xsrfRefreshAfter 之后命中缓存时照常返回,但在后台重抓一次页面。
1766
+ +//
1767
+ +// /app 页面约 770KB,抓一次 1-3 秒,不能放在请求的关键路径上;但同步重抓顺带
1768
+ +// 起到「cookie 还活着吗」的探测作用(失效的号抓不到 SNlM0e)。后台刷新把这个探测
1769
+ +// 挪出关键路径:刷新失败就丢掉缓存,下一个请求同步重取时照样报出失效、走换号逻辑。
1770
+ +const xsrfRefreshAfter = 5 * time.Minute
1771
+ +
1772
+ var snlm0eRe = regexp.MustCompile(`"SNlM0e":"([^"]{10,200})"`)
1773
+
1774
+ // 上传要的两个页面参数,跟 XSRF token 同页取,省一次页面请求。
1775
+ @@ -44,8 +52,18 @@ var pushIDRe = regexp.MustCompile(`"qKIAYe":"([^"]{4,400})"`)
1776
+ var pctxRe = regexp.MustCompile(`"Ylro7b":"([^"]{4,400})"`)
1777
+
1778
+ // cookieKey 用 cookie 的短摘要当缓存键,避免把整串凭证塞进 map key。
1779
+ +//
1780
+ +// 摘要只取账号身份(SAPISID + __Secure-1PSID,见 cookieIdentity),不取整串:
1781
+ +// 上游几乎每个响应都刷新 *SIDCC,streamGenerate 合并 Set-Cookie 后写回账号,
1782
+ +// 按整串取键的话下一个请求必然 miss,每次都要多抓一次 /app 页面(实测登录态每个
1783
+ +// 请求多出约 0.9 秒,且不计入 ttfb_ms / total_ms)。token 跟会话绑定、不跟 SIDCC
1784
+ +// 绑定;真过期了上游回 xsrf 错误,调用方 invalidate 后重取。
1785
+ func cookieKey(cookie string) string {
1786
+ - sum := sha1.Sum([]byte(cookie))
1787
+ + id := cookieIdentity(cookie)
1788
+ + if id == "|" { // 两项都没有:退回整串,至少不同 cookie 不会撞键
1789
+ + id = cookie
1790
+ + }
1791
+ + sum := sha1.Sum([]byte(id))
1792
+ return hex.EncodeToString(sum[:8])
1793
+ }
1794
+
1795
+ @@ -67,12 +85,9 @@ func getXSRF(cookie, proxyURL string) (string, error) {
1796
+ }
1797
+ key := cookieKey(cookie)
1798
+
1799
+ - xsrfMu.Lock()
1800
+ - if e, ok := xsrfCache[key]; ok && time.Since(e.fetched) < xsrfTTL {
1801
+ - xsrfMu.Unlock()
1802
+ + if e, ok := cachedAppTokens(key, cookie, proxyURL); ok {
1803
+ return e.token, nil
1804
+ }
1805
+ - xsrfMu.Unlock()
1806
+
1807
+ e, err := fetchAppTokens(cookie, proxyURL)
1808
+ if err != nil {
1809
+ @@ -84,16 +99,59 @@ func getXSRF(cookie, proxyURL string) (string, error) {
1810
+ return e.token, nil
1811
+ }
1812
+
1813
+ +// cachedAppTokens 返回未过期的缓存项;过了 xsrfRefreshAfter 时顺带踢一次后台刷新。
1814
+ +func cachedAppTokens(key, cookie, proxyURL string) (xsrfEntry, bool) {
1815
+ + xsrfMu.Lock()
1816
+ + defer xsrfMu.Unlock()
1817
+ + e, ok := xsrfCache[key]
1818
+ + if !ok || time.Since(e.fetched) >= xsrfTTL {
1819
+ + return xsrfEntry{}, false
1820
+ + }
1821
+ + if !e.refreshing && time.Since(e.fetched) >= xsrfRefreshAfter {
1822
+ + e.refreshing = true
1823
+ + xsrfCache[key] = e
1824
+ + go refreshAppTokens(key, cookie, proxyURL)
1825
+ + }
1826
+ + return e, true
1827
+ +}
1828
+ +
1829
+ +// refreshAppTokens 后台重抓页面。失败就丢掉缓存,让下一个请求同步重取并报出失效。
1830
+ +func refreshAppTokens(key, cookie, proxyURL string) {
1831
+ + if err := storeAppTokens(key, cookie, proxyURL); err != nil {
1832
+ + logf("[xsrf] 后台刷新失败,已作废缓存: %v", err)
1833
+ + }
1834
+ +}
1835
+ +
1836
+ +// refreshXSRF 立即重抓页面并写回缓存,失败则作废缓存。
1837
+ +//
1838
+ +// 给本来就不在请求关键路径上的调用方用(cookie 轮转):轮转后直接作废的话,
1839
+ +// 缓存按账号身份取键,下一个请求就得同步抓一次页面(实测约 1.2 秒)。
1840
+ +func refreshXSRF(cookie, proxyURL string) error {
1841
+ + if cookie == "" {
1842
+ + return nil
1843
+ + }
1844
+ + return storeAppTokens(cookieKey(cookie), cookie, proxyURL)
1845
+ +}
1846
+ +
1847
+ +func storeAppTokens(key, cookie, proxyURL string) error {
1848
+ + e, err := fetchAppTokens(cookie, proxyURL)
1849
+ + xsrfMu.Lock()
1850
+ + defer xsrfMu.Unlock()
1851
+ + if err != nil {
1852
+ + delete(xsrfCache, key)
1853
+ + return err
1854
+ + }
1855
+ + xsrfCache[key] = e
1856
+ + return nil
1857
+ +}
1858
+ +
1859
+ // getUploadTokens 取上传要用的 Push-ID / X-Client-Pctx,跟 XSRF token 同一份缓存。
1860
+ func getUploadTokens(cookie, proxyURL string) (pushID, pctx string, err error) {
1861
+ key := cookieKey(cookie)
1862
+
1863
+ - xsrfMu.Lock()
1864
+ - if e, ok := xsrfCache[key]; ok && time.Since(e.fetched) < xsrfTTL {
1865
+ - xsrfMu.Unlock()
1866
+ + if e, ok := cachedAppTokens(key, cookie, proxyURL); ok {
1867
+ return e.pushID, e.pctx, nil
1868
+ }
1869
+ - xsrfMu.Unlock()
1870
+
1871
+ e, err := fetchAppTokens(cookie, proxyURL)
1872
+ if err != nil {