feat(agent): 云端 Agent 运行时 - 完善 Pi 桥接、上下文压力与临时故障重试
This commit is contained in:
1 parent
0030f4da9b
commit
76ca0fd247
32 files changed
+1663
-1485
No files matched your search
@@ -21,7 +21,38 @@ import (
|
||||
|
||||
// canonicalFromRuntimeMessages 把运行时的会话消息(user/assistant/toolResult,
|
||||
// 内容块为 text/image/thinking/toolCall)转换成供应商层接受的规范格式。
|
||||
func canonicalFromRuntimeMessages(messages []map[string]any, tools []map[string]interface{}, systemPrompt string) canonicalAgentRequest {
|
||||
const cloudAgentPiCompactionSummaryMessagePrefix = "The conversation history before this point was compacted into the following summary:\n\n<summary>\n"
|
||||
const cloudAgentPiCompactionSummaryMessageSuffix = "\n</summary>"
|
||||
|
||||
// strictRuntimeStringAliases resolves protocol aliases without silently
|
||||
// choosing one when two producers disagree.
|
||||
func strictRuntimeStringAliases(fields map[string]interface{}, label string, aliases ...string) (string, error) {
|
||||
value := ""
|
||||
firstAlias := ""
|
||||
for _, alias := range aliases {
|
||||
raw, present := fields[alias]
|
||||
if !present || raw == nil {
|
||||
continue
|
||||
}
|
||||
text, ok := raw.(string)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("%s 字段 %q 必须是字符串", label, alias)
|
||||
}
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
continue
|
||||
}
|
||||
if value != "" && value != text {
|
||||
return "", fmt.Errorf("%s 的别名 %q 与 %q 冲突", label, firstAlias, alias)
|
||||
}
|
||||
if value == "" {
|
||||
value, firstAlias = text, alias
|
||||
}
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func canonicalFromRuntimeMessages(messages []map[string]any, tools []map[string]interface{}, systemPrompt string) (canonicalAgentRequest, error) {
|
||||
canonical := canonicalAgentRequest{Tools: tools, ToolChoice: "auto", SystemPrompt: systemPrompt}
|
||||
for _, message := range messages {
|
||||
switch stringField(message, "role") {
|
||||
@@ -29,6 +60,14 @@ func canonicalFromRuntimeMessages(messages []map[string]any, tools []map[string]
|
||||
if text := runtimeContentText(message["content"]); strings.TrimSpace(text) != "" {
|
||||
canonical.Messages = append(canonical.Messages, map[string]interface{}{"role": "system", "content": text})
|
||||
}
|
||||
case "compactionSummary":
|
||||
summary := stringField(message, "summary")
|
||||
if summary != "" {
|
||||
canonical.Messages = append(canonical.Messages, map[string]interface{}{
|
||||
"role": "user",
|
||||
"content": cloudAgentPiCompactionSummaryMessagePrefix + summary + cloudAgentPiCompactionSummaryMessageSuffix,
|
||||
})
|
||||
}
|
||||
case "user":
|
||||
canonical.Messages = append(canonical.Messages, map[string]interface{}{"role": "user", "content": runtimeUserContent(message["content"])})
|
||||
case "assistant":
|
||||
@@ -45,10 +84,25 @@ func canonicalFromRuntimeMessages(messages []map[string]any, tools []map[string]
|
||||
if part["arguments"] == nil {
|
||||
arguments = []byte("{}")
|
||||
}
|
||||
calls = append(calls, map[string]interface{}{
|
||||
"id": stringField(part, "id"),
|
||||
callID, err := strictRuntimeStringAliases(part, "Pi 工具调用 ID", "id", "call_id", "toolCallId", "tool_call_id")
|
||||
if err != nil {
|
||||
return canonicalAgentRequest{}, err
|
||||
}
|
||||
if callID == "" {
|
||||
return canonicalAgentRequest{}, errors.New("Pi 工具调用缺少 call id")
|
||||
}
|
||||
itemID, err := strictRuntimeStringAliases(part, "Pi 工具调用 item id", "item_id", "itemId")
|
||||
if err != nil {
|
||||
return canonicalAgentRequest{}, err
|
||||
}
|
||||
call := map[string]interface{}{
|
||||
"id": callID,
|
||||
"function": map[string]interface{}{"name": stringField(part, "name"), "arguments": string(arguments)},
|
||||
})
|
||||
}
|
||||
if itemID != "" {
|
||||
call["item_id"] = itemID
|
||||
}
|
||||
calls = append(calls, call)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -63,9 +117,12 @@ func canonicalFromRuntimeMessages(messages []map[string]any, tools []map[string]
|
||||
}
|
||||
canonical.Messages = append(canonical.Messages, converted)
|
||||
case "toolResult", "tool":
|
||||
id := firstNonEmpty(stringField(message, "toolCallId"), stringField(message, "tool_call_id"))
|
||||
id, err := strictRuntimeStringAliases(message, "Pi 工具结果 call id", "toolCallId", "tool_call_id", "call_id")
|
||||
if err != nil {
|
||||
return canonicalAgentRequest{}, err
|
||||
}
|
||||
if id == "" {
|
||||
continue
|
||||
return canonicalAgentRequest{}, errors.New("Pi 工具结果缺少 call id")
|
||||
}
|
||||
canonical.Messages = append(canonical.Messages, map[string]interface{}{"role": "tool", "tool_call_id": id, "content": runtimeContentText(message["content"])})
|
||||
}
|
||||
@@ -82,7 +139,85 @@ func canonicalFromRuntimeMessages(messages []map[string]any, tools []map[string]
|
||||
canonical.Messages = append([]map[string]interface{}{{"role": "system", "content": systemPrompt}}, canonical.Messages...)
|
||||
}
|
||||
}
|
||||
return canonical
|
||||
return canonical, nil
|
||||
}
|
||||
|
||||
func validateRuntimeMessagesForModel(messages []map[string]any) error {
|
||||
pending := make(map[string]struct{})
|
||||
for _, message := range messages {
|
||||
switch stringField(message, "role") {
|
||||
case "assistant":
|
||||
if len(pending) > 0 {
|
||||
return fmt.Errorf("Pi 工具调用 %q 缺少结果", firstPendingRuntimeCall(pending))
|
||||
}
|
||||
parts, _ := message["content"].([]interface{})
|
||||
for _, value := range parts {
|
||||
part, _ := value.(map[string]interface{})
|
||||
if stringField(part, "type") != "toolCall" {
|
||||
continue
|
||||
}
|
||||
callID, err := strictRuntimeStringAliases(part, "Pi 工具调用 ID", "id", "call_id", "toolCallId", "tool_call_id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if callID == "" {
|
||||
return errors.New("Pi 工具调用缺少 call id")
|
||||
}
|
||||
if _, exists := pending[callID]; exists {
|
||||
return fmt.Errorf("Pi 工具调用 %q 重复或缺少结果", callID)
|
||||
}
|
||||
arguments := part["arguments"]
|
||||
if arguments == nil {
|
||||
arguments = map[string]interface{}{}
|
||||
}
|
||||
encoded, err := json.Marshal(arguments)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Pi 工具调用 %q 参数无效: %w", callID, err)
|
||||
}
|
||||
var object map[string]interface{}
|
||||
if err := json.Unmarshal(encoded, &object); err != nil || object == nil {
|
||||
return fmt.Errorf("Pi 工具调用 %q 参数不是 JSON 对象", callID)
|
||||
}
|
||||
pending[callID] = struct{}{}
|
||||
}
|
||||
case "toolResult", "tool":
|
||||
callID, err := strictRuntimeStringAliases(message, "Pi 工具结果 call id", "toolCallId", "tool_call_id", "call_id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if callID == "" {
|
||||
return errors.New("Pi 工具结果缺少 call id")
|
||||
}
|
||||
if _, exists := pending[callID]; !exists {
|
||||
return fmt.Errorf("Pi 工具结果 %q 没有对应的工具调用", callID)
|
||||
}
|
||||
delete(pending, callID)
|
||||
case "user", "system":
|
||||
if len(pending) > 0 {
|
||||
return fmt.Errorf("Pi 工具调用 %q 缺少结果", firstPendingRuntimeCall(pending))
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(pending) > 0 {
|
||||
return fmt.Errorf("Pi 工具调用 %q 缺少结果", firstPendingRuntimeCall(pending))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func firstPendingRuntimeCall(pending map[string]struct{}) string {
|
||||
for callID := range pending {
|
||||
return callID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func cloudAgentPiHasCompactionSummary(messages []map[string]any) bool {
|
||||
for _, message := range messages {
|
||||
if stringField(message, "role") == "compactionSummary" && strings.TrimSpace(stringField(message, "summary")) != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func runtimeContentText(content interface{}) string {
|
||||
@@ -158,7 +293,11 @@ func runtimeToolCalls(calls []cloudAgentCall) []map[string]any {
|
||||
if strings.TrimSpace(call.Function.Arguments) != "" {
|
||||
_ = json.Unmarshal([]byte(call.Function.Arguments), &arguments)
|
||||
}
|
||||
result = append(result, map[string]any{"id": call.ID, "name": call.Function.Name, "arguments": arguments})
|
||||
entry := map[string]any{"id": call.ID, "name": call.Function.Name, "arguments": arguments}
|
||||
if call.ItemID != "" {
|
||||
entry["item_id"] = call.ItemID
|
||||
}
|
||||
result = append(result, entry)
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -166,25 +305,32 @@ func runtimeToolCalls(calls []cloudAgentCall) []map[string]any {
|
||||
// cloudAgentPiTool 工具调用桥接:所有工具都交给唯一的 Go 业务执行器
|
||||
// advanceCloudAgentTool(权限、审批、计费、画布写入都在那里治理)。
|
||||
func (s *Service) cloudAgentPiTool(ctx context.Context, userID, runID string, payload map[string]json.RawMessage) (any, error) {
|
||||
var request struct {
|
||||
CallID string `json:"callId"`
|
||||
Name string `json:"name"`
|
||||
ToolName string `json:"toolName"`
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
callID, err := decodePiStringAliases(payload, "Pi 工具调用 ID", "callId", "call_id", "toolCallId", "tool_call_id", "id")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := decodePiPayload(payload, &request); err != nil {
|
||||
if callID == "" {
|
||||
return nil, errors.New("Pi 工具调用缺少 call id")
|
||||
}
|
||||
name, err := decodePiStringAliases(payload, "Pi 工具名称", "name", "toolName")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var call cloudAgentCall
|
||||
call.ID = firstNonEmpty(request.CallID, generateID())
|
||||
call.Function.Name = firstNonEmpty(request.Name, request.ToolName)
|
||||
call.Function.Arguments = strings.TrimSpace(string(request.Arguments))
|
||||
call.ID = callID
|
||||
call.Function.Name = name
|
||||
if raw, exists := payload["arguments"]; exists {
|
||||
call.Function.Arguments = strings.TrimSpace(string(raw))
|
||||
}
|
||||
if call.Function.Arguments == "" || call.Function.Arguments == "null" {
|
||||
call.Function.Arguments = "{}"
|
||||
}
|
||||
if call.Function.Name == "" {
|
||||
return nil, fmt.Errorf("tool call is missing a name")
|
||||
}
|
||||
if err := validateCloudAgentCalls([]cloudAgentCall{call}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 工具白名单校验:拒绝未声明的工具调用
|
||||
run, err := s.repo.CloudAgent(userID, runID)
|
||||
@@ -221,18 +367,29 @@ func (s *Service) executeCloudAgentRuntimeTool(ctx context.Context, userID, runI
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cloudAgentRunTerminal(run.Status) {
|
||||
return nil, fmt.Errorf("run already terminated")
|
||||
}
|
||||
state, err := cloudAgentDecode(run)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A runtime may retry the same /tool request after the bridge response was
|
||||
// lost. Replay the committed result before inspecting CallIndex: the
|
||||
// executor may already have advanced to the next call or completed the run.
|
||||
if content, ok := cloudAgentToolMessage(&state, call.ID); ok {
|
||||
return cloudAgentPiToolResult(call, content), nil
|
||||
}
|
||||
if cloudAgentRunTerminal(run.Status) {
|
||||
return nil, fmt.Errorf("run already terminated")
|
||||
}
|
||||
if state.StepLimits, err = s.cloudAgentStepLimits(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
state.Calls = []cloudAgentCall{call}
|
||||
state.CallIndex = 0
|
||||
if state.CallIndex < 0 || state.CallIndex >= len(state.Calls) {
|
||||
return nil, fmt.Errorf("工具调用 %q 没有对应的模型工具调用", call.ID)
|
||||
}
|
||||
expected := state.Calls[state.CallIndex]
|
||||
if !cloudAgentToolCallsEquivalent(expected, call) {
|
||||
return nil, fmt.Errorf("工具调用 %q 与模型声明的工具调用不一致", call.ID)
|
||||
}
|
||||
state.Approval = nil
|
||||
err = s.advanceCloudAgentTool(run, &state)
|
||||
if errors.Is(err, repository.ErrCreationConflict) {
|
||||
@@ -264,18 +421,7 @@ func (s *Service) executeCloudAgentRuntimeTool(ctx context.Context, userID, runI
|
||||
return nil, fmt.Errorf("%s", firstNonEmpty(run.FailureMessage, "Agent 工具执行失败"))
|
||||
}
|
||||
if content, ok := cloudAgentToolMessage(&state, call.ID); ok {
|
||||
if trimmed := strings.TrimSpace(content); trimmed == "" || trimmed == "null" {
|
||||
content = `{"error":"工具没有返回结果"}`
|
||||
}
|
||||
result := map[string]any{"content": content, "isError": cloudAgentToolContentIsError(content)}
|
||||
if call.Function.Name == "ask_user" {
|
||||
var payload map[string]any
|
||||
if json.Unmarshal([]byte(content), &payload) == nil && stringValue(payload["phase"]) == "question" {
|
||||
// ask_user 已经把本轮交给用户,Pi 不能再发起下一次模型调用。
|
||||
result["terminate"] = true
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
return cloudAgentPiToolResult(call, content), nil
|
||||
}
|
||||
if state.MediaTaskID == "" {
|
||||
return nil, fmt.Errorf("tool %s produced no result", call.Function.Name)
|
||||
@@ -289,6 +435,39 @@ func (s *Service) executeCloudAgentRuntimeTool(ctx context.Context, userID, runI
|
||||
}
|
||||
}
|
||||
|
||||
func cloudAgentToolCallsEquivalent(expected, received cloudAgentCall) bool {
|
||||
if expected.ID == "" || expected.ID != received.ID || expected.Function.Name != received.Function.Name {
|
||||
return false
|
||||
}
|
||||
var expectedArgs, receivedArgs map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(expected.Function.Arguments), &expectedArgs); err != nil || expectedArgs == nil {
|
||||
return false
|
||||
}
|
||||
if err := json.Unmarshal([]byte(received.Function.Arguments), &receivedArgs); err != nil || receivedArgs == nil {
|
||||
return false
|
||||
}
|
||||
left, err := json.Marshal(expectedArgs)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
right, err := json.Marshal(receivedArgs)
|
||||
return err == nil && string(left) == string(right)
|
||||
}
|
||||
|
||||
func cloudAgentPiToolResult(call cloudAgentCall, content string) map[string]any {
|
||||
if trimmed := strings.TrimSpace(content); trimmed == "" || trimmed == "null" {
|
||||
content = `{"error":"工具没有返回结果"}`
|
||||
}
|
||||
result := map[string]any{"content": content, "isError": cloudAgentToolContentIsError(content)}
|
||||
if call.Function.Name == "ask_user" {
|
||||
var payload map[string]any
|
||||
if json.Unmarshal([]byte(content), &payload) == nil && stringValue(payload["phase"]) == "question" {
|
||||
result["terminate"] = true
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// settleCloudAgentMedia 在媒体任务结束后用唯一的业务执行器回写画布、记录工具结果并释放
|
||||
// MediaTaskID。任务仍在生成时直接返回;并发写冲突时重读重试。
|
||||
func (s *Service) settleCloudAgentMedia(userID, runID string) error {
|
||||
@@ -366,6 +545,15 @@ func (s *Service) cloudAgentPiEvent(ctx context.Context, userID, runID string, p
|
||||
return s.handleMessageEnd(userID, runID, data)
|
||||
case "session_snapshot":
|
||||
return s.handlePiSessionSnapshot(userID, runID, data)
|
||||
case "compaction_start", "compaction_end":
|
||||
kind, eventPayload, ok := cloudAgentPiCompactionEvent(eventType, data)
|
||||
if !ok {
|
||||
return map[string]any{"ok": true}, nil
|
||||
}
|
||||
if err := s.broadcastAgentEvent(userID, runID, kind, eventPayload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true}, nil
|
||||
case "tool_call", "tool_call_start", "tool_call_end":
|
||||
return s.handleToolCall(userID, runID, data)
|
||||
case "error":
|
||||
@@ -375,6 +563,57 @@ func (s *Service) cloudAgentPiEvent(ctx context.Context, userID, runID string, p
|
||||
}
|
||||
}
|
||||
|
||||
func cloudAgentPiCompactionEvent(eventType string, data map[string]any) (string, map[string]any, bool) {
|
||||
reason := stringField(data, "reason")
|
||||
contextUsage, _ := data["contextUsage"].(map[string]any)
|
||||
switch eventType {
|
||||
case "compaction_start":
|
||||
payload := map[string]any{
|
||||
"basis": "tokens",
|
||||
"reason": reason,
|
||||
"contextUsage": contextUsage,
|
||||
}
|
||||
if compactionID := strings.TrimSpace(stringField(data, "compactionId")); compactionID != "" {
|
||||
payload["compactionId"] = compactionID
|
||||
}
|
||||
return "context_compaction_requested", payload, true
|
||||
case "compaction_end":
|
||||
payload := map[string]any{
|
||||
"reason": reason,
|
||||
"aborted": data["aborted"],
|
||||
"willRetry": data["willRetry"],
|
||||
"contextUsage": contextUsage,
|
||||
}
|
||||
if compactionID := strings.TrimSpace(stringField(data, "compactionId")); compactionID != "" {
|
||||
payload["compactionId"] = compactionID
|
||||
}
|
||||
for _, key := range []string{"tokensBefore", "estimatedTokensAfter"} {
|
||||
if value, exists := data[key]; exists {
|
||||
payload[key] = value
|
||||
}
|
||||
}
|
||||
aborted, _ := data["aborted"].(bool)
|
||||
hasResult, _ := data["hasResult"].(bool)
|
||||
errorMessage := strings.TrimSpace(stringField(data, "errorMessage"))
|
||||
if hasResult && !aborted && errorMessage == "" {
|
||||
return "context_compacted", payload, true
|
||||
}
|
||||
payload["cancelled"] = aborted
|
||||
if aborted {
|
||||
payload["text"] = "上下文压缩已取消,原有对话历史已保留"
|
||||
} else {
|
||||
if errorMessage == "" {
|
||||
errorMessage = "Pi 未能生成上下文摘要"
|
||||
}
|
||||
payload["errorMessage"] = truncateRunes(errorMessage, 1000)
|
||||
payload["text"] = "上下文压缩失败,原有对话历史已保留:" + truncateRunes(errorMessage, 1000)
|
||||
}
|
||||
return "context_compaction_failed", payload, true
|
||||
default:
|
||||
return "", nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// handlePiSessionSnapshot 持久化 Pi 原生会话 JSONL,用于审批恢复和续轮。
|
||||
func (s *Service) handlePiSessionSnapshot(userID, runID string, data map[string]any) (any, error) {
|
||||
sessionJSONL, _ := data["sessionJSONL"].(string)
|
||||
@@ -411,6 +650,22 @@ func stateCanonicalFromInput(input map[string]any) canonicalAgentRequest {
|
||||
return canonical
|
||||
}
|
||||
|
||||
func canonicalAgentRequestFromInput(input map[string]any) (canonicalAgentRequest, bool) {
|
||||
requests, ok := input["agentRequests"].(map[string]any)
|
||||
if !ok || requests["canonical"] == nil {
|
||||
return canonicalAgentRequest{}, false
|
||||
}
|
||||
raw, err := json.Marshal(requests["canonical"])
|
||||
if err != nil {
|
||||
return canonicalAgentRequest{}, false
|
||||
}
|
||||
var canonical canonicalAgentRequest
|
||||
if err := json.Unmarshal(raw, &canonical); err != nil {
|
||||
return canonicalAgentRequest{}, false
|
||||
}
|
||||
return canonical, true
|
||||
}
|
||||
|
||||
func piToolDefinitions(source []map[string]interface{}) []map[string]any {
|
||||
result := make([]map[string]any, 0, len(source))
|
||||
for _, tool := range source {
|
||||
@@ -449,11 +704,19 @@ func decodePiPayload(payload map[string]json.RawMessage, target interface{}) err
|
||||
return fmt.Errorf("failed to decode payload")
|
||||
}
|
||||
|
||||
func decodePiStringAliases(payload map[string]json.RawMessage, label string, aliases ...string) (string, error) {
|
||||
fields := make(map[string]interface{}, len(payload))
|
||||
for key, raw := range payload {
|
||||
var value interface{}
|
||||
if err := json.Unmarshal(raw, &value); err != nil {
|
||||
return "", fmt.Errorf("decode Pi field %q: %w", key, err)
|
||||
}
|
||||
fields[key] = value
|
||||
}
|
||||
return strictRuntimeStringAliases(fields, label, aliases...)
|
||||
}
|
||||
|
||||
func mustMarshal(v any) string {
|
||||
data, _ := json.Marshal(v)
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func generateID() string {
|
||||
return fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
}
|
||||
Reference in new issue
Block a user