~kris/9p

llm9p

ref: 054039ea9bfbafe6e6a89c7800e8b7ef9ea3df2b llm9p/internal/llmfs/context.go -rw-r--r-- 1.2 KiB
054039ea — pdfinn feat: Add CLI backend for Claude Max subscription 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
package llmfs

import (
	"io"
	"strings"

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

// ContextFile exposes the conversation history
// Read: returns JSON of conversation history
// Write: appends a system message to context
type ContextFile struct {
	*protocol.BaseFile
	client llm.Backend
}

// NewContextFile creates the context file
func NewContextFile(client llm.Backend) *ContextFile {
	return &ContextFile{
		BaseFile: protocol.NewBaseFile("context", 0666),
		client:   client,
	}
}

func (f *ContextFile) Read(p []byte, offset int64) (int, error) {
	content, err := f.client.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
}

func (f *ContextFile) Write(p []byte, offset int64) (int, error) {
	// Writing appends a system message to the context
	msg := strings.TrimSpace(string(p))
	if msg != "" {
		f.client.AddSystemMessage(msg)
	}
	return len(p), nil
}

func (f *ContextFile) Stat() protocol.Stat {
	s := f.BaseFile.Stat()
	content, _ := f.client.MessagesJSON()
	s.Length = uint64(len(content) + 1) // +1 for newline
	return s
}