~kris/9p

llm9p

ref: c94202ec097d36893d9ee9ff9b0914c2576cfb13 llm9p/internal/llmfs/compact.go -rw-r--r-- 1.5 KiB
c94202ec — pdfinn fix(llm): harden tool-use history to prevent cascading failures 6 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
61
62
63
64
65
66
67
68
69
70
71
72
73
package llmfs

import (
	"context"
	"fmt"
	"io"
	"strings"
	"sync"

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

// CompactFile allows manual compaction trigger
// Write anything to trigger compaction
// Read returns status ("ok" or "error: ...")
type CompactFile struct {
	*protocol.BaseFile
	client     llm.Backend
	mu         sync.RWMutex
	lastResult string
}

// NewCompactFile creates the compact file
func NewCompactFile(client llm.Backend) *CompactFile {
	return &CompactFile{
		BaseFile:   protocol.NewBaseFile("compact", 0666),
		client:     client,
		lastResult: "ready\n",
	}
}

func (f *CompactFile) Read(p []byte, offset int64) (int, error) {
	f.mu.RLock()
	content := f.lastResult
	f.mu.RUnlock()

	if offset >= int64(len(content)) {
		return 0, io.EOF
	}
	n := copy(p, content[offset:])
	return n, nil
}

func (f *CompactFile) Write(p []byte, offset int64) (int, error) {
	cmd := strings.TrimSpace(string(p))
	if cmd == "" {
		return len(p), nil
	}

	// Trigger compaction
	err := f.client.Compact(context.Background())

	f.mu.Lock()
	if err != nil {
		f.lastResult = fmt.Sprintf("error: %v\n", err)
	} else {
		tokens := f.client.TotalTokens()
		limit := f.client.ContextLimit()
		f.lastResult = fmt.Sprintf("ok: %d/%d\n", tokens, limit)
	}
	f.mu.Unlock()

	return len(p), nil
}

func (f *CompactFile) Stat() protocol.Stat {
	s := f.BaseFile.Stat()
	f.mu.RLock()
	s.Length = uint64(len(f.lastResult))
	f.mu.RUnlock()
	return s
}