SessionFromEvents reconstructs a session from raw container output events. This parses the JSON events emitted by docker agent run --exec --json and builds a session with the conversation history.
(events []map[string]any, title string, questions []string)
| 56 | // This parses the JSON events emitted by docker agent run --exec --json and builds a session |
| 57 | // with the conversation history. |
| 58 | func SessionFromEvents(events []map[string]any, title string, questions []string) *session.Session { |
| 59 | sess := session.New( |
| 60 | session.WithTitle(title), |
| 61 | session.WithToolsApproved(true), |
| 62 | session.WithNonInteractive(true), |
| 63 | ) |
| 64 | |
| 65 | // Add user questions as initial messages. |
| 66 | // For multi-turn evals, these are interleaved with agent responses |
| 67 | // as they appear in the event stream. User messages are added when |
| 68 | // a "user_message" event is encountered (which carries the correct |
| 69 | // timestamp), or when a "stream_stopped" event indicates the agent |
| 70 | // finished processing the previous turn in a multi-turn eval. |
| 71 | // If no "user_message" event is found before the first agent response, |
| 72 | // the question is added with the timestamp of that first response. |
| 73 | questionIdx := 0 |
| 74 | userMessageAdded := false |
| 75 | addNextQuestion := func(timestamp string) { |
| 76 | if questionIdx < len(questions) { |
| 77 | msg := &session.Message{ |
| 78 | Message: chat.Message{ |
| 79 | Role: chat.MessageRoleUser, |
| 80 | Content: questions[questionIdx], |
| 81 | CreatedAt: timestamp, |
| 82 | }, |
| 83 | } |
| 84 | sess.AddMessage(msg) |
| 85 | questionIdx++ |
| 86 | userMessageAdded = true |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | // Track current assistant message being built |
| 91 | var currentContent strings.Builder |
| 92 | var currentReasoningContent strings.Builder |
| 93 | var currentToolCalls []tools.ToolCall |
| 94 | var currentToolDefinitions []tools.Tool |
| 95 | var currentAgentName string |
| 96 | var currentModel string |
| 97 | var currentUsage *chat.Usage |
| 98 | var currentCost float64 |
| 99 | var currentTimestamp string |
| 100 | |
| 101 | // Helper to flush current assistant message |
| 102 | flushAssistantMessage := func() { |
| 103 | if currentContent.Len() > 0 || currentReasoningContent.Len() > 0 || len(currentToolCalls) > 0 { |
| 104 | msg := &session.Message{ |
| 105 | AgentName: currentAgentName, |
| 106 | Message: chat.Message{ |
| 107 | Role: chat.MessageRoleAssistant, |
| 108 | Content: currentContent.String(), |
| 109 | ReasoningContent: currentReasoningContent.String(), |
| 110 | ToolCalls: currentToolCalls, |
| 111 | ToolDefinitions: currentToolDefinitions, |
| 112 | CreatedAt: currentTimestamp, |
| 113 | Model: currentModel, |
| 114 | Usage: currentUsage, |
| 115 | Cost: currentCost, |