-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththread.go
More file actions
241 lines (213 loc) · 5.87 KB
/
thread.go
File metadata and controls
241 lines (213 loc) · 5.87 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
package codex
import (
"context"
"encoding/json"
"errors"
"fmt"
"sync"
)
// Turn is a completed turn.
type Turn struct {
// Items contains completed items emitted during the turn.
Items []ThreadItem
// FinalResponse is the latest completed agent message text, if any.
FinalResponse string
// Usage contains token usage from the completed turn.
Usage *Usage
}
// RunResult is an alias for Turn.
type RunResult = Turn
// RunStreamedResult provides a stream of events and a terminal wait handle.
type RunStreamedResult struct {
Events <-chan ThreadEvent
done <-chan error
}
// Wait waits for the streamed turn to finish and returns any terminal error.
func (r *RunStreamedResult) Wait() error {
if r == nil || r.done == nil {
return nil
}
return <-r.done
}
// UserInput represents a structured input segment for a turn.
type UserInput struct {
// Type is either `text` or `local_image`.
Type string `json:"type"`
// Text contains prompt text for `text` items.
Text string `json:"text,omitempty"`
// Path contains the local image path for `local_image` items.
Path string `json:"path,omitempty"`
}
// Input is either a prompt string or a slice of UserInput values.
type Input = any
// Thread represents a conversation with the agent.
type Thread struct {
exec *CodexExec
options CodexOptions
threadOptions ThreadOptions
mu sync.RWMutex
id string
}
func newThread(exec *CodexExec, options CodexOptions, threadOptions ThreadOptions, id string) *Thread {
return &Thread{
exec: exec,
options: options,
threadOptions: threadOptions,
id: id,
}
}
// ID returns the thread ID, populated after the first thread.started event.
func (t *Thread) ID() string {
t.mu.RLock()
defer t.mu.RUnlock()
return t.id
}
func (t *Thread) setID(id string) {
t.mu.Lock()
defer t.mu.Unlock()
t.id = id
}
// RunStreamed starts a turn and streams structured events.
func (t *Thread) RunStreamed(input Input, options ...TurnOptions) (*RunStreamedResult, error) {
var turnOptions TurnOptions
if len(options) > 0 {
turnOptions = options[0]
}
schemaPath, cleanup, err := createOutputSchemaFile(turnOptions.OutputSchema)
if err != nil {
return nil, err
}
prompt, images, err := normalizeInput(input)
if err != nil {
_ = cleanup()
return nil, err
}
ctx := turnOptions.Context
if ctx == nil {
ctx = context.Background()
}
events := make(chan ThreadEvent)
done := make(chan error, 1)
go func() {
defer close(events)
defer close(done)
defer func() {
_ = cleanup()
}()
err := t.exec.Run(ctx, CodexExecArgs{
Input: prompt,
BaseURL: t.options.BaseURL,
APIKey: t.options.APIKey,
ThreadID: t.ID(),
Images: images,
Model: t.threadOptions.Model,
SandboxMode: t.threadOptions.SandboxMode,
WorkingDirectory: t.threadOptions.WorkingDirectory,
SkipGitRepoCheck: t.threadOptions.SkipGitRepoCheck,
OutputSchemaFile: schemaPath,
ModelReasoningEffort: t.threadOptions.ModelReasoningEffort,
NetworkAccessEnabled: t.threadOptions.NetworkAccessEnabled,
WebSearchMode: t.threadOptions.WebSearchMode,
WebSearchEnabled: t.threadOptions.WebSearchEnabled,
ApprovalPolicy: t.threadOptions.ApprovalPolicy,
AdditionalDirectories: t.threadOptions.AdditionalDirectories,
}, func(line string) error {
var event ThreadEvent
if err := json.Unmarshal([]byte(line), &event); err != nil {
return fmt.Errorf("failed to parse item: %s: %w", line, err)
}
if event.Type == "thread.started" && event.ThreadID != "" {
t.setID(event.ThreadID)
}
select {
case events <- event:
return nil
case <-ctx.Done():
return ctx.Err()
}
})
done <- err
}()
return &RunStreamedResult{Events: events, done: done}, nil
}
// Run starts a turn and buffers the completed result.
func (t *Thread) Run(input Input, options ...TurnOptions) (Turn, error) {
stream, err := t.RunStreamed(input, options...)
if err != nil {
return Turn{}, err
}
items := make([]ThreadItem, 0)
var finalResponse string
var usage *Usage
var turnFailure *ThreadError
for event := range stream.Events {
switch event.Type {
case "item.completed":
if event.Item != nil {
if event.Item.Type == "agent_message" {
finalResponse = event.Item.Text
}
items = append(items, *event.Item)
}
case "turn.completed":
usage = event.Usage
case "turn.failed":
turnFailure = event.Error
}
}
if err := stream.Wait(); err != nil {
return Turn{}, err
}
if turnFailure != nil {
return Turn{}, errors.New(turnFailure.Message)
}
return Turn{
Items: items,
FinalResponse: finalResponse,
Usage: usage,
}, nil
}
func normalizeInput(input Input) (string, []string, error) {
switch value := input.(type) {
case string:
return value, nil, nil
case []UserInput:
return normalizeStructuredInput(value)
case []*UserInput:
items := make([]UserInput, 0, len(value))
for _, item := range value {
if item == nil {
return "", nil, fmt.Errorf("input items cannot be nil")
}
items = append(items, *item)
}
return normalizeStructuredInput(items)
default:
return "", nil, fmt.Errorf("input must be a string or []UserInput")
}
}
func normalizeStructuredInput(input []UserInput) (string, []string, error) {
promptParts := make([]string, 0, len(input))
images := make([]string, 0)
for _, item := range input {
switch item.Type {
case "text":
promptParts = append(promptParts, item.Text)
case "local_image":
images = append(images, item.Path)
default:
return "", nil, fmt.Errorf("unsupported input type: %s", item.Type)
}
}
return joinPromptParts(promptParts), images, nil
}
func joinPromptParts(parts []string) string {
if len(parts) == 0 {
return ""
}
result := parts[0]
for i := 1; i < len(parts); i++ {
result += "\n\n" + parts[i]
}
return result
}