-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompile_target.go
More file actions
273 lines (259 loc) · 7.95 KB
/
Copy pathcompile_target.go
File metadata and controls
273 lines (259 loc) · 7.95 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package contexty
import (
"context"
"errors"
"fmt"
"maps"
"strings"
)
// CompileTarget requests an additional named projection from the same compile pass.
type CompileTarget struct {
Name string
// View requests a built-in rendered view and is mutually exclusive with
// SourceSegment, Budget, and Formatter.
View string
SourceSegment SegmentName
Budget *BudgetPipeline
Formatter SegmentFormatter
}
// CompileProjection is a named compile output with traceability to the shared pass.
type CompileProjection struct {
Name string
Text string
Messages []Message
Transformations map[string]TransformRecord
Source CompileRequest // normalized request before pipeline mutations
InputSnapshot ConversationSnapshot // compiled snapshot used as target input
ArtifactIDs []string
}
func (p CompileProjection) clone() CompileProjection {
return CompileProjection{
Name: p.Name,
Text: p.Text,
Messages: cloneMessageSlice(p.Messages),
Transformations: cloneTransformRecords(p.Transformations),
Source: p.Source.Freeze(),
InputSnapshot: p.InputSnapshot.AllSegmentsSnapshot(),
ArtifactIDs: append([]string(nil), p.ArtifactIDs...),
}
}
func cloneCompileProjections(in map[string]CompileProjection) map[string]CompileProjection {
if len(in) == 0 {
return nil
}
out := make(map[string]CompileProjection, len(in))
for k, v := range in {
out[k] = v.clone()
}
return out
}
func cloneTransformRecords(in map[string]TransformRecord) map[string]TransformRecord {
if len(in) == 0 {
return nil
}
out := make(map[string]TransformRecord, len(in))
maps.Copy(out, in)
return out
}
func validateCompileTargets(targets []CompileTarget) error {
if len(targets) == 0 {
return nil
}
seen := make(map[string]struct{}, len(targets))
for _, target := range targets {
name := strings.TrimSpace(target.Name)
if name == "" {
return errors.New("contexty: compile target name is empty")
}
if _, ok := seen[name]; ok {
return ErrDuplicateCompileTarget
}
if target.View != "" {
if _, ok := builtinViewFormatter(target.View); !ok {
return fmt.Errorf("%w: %s", ErrUnknownCompileTargetView, target.View)
}
if target.SourceSegment != "" || target.Budget != nil || target.Formatter != nil {
return fmt.Errorf("%w: target %q view is mutually exclusive", ErrConflictingCompileTargetFields, name)
}
}
if target.SourceSegment != "" && !isKnownSegment(target.SourceSegment) {
return fmt.Errorf("%w: %s", ErrInvalidCompileTargetSegment, target.SourceSegment)
}
seen[name] = struct{}{}
}
return nil
}
func isKnownSegment(seg SegmentName) bool {
switch seg {
case SegmentSystem, SegmentHistory, SegmentTools, SegmentMemory:
return true
default:
return false
}
}
func (e *Engine) compileTargets(
ctx context.Context,
snap ConversationSnapshot,
targets []CompileTarget,
source CompileRequest,
transforms map[string]TransformRecord,
artifacts []ContextArtifact,
) (map[string]CompileProjection, error) {
if len(targets) == 0 {
return map[string]CompileProjection{}, nil
}
out := make(map[string]CompileProjection, len(targets))
artifactIDs := make([]string, 0, len(artifacts))
for _, artifact := range artifacts {
if artifact.ID != "" {
artifactIDs = append(artifactIDs, artifact.ID)
}
}
for _, target := range targets {
proj, err := e.compileTarget(ctx, snap, target, source, transforms)
if err != nil {
return nil, err
}
proj.Source = source.Freeze()
proj.ArtifactIDs = append([]string(nil), artifactIDs...)
out[proj.Name] = proj
}
return out, nil
}
func (e *Engine) compileTarget(
ctx context.Context,
snap ConversationSnapshot,
target CompileTarget,
source CompileRequest,
transforms map[string]TransformRecord,
) (CompileProjection, error) {
if err := ctx.Err(); err != nil {
return CompileProjection{}, fmt.Errorf("contexty: compile target %q: %w", target.Name, err)
}
name := strings.TrimSpace(target.Name)
ctx = withCompileIdentity(ctx, source.IdentityPolicy, source.RequireDurableIdentity, source.TurnID, name)
localTransforms := cloneTransformRecords(transforms)
if target.View != "" {
f, _ := builtinViewFormatter(target.View)
text, err := f.Format(ctx, snap)
if err != nil {
return CompileProjection{}, fmt.Errorf("contexty: compile target %q: %w", name, err)
}
return CompileProjection{
Name: name,
Text: text,
Messages: nil,
Transformations: localTransforms,
Source: emptyCompileRequest(),
InputSnapshot: snap.AllSegmentsSnapshot(),
ArtifactIDs: nil,
}, nil
}
seg := target.SourceSegment
if seg == "" {
seg = SegmentHistory
}
working := snap.Segment(seg)
if target.Budget != nil {
before := cloneMessageSlice(working)
budgetCtx := withBudgetIdentitySegment(ctx, seg)
trimmed, err := target.Budget.Apply(budgetCtx, working)
if err != nil {
return CompileProjection{}, fmt.Errorf("contexty: compile target %q budget: %w", name, err)
}
working = trimmed
recordProjectionBudgetTransforms(localTransforms, before, working)
}
if target.Formatter != nil {
before := cloneMessageSlice(working)
formatted, err := target.Formatter(ctx, cloneMessageSlice(working))
if err != nil {
return CompileProjection{}, fmt.Errorf("contexty: compile target %q formatter: %w", name, err)
}
working, err = ensureMessageIDsFromContext(ctx, seg, 0, formatted)
if err != nil {
return CompileProjection{}, fmt.Errorf("contexty: compile target %q identity: %w", name, err)
}
recordProjectionFormatterTransforms(localTransforms, before, working)
}
if err := validateUniqueMessageIDs(working); err != nil {
return CompileProjection{}, fmt.Errorf("contexty: compile target %q identity: %w", name, err)
}
return CompileProjection{
Name: name,
Text: plainMessagesText(working),
Messages: cloneMessageSlice(working),
Transformations: localTransforms,
Source: emptyCompileRequest(),
InputSnapshot: snap.AllSegmentsSnapshot(),
ArtifactIDs: nil,
}, nil
}
func emptyCompileRequest() CompileRequest {
return CompileRequest{
TurnID: "",
System: nil,
History: nil,
Memory: nil,
Tools: nil,
Pending: nil,
CurrentTurn: nil,
Artifacts: nil,
Options: nil,
IdentityPolicy: nil,
RequireDurableIdentity: false,
Targets: nil,
}
}
func plainMessagesText(msgs []Message) string {
var b strings.Builder
for _, m := range msgs {
b.WriteString(formatPartsPlain(m.Parts))
}
return b.String()
}
func recordProjectionBudgetTransforms(records map[string]TransformRecord, before, after []Message) {
beforeSet := messageIDSet(before)
afterSet := messageIDSet(after)
for _, msg := range before {
if msg.ID == "" {
continue
}
if _, kept := afterSet[msg.ID]; !kept {
records[msg.ID] = TransformRecord{Action: ActionTruncated, Reason: ReasonTokenBudgetExceeded}
}
}
for _, msg := range after {
if msg.ID == "" {
continue
}
if _, existed := beforeSet[msg.ID]; !existed {
records[msg.ID] = TransformRecord{Action: ActionPassed, Reason: ""}
}
}
}
func recordProjectionFormatterTransforms(records map[string]TransformRecord, before, after []Message) {
beforeSet := messageIDSet(before)
afterSet := messageIDSet(after)
for _, msg := range before {
if msg.ID == "" {
continue
}
if _, kept := afterSet[msg.ID]; !kept {
records[msg.ID] = TransformRecord{Action: ActionFormatted, Reason: ReasonReplacedByFormatter}
continue
}
formatted := findMessageByID(after, msg.ID)
if !MessageEqual(msg, formatted) {
records[msg.ID] = TransformRecord{Action: ActionFormatted, Reason: ReasonSegmentFormatter}
}
}
for _, msg := range after {
if msg.ID == "" {
continue
}
if _, existed := beforeSet[msg.ID]; !existed {
records[msg.ID] = TransformRecord{Action: ActionFormatted, Reason: ReasonSegmentFormatter}
}
}
}