~kris/9p

llm9p

ref: fa3820070ac0cb7b9932cdd5cbf1137886348f4e llm9p/internal/llmfs/ask.go -rw-r--r-- 2.3 KiB
fa382007 — pdfinn feat(llm): Add extended thinking support and usage tracking 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package llmfs

import (
	"context"
	"io"
	"log"
	"strings"
	"sync"

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

// CompactThreshold is the percentage of context limit at which auto-compaction triggers
const CompactThreshold = 0.80

// AskFile is the main interaction file - write a prompt, read the response
type AskFile struct {
	*protocol.BaseFile
	client       llm.Backend
	mu           sync.RWMutex
	lastResponse string
}

// NewAskFile creates the ask file
func NewAskFile(client llm.Backend) *AskFile {
	return &AskFile{
		BaseFile: protocol.NewBaseFile("ask", 0666),
		client:   client,
	}
}

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

	// Add newline if not present
	if content != "" && !strings.HasSuffix(content, "\n") {
		content += "\n"
	}

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

func (f *AskFile) Write(p []byte, offset int64) (int, error) {
	prompt := strings.TrimSpace(string(p))
	if prompt == "" {
		return len(p), nil // Empty write is a no-op
	}

	ctx := context.Background()

	// Check if we need to auto-compact before processing
	tokens := f.client.TotalTokens()
	limit := f.client.ContextLimit()
	threshold := int(float64(limit) * CompactThreshold)

	if tokens > threshold {
		log.Printf("llm9p: auto-compacting at %d/%d tokens (%.0f%% threshold)",
			tokens, limit, CompactThreshold*100)
		if err := f.client.Compact(ctx); err != nil {
			log.Printf("llm9p: auto-compact failed: %v", err)
			// Continue anyway - better to try than to fail
		} else {
			log.Printf("llm9p: auto-compact complete, now at %d tokens",
				f.client.TotalTokens())
		}
	}

	// Make the API call
	response, err := f.client.Ask(ctx, prompt)
	if err != nil {
		// Store error as response so it can be read
		f.mu.Lock()
		f.lastResponse = "Error: " + err.Error()
		f.mu.Unlock()
		return len(p), nil // Return success so client knows write completed
	}

	f.mu.Lock()
	f.lastResponse = response
	f.mu.Unlock()

	return len(p), nil
}

func (f *AskFile) Stat() protocol.Stat {
	s := f.BaseFile.Stat()
	f.mu.RLock()
	content := f.lastResponse
	f.mu.RUnlock()
	if content != "" && !strings.HasSuffix(content, "\n") {
		content += "\n"
	}
	s.Length = uint64(len(content))
	return s
}