Agnes 2.0-flash是推理模型,推理token占大量预算。 800仍不够→JSON截断(parse error: unexpected end of JSON input)。 1200确保推理+正文都够用。
110 lines
2.7 KiB
Go
110 lines
2.7 KiB
Go
// 织忆 MemoryWeave — Unix Socket IPC (Go → Rust 整合引擎)
|
|
// 与 consolidate/client.go 互补:ipc.go 提供全局 IPC 实例,供 trigger 循环等场景使用
|
|
package routes
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net"
|
|
"os"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// ─── Unix Socket IPC ────────────────────────────────────
|
|
|
|
type UnixIPC struct {
|
|
mu sync.Mutex
|
|
sockPath string
|
|
conn net.Conn
|
|
}
|
|
|
|
func NewUnixIPC(sockPath string) *UnixIPC {
|
|
return &UnixIPC{sockPath: sockPath}
|
|
}
|
|
|
|
// Call 通过 Unix Socket 调用 Rust sidecar
|
|
func (ipc *UnixIPC) Call(method string, payload []byte) ([]byte, error) {
|
|
ipc.mu.Lock()
|
|
defer ipc.mu.Unlock()
|
|
|
|
// 建立连接(如果尚未建立)
|
|
if ipc.conn == nil {
|
|
if err := ipc.connect(); err != nil {
|
|
return nil, fmt.Errorf("ipc connect: %w", err)
|
|
}
|
|
}
|
|
|
|
// 构造帧: [4字节长度][JSON payload]
|
|
frame := make([]byte, 4+len(payload))
|
|
copy(frame[0:4], intToBytes(len(payload)))
|
|
copy(frame[4:], payload)
|
|
|
|
// 设置超时
|
|
ipc.conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
|
if _, err := ipc.conn.Write(frame); err != nil {
|
|
ipc.conn.Close()
|
|
ipc.conn = nil
|
|
return nil, fmt.Errorf("ipc write: %w", err)
|
|
}
|
|
|
|
// 读取响应
|
|
ipc.conn.SetReadDeadline(time.Now().Add(10 * time.Second))
|
|
lenBuf := make([]byte, 4)
|
|
if _, err := ipc.conn.Read(lenBuf); err != nil {
|
|
ipc.conn.Close()
|
|
ipc.conn = nil
|
|
return nil, fmt.Errorf("ipc read len: %w", err)
|
|
}
|
|
|
|
respLen := bytesToInt(lenBuf)
|
|
if respLen > 10*1024*1024 { // 10MB 上限
|
|
return nil, fmt.Errorf("ipc response too large: %d", respLen)
|
|
}
|
|
|
|
respBuf := make([]byte, respLen)
|
|
if _, err := ipc.conn.Read(respBuf); err != nil {
|
|
ipc.conn.Close()
|
|
ipc.conn = nil
|
|
return nil, fmt.Errorf("ipc read body: %w", err)
|
|
}
|
|
|
|
return respBuf, nil
|
|
}
|
|
|
|
func (ipc *UnixIPC) connect() error {
|
|
if err := os.Remove(ipc.sockPath); err != nil && !os.IsNotExist(err) {
|
|
log.Printf("[ipc] remove stale socket: %v", err)
|
|
}
|
|
|
|
conn, err := net.DialTimeout("unix", ipc.sockPath, 3*time.Second)
|
|
if err != nil {
|
|
return fmt.Errorf("dial %s: %w", ipc.sockPath, err)
|
|
}
|
|
ipc.conn = conn
|
|
return nil
|
|
}
|
|
|
|
// Close 关闭连接
|
|
func (ipc *UnixIPC) Close() {
|
|
ipc.mu.Lock()
|
|
defer ipc.mu.Unlock()
|
|
if ipc.conn != nil {
|
|
ipc.conn.Close()
|
|
ipc.conn = nil
|
|
}
|
|
}
|
|
|
|
// 全局 IPC 实例
|
|
var IPCSock = NewUnixIPC("/tmp/zhiyi-consolidate.sock")
|
|
|
|
// ─── 辅助 ─────────────────────────────────────────────
|
|
|
|
func intToBytes(n int) []byte {
|
|
return []byte{byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n)}
|
|
}
|
|
|
|
func bytesToInt(b []byte) int {
|
|
return int(b[0])<<24 | int(b[1])<<16 | int(b[2])<<8 | int(b[3])
|
|
}
|