Initial commit: Go agentic harness extracted from Felix
This commit is contained in:
commit
1f2c471ff9
89 files changed
+19388
No files matched your search
@@ -0,0 +1,414 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// EntryType describes the kind of session entry.
|
||||
type EntryType string
|
||||
|
||||
const (
|
||||
EntryTypeMessage EntryType = "message"
|
||||
EntryTypeToolCall EntryType = "tool_call"
|
||||
EntryTypeToolResult EntryType = "tool_result"
|
||||
EntryTypeMeta EntryType = "meta"
|
||||
EntryTypeCompaction EntryType = "compaction"
|
||||
)
|
||||
|
||||
// SessionEntry is a single node in the session DAG.
|
||||
type SessionEntry struct {
|
||||
ID string `json:"id"`
|
||||
ParentID string `json:"parentId,omitempty"`
|
||||
Type EntryType `json:"type"`
|
||||
Role string `json:"role,omitempty"` // user, assistant, system
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
// ImageData holds a base64-encoded image for session persistence.
|
||||
type ImageData struct {
|
||||
MimeType string `json:"mime_type"`
|
||||
Data string `json:"data"` // base64-encoded
|
||||
}
|
||||
|
||||
// MessageData holds text message content.
|
||||
type MessageData struct {
|
||||
Text string `json:"text"`
|
||||
Images []ImageData `json:"images,omitempty"`
|
||||
}
|
||||
|
||||
// ToolCallData holds a tool call's details.
|
||||
type ToolCallData struct {
|
||||
Tool string `json:"tool"`
|
||||
ID string `json:"id"`
|
||||
Input json.RawMessage `json:"input"`
|
||||
}
|
||||
|
||||
// ToolResultData holds the result of a tool call.
|
||||
type ToolResultData struct {
|
||||
ToolCallID string `json:"tool_call_id"`
|
||||
Output string `json:"output"`
|
||||
Error string `json:"error,omitempty"`
|
||||
IsError bool `json:"is_error,omitempty"`
|
||||
Aborted bool `json:"aborted,omitempty"` // true when the user cancelled mid-dispatch
|
||||
Images []ImageData `json:"images,omitempty"`
|
||||
}
|
||||
|
||||
// CompactionData holds an append-only summary of an older portion of the
|
||||
// session. The session view assembles messages by reading entries after the
|
||||
// most recent CompactionData entry, prepending the summary as a leading
|
||||
// synthetic user message. The raw entries before the compaction stay on
|
||||
// disk in JSONL — they are skipped at view assembly only.
|
||||
type CompactionData struct {
|
||||
Summary string `json:"summary"`
|
||||
RangeStartID string `json:"range_start_id,omitempty"` // first entry covered by the summary
|
||||
RangeEndID string `json:"range_end_id,omitempty"` // last entry covered by the summary
|
||||
Model string `json:"model"` // e.g. "local/qwen2.5:3b-instruct"
|
||||
TokensBefore int `json:"tokens_before"`
|
||||
TokensEstimatedAfter int `json:"tokens_estimated_after"`
|
||||
TurnsCompacted int `json:"turns_compacted"`
|
||||
}
|
||||
|
||||
// Session holds a conversation session with DAG-structured entries.
|
||||
type Session struct {
|
||||
ID string
|
||||
AgentID string
|
||||
Key string // channel + peer derived key
|
||||
|
||||
mu sync.RWMutex // guards entries / entryMap / leafID
|
||||
entries []SessionEntry
|
||||
entryMap map[string]*SessionEntry
|
||||
leafID string // current leaf for history traversal
|
||||
store *Store
|
||||
}
|
||||
|
||||
// NewSession creates a new empty session.
|
||||
func NewSession(agentID, key string) *Session {
|
||||
return &Session{
|
||||
ID: generateID("ses"),
|
||||
AgentID: agentID,
|
||||
Key: key,
|
||||
entryMap: make(map[string]*SessionEntry),
|
||||
}
|
||||
}
|
||||
|
||||
// Append adds an entry to the session.
|
||||
func (s *Session) Append(entry SessionEntry) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if entry.ID == "" {
|
||||
entry.ID = generateID("e")
|
||||
}
|
||||
if entry.Timestamp == 0 {
|
||||
entry.Timestamp = time.Now().Unix()
|
||||
}
|
||||
if s.leafID != "" && entry.ParentID == "" {
|
||||
entry.ParentID = s.leafID
|
||||
}
|
||||
|
||||
s.entries = append(s.entries, entry)
|
||||
s.entryMap[entry.ID] = &s.entries[len(s.entries)-1]
|
||||
s.leafID = entry.ID
|
||||
|
||||
// Persist if store is set
|
||||
if s.store != nil {
|
||||
s.store.AppendEntry(s, entry)
|
||||
}
|
||||
}
|
||||
|
||||
// History walks the DAG from root to current leaf and returns the path.
|
||||
func (s *Session) History() []SessionEntry {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
if len(s.entries) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Build path from leaf back to root
|
||||
var path []SessionEntry
|
||||
current := s.leafID
|
||||
for current != "" {
|
||||
entry, ok := s.entryMap[current]
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
path = append(path, *entry)
|
||||
current = entry.ParentID
|
||||
}
|
||||
|
||||
// Reverse to get root→leaf order
|
||||
for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
|
||||
path[i], path[j] = path[j], path[i]
|
||||
}
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
// View returns the post-compaction message view for the LLM. Walks the
|
||||
// current branch from leaf back to root via ParentID; if a compaction entry
|
||||
// is encountered it becomes the first emitted entry and everything before
|
||||
// it is dropped. Without any compaction entries, View() is identical to
|
||||
// History().
|
||||
//
|
||||
// Multiple compaction entries stack naturally — only the most recent one
|
||||
// matters for assembly. Older compactions remain on disk in JSONL.
|
||||
func (s *Session) View() []SessionEntry {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
if len(s.entries) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var path []SessionEntry
|
||||
current := s.leafID
|
||||
for current != "" {
|
||||
entry, ok := s.entryMap[current]
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
path = append(path, *entry)
|
||||
if entry.Type == EntryTypeCompaction {
|
||||
break // most recent compaction terminates the walk-back
|
||||
}
|
||||
current = entry.ParentID
|
||||
}
|
||||
|
||||
// Reverse to root→leaf order.
|
||||
for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
|
||||
path[i], path[j] = path[j], path[i]
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// Entries returns all entries in append order.
|
||||
func (s *Session) Entries() []SessionEntry {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
out := make([]SessionEntry, len(s.entries))
|
||||
copy(out, s.entries)
|
||||
return out
|
||||
}
|
||||
|
||||
// LeafID returns the current leaf entry ID.
|
||||
func (s *Session) LeafID() string {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.leafID
|
||||
}
|
||||
|
||||
// Branch moves the leaf pointer to the specified entry ID, creating a branch.
|
||||
// New entries appended after this will have the branch point as their parent.
|
||||
//
|
||||
// NOTE: not lock-guarded — see Phase B spec, runs during /resume or DAG branching, never from parallel dispatch goroutines.
|
||||
func (s *Session) Branch(entryID string) error {
|
||||
if _, ok := s.entryMap[entryID]; !ok {
|
||||
return fmt.Errorf("entry %q not found in session", entryID)
|
||||
}
|
||||
s.leafID = entryID
|
||||
return nil
|
||||
}
|
||||
|
||||
// EstimateTokens returns a rough token estimate for the current history.
|
||||
// Uses a simple heuristic of ~4 characters per token.
|
||||
func (s *Session) EstimateTokens() int {
|
||||
history := s.History()
|
||||
totalChars := 0
|
||||
for _, entry := range history {
|
||||
totalChars += len(entry.Data)
|
||||
totalChars += len(entry.Role)
|
||||
}
|
||||
return totalChars / 4
|
||||
}
|
||||
|
||||
// Compact replaces older history entries with a summary entry.
|
||||
// It keeps the most recent keepEntries entries and replaces everything
|
||||
// before them with a single summary meta entry.
|
||||
// The summary text should be generated by the caller (typically by asking
|
||||
// the LLM to summarize).
|
||||
//
|
||||
// NOTE: not lock-guarded — runs between turns only. Calls History() and
|
||||
// Entries() (via store.Rewrite) internally; do NOT wrap in s.mu.Lock()
|
||||
// without also restructuring those calls, or you will deadlock on the
|
||||
// non-recursive sync.RWMutex.
|
||||
func (s *Session) Compact(summary string, keepEntries int) {
|
||||
history := s.History()
|
||||
if len(history) <= keepEntries {
|
||||
return // nothing to compact
|
||||
}
|
||||
|
||||
// Split into old (to compact) and recent (to keep)
|
||||
cutoff := len(history) - keepEntries
|
||||
recentEntries := history[cutoff:]
|
||||
|
||||
// Create summary meta entry
|
||||
summaryData, _ := json.Marshal(MessageData{Text: summary})
|
||||
summaryEntry := SessionEntry{
|
||||
ID: generateID("compact"),
|
||||
Type: EntryTypeMeta,
|
||||
Role: "system",
|
||||
Timestamp: time.Now().Unix(),
|
||||
Data: summaryData,
|
||||
}
|
||||
|
||||
// Rebuild the session with summary + recent entries
|
||||
s.entries = nil
|
||||
s.entryMap = make(map[string]*SessionEntry)
|
||||
s.leafID = ""
|
||||
|
||||
// Add summary entry
|
||||
s.entries = append(s.entries, summaryEntry)
|
||||
s.entryMap[summaryEntry.ID] = &s.entries[0]
|
||||
s.leafID = summaryEntry.ID
|
||||
|
||||
// Add recent entries, re-parenting the first one to the summary
|
||||
for i, entry := range recentEntries {
|
||||
if i == 0 {
|
||||
entry.ParentID = summaryEntry.ID
|
||||
} else {
|
||||
entry.ParentID = recentEntries[i-1].ID
|
||||
}
|
||||
s.entries = append(s.entries, entry)
|
||||
s.entryMap[entry.ID] = &s.entries[len(s.entries)-1]
|
||||
s.leafID = entry.ID
|
||||
}
|
||||
|
||||
// Rewrite the session file if store is set
|
||||
if s.store != nil {
|
||||
s.store.Rewrite(s)
|
||||
}
|
||||
}
|
||||
|
||||
// SetStore associates a Store for automatic persistence.
|
||||
//
|
||||
// NOTE: not lock-guarded — must be called once during session construction,
|
||||
// before the session is shared with any goroutine.
|
||||
func (s *Session) SetStore(store *Store) {
|
||||
s.store = store
|
||||
}
|
||||
|
||||
// Helper constructors for common entry types
|
||||
|
||||
// UserMessageEntry creates a user message entry.
|
||||
func UserMessageEntry(text string) SessionEntry {
|
||||
data, _ := json.Marshal(MessageData{Text: text})
|
||||
return SessionEntry{
|
||||
Type: EntryTypeMessage,
|
||||
Role: "user",
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// UserMessageWithImagesEntry creates a user message entry with image attachments.
|
||||
func UserMessageWithImagesEntry(text string, images []ImageData) SessionEntry {
|
||||
data, _ := json.Marshal(MessageData{Text: text, Images: images})
|
||||
return SessionEntry{
|
||||
Type: EntryTypeMessage,
|
||||
Role: "user",
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// AssistantMessageEntry creates an assistant message entry.
|
||||
func AssistantMessageEntry(text string) SessionEntry {
|
||||
data, _ := json.Marshal(MessageData{Text: text})
|
||||
return SessionEntry{
|
||||
Type: EntryTypeMessage,
|
||||
Role: "assistant",
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// ToolCallEntry creates a tool call entry.
|
||||
//
|
||||
// input is sanitised to "{}" when empty or not valid JSON. The
|
||||
// marshal step is fragile against malformed RawMessage: an empty-
|
||||
// but-non-nil json.RawMessage (length 0 but allocated, which is
|
||||
// what happens when the LLM emits a tool_use whose arguments
|
||||
// stream produced zero bytes) makes json.Marshal return an error.
|
||||
// The previous `data, _ := json.Marshal(...)` swallowed that error
|
||||
// and persisted Data: nil, which serialises on disk as `"data":null`.
|
||||
// On reload, assembleMessages would then build a ToolCall with an
|
||||
// empty ID, breaking the tool_use ↔ tool_result pairing in the next
|
||||
// LLM request and producing a 400 from Anthropic of the form
|
||||
// `messages.N.content.0: unexpected tool_use_id ... Each tool_result
|
||||
// block must have a corresponding tool_use block in the previous
|
||||
// message.` Substituting "{}" produces a valid empty-args tool_use,
|
||||
// which the model can interpret correctly on the next turn.
|
||||
func ToolCallEntry(toolCallID, toolName string, input json.RawMessage) SessionEntry {
|
||||
if len(input) == 0 || !json.Valid(input) {
|
||||
input = json.RawMessage(`{}`)
|
||||
}
|
||||
data, _ := json.Marshal(ToolCallData{
|
||||
Tool: toolName,
|
||||
ID: toolCallID,
|
||||
Input: input,
|
||||
})
|
||||
return SessionEntry{
|
||||
Type: EntryTypeToolCall,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// ToolResultEntry creates a tool result entry.
|
||||
func ToolResultEntry(toolCallID, output, errMsg string, images []ImageData) SessionEntry {
|
||||
data, _ := json.Marshal(ToolResultData{
|
||||
ToolCallID: toolCallID,
|
||||
Output: output,
|
||||
Error: errMsg,
|
||||
IsError: errMsg != "",
|
||||
Images: images,
|
||||
})
|
||||
return SessionEntry{
|
||||
Type: EntryTypeToolResult,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// AbortedToolResultEntry creates a synthetic tool result for a tool call that
|
||||
// was cancelled before completion. Pairs with a previously-appended ToolCallEntry
|
||||
// to satisfy the API invariant that every tool_use has a matching tool_result.
|
||||
func AbortedToolResultEntry(toolCallID string) SessionEntry {
|
||||
data, _ := json.Marshal(ToolResultData{
|
||||
ToolCallID: toolCallID,
|
||||
Error: "aborted by user",
|
||||
IsError: true,
|
||||
Aborted: true,
|
||||
})
|
||||
return SessionEntry{
|
||||
Type: EntryTypeToolResult,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// CompactionEntry creates a new compaction entry summarizing an older
|
||||
// range of session history. The append-only path: callers Append() this
|
||||
// entry, the JSONL on disk is never rewritten.
|
||||
func CompactionEntry(summary, rangeStartID, rangeEndID, model string, tokensBefore, tokensEstimatedAfter, turnsCompacted int) SessionEntry {
|
||||
data, _ := json.Marshal(CompactionData{
|
||||
Summary: summary,
|
||||
RangeStartID: rangeStartID,
|
||||
RangeEndID: rangeEndID,
|
||||
Model: model,
|
||||
TokensBefore: tokensBefore,
|
||||
TokensEstimatedAfter: tokensEstimatedAfter,
|
||||
TurnsCompacted: turnsCompacted,
|
||||
})
|
||||
return SessionEntry{
|
||||
Type: EntryTypeCompaction,
|
||||
Role: "system",
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
func generateID(prefix string) string {
|
||||
b := make([]byte, 8)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return fmt.Sprintf("%s_%d", prefix, time.Now().UnixNano())
|
||||
}
|
||||
return prefix + "_" + hex.EncodeToString(b)
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSessionAppendAndHistory(t *testing.T) {
|
||||
sess := NewSession("default", "test")
|
||||
|
||||
sess.Append(UserMessageEntry("hello"))
|
||||
sess.Append(AssistantMessageEntry("hi there"))
|
||||
sess.Append(UserMessageEntry("how are you?"))
|
||||
|
||||
history := sess.History()
|
||||
assert.Len(t, history, 3)
|
||||
|
||||
assert.Equal(t, EntryTypeMessage, history[0].Type)
|
||||
assert.Equal(t, "user", history[0].Role)
|
||||
assert.Equal(t, "assistant", history[1].Role)
|
||||
assert.Equal(t, "user", history[2].Role)
|
||||
}
|
||||
|
||||
func TestSessionDAGTraversal(t *testing.T) {
|
||||
sess := NewSession("default", "test")
|
||||
|
||||
sess.Append(UserMessageEntry("first"))
|
||||
sess.Append(AssistantMessageEntry("second"))
|
||||
|
||||
history := sess.History()
|
||||
assert.Len(t, history, 2)
|
||||
|
||||
// Parent chain should be connected
|
||||
assert.Empty(t, history[0].ParentID)
|
||||
assert.Equal(t, history[0].ID, history[1].ParentID)
|
||||
}
|
||||
|
||||
func TestStorePersistence(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := NewStore(dir)
|
||||
|
||||
// Create and populate a session
|
||||
sess, err := store.Load("agent1", "test_peer")
|
||||
require.NoError(t, err)
|
||||
|
||||
sess.Append(UserMessageEntry("hello"))
|
||||
sess.Append(AssistantMessageEntry("world"))
|
||||
|
||||
// Reload from disk
|
||||
sess2, err := store.Load("agent1", "test_peer")
|
||||
require.NoError(t, err)
|
||||
|
||||
history := sess2.History()
|
||||
assert.Len(t, history, 2)
|
||||
|
||||
// Check file exists
|
||||
path := filepath.Join(dir, "agent1", "test_peer.jsonl")
|
||||
assert.FileExists(t, path)
|
||||
}
|
||||
|
||||
func TestToolCallEntries(t *testing.T) {
|
||||
sess := NewSession("default", "test")
|
||||
|
||||
sess.Append(UserMessageEntry("run ls"))
|
||||
sess.Append(ToolCallEntry("tc_1", "bash", []byte(`{"command":"ls"}`)))
|
||||
sess.Append(ToolResultEntry("tc_1", "file1\nfile2", "", nil))
|
||||
sess.Append(AssistantMessageEntry("Here are the files."))
|
||||
|
||||
history := sess.History()
|
||||
assert.Len(t, history, 4)
|
||||
assert.Equal(t, EntryTypeToolCall, history[1].Type)
|
||||
assert.Equal(t, EntryTypeToolResult, history[2].Type)
|
||||
}
|
||||
|
||||
// TestToolCallEntrySanitisesEmptyInput is the regression guard for
|
||||
// the "data:null" bug. When the LLM emits a tool_use whose arguments
|
||||
// stream produces zero bytes (or an empty/non-nil json.RawMessage,
|
||||
// or invalid JSON), the unsanitised version of ToolCallEntry hit
|
||||
// json.Marshal's "unexpected end of JSON input" path, swallowed the
|
||||
// error via `data, _ :=`, and persisted Data: nil. On disk: `"data":null`.
|
||||
// On reload, assembleMessages would build a tool_use with an empty
|
||||
// ID, and the next LLM call would fail with the Anthropic 400:
|
||||
// "messages.N.content.0: unexpected `tool_use_id` ... Each
|
||||
// `tool_result` block must have a corresponding `tool_use` block in
|
||||
// the previous message." The fix substitutes "{}" for invalid input;
|
||||
// this test asserts the entry's Data is non-nil and round-trips.
|
||||
func TestToolCallEntrySanitisesEmptyInput(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
input json.RawMessage
|
||||
}{
|
||||
{"nil_input", nil},
|
||||
{"empty_non_nil_input", json.RawMessage{}},
|
||||
{"truncated_object", json.RawMessage(`{"a":`)},
|
||||
{"plain_text", json.RawMessage(`hello`)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
e := ToolCallEntry("toolu_x", "search", tc.input)
|
||||
require.NotNil(t, e.Data, "Data must not be nil — that's the bug")
|
||||
require.True(t, json.Valid(e.Data), "Data must be valid JSON")
|
||||
|
||||
var td ToolCallData
|
||||
require.NoError(t, json.Unmarshal(e.Data, &td))
|
||||
assert.Equal(t, "toolu_x", td.ID, "ID must round-trip")
|
||||
assert.Equal(t, "search", td.Tool, "Tool must round-trip")
|
||||
assert.True(t, json.Valid(td.Input), "Input must round-trip as valid JSON")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionBranch(t *testing.T) {
|
||||
sess := NewSession("default", "test")
|
||||
|
||||
sess.Append(UserMessageEntry("first"))
|
||||
firstID := sess.LeafID()
|
||||
sess.Append(AssistantMessageEntry("response 1"))
|
||||
sess.Append(UserMessageEntry("second"))
|
||||
|
||||
// Branch back to first entry
|
||||
err := sess.Branch(firstID)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, firstID, sess.LeafID())
|
||||
|
||||
// Append on the branch
|
||||
sess.Append(AssistantMessageEntry("alternate response"))
|
||||
|
||||
// History should follow the branch
|
||||
history := sess.History()
|
||||
assert.Len(t, history, 2) // first + alternate response
|
||||
assert.Equal(t, "user", history[0].Role)
|
||||
assert.Equal(t, "assistant", history[1].Role)
|
||||
}
|
||||
|
||||
func TestSessionBranchInvalidID(t *testing.T) {
|
||||
sess := NewSession("default", "test")
|
||||
sess.Append(UserMessageEntry("hello"))
|
||||
|
||||
err := sess.Branch("nonexistent")
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestSessionCompact(t *testing.T) {
|
||||
sess := NewSession("default", "test")
|
||||
|
||||
// Add 10 exchanges
|
||||
for i := 0; i < 10; i++ {
|
||||
sess.Append(UserMessageEntry("question " + string(rune('0'+i))))
|
||||
sess.Append(AssistantMessageEntry("answer " + string(rune('0'+i))))
|
||||
}
|
||||
|
||||
history := sess.History()
|
||||
assert.Len(t, history, 20)
|
||||
|
||||
// Compact, keeping last 4 entries
|
||||
sess.Compact("Summary of conversation: discussed topics 0-7", 4)
|
||||
|
||||
history = sess.History()
|
||||
// Should have: 1 summary + 4 kept entries = 5
|
||||
assert.Len(t, history, 5)
|
||||
|
||||
// First entry should be the summary meta entry
|
||||
assert.Equal(t, EntryTypeMeta, history[0].Type)
|
||||
assert.Equal(t, "system", history[0].Role)
|
||||
}
|
||||
|
||||
func TestSessionCompactNoOp(t *testing.T) {
|
||||
sess := NewSession("default", "test")
|
||||
sess.Append(UserMessageEntry("hello"))
|
||||
sess.Append(AssistantMessageEntry("world"))
|
||||
|
||||
// Compacting with keepEntries >= history length should be a no-op
|
||||
sess.Compact("summary", 10)
|
||||
|
||||
history := sess.History()
|
||||
assert.Len(t, history, 2)
|
||||
}
|
||||
|
||||
func TestSessionCompactWithStore(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := NewStore(dir)
|
||||
|
||||
sess, err := store.Load("agent1", "compact_test")
|
||||
require.NoError(t, err)
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
sess.Append(UserMessageEntry("msg " + string(rune('0'+i))))
|
||||
sess.Append(AssistantMessageEntry("reply " + string(rune('0'+i))))
|
||||
}
|
||||
|
||||
sess.Compact("Summary of conversation", 4)
|
||||
|
||||
// Reload and verify
|
||||
sess2, err := store.Load("agent1", "compact_test")
|
||||
require.NoError(t, err)
|
||||
|
||||
history := sess2.History()
|
||||
assert.Len(t, history, 5) // 1 summary + 4 kept
|
||||
assert.Equal(t, EntryTypeMeta, history[0].Type)
|
||||
}
|
||||
|
||||
func TestEstimateTokens(t *testing.T) {
|
||||
sess := NewSession("default", "test")
|
||||
sess.Append(UserMessageEntry("Hello, how are you doing today?"))
|
||||
sess.Append(AssistantMessageEntry("I'm doing well, thank you for asking!"))
|
||||
|
||||
tokens := sess.EstimateTokens()
|
||||
assert.Greater(t, tokens, 0)
|
||||
}
|
||||
|
||||
func TestSessionViewWithoutCompactionMatchesHistory(t *testing.T) {
|
||||
sess := NewSession("default", "test")
|
||||
sess.Append(UserMessageEntry("hi"))
|
||||
sess.Append(AssistantMessageEntry("hello"))
|
||||
sess.Append(UserMessageEntry("hello again"))
|
||||
|
||||
view := sess.View()
|
||||
hist := sess.History()
|
||||
assert.Equal(t, len(hist), len(view))
|
||||
for i := range hist {
|
||||
assert.Equal(t, hist[i].ID, view[i].ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionViewWithSingleCompaction(t *testing.T) {
|
||||
sess := NewSession("default", "test")
|
||||
sess.Append(UserMessageEntry("u1"))
|
||||
sess.Append(AssistantMessageEntry("a1"))
|
||||
sess.Append(UserMessageEntry("u2"))
|
||||
// Simulate compaction over [u1, a1, u2]: append a CompactionEntry,
|
||||
// then continue appending normal entries after it.
|
||||
sess.Append(CompactionEntry("summary of u1/a1/u2", "", "", "ollama/qwen2.5:3b-instruct", 100, 25, 3))
|
||||
sess.Append(AssistantMessageEntry("a2 after compaction"))
|
||||
sess.Append(UserMessageEntry("u3"))
|
||||
|
||||
view := sess.View()
|
||||
require.Len(t, view, 3)
|
||||
assert.Equal(t, EntryTypeCompaction, view[0].Type)
|
||||
assert.Equal(t, EntryTypeMessage, view[1].Type)
|
||||
assert.Equal(t, "assistant", view[1].Role)
|
||||
assert.Equal(t, "user", view[2].Role)
|
||||
}
|
||||
|
||||
func TestSessionViewWithMultipleCompactions(t *testing.T) {
|
||||
sess := NewSession("default", "test")
|
||||
sess.Append(UserMessageEntry("old"))
|
||||
sess.Append(CompactionEntry("first summary", "", "", "m", 0, 0, 1))
|
||||
sess.Append(UserMessageEntry("middle"))
|
||||
sess.Append(CompactionEntry("second summary", "", "", "m", 0, 0, 1))
|
||||
sess.Append(UserMessageEntry("recent"))
|
||||
|
||||
view := sess.View()
|
||||
require.Len(t, view, 2)
|
||||
// Most recent compaction supersedes the first — view starts at it.
|
||||
var cd CompactionData
|
||||
require.NoError(t, json.Unmarshal(view[0].Data, &cd))
|
||||
assert.Equal(t, "second summary", cd.Summary)
|
||||
assert.Equal(t, "user", view[1].Role)
|
||||
}
|
||||
|
||||
func TestCompactionEntryHasCorrectFields(t *testing.T) {
|
||||
e := CompactionEntry("hello summary", "start_id", "end_id", "ollama/qwen2.5:3b", 1000, 250, 12)
|
||||
assert.Equal(t, EntryTypeCompaction, e.Type)
|
||||
assert.Equal(t, "system", e.Role)
|
||||
var cd CompactionData
|
||||
require.NoError(t, json.Unmarshal(e.Data, &cd))
|
||||
assert.Equal(t, "hello summary", cd.Summary)
|
||||
assert.Equal(t, "start_id", cd.RangeStartID)
|
||||
assert.Equal(t, "end_id", cd.RangeEndID)
|
||||
assert.Equal(t, "ollama/qwen2.5:3b", cd.Model)
|
||||
assert.Equal(t, 1000, cd.TokensBefore)
|
||||
assert.Equal(t, 250, cd.TokensEstimatedAfter)
|
||||
assert.Equal(t, 12, cd.TurnsCompacted)
|
||||
}
|
||||
|
||||
func TestToolResultData_AbortedFieldRoundTrip(t *testing.T) {
|
||||
entry := AbortedToolResultEntry("tc_abc")
|
||||
require.Equal(t, EntryTypeToolResult, entry.Type)
|
||||
|
||||
var data ToolResultData
|
||||
require.NoError(t, json.Unmarshal(entry.Data, &data))
|
||||
|
||||
require.Equal(t, "tc_abc", data.ToolCallID)
|
||||
require.Equal(t, "aborted by user", data.Error)
|
||||
require.True(t, data.IsError)
|
||||
require.True(t, data.Aborted)
|
||||
require.Empty(t, data.Output)
|
||||
}
|
||||
|
||||
func TestToolResultData_OldJSONLWithoutAbortedField(t *testing.T) {
|
||||
// Simulate an old session entry written before the Aborted field existed.
|
||||
oldJSON := []byte(`{"tool_call_id":"tc_old","output":"hello","is_error":false}`)
|
||||
var data ToolResultData
|
||||
require.NoError(t, json.Unmarshal(oldJSON, &data))
|
||||
|
||||
require.Equal(t, "tc_old", data.ToolCallID)
|
||||
require.Equal(t, "hello", data.Output)
|
||||
require.False(t, data.IsError)
|
||||
require.False(t, data.Aborted, "missing field must default to false")
|
||||
}
|
||||
|
||||
func TestSession_AppendConcurrent(t *testing.T) {
|
||||
// Race-detector test: 100 goroutines each Append a uniquely-IDed entry.
|
||||
// Run with `go test -race` to catch any unguarded mutation.
|
||||
sess := NewSession("a", "k")
|
||||
|
||||
const N = 100
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(N)
|
||||
for i := 0; i < N; i++ {
|
||||
i := i
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
sess.Append(SessionEntry{
|
||||
ID: fmt.Sprintf("e_%d", i),
|
||||
Type: EntryTypeMessage,
|
||||
})
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
view := sess.View()
|
||||
require.Len(t, view, N, "every Append must land")
|
||||
|
||||
seen := map[string]bool{}
|
||||
for _, e := range view {
|
||||
require.False(t, seen[e.ID], "duplicate ID %s", e.ID)
|
||||
seen[e.ID] = true
|
||||
}
|
||||
require.Len(t, seen, N)
|
||||
}
|
||||
|
||||
func TestSession_ViewReturnsCopy(t *testing.T) {
|
||||
// Mutating the returned slice must not affect subsequent View() calls.
|
||||
sess := NewSession("a", "k")
|
||||
sess.Append(SessionEntry{ID: "e_1", Type: EntryTypeMessage})
|
||||
|
||||
v1 := sess.View()
|
||||
require.Len(t, v1, 1)
|
||||
v1[0] = SessionEntry{ID: "MUTATED"}
|
||||
|
||||
v2 := sess.View()
|
||||
require.Len(t, v2, 1)
|
||||
require.Equal(t, "e_1", v2[0].ID, "internal state must not be mutated by caller's slice modification")
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SessionInfo describes a session without loading its full contents.
|
||||
type SessionInfo struct {
|
||||
Key string `json:"key"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
LastActivity time.Time `json:"lastActivity"`
|
||||
EntryCount int `json:"entryCount"`
|
||||
}
|
||||
|
||||
// Store handles JSONL file I/O for sessions.
|
||||
type Store struct {
|
||||
baseDir string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// NewStore creates a new session store.
|
||||
func NewStore(baseDir string) *Store {
|
||||
return &Store{baseDir: baseDir}
|
||||
}
|
||||
|
||||
// sessionDir returns the directory for a given agent's sessions.
|
||||
func (s *Store) sessionDir(agentID string) string {
|
||||
return filepath.Join(s.baseDir, agentID)
|
||||
}
|
||||
|
||||
// sessionPath returns the file path for a session.
|
||||
func (s *Store) sessionPath(agentID, key string) string {
|
||||
return filepath.Join(s.sessionDir(agentID), key+".jsonl")
|
||||
}
|
||||
|
||||
// Load reads a session from its JSONL file.
|
||||
func (s *Store) Load(agentID, key string) (*Session, error) {
|
||||
path := s.sessionPath(agentID, key)
|
||||
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
sess := NewSession(agentID, key)
|
||||
sess.SetStore(s)
|
||||
return sess, nil
|
||||
}
|
||||
return nil, fmt.Errorf("open session file: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
sess := NewSession(agentID, key)
|
||||
sess.SetStore(s)
|
||||
|
||||
scanner := bufio.NewScanner(f)
|
||||
scanner.Buffer(make([]byte, 0, 1024*1024), 10*1024*1024) // 10MB max line
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Bytes()
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
var entry SessionEntry
|
||||
if err := json.Unmarshal(line, &entry); err != nil {
|
||||
slog.Warn("skipping malformed session entry", "error", err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Add to session without re-persisting
|
||||
sess.entries = append(sess.entries, entry)
|
||||
sess.entryMap[entry.ID] = &sess.entries[len(sess.entries)-1]
|
||||
sess.leafID = entry.ID
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, fmt.Errorf("read session file: %w", err)
|
||||
}
|
||||
|
||||
return sess, nil
|
||||
}
|
||||
|
||||
// AppendEntry writes a single entry to the session's JSONL file.
|
||||
func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
dir := s.sessionDir(sess.AgentID)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
slog.Error("failed to create session dir", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
path := s.sessionPath(sess.AgentID, sess.Key)
|
||||
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
slog.Error("failed to open session file", "error", err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
data, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
slog.Error("failed to marshal session entry", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
data = append(data, '\n')
|
||||
if _, err := f.Write(data); err != nil {
|
||||
slog.Error("failed to write session entry", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates an empty session file on disk so it shows up in List.
|
||||
func (s *Store) Create(agentID, key string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
dir := s.sessionDir(agentID)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return fmt.Errorf("create session dir: %w", err)
|
||||
}
|
||||
|
||||
path := s.sessionPath(agentID, key)
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create session file: %w", err)
|
||||
}
|
||||
return f.Close()
|
||||
}
|
||||
|
||||
// List returns metadata for all sessions belonging to the given agent.
|
||||
func (s *Store) List(agentID string) ([]SessionInfo, error) {
|
||||
dir := s.sessionDir(agentID)
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("read session dir: %w", err)
|
||||
}
|
||||
|
||||
var sessions []SessionInfo
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".jsonl") {
|
||||
continue
|
||||
}
|
||||
|
||||
key := strings.TrimSuffix(entry.Name(), ".jsonl")
|
||||
path := filepath.Join(dir, entry.Name())
|
||||
|
||||
info := SessionInfo{Key: key}
|
||||
|
||||
// Count lines and extract timestamps from first/last entries
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
scanner := bufio.NewScanner(f)
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 1*1024*1024)
|
||||
var firstTS, lastTS int64
|
||||
lineCount := 0
|
||||
for scanner.Scan() {
|
||||
line := scanner.Bytes()
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
lineCount++
|
||||
var partial struct {
|
||||
Timestamp int64 `json:"timestamp"`
|
||||
}
|
||||
if json.Unmarshal(line, &partial) == nil && partial.Timestamp > 0 {
|
||||
if firstTS == 0 {
|
||||
firstTS = partial.Timestamp
|
||||
}
|
||||
lastTS = partial.Timestamp
|
||||
}
|
||||
}
|
||||
f.Close()
|
||||
|
||||
info.EntryCount = lineCount
|
||||
if firstTS > 0 {
|
||||
info.CreatedAt = time.Unix(firstTS, 0)
|
||||
} else {
|
||||
// Fall back to file modification time
|
||||
if fi, err := entry.Info(); err == nil {
|
||||
info.CreatedAt = fi.ModTime()
|
||||
}
|
||||
}
|
||||
if lastTS > 0 {
|
||||
info.LastActivity = time.Unix(lastTS, 0)
|
||||
} else {
|
||||
info.LastActivity = info.CreatedAt
|
||||
}
|
||||
|
||||
sessions = append(sessions, info)
|
||||
}
|
||||
|
||||
return sessions, nil
|
||||
}
|
||||
|
||||
// Exists checks whether a session file exists for the given agent and key.
|
||||
func (s *Store) Exists(agentID, key string) bool {
|
||||
path := s.sessionPath(agentID, key)
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Rename renames a session file from oldKey to newKey.
|
||||
func (s *Store) Rename(agentID, oldKey, newKey string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
oldPath := s.sessionPath(agentID, oldKey)
|
||||
newPath := s.sessionPath(agentID, newKey)
|
||||
|
||||
if _, err := os.Stat(oldPath); os.IsNotExist(err) {
|
||||
return fmt.Errorf("session %q does not exist", oldKey)
|
||||
}
|
||||
if _, err := os.Stat(newPath); err == nil {
|
||||
return fmt.Errorf("session %q already exists", newKey)
|
||||
}
|
||||
|
||||
return os.Rename(oldPath, newPath)
|
||||
}
|
||||
|
||||
// Delete removes a session's JSONL file.
|
||||
func (s *Store) Delete(agentID, key string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
path := s.sessionPath(agentID, key)
|
||||
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("remove session file: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Rewrite replaces the entire session JSONL file with the current entries.
|
||||
// Used after compaction to replace the old file.
|
||||
func (s *Store) Rewrite(sess *Session) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
dir := s.sessionDir(sess.AgentID)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
slog.Error("failed to create session dir", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
path := s.sessionPath(sess.AgentID, sess.Key)
|
||||
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
slog.Error("failed to create session file for rewrite", "error", err)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
w := bufio.NewWriter(f)
|
||||
for _, entry := range sess.Entries() {
|
||||
data, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
slog.Error("failed to marshal session entry", "error", err)
|
||||
continue
|
||||
}
|
||||
w.Write(data)
|
||||
w.WriteByte('\n')
|
||||
}
|
||||
|
||||
if err := w.Flush(); err != nil {
|
||||
slog.Error("failed to flush session file", "error", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user