diff --git a/internal/agent/generated_context.go b/internal/agent/generated_context.go index 82b1db7b..f0a0794a 100644 --- a/internal/agent/generated_context.go +++ b/internal/agent/generated_context.go @@ -5,7 +5,8 @@ package agent const GeneratedContextTypeKey = "_csai_generated_context_type" const PlanExecuteExecutorContext = "plan_execute_executor" const PlanExecuteReplannerContext = "plan_execute_replanner" +const OutputTruncationContinueContext = "output_truncation_continue" func IsGeneratedExecutionContext(kind string) bool { - return kind == PlanExecuteExecutorContext || kind == PlanExecuteReplannerContext + return kind == PlanExecuteExecutorContext || kind == PlanExecuteReplannerContext || kind == OutputTruncationContinueContext } diff --git a/internal/agentfinalizer/runtime_status_test.go b/internal/agentfinalizer/runtime_status_test.go index 14a6189a..72dfd3cf 100644 --- a/internal/agentfinalizer/runtime_status_test.go +++ b/internal/agentfinalizer/runtime_status_test.go @@ -23,3 +23,11 @@ func TestTruncatedOutputRetainsReasonWithoutFinalText(t *testing.T) { t.Fatalf("unexpected delivery: %+v", decision) } } + +func TestTruncatedOutputKeepsCandidateText(t *testing.T) { + result := &multiagent.RunResult{Response: "已生成的前半段", RuntimeStatus: StatusBlocked, RuntimeCompletionReason: multiagent.ReasonModelOutputTruncated} + decision := FromRunResult(nil, result, Input{}) + if decision.Finalizable || decision.Finalized || decision.FinalText != "已生成的前半段" || decision.CompletionReason != multiagent.ReasonModelOutputTruncated { + t.Fatalf("unexpected delivery: %+v", decision) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 60787d45..e6cd7382 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -223,6 +223,8 @@ type AgentTuningConfig struct { RunRetryMaxBackoffSec int `yaml:"run_retry_max_backoff_sec,omitempty" json:"run_retry_max_backoff_sec,omitempty"` // EmptyResponseContinueMaxAttempts Run 成功但未捕获助手正文时 Handler 层退避续跑次数;0=默认 5。 EmptyResponseContinueMaxAttempts int `yaml:"empty_response_continue_max_attempts,omitempty" json:"empty_response_continue_max_attempts,omitempty"` + // OutputTruncationContinueMaxAttempts 模型输出触达长度上限后的自动续写次数;0=默认 2,小于 0 关闭,大于 5 按 5。 + OutputTruncationContinueMaxAttempts int `yaml:"output_truncation_continue_max_attempts,omitempty" json:"output_truncation_continue_max_attempts,omitempty"` // TaskToolDescriptionPrefix when non-empty sets deep.Config TaskToolDescriptionGenerator (sub-agent names appended). TaskToolDescriptionPrefix string `yaml:"task_tool_description_prefix,omitempty" json:"task_tool_description_prefix,omitempty"` } diff --git a/internal/handler/finalization_helpers.go b/internal/handler/finalization_helpers.go index ddd92de3..6ab30092 100644 --- a/internal/handler/finalization_helpers.go +++ b/internal/handler/finalization_helpers.go @@ -190,22 +190,19 @@ func finalizationBlockedMessage(d agentfinalizer.Decision) string { if d.CompletionReason == "workflow_rejected" && strings.TrimSpace(d.FinalText) != "" { return d.FinalText } - var notice string - switch d.CompletionReason { - case agentfinalizer.ReasonPendingToolsCancelled: - notice = "收尾时取消了仍在运行的工具,任务未完成。" - case multiagent.ReasonUnfinishedPlan: - notice = unfinishedPlanNotice(d.UnfinishedPlanSteps) + if d.CompletionReason == multiagent.ReasonUnfinishedPlan { + notice := unfinishedPlanNotice(d.UnfinishedPlanSteps) if text := strings.TrimSpace(d.FinalText); text != "" { return notice + "\n\n**本轮已生成的内容(阶段性结果)**\n\n" + text } return notice - case multiagent.ReasonModelOutputTruncated: - notice = "模型输出达到长度上限,本轮回复未完成。" - default: - notice = "任务尚未达到最终回复条件,暂不生成成功结论。" } - parts := []string{notice} + notice, keepText := finalizationBlockNotice(d) + parts := make([]string, 0, 4) + if keepText { + parts = append(parts, strings.TrimSpace(d.FinalText), "---") + } + parts = append(parts, notice) if d.CompletionReason != "" { parts = append(parts, "原因: "+d.CompletionReason) } @@ -218,6 +215,20 @@ func finalizationBlockedMessage(d agentfinalizer.Decision) string { return strings.Join(parts, "\n") } +func finalizationBlockNotice(d agentfinalizer.Decision) (string, bool) { + switch d.CompletionReason { + case agentfinalizer.ReasonPendingToolsCancelled: + return "收尾时取消了仍在运行的工具,任务未完成。", false + case multiagent.ReasonModelOutputTruncated: + if strings.TrimSpace(d.FinalText) != "" { + return "模型输出达到长度上限,已保留以上已生成内容。本轮回复仍未完成。可发送「继续」接着生成。", true + } + return "模型输出达到长度上限,本轮回复未完成。", false + default: + return "任务尚未达到最终回复条件,暂不生成成功结论。", false + } +} + func finalizationResponsePayload(d agentfinalizer.Decision, extra map[string]interface{}) map[string]interface{} { return agentfinalizer.ResponsePayload(d, extra) } diff --git a/internal/handler/finalization_truncation_test.go b/internal/handler/finalization_truncation_test.go new file mode 100644 index 00000000..184a7e19 --- /dev/null +++ b/internal/handler/finalization_truncation_test.go @@ -0,0 +1,95 @@ +package handler + +import ( + "path/filepath" + "strings" + "testing" + + "cyberstrike-ai/internal/agentfinalizer" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/multiagent" + + "go.uber.org/zap" +) + +func TestFinalizationBlockedMessageKeepsTruncatedText(t *testing.T) { + decision := agentfinalizer.Decision{ + Status: agentfinalizer.StatusBlocked, + CompletionReason: multiagent.ReasonModelOutputTruncated, + FinalText: "已经写好的前半段。", + MissingChecks: []string{"agent run status is blocked"}, + } + got := finalizationBlockedMessage(decision) + if !strings.Contains(got, "已经写好的前半段。") || !strings.Contains(got, "\n---\n") || !strings.Contains(got, "可发送「继续」接着生成。") { + t.Fatalf("truncated text was discarded: %q", got) + } + if strings.TrimSpace(got) == "模型输出达到长度上限,本轮回复未完成。\n原因: model_output_truncated\n缺失检查: agent run status is blocked" { + t.Fatal("blocked notice replaced the generated text") + } + + empty := finalizationBlockedMessage(agentfinalizer.Decision{ + Status: agentfinalizer.StatusBlocked, + CompletionReason: multiagent.ReasonModelOutputTruncated, + MissingChecks: []string{"agent run status is blocked"}, + }) + if strings.Contains(empty, "---") || !strings.HasPrefix(empty, "模型输出达到长度上限,本轮回复未完成。") { + t.Fatalf("empty truncation should stay a notice: %q", empty) + } + + unfinished := finalizationBlockedMessage(agentfinalizer.Decision{ + Status: agentfinalizer.StatusBlocked, + CompletionReason: multiagent.ReasonUnfinishedPlan, + FinalText: "计划正文", + }) + if !strings.Contains(unfinished, "计划正文") || !strings.Contains(unfinished, "未完成") || strings.Contains(unfinished, "长度上限") { + t.Fatalf("unfinished plan notice changed: %q", unfinished) + } + + hitl := finalizationBlockedMessage(agentfinalizer.Decision{ + Status: agentfinalizer.StatusAwaitingHITL, + CompletionReason: agentfinalizer.ReasonAwaitingHITL, + FinalText: "等待审批的正文", + }) + if strings.Contains(hitl, "等待审批的正文") { + t.Fatalf("awaiting HITL should keep its status notice: %q", hitl) + } +} + +func TestPersistTruncatedFinalizationKeepsGeneratedText(t *testing.T) { + logger := zap.NewNop() + db, err := database.NewDB(filepath.Join(t.TempDir(), "truncation.db"), logger) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + conv, err := db.CreateConversation("truncation", database.ConversationCreateMeta{}) + if err != nil { + t.Fatal(err) + } + msg, err := db.AddMessage(conv.ID, "assistant", "占位", nil) + if err != nil { + t.Fatal(err) + } + h := &AgentHandler{db: db, logger: logger} + decision := agentfinalizer.Decision{ + Status: agentfinalizer.StatusBlocked, + CompletionReason: multiagent.ReasonModelOutputTruncated, + FinalText: "已经写好的前半段。", + MissingChecks: []string{"agent run status is blocked"}, + Finalizable: false, + } + h.persistFinalizationDecision(conv.ID, msg.ID, "single", nil, "", decision) + messages, err := db.GetMessages(conv.ID) + if err != nil { + t.Fatal(err) + } + var stored string + for _, message := range messages { + if message.ID == msg.ID { + stored = message.Content + } + } + if !strings.Contains(stored, "已经写好的前半段。") || !strings.Contains(stored, multiagent.ReasonModelOutputTruncated) { + t.Fatalf("stored content discarded the partial answer: %q", stored) + } +} diff --git a/internal/multiagent/output_truncation.go b/internal/multiagent/output_truncation.go new file mode 100644 index 00000000..ef2f273b --- /dev/null +++ b/internal/multiagent/output_truncation.go @@ -0,0 +1,464 @@ +package multiagent + +import ( + "context" + "encoding/json" + "strings" + + "cyberstrike-ai/internal/agent" + "cyberstrike-ai/internal/config" +) + +const ( + defaultOutputTruncationContinueMaxAttempts = 2 + outputTruncationContinueAttemptCap = 5 + truncationOverlapMinRunes = 3 + truncationOverlapMaxRunes = 480 + outputTruncationContinueMarker = "【系统自动续写 / Auto continue】" +) + +// OutputTruncationContinueMaxAttemptsFromConfig 是长度截断后的自动续写上限。 +// 0 使用默认 2 次;小于 0 关闭;大于 5 按 5,避免无限续写。 +func OutputTruncationContinueMaxAttemptsFromConfig(mw *config.AgentTuningConfig) int { + if mw == nil || mw.OutputTruncationContinueMaxAttempts == 0 { + return defaultOutputTruncationContinueMaxAttempts + } + if mw.OutputTruncationContinueMaxAttempts < 0 { + return 0 + } + if mw.OutputTruncationContinueMaxAttempts > outputTruncationContinueAttemptCap { + return outputTruncationContinueAttemptCap + } + return mw.OutputTruncationContinueMaxAttempts +} + +func outputTruncationContinueInstruction() string { + return outputTruncationContinueMarker + "\n上一段助手输出因达到长度上限在中途截断。请从中断处紧接续写,不要重复已写出的正文,不要重新开题,也不要总结前文。若内容已经完整,直接结束。" +} + +func isOutputContinuationPrompt(content string) bool { + return strings.Contains(content, outputTruncationContinueMarker) +} + +// shouldContinueTruncatedOutput 只对仍可恢复的长度截断续写。 +// unfinished_plan、awaiting_hitl、cancelled、failed 都不走这条路径。 +func shouldContinueTruncatedOutput(result *RunResult, attempt, max int) bool { + if result == nil || max <= 0 || attempt >= max { + return false + } + switch result.RuntimeStatus { + case "cancelled", "failed", "awaiting_hitl": + return false + } + if result.RuntimeCompletionReason != ReasonModelOutputTruncated { + return false + } + if strings.TrimSpace(result.Response) != "" { + return true + } + return hasUsableTruncationTrace(result.LastAgentTraceInput) +} + +func hasUsableTruncationTrace(historyJSON string) bool { + msgs, ok := parseHistory(historyJSON) + return ok && len(msgs) > 0 +} + +// continueAfterOutputTruncation 在首次截断之后续写,并把各段正文、执行 ID 和轨迹合成一个结果。 +// next 收到的 history 已补上被截断的助手正文;instruction 只进入下一次模型请求,不写入消息表。 +func continueAfterOutputTruncation( + ctx context.Context, + maxAttempts int, + initial *RunResult, + next func(ctx context.Context, attempt int, history, instruction string) (*RunResult, error), + notify func(attempt, maxAttempts int), +) (*RunResult, error) { + if initial == nil { + return nil, nil + } + if ctx == nil { + ctx = context.Background() + } + merged := cloneRunResult(initial) + fragment := initial.Response + merged.LastAgentTraceInput = prepareTruncationHistory(merged.LastAgentTraceInput, fragment, "") + latest := merged + instruction := outputTruncationContinueInstruction() + for attempt := 1; attempt <= maxAttempts; attempt++ { + if !shouldContinueTruncatedOutput(latest, attempt-1, maxAttempts) { + break + } + if err := ctx.Err(); err != nil { + return merged, err + } + if notify != nil { + notify(attempt, maxAttempts) + } + history := prepareTruncationHistory(merged.LastAgentTraceInput, fragment, "") + seg, segErr := next(ctx, attempt, history, instruction) + if segErr != nil { + if seg != nil { + merged = mergeTruncatedSegment(merged, seg, fragment, "") + } + return merged, segErr + } + if seg == nil { + return merged, nil + } + previous := merged.Response + merged = mergeTruncatedSegment(merged, seg, fragment, "") + fragment = seg.Response + latest = seg + if seg.RuntimeCompletionReason == ReasonModelOutputTruncated && merged.Response == previous { + break + } + } + merged.LastAgentTraceInput = tagOutputContinuationPrompts(merged.LastAgentTraceInput) + return merged, nil +} + +func cloneRunResult(in *RunResult) *RunResult { + if in == nil { + return nil + } + out := *in + out.UnfinishedPlanSteps = append([]PlanStep(nil), in.UnfinishedPlanSteps...) + out.MCPExecutionIDs = append([]string(nil), in.MCPExecutionIDs...) + out.EvidenceRefs = append([]string(nil), in.EvidenceRefs...) + out.PendingExecutionIDs = append([]string(nil), in.PendingExecutionIDs...) + out.MissingChecks = append([]string(nil), in.MissingChecks...) + return &out +} + +func mergeTruncatedSegment(base, next *RunResult, priorFragment, reasoning string) *RunResult { + if base == nil { + return cloneRunResult(next) + } + if next == nil { + return cloneRunResult(base) + } + out := cloneRunResult(next) + out.Response = stitchOutputSegments(base.Response, next.Response) + out.MCPExecutionIDs = mergeExecutionIDs(base.MCPExecutionIDs, next.MCPExecutionIDs) + out.LastAgentTraceInput = mergeTruncationHistories(base.LastAgentTraceInput, next.LastAgentTraceInput, priorFragment, reasoning) + if strings.TrimSpace(next.Response) != "" { + out.LastAgentTraceOutput = next.Response + } else if strings.TrimSpace(base.LastAgentTraceOutput) != "" { + out.LastAgentTraceOutput = base.LastAgentTraceOutput + } + return out +} + +func mergeExecutionIDs(parts ...[]string) []string { + seen := make(map[string]struct{}) + out := make([]string, 0) + for _, part := range parts { + for _, id := range part { + id = strings.TrimSpace(id) + if id == "" { + continue + } + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + out = append(out, id) + } + } + return out +} + +func stitchOutputSegments(base, next string) string { + if base == "" { + return next + } + if next == "" { + return base + } + if strings.HasPrefix(next, base) { + next = next[len(base):] + } else { + br := []rune(base) + nr := []rune(next) + limit := len(br) + if len(nr) < limit { + limit = len(nr) + } + if limit > truncationOverlapMaxRunes { + limit = truncationOverlapMaxRunes + } + cut := 0 + for n := limit; n >= truncationOverlapMinRunes; n-- { + if string(br[len(br)-n:]) == string(nr[:n]) { + cut = n + break + } + } + if cut > 0 { + next = string(nr[cut:]) + } + } + if next == "" { + return base + } + return joinOutputBoundary(base, next) +} + +func joinOutputBoundary(base, next string) string { + baseTrimmed := strings.TrimRight(base, " \t") + nextTrimmed := strings.TrimLeft(next, " \t") + hadSpace := baseTrimmed != base || nextTrimmed != next + for strings.HasSuffix(baseTrimmed, "\n") && strings.HasPrefix(nextTrimmed, "\n") { + nextTrimmed = strings.TrimPrefix(nextTrimmed, "\n") + } + if strings.HasSuffix(baseTrimmed, "\n") || strings.HasPrefix(nextTrimmed, "\n") { + return baseTrimmed + nextTrimmed + } + if hadSpace { + return baseTrimmed + " " + nextTrimmed + } + return base + next +} + +func prepareTruncationHistory(historyJSON, fragment, reasoning string) string { + return tagOutputContinuationPrompts(ensureTruncatedAssistantHistory(historyJSON, fragment, reasoning)) +} + +func ensureTruncatedAssistantHistory(historyJSON, fragment, reasoning string) string { + if strings.TrimSpace(fragment) == "" && strings.TrimSpace(reasoning) == "" { + return historyJSON + } + msgs, ok := parseHistory(historyJSON) + if !ok { + if strings.TrimSpace(fragment) == "" { + return historyJSON + } + msgs = nil + } + changed := false + if idx := lastAssistantIndex(msgs); idx >= 0 && !hasToolCalls(msgs[idx]) { + content := messageContent(msgs[idx]) + covered, upgrade := fragmentCovered(content, fragment) + if covered { + if upgrade && strings.TrimSpace(fragment) != "" { + msgs[idx]["content"] = fragment + changed = true + } + if fillReasoning(msgs[idx], reasoning) { + changed = true + } + if !changed { + return historyJSON + } + return marshalHistory(msgs) + } + } + for _, msg := range msgs { + role, _ := msg["role"].(string) + if !strings.EqualFold(role, "assistant") || hasToolCalls(msg) { + continue + } + content := messageContent(msg) + if content == fragment || strings.TrimSpace(content) == strings.TrimSpace(fragment) || (fragment != "" && strings.HasSuffix(content, fragment)) { + if fillReasoning(msg, reasoning) { + return marshalHistory(msgs) + } + return historyJSON + } + } + if strings.TrimSpace(fragment) == "" { + return historyJSON + } + msg := map[string]any{"role": "assistant", "content": fragment} + if strings.TrimSpace(reasoning) != "" { + msg["reasoning_content"] = reasoning + } + return marshalHistory(append(msgs, msg)) +} + +func mergeTruncationHistories(prev, next, fragment, reasoning string) string { + prev = ensureTruncatedAssistantHistory(prev, fragment, reasoning) + prevMsgs, prevOK := parseHistory(prev) + nextMsgs, nextOK := parseHistory(next) + if !nextOK || len(nextMsgs) == 0 { + return tagOutputContinuationPrompts(prev) + } + if !prevOK { + return tagOutputContinuationPrompts(ensureTruncatedAssistantHistory(next, fragment, reasoning)) + } + merged := mergeHistoryMessages(prevMsgs, nextMsgs) + return tagOutputContinuationPrompts(ensureTruncatedAssistantHistory(marshalHistory(merged), fragment, reasoning)) +} + +func mergeHistoryMessages(prev, next []map[string]any) []map[string]any { + out := make([]map[string]any, 0, len(prev)+len(next)) + for _, msg := range prev { + out = append(out, cloneHistoryMessage(msg)) + } + for _, msg := range next { + if i := indexSameMessage(out, msg); i >= 0 { + mergeMessageFields(out[i], msg) + continue + } + out = append(out, cloneHistoryMessage(msg)) + } + return out +} + +func indexSameMessage(msgs []map[string]any, candidate map[string]any) int { + for i, msg := range msgs { + if sameHistoryMessage(msg, candidate) { + return i + } + } + return -1 +} + +func sameHistoryMessage(a, b map[string]any) bool { + roleA, _ := a["role"].(string) + roleB, _ := b["role"].(string) + if !strings.EqualFold(strings.TrimSpace(roleA), strings.TrimSpace(roleB)) { + return false + } + if strings.EqualFold(roleA, "tool") { + idA, _ := a["tool_call_id"].(string) + idB, _ := b["tool_call_id"].(string) + return idA != "" && idA == idB + } + return messageContent(a) == messageContent(b) +} + +func mergeMessageFields(dst, src map[string]any) { + if strings.TrimSpace(messageString(dst["reasoning_content"])) == "" { + if rc := strings.TrimSpace(messageString(src["reasoning_content"])); rc != "" { + dst["reasoning_content"] = rc + } + } + dstContent := messageContent(dst) + srcContent := messageContent(src) + if !hasToolCalls(dst) && !hasToolCalls(src) && dstContent != "" && strings.HasPrefix(srcContent, dstContent) && len(srcContent) > len(dstContent) { + dst["content"] = srcContent + } + if dst["extra"] == nil && src["extra"] != nil { + dst["extra"] = src["extra"] + } +} + +func tagOutputContinuationPrompts(historyJSON string) string { + msgs, ok := parseHistory(historyJSON) + if !ok || len(msgs) == 0 { + return historyJSON + } + changed := false + for _, msg := range msgs { + role, _ := msg["role"].(string) + if !strings.EqualFold(role, "user") || !isOutputContinuationPrompt(messageContent(msg)) { + continue + } + extra, _ := msg["extra"].(map[string]any) + if extra == nil { + extra = map[string]any{} + } + if extra[agent.GeneratedContextTypeKey] == agent.OutputTruncationContinueContext { + msg["extra"] = extra + continue + } + extra[agent.GeneratedContextTypeKey] = agent.OutputTruncationContinueContext + msg["extra"] = extra + changed = true + } + if !changed { + return historyJSON + } + return marshalHistory(msgs) +} + +func fillReasoning(msg map[string]any, reasoning string) bool { + if strings.TrimSpace(reasoning) == "" || strings.TrimSpace(messageString(msg["reasoning_content"])) != "" { + return false + } + msg["reasoning_content"] = reasoning + return true +} + +func fragmentCovered(content, fragment string) (covered bool, upgrade bool) { + if strings.TrimSpace(fragment) == "" { + return true, false + } + if content == fragment || strings.TrimSpace(content) == strings.TrimSpace(fragment) || strings.HasSuffix(content, fragment) { + return true, false + } + if content != "" && strings.HasPrefix(fragment, content) { + return true, true + } + return false, false +} + +func lastAssistantIndex(msgs []map[string]any) int { + for i := len(msgs) - 1; i >= 0; i-- { + role, _ := msgs[i]["role"].(string) + if strings.EqualFold(role, "assistant") { + return i + } + } + return -1 +} + +func hasToolCalls(msg map[string]any) bool { + switch calls := msg["tool_calls"].(type) { + case []any: + return len(calls) > 0 + case []map[string]any: + return len(calls) > 0 + default: + return false + } +} + +func messageContent(msg map[string]any) string { + return messageString(msg["content"]) +} + +func messageString(value any) string { + text, _ := value.(string) + return text +} + +func parseHistory(historyJSON string) ([]map[string]any, bool) { + historyJSON = strings.TrimSpace(historyJSON) + if historyJSON == "" || historyJSON == "null" { + return nil, true + } + var msgs []map[string]any + if err := json.Unmarshal([]byte(historyJSON), &msgs); err != nil { + return nil, false + } + return msgs, true +} + +func marshalHistory(msgs []map[string]any) string { + if msgs == nil { + msgs = []map[string]any{} + } + body, err := json.Marshal(msgs) + if err != nil { + return "[]" + } + return string(body) +} + +func cloneHistoryMessage(msg map[string]any) map[string]any { + body, err := json.Marshal(msg) + if err != nil { + out := make(map[string]any, len(msg)) + for key, value := range msg { + out[key] = value + } + return out + } + var out map[string]any + if json.Unmarshal(body, &out) != nil || out == nil { + return msg + } + return out +} diff --git a/internal/multiagent/output_truncation_test.go b/internal/multiagent/output_truncation_test.go new file mode 100644 index 00000000..258abccd --- /dev/null +++ b/internal/multiagent/output_truncation_test.go @@ -0,0 +1,272 @@ +package multiagent + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "cyberstrike-ai/internal/agent" + "cyberstrike-ai/internal/config" +) + +func TestOutputTruncationContinueMaxAttemptsFromConfig(t *testing.T) { + if got := OutputTruncationContinueMaxAttemptsFromConfig(nil); got != defaultOutputTruncationContinueMaxAttempts { + t.Fatalf("default: got %d", got) + } + if got := OutputTruncationContinueMaxAttemptsFromConfig(&config.AgentTuningConfig{}); got != 2 { + t.Fatalf("zero: got %d", got) + } + if got := OutputTruncationContinueMaxAttemptsFromConfig(&config.AgentTuningConfig{OutputTruncationContinueMaxAttempts: -1}); got != 0 { + t.Fatalf("disabled: got %d", got) + } + if got := OutputTruncationContinueMaxAttemptsFromConfig(&config.AgentTuningConfig{OutputTruncationContinueMaxAttempts: 3}); got != 3 { + t.Fatalf("custom: got %d", got) + } + if got := OutputTruncationContinueMaxAttemptsFromConfig(&config.AgentTuningConfig{OutputTruncationContinueMaxAttempts: 99}); got != outputTruncationContinueAttemptCap { + t.Fatalf("cap: got %d", got) + } +} + +func TestStitchOutputSegmentsJoinsOverlapAndWhitespace(t *testing.T) { + if got := stitchOutputSegments("Alpha-", "Beta."); got != "Alpha-Beta." { + t.Fatalf("direct join: %q", got) + } + if got := stitchOutputSegments("Hello wor", "world"); got != "Hello world" { + t.Fatalf("overlap: %q", got) + } + if got := stitchOutputSegments("First,", "First,"); got != "First," { + t.Fatalf("duplicate: %q", got) + } + if got := stitchOutputSegments("段落结束\n\n", "\n\n下一段"); got != "段落结束\n\n下一段" { + t.Fatalf("blank lines: %q", got) + } + if got := stitchOutputSegments("这里是已经写完的前半段内容", "前半段内容以及后续"); got != "这里是已经写完的前半段内容以及后续" { + t.Fatalf("rune overlap: %q", got) + } + if got := stitchOutputSegments("Hello ", " world"); got != "Hello world" { + t.Fatalf("space: %q", got) + } +} + +func TestContinueAfterOutputTruncationStitchesTextAndExecutionIDs(t *testing.T) { + initial := &RunResult{ + RuntimeStatus: "blocked", + RuntimeCompletionReason: ReasonModelOutputTruncated, + Status: "output_truncated", + Response: "Alpha-", + LastAgentTraceOutput: "Alpha-", + LastAgentTraceInput: `[{"role":"user","content":"write"}]`, + MCPExecutionIDs: []string{"exec-1"}, + } + calls := 0 + var sawFragment bool + var events []int + out, err := continueAfterOutputTruncation(context.Background(), 2, initial, func(_ context.Context, attempt int, history, instruction string) (*RunResult, error) { + calls++ + if attempt != 1 { + t.Fatalf("attempt = %d", attempt) + } + if !strings.Contains(history, "Alpha-") { + t.Fatalf("history lost the truncated assistant: %s", history) + } + sawFragment = true + if !strings.Contains(instruction, outputTruncationContinueMarker) { + t.Fatalf("instruction = %q", instruction) + } + historyBody, err := json.Marshal([]map[string]string{ + {"role": "user", "content": "write"}, + {"role": "assistant", "content": "Alpha-", "reasoning_content": "think-1"}, + {"role": "user", "content": instruction}, + {"role": "assistant", "content": "Beta.", "reasoning_content": "think-2"}, + }) + if err != nil { + t.Fatal(err) + } + return &RunResult{ + RuntimeStatus: "completed", + Status: "completed", + Response: "Beta.", + LastAgentTraceOutput: "Beta.", + LastAgentTraceInput: string(historyBody), + MCPExecutionIDs: []string{"exec-2"}, + }, nil + }, func(attempt, maxAttempts int) { + events = append(events, attempt) + if maxAttempts != 2 { + t.Fatalf("max = %d", maxAttempts) + } + }) + if err != nil { + t.Fatal(err) + } + if !sawFragment || calls != 1 || len(events) != 1 { + t.Fatalf("calls=%d events=%v saw=%v", calls, events, sawFragment) + } + if out.RuntimeStatus != "completed" || out.Response != "Alpha-Beta." { + t.Fatalf("stitched result: %+v", out) + } + if strings.Join(out.MCPExecutionIDs, ",") != "exec-1,exec-2" { + t.Fatalf("ids: %#v", out.MCPExecutionIDs) + } + if out.LastAgentTraceOutput != "Beta." { + t.Fatalf("trace output should stay the last segment: %q", out.LastAgentTraceOutput) + } + if !strings.Contains(out.LastAgentTraceInput, "think-1") || !strings.Contains(out.LastAgentTraceInput, "think-2") { + t.Fatalf("reasoning was dropped: %s", out.LastAgentTraceInput) + } + parsed, err := agent.ParseTraceMessages(out.LastAgentTraceInput) + if err != nil { + t.Fatal(err) + } + var prompt agent.ChatMessage + found := false + for _, msg := range parsed { + if strings.Contains(msg.Content, outputTruncationContinueMarker) { + prompt = msg + found = true + } + } + if !found || prompt.GeneratedContextKind != agent.OutputTruncationContinueContext { + t.Fatalf("continuation prompt was not marked generated: %+v", parsed) + } + provider, err := piHistoryJSON(parsed) + if err != nil { + t.Fatal(err) + } + var replayed []agent.ChatMessage + if err := jsonUnmarshalHistory(provider, &replayed); err != nil { + t.Fatal(err) + } + for _, msg := range replayed { + if msg.Role == "user" && strings.Contains(msg.Content, outputTruncationContinueMarker) { + t.Fatalf("continuation prompt replayed as a user turn: %+v", replayed) + } + } +} + +func TestContinueAfterOutputTruncationExhaustedKeepsPartial(t *testing.T) { + initial := &RunResult{ + RuntimeStatus: "blocked", + RuntimeCompletionReason: ReasonModelOutputTruncated, + Response: "这里是已经写完的前半段内容", + MCPExecutionIDs: []string{"exec-1"}, + LastAgentTraceInput: `[{"role":"user","content":"write"}]`, + } + calls := 0 + out, err := continueAfterOutputTruncation(context.Background(), 1, initial, func(context.Context, int, string, string) (*RunResult, error) { + calls++ + return &RunResult{ + RuntimeStatus: "blocked", + RuntimeCompletionReason: ReasonModelOutputTruncated, + Status: "output_truncated", + Response: "前半段内容以及后续", + MCPExecutionIDs: []string{"exec-2"}, + LastAgentTraceInput: `[{"role":"assistant","content":"前半段内容以及后续"}]`, + }, nil + }, nil) + if err != nil { + t.Fatal(err) + } + if calls != 1 { + t.Fatalf("calls = %d", calls) + } + if out.RuntimeStatus != "blocked" || out.RuntimeCompletionReason != ReasonModelOutputTruncated { + t.Fatalf("status: %+v", out) + } + if out.Response != "这里是已经写完的前半段内容以及后续" { + t.Fatalf("response = %q", out.Response) + } + if strings.Join(out.MCPExecutionIDs, ",") != "exec-1,exec-2" { + t.Fatalf("ids: %#v", out.MCPExecutionIDs) + } + if !strings.Contains(out.LastAgentTraceInput, "这里是已经写完的前半段内容") { + t.Fatalf("degraded trace lost the first fragment: %s", out.LastAgentTraceInput) + } +} + +func TestContinueAfterOutputTruncationStopsWhenContextCanceled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + initial := &RunResult{ + RuntimeStatus: "blocked", + RuntimeCompletionReason: ReasonModelOutputTruncated, + Response: "部分内容", + LastAgentTraceInput: `[{"role":"assistant","content":"部分内容"}]`, + } + calls := 0 + out, err := continueAfterOutputTruncation(ctx, 2, initial, func(context.Context, int, string, string) (*RunResult, error) { + calls++ + return &RunResult{Response: "不应出现"}, nil + }, nil) + if !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v", err) + } + if calls != 0 { + t.Fatalf("continuation started after cancel: %d", calls) + } + if out.Response != "部分内容" { + t.Fatalf("partial text lost: %q", out.Response) + } +} + +func TestContinueAfterOutputTruncationAbortsInFlightSegment(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + started := make(chan struct{}) + go func() { + <-started + cancel() + }() + initial := &RunResult{ + RuntimeStatus: "blocked", + RuntimeCompletionReason: ReasonModelOutputTruncated, + Response: "AAA", + LastAgentTraceInput: `[{"role":"assistant","content":"AAA"}]`, + } + calls := 0 + out, err := continueAfterOutputTruncation(ctx, 3, initial, func(waitCtx context.Context, _ int, _, _ string) (*RunResult, error) { + calls++ + close(started) + <-waitCtx.Done() + return nil, waitCtx.Err() + }, nil) + if !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v", err) + } + if calls != 1 { + t.Fatalf("calls = %d", calls) + } + if out.Response != "AAA" { + t.Fatalf("response = %q", out.Response) + } +} + +func TestShouldContinueTruncatedOutputSkipsUnfinishedPlanAndHITL(t *testing.T) { + cases := []*RunResult{ + {RuntimeStatus: "blocked", RuntimeCompletionReason: ReasonUnfinishedPlan, Response: "计划还在"}, + {RuntimeStatus: "awaiting_hitl", RuntimeCompletionReason: "awaiting_hitl", Response: "等待审批"}, + {RuntimeStatus: "cancelled", RuntimeCompletionReason: "cancelled", Response: "已取消"}, + {RuntimeStatus: "failed", RuntimeCompletionReason: "failed", Response: "失败"}, + {RuntimeStatus: "completed", RuntimeCompletionReason: "verified", Response: "完成"}, + } + for _, result := range cases { + if shouldContinueTruncatedOutput(result, 0, 2) { + t.Fatalf("continued for %+v", result) + } + } + truncated := &RunResult{RuntimeStatus: "blocked", RuntimeCompletionReason: ReasonModelOutputTruncated, Response: "半段"} + if !shouldContinueTruncatedOutput(truncated, 0, 2) { + t.Fatal("truncated output should continue") + } + if shouldContinueTruncatedOutput(truncated, 2, 2) { + t.Fatal("attempt cap ignored") + } + if shouldContinueTruncatedOutput(&RunResult{RuntimeStatus: "blocked", RuntimeCompletionReason: ReasonModelOutputTruncated, Response: " "}, 0, 2) { + t.Fatal("empty truncation has no context") + } +} + +func jsonUnmarshalHistory(body []byte, dest *[]agent.ChatMessage) error { + return json.Unmarshal(body, dest) +} diff --git a/internal/multiagent/pi_integration_test.go b/internal/multiagent/pi_integration_test.go index 9cc6799c..72ab2ad5 100644 --- a/internal/multiagent/pi_integration_test.go +++ b/internal/multiagent/pi_integration_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "io" "net/http" "net/http/httptest" "os" @@ -699,6 +700,7 @@ func TestPiPlanExecuteRetainsSubmittedDraftForUnfinishedPlan(t *testing.T) { func TestPiReportsTruncatedModelOutput(t *testing.T) { cfg := piTestConfig(t) + cfg.MultiAgent.Runtime.OutputTruncationContinueMaxAttempts = -1 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/event-stream") fmt.Fprint(w, `data: {"id":"fixture","model":"fixture","choices":[{"index":0,"delta":{"role":"assistant","content":"First,"},"finish_reason":"length"}]}`+"\n\ndata: [DONE]\n\n") @@ -718,6 +720,72 @@ func TestPiReportsTruncatedModelOutput(t *testing.T) { } } +func TestPiContinuesTruncatedModelOutput(t *testing.T) { + cfg := piTestConfig(t) + cfg.MultiAgent.Runtime.OutputTruncationContinueMaxAttempts = 2 + var calls atomic.Int32 + var requestsMu sync.Mutex + var requests []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + requestsMu.Lock() + requests = append(requests, string(body)) + n := calls.Add(1) + requestsMu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + if n == 1 { + fmt.Fprint(w, `data: {"id":"fixture","model":"fixture","choices":[{"index":0,"delta":{"role":"assistant","content":"Alpha-"},"finish_reason":"length"}]}`+"\n\ndata: [DONE]\n\n") + return + } + fmt.Fprint(w, `data: {"id":"fixture","model":"fixture","choices":[{"index":0,"delta":{"role":"assistant","content":"Beta."},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n") + })) + defer server.Close() + cfg.OpenAI.BaseURL = server.URL + "/v1" + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + var continued atomic.Int32 + var continuationAccumulated []string + result, err := RunSingleAgent(ctx, cfg, &cfg.MultiAgent, piTestAgent(cfg, nil), nil, zap.NewNop(), "truncation-continue", "", "Write the notes.", nil, nil, + func(kind, _ string, data interface{}) { + payload, _ := data.(map[string]any) + switch kind { + case "agent_output_truncated_continue": + continued.Add(1) + if payload["attempt"] != 1 || payload["maxAttempts"] != 2 || payload["contextPersisted"] != false { + t.Errorf("continue event: %#v", payload) + } + case "response_delta": + if continued.Load() == 0 { + return + } + acc, _ := payload["accumulated"].(string) + continuationAccumulated = append(continuationAccumulated, acc) + } + }, nil, "") + if err != nil { + t.Fatal(err) + } + if result.RuntimeStatus != "completed" || result.Response != "Alpha-Beta." || continued.Load() != 1 || calls.Load() != 2 { + t.Fatalf("result=%+v calls=%d events=%d", result, calls.Load(), continued.Load()) + } + if len(continuationAccumulated) == 0 { + t.Fatal("expected continuation response_delta events") + } + for _, acc := range continuationAccumulated { + if acc == "Beta." || !strings.Contains(acc, "Alpha-") { + t.Fatalf("continuation accumulated dropped the earlier text: %q (all=%#v)", acc, continuationAccumulated) + } + } + if last := continuationAccumulated[len(continuationAccumulated)-1]; !strings.Contains(last, "Alpha-Beta.") { + t.Fatalf("continuation accumulated = %q, want stitched Alpha-Beta.", last) + } + requestsMu.Lock() + defer requestsMu.Unlock() + if len(requests) < 2 || !strings.Contains(requests[1], "Alpha-") || !strings.Contains(requests[1], "系统自动续写") { + t.Fatalf("continuation request lost the truncated text: %s", requests[1]) + } +} + func TestPiReportsIncompleteModelStreamRetries(t *testing.T) { cfg := piTestConfig(t) cfg.MultiAgent.Runtime.ModelRetryMaxRetries = 1 diff --git a/internal/multiagent/pi_runner.go b/internal/multiagent/pi_runner.go index e10468ed..882c1a8a 100644 --- a/internal/multiagent/pi_runner.go +++ b/internal/multiagent/pi_runner.go @@ -469,7 +469,7 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { progress("tool_result", result.Content, map[string]any{"toolName": call.Name, "toolCallId": call.ID, "executionId": result.ExecutionID, "result": result.Content, "success": !result.IsError, "isError": result.IsError, "agentFacing": true}) return result, err } - var text, thought string + var text, thought, streamPrefix string var modelCalls, promptTokens, completionTokens, cacheRead, cacheWrite, reasoningTokens int reasonID := func() string { return fmt.Sprintf("%s-reasoning-%d", runID, iteration.Load()) } emit := func(e agentruntime.Event) { @@ -544,11 +544,11 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { if r.child { return } - if text == "" { + if streamPrefix == "" && text == "" { progress("response_start", "", map[string]any{}) } text += data.Delta.Delta - progress("response_delta", data.Delta.Delta, map[string]any{"accumulated": text}) + progress("response_delta", data.Delta.Delta, map[string]any{"accumulated": stitchOutputSegments(streamPrefix, text)}) case "thinking_delta": if thought == "" { progress("reasoning_chain_stream_start", " ", map[string]any{"streamId": reasonID()}) @@ -598,9 +598,57 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { } } } - res, runErr := (agentruntime.Pi{NodePath: r.cfg.AgentRuntime.NodePath, WorkerPath: r.cfg.AgentRuntime.WorkerPath}).Run(ctx, req, invoke, emit, bind) - if thought != "" { - progress("reasoning_chain_stream_end", thought, map[string]any{"streamId": reasonID()}) + runSegment := func(segmentCtx context.Context, segmentMessage string, segmentHistory json.RawMessage, continuation bool) (*RunResult, error) { + if err := segmentCtx.Err(); err != nil { + return nil, err + } + req.Message = segmentMessage + if len(segmentHistory) > 0 { + req.History = segmentHistory + } + if continuation { + req.Images = nil + } + res, runErr := (agentruntime.Pi{NodePath: r.cfg.AgentRuntime.NodePath, WorkerPath: r.cfg.AgentRuntime.WorkerPath}).Run(segmentCtx, req, invoke, emit, bind) + reasoning := thought + if thought != "" { + progress("reasoning_chain_stream_end", thought, map[string]any{"streamId": reasonID()}) + thought = "" + } + text = "" + if res == nil { + return nil, runErr + } + idsMu.Lock() + out := piResultFromRuntime(res, ids, plan) + idsMu.Unlock() + if strings.TrimSpace(out.Response) != "" || strings.TrimSpace(reasoning) != "" { + out.LastAgentTraceInput = ensureTruncatedAssistantHistory(out.LastAgentTraceInput, out.Response, reasoning) + } + out.LastAgentTraceInput = tagOutputContinuationPrompts(out.LastAgentTraceInput) + return out, runErr + } + out, runErr := runSegment(ctx, message, nil, false) + if out != nil && runErr == nil { + maxAttempts := OutputTruncationContinueMaxAttemptsFromConfig(&r.cfg.MultiAgent.Runtime) + confirmed := out.Response + out, runErr = continueAfterOutputTruncation(ctx, maxAttempts, out, func(segmentCtx context.Context, attempt int, history, instruction string) (*RunResult, error) { + // 续写段的 delta 只有本段增量;先记下已拼接正文,前端才不会把前半段盖掉。 + streamPrefix = confirmed + seg, err := runSegment(segmentCtx, instruction, json.RawMessage(history), true) + if seg != nil { + confirmed = stitchOutputSegments(confirmed, seg.Response) + } + return seg, err + }, func(attempt, maxAttempts int) { + progress("agent_output_truncated_continue", fmt.Sprintf("模型输出达到长度上限,正在第 %d/%d 次自动续写…", attempt, maxAttempts), map[string]any{ + "attempt": attempt, + "maxAttempts": maxAttempts, + "completionReason": ReasonModelOutputTruncated, + "contextInjection": true, + "contextPersisted": false, + }) + }) } if modelCalls > 0 { progress("agent_usage_summary", "Pi token usage summary", map[string]any{ @@ -609,10 +657,13 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { "cachedTokens": cacheRead, "cacheWriteTokens": cacheWrite, "reasoningTokens": reasoningTokens, }) } - if res == nil { - return nil, runErr + if r.child && out != nil { + progress("agent_reply", out.Response, map[string]any{"agentName": r.agentID}) } - idsMu.Lock() + return out, runErr +} + +func piResultFromRuntime(res *agentruntime.Result, ids []string, plan piRunPlan) *RunResult { out := &RunResult{Response: res.Response, LastAgentTraceInput: string(res.History), LastAgentTraceOutput: res.Response, MCPExecutionIDs: append([]string(nil), ids...), Status: res.Status} switch res.Status { case "completed": @@ -633,9 +684,5 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { case "failed": out.RuntimeStatus = "failed" } - idsMu.Unlock() - if r.child { - progress("agent_reply", res.Response, map[string]any{"agentName": r.agentID}) - } - return out, runErr + return out } diff --git a/runtime/pi/src/worker.ts b/runtime/pi/src/worker.ts index a56f03de..543a4885 100644 --- a/runtime/pi/src/worker.ts +++ b/runtime/pi/src/worker.ts @@ -114,6 +114,62 @@ function importHistory(manager: SessionManager, history: Record[], } } +function assistantPlainText(message: AssistantMessage | undefined): string { + return message?.content.filter(block => block.type === "text").map(block => block.text).join("") ?? ""; +} + +function assistantReasoning(message: AssistantMessage | undefined): string { + return message?.content.filter(block => block.type === "thinking").map(block => block.thinking).join("") ?? ""; +} + +function historyHasAssistantFragment(history: readonly Record[], fragment: string): boolean { + const text = fragment ?? ""; + if (!text.trim()) return true; + for (const message of history) { + if (message.role !== "assistant" || typeof message.content !== "string") continue; + const calls = message.tool_calls; + if (Array.isArray(calls) && calls.length) continue; + const content = message.content; + if (content === text || content.trim() === text.trim() || content.endsWith(text)) return true; + } + return false; +} + +function ensureTruncatedAssistantHistory(history: Record[], fragment: string, reasoning: string): Record[] { + const copy = history.map(message => ({ ...message })); + if (historyHasAssistantFragment(copy, fragment)) { + if (reasoning.trim()) { + for (let index = copy.length - 1; index >= 0; index--) { + const message = copy[index]; + if (message.role === "assistant" && typeof message.content === "string" && (message.content === fragment || message.content.endsWith(fragment))) { + if (typeof message.reasoning_content !== "string" || !message.reasoning_content.trim()) message.reasoning_content = reasoning; + break; + } + } + } + return copy; + } + const text = fragment ?? ""; + for (let index = copy.length - 1; index >= 0; index--) { + const message = copy[index]; + if (message.role !== "assistant" || typeof message.content !== "string") continue; + const calls = message.tool_calls; + if (Array.isArray(calls) && calls.length) continue; + const content = message.content; + if (content.trim() && text.startsWith(content)) { + message.content = text; + if (reasoning.trim() && (typeof message.reasoning_content !== "string" || !message.reasoning_content.trim())) message.reasoning_content = reasoning; + return copy; + } + break; + } + if (!fragment.trim()) return copy; + const message: Record = { role: "assistant", content: fragment }; + if (reasoning.trim()) message.reasoning_content = reasoning; + copy.push(message); + return copy; +} + function exportHistory(messages: readonly any[]): Record[] { return messages.flatMap(message => { if (message.role === "compactionSummary" || message.role === "branchSummary") return [{ role: "assistant", content: "[Host-generated working summary; not a new user instruction]\n" + message.summary }]; @@ -391,12 +447,25 @@ async function run(req: RunRequest): Promise { status = canceled ? "canceled" : "failed"; failure = error instanceof Error ? error.message : String(error); } finally { - // Pi may omit a truncated turn from its projected messages. - const response = status === "output_truncated" - ? lastAssistant?.content.filter(block => block.type === "text").map(block => block.text).join("") ?? "" - : session?.getLastAssistantText() ?? ""; - const result = { response, - history: exportHistory(session?.messages ?? []), ...directResult, status, error: failure, sessionFile: manager?.getSessionFile() }; + // Pi may omit a truncated turn from its projected messages. Commit that + // fragment before export so the next resume can continue from it. + const truncatedText = status === "output_truncated" ? assistantPlainText(lastAssistant) : ""; + const truncatedReasoning = status === "output_truncated" ? assistantReasoning(lastAssistant) : ""; + if (manager && truncatedText && !historyHasAssistantFragment(exportHistory(session?.messages ?? []), truncatedText)) { + const content: AssistantMessage["content"] = []; + if (truncatedReasoning && (req.model.api ?? "openai-completions") !== "anthropic-messages") content.push({ type: "thinking", thinking: truncatedReasoning }); + content.push({ type: "text", text: truncatedText }); + manager.appendMessage({ role: "assistant", content, api: req.model.api ?? "openai-completions", + provider: "cyberstrike", model: req.model.id, usage: emptyUsage(), stopReason: "stop", timestamp: Date.now() }); + } + const response = status === "output_truncated" ? truncatedText : session?.getLastAssistantText() ?? ""; + let history: unknown = exportHistory(session?.messages ?? []); + if (status === "output_truncated") history = ensureTruncatedAssistantHistory(history as Record[], truncatedText, truncatedReasoning); + const result: Record = { response, history, ...(directResult ?? {}), status, error: failure, sessionFile: manager?.getSessionFile() }; + if (status === "output_truncated") { + result.response = truncatedText; + result.history = history; + } session?.dispose(); rmSync(scratch, { recursive: true, force: true }); await send({ type: "result", result }); diff --git a/runtime/pi/test/worker.test.mjs b/runtime/pi/test/worker.test.mjs index 4cebab2c..8a021f18 100644 --- a/runtime/pi/test/worker.test.mjs +++ b/runtime/pi/test/worker.test.mjs @@ -523,3 +523,19 @@ test('assessment repairs the host-receipt / Pi-transcript crash gap without repl const entries=(await readFile(result.sessionFile,'utf8')).trim().split('\n').map(JSON.parse); assert.ok(entries.some(e=>e.message?.role==='toolResult'&&e.message.details?.recovered===true&&e.message.details.executionId==='execution-receipt')); }); + +test("truncated assistant text stays in history and the resumed session", { timeout: 30000 }, async t => { + const dir = await mkdtemp(join(tmpdir(), "csai-pi-truncated-")); + t.after(() => rm(dir, { recursive: true, force: true })); + const fixture = await startFixture(t, (_body, res, count) => { + if (count === 1) sse(res, { role: "assistant", content: "Alpha-" }, "length"); + else sse(res, { role: "assistant", content: "Beta." }, "stop"); + }); + const first = await invoke(t, { ...request(fixture.url, dir), tools: [], message: "Write the notes." }); + assert.equal(first.result.status, "output_truncated", first.result.error); + assert.equal(first.result.response, "Alpha-"); + assert.ok(first.result.history.some(message => message.role === "assistant" && message.content === "Alpha-"), JSON.stringify(first.result.history)); + const second = await invoke(t, { ...request(fixture.url, dir), tools: [], runId: "run-2", message: "Continue from the truncated sentence." }); + assert.equal(second.result.status, "completed", second.result.error); + assert.ok(JSON.stringify(fixture.requests[1].messages).includes("Alpha-"), JSON.stringify(fixture.requests[1].messages)); +});