~kris/9p

llm9p

ref: 4191d4e78cf8495fd39a4588ec5649646ae2df88 llm9p/internal/llmfs/session_ask.go -rw-r--r-- 4.7 KiB
4191d4e7 — pdfinn fix(llmfs): correct model alias IDs to match actual Anthropic API 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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package llmfs

import (
	"context"
	"fmt"
	"io"
	"log"
	"strings"

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

// SessionAskFile is the ask file for a specific session: /n/llm/N/ask
// Write a prompt, read the response.
type SessionAskFile struct {
	*protocol.BaseFile
	sm *llm.SessionManager
	id int
}

// NewSessionAskFile creates an ask file for the given session.
func NewSessionAskFile(sm *llm.SessionManager, id int) *SessionAskFile {
	return &SessionAskFile{
		BaseFile: protocol.NewBaseFile("ask", 0666),
		sm:       sm,
		id:       id,
	}
}

// Read returns the last response from this session.
// Blocks until any in-progress generation completes before returning content.
func (f *SessionAskFile) Read(p []byte, offset int64) (int, error) {
	session := f.sm.Get(f.id)
	if session == nil {
		return 0, protocol.ErrNotFound
	}

	// Wait for the background generation goroutine (if any) to finish.
	session.WaitDone()

	content := session.LastResponse()
	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
}

// Write sends a prompt to the LLM using this session's settings.
// Returns immediately after starting the generation in a background goroutine.
// The response is available via Read (pread) once generation completes.
//
// If the write begins with "TOOL_RESULTS\n", it is parsed as tool execution
// results and submitted via AskWithToolResults instead of a plain Ask.
//
// TOOL_RESULTS format:
//
//	TOOL_RESULTS
//	<tool_use_id>
//	<result content (may be multi-line)>
//	---
//	<tool_use_id2>
//	<result content>
//	---
func (f *SessionAskFile) Write(p []byte, offset int64) (int, error) {
	log.Printf("llm9p: SessionAskFile.Write session=%d len=%d", f.id, len(p))

	prompt := strings.TrimSpace(string(p))
	if prompt == "" {
		return len(p), nil // Empty write is a no-op
	}

	session := f.sm.Get(f.id)
	if session == nil {
		return 0, protocol.ErrNotFound
	}
	if session.IsClosed() {
		return 0, protocol.ErrPermission
	}

	// Allocate streaming channel and done signal before launching goroutine.
	// This ensures the stream file can observe a non-nil channel immediately
	// after the write returns (no race between Write and stream Read).
	session.BeginGeneration()

	// Launch generation goroutine — Write returns to the caller immediately.
	sm := f.sm
	id := f.id
	go func() {
		defer session.EndGeneration()
		ctx := context.Background()

		if strings.HasPrefix(prompt, "TOOL_RESULTS\n") {
			results, err := parseToolResults(prompt)
			if err != nil {
				log.Printf("llm9p: async gen TOOL_RESULTS parse error: %v", err)
				session.SetLastResponse("Error: " + err.Error())
				return
			}
			log.Printf("llm9p: async gen submitting %d tool results", len(results))
			if _, err = sm.AskWithToolResults(ctx, id, results); err != nil {
				log.Printf("llm9p: async gen tool results error: %v", err)
			}
			return
		}

		log.Printf("llm9p: async gen prompt: %s", prompt[:min(len(prompt), 50)])
		if _, err := sm.Ask(ctx, id, prompt); err != nil {
			log.Printf("llm9p: async gen error: %v", err)
		}
	}()

	return len(p), nil
}

// parseToolResults parses the TOOL_RESULTS wire format into a slice of ToolResult.
// Each result block starts with a tool_use_id line, followed by content lines,
// terminated by "---" (or end of input).
func parseToolResults(text string) ([]llm.ToolResult, error) {
	lines := strings.Split(text, "\n")
	if len(lines) < 2 || lines[0] != "TOOL_RESULTS" {
		return nil, fmt.Errorf("missing TOOL_RESULTS header")
	}

	var results []llm.ToolResult
	i := 1 // Skip "TOOL_RESULTS" header

	for i < len(lines) {
		// Skip blank lines between blocks
		if strings.TrimSpace(lines[i]) == "" {
			i++
			continue
		}

		// Next non-empty line is the tool_use_id
		toolUseID := strings.TrimSpace(lines[i])
		i++

		// Collect content lines until "---" separator or end
		var contentLines []string
		for i < len(lines) && lines[i] != "---" {
			contentLines = append(contentLines, lines[i])
			i++
		}
		// Skip "---" separator
		if i < len(lines) && lines[i] == "---" {
			i++
		}

		content := strings.TrimRight(strings.Join(contentLines, "\n"), "\n")
		results = append(results, llm.ToolResult{
			ToolUseID: toolUseID,
			Content:   content,
		})
	}

	if len(results) == 0 {
		return nil, fmt.Errorf("TOOL_RESULTS contained no results")
	}

	return results, nil
}

// Stat returns the file's metadata.
func (f *SessionAskFile) Stat() protocol.Stat {
	s := f.BaseFile.Stat()
	// Length is dynamic based on last response
	session := f.sm.Get(f.id)
	if session != nil {
		s.Length = uint64(len(session.LastResponse()))
	}
	return s
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}