~kris/9p

llm9p

ref: a3dc06aa1a37febcbe7d8d340be3d9b5a2a3f6ea llm9p/internal/llmfs/session_context.go -rw-r--r-- 1.3 KiB
a3dc06aa — pdfinn feat(llm9p): Implement clone-based session architecture 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package llmfs

import (
	"io"

	"github.com/NERVsystems/llm9p/internal/llm"
	"github.com/NERVsystems/llm9p/internal/protocol"
)

// SessionContextFile exposes the conversation history: /n/llm/N/context
// Read returns JSON of the conversation history.
type SessionContextFile struct {
	*protocol.BaseFile
	sm *llm.SessionManager
	id int
}

// NewSessionContextFile creates a context file for the given session.
func NewSessionContextFile(sm *llm.SessionManager, id int) *SessionContextFile {
	return &SessionContextFile{
		BaseFile: protocol.NewBaseFile("context", 0444),
		sm:       sm,
		id:       id,
	}
}

// Read returns the conversation history as JSON.
func (f *SessionContextFile) Read(p []byte, offset int64) (int, error) {
	session := f.sm.Get(f.id)
	if session == nil {
		return 0, protocol.ErrNotFound
	}

	content, err := session.MessagesJSON()
	if err != nil {
		return 0, err
	}
	// Add newline
	content = append(content, '\n')

	if offset >= int64(len(content)) {
		return 0, io.EOF
	}

	n := copy(p, content[offset:])
	return n, nil
}

// Stat returns the file's metadata.
func (f *SessionContextFile) Stat() protocol.Stat {
	s := f.BaseFile.Stat()
	session := f.sm.Get(f.id)
	if session != nil {
		content, err := session.MessagesJSON()
		if err == nil {
			s.Length = uint64(len(content) + 1)
		}
	}
	return s
}