-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.go
More file actions
228 lines (203 loc) · 5.42 KB
/
Copy pathsession.go
File metadata and controls
228 lines (203 loc) · 5.42 KB
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package gcf
import (
"fmt"
"sync"
)
// Session tracks symbols that have been transmitted to a client, enabling
// subsequent responses to reference them by ID without full retransmission.
// This makes multi-call workflows progressively cheaper.
//
// Thread-safe: multiple tool handlers may encode concurrently within a session.
type Session struct {
mu sync.Mutex
symbols map[string]int // qualified_name -> global session ID
nextID int
}
// NewSession creates a new empty session.
func NewSession() *Session {
return &Session{
symbols: make(map[string]int),
}
}
// Transmitted returns true if the symbol has been sent in a previous response.
func (s *Session) Transmitted(qname string) bool {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.symbols[qname]
return ok
}
// GetID returns the session-global ID for a previously transmitted symbol.
// Returns -1 if not found.
func (s *Session) GetID(qname string) int {
s.mu.Lock()
defer s.mu.Unlock()
id, ok := s.symbols[qname]
if !ok {
return -1
}
return id
}
// Record marks symbols as transmitted and assigns session-global IDs.
// Call this after a successful encode to register newly-sent symbols.
func (s *Session) Record(symbols []Symbol) {
s.mu.Lock()
defer s.mu.Unlock()
for _, sym := range symbols {
if _, exists := s.symbols[sym.QualifiedName]; !exists {
s.symbols[sym.QualifiedName] = s.nextID
s.nextID++
}
}
}
// nextSessionID returns the next available session ID without consuming it.
func (s *Session) nextSessionID() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.nextID
}
// Size returns the number of symbols tracked in this session.
func (s *Session) Size() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.symbols)
}
// Reset clears the session state.
func (s *Session) Reset() {
s.mu.Lock()
defer s.mu.Unlock()
s.symbols = make(map[string]int)
s.nextID = 0
}
// EncodeWithSession encodes a payload using GCF with session deduplication.
// Symbols that were already transmitted in prior responses are emitted as
// bare references (`@N # previously transmitted`) instead of full declarations.
// After encoding, newly-sent symbols are recorded in the session.
func EncodeWithSession(p *Payload, sess *Session) string {
if sess == nil {
return Encode(p)
}
// Partition symbols into new (need full declaration) and known (bare ref).
type symbolEntry struct {
symbol Symbol
isNew bool
}
entries := make([]symbolEntry, len(p.Symbols))
for i, s := range p.Symbols {
entries[i] = symbolEntry{
symbol: s,
isNew: !sess.Transmitted(s.QualifiedName),
}
}
var b stringBuilder
// Header with session=true marker.
b.sprintf("GCF profile=graph tool=%s", p.Tool)
if p.TokenBudget > 0 {
b.sprintf(" budget=%d", p.TokenBudget)
}
if p.TokensUsed > 0 {
b.sprintf(" tokens=%d", p.TokensUsed)
}
b.sprintf(" symbols=%d", len(p.Symbols))
if len(p.Edges) > 0 {
b.sprintf(" edges=%d", len(p.Edges))
}
b.sprintf(" session=true")
if p.PackRoot != "" {
b.sprintf(" pack_root=%s", p.PackRoot)
}
b.writeByte('\n')
// Build ID mapping using session-stable IDs.
// Known symbols keep their existing session ID.
// New symbols get the next available session ID.
localIndex := make(map[string]int, len(p.Symbols))
for _, e := range entries {
if !e.isNew {
localIndex[e.symbol.QualifiedName] = sess.GetID(e.symbol.QualifiedName)
}
}
nextNew := sess.nextSessionID()
for _, e := range entries {
if e.isNew {
localIndex[e.symbol.QualifiedName] = nextNew
nextNew++
}
}
// Group by distance.
groups := groupByDistance(p.Symbols)
groupNames := []string{"targets", "related", "extended"}
for _, g := range groups {
if len(g.symbols) == 0 {
continue
}
name := "targets"
if g.distance < len(groupNames) {
name = groupNames[g.distance]
} else {
b.sprintf("## distance_%d", g.distance)
b.writeByte('\n')
name = ""
}
if name != "" {
b.writeString("## ")
b.writeString(name)
b.writeByte('\n')
}
for _, s := range g.symbols {
idx := localIndex[s.QualifiedName]
if sess.Transmitted(s.QualifiedName) {
// Bare reference: symbol was sent in a prior response.
b.sprintf("@%d # previously transmitted", idx)
} else {
// Full declaration.
kind := KindAbbrev[s.Kind]
if kind == "" {
kind = s.Kind
}
b.sprintf("@%d %s %s %.2f %s", idx, kind, s.QualifiedName, s.Score, s.Provenance)
}
b.writeByte('\n')
}
}
// Edges section.
if len(p.Edges) > 0 {
b.sprintf("## edges [%d]\n", len(p.Edges))
for _, e := range p.Edges {
srcIdx, srcOk := localIndex[e.Source]
tgtIdx, tgtOk := localIndex[e.Target]
if !srcOk || !tgtOk {
continue
}
b.sprintf("@%d<@%d %s", tgtIdx, srcIdx, e.EdgeType)
if e.Status != "" && e.Status != "unchanged" {
b.writeString(" ")
b.writeString(e.Status)
}
b.writeByte('\n')
}
}
// Record all new symbols in the session.
var newSymbols []Symbol
for _, e := range entries {
if e.isNew {
newSymbols = append(newSymbols, e.symbol)
}
}
sess.Record(newSymbols)
return b.String()
}
// stringBuilder is a thin wrapper to keep the encoder readable.
type stringBuilder struct {
buf []byte
}
func (b *stringBuilder) sprintf(format string, args ...any) {
b.buf = append(b.buf, fmt.Sprintf(format, args...)...)
}
func (b *stringBuilder) writeString(s string) {
b.buf = append(b.buf, s...)
}
func (b *stringBuilder) writeByte(c byte) {
b.buf = append(b.buf, c)
}
func (b *stringBuilder) String() string {
return string(b.buf)
}