-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
296 lines (231 loc) · 7.28 KB
/
main.go
File metadata and controls
296 lines (231 loc) · 7.28 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
package main
import (
"context"
"fmt"
"log/slog"
"os"
"strings"
"time"
codexsdk "github.com/ethpandaops/codex-agent-sdk-go"
)
const systemMessageSubtypeInit = "init"
// displayMessage standardizes message display across examples.
func displayMessage(msg codexsdk.Message) {
switch m := msg.(type) {
case *codexsdk.UserMessage:
var text strings.Builder
for _, block := range m.Content.Blocks() {
if textBlock, ok := block.(*codexsdk.TextBlock); ok {
text.WriteString(textBlock.Text)
}
}
if text.Len() > 0 {
fmt.Printf("User: %s\n", text.String())
}
case *codexsdk.AssistantMessage:
var text strings.Builder
for _, block := range m.Content {
if textBlock, ok := block.(*codexsdk.TextBlock); ok {
text.WriteString(textBlock.Text)
}
}
if text.Len() > 0 {
fmt.Printf("Codex: %s\n", text.String())
}
case *codexsdk.SystemMessage:
// Ignore system messages in display
case *codexsdk.ResultMessage:
fmt.Println("Result ended")
if m.Usage != nil {
fmt.Printf("Tokens: %d in / %d out\n", m.Usage.InputTokens, m.Usage.OutputTokens)
}
}
}
// extractTools extracts tool names from a system message.
func extractTools(msg *codexsdk.SystemMessage) []string {
if msg.Subtype != systemMessageSubtypeInit || msg.Data == nil {
return nil
}
tools, ok := msg.Data["tools"].([]any)
if !ok {
return nil
}
result := make([]string, 0, len(tools))
for _, tool := range tools {
if toolStr, ok := tool.(string); ok {
result = append(result, toolStr)
}
}
return result
}
// toolsArrayExample demonstrates restricting tools to a specific array.
func toolsArrayExample() {
fmt.Println("=== Tools Array Example ===")
fmt.Println("Setting requested Tools=['Read', 'Glob', 'Grep']")
fmt.Println("This run compares requested configuration vs observed runtime tools.")
fmt.Println()
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
client := codexsdk.NewClient()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
defer func() {
if err := client.Close(); err != nil {
fmt.Fprintf(os.Stderr, "failed to close client: %v\n", err)
}
}()
if err := client.Start(ctx,
codexsdk.WithLogger(logger),
codexsdk.WithTools(codexsdk.ToolsList{"Read", "Glob", "Grep"}),
); err != nil {
fmt.Printf("Failed to connect: %v\n", err)
return
}
if err := client.Query(ctx, codexsdk.Text("List your currently available tools briefly.")); err != nil {
fmt.Printf("Failed to send query: %v\n", err)
return
}
for msg, err := range client.ReceiveMessages(ctx) {
if err != nil {
break
}
// Special handling for init message to show tools
if systemMsg, ok := msg.(*codexsdk.SystemMessage); ok && systemMsg.Subtype == systemMessageSubtypeInit {
tools := extractTools(systemMsg)
fmt.Printf("Tools from system message: %v\n", tools)
fmt.Println()
}
displayMessage(msg)
if _, ok := msg.(*codexsdk.ResultMessage); ok {
break
}
}
fmt.Println()
}
// toolsSingleToolExample demonstrates restricting to a single tool.
func toolsSingleToolExample() {
fmt.Println("=== Tools Single Tool Example ===")
fmt.Println("Setting requested Tools=['Read']")
fmt.Println("This run compares requested configuration vs observed runtime tools.")
fmt.Println()
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
client := codexsdk.NewClient()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
defer func() {
if err := client.Close(); err != nil {
fmt.Fprintf(os.Stderr, "failed to close client: %v\n", err)
}
}()
if err := client.Start(ctx,
codexsdk.WithLogger(logger),
codexsdk.WithTools(codexsdk.ToolsList{"Read"}),
); err != nil {
fmt.Printf("Failed to connect: %v\n", err)
return
}
if err := client.Query(ctx, codexsdk.Text("List your currently available tools briefly.")); err != nil {
fmt.Printf("Failed to send query: %v\n", err)
return
}
for msg, err := range client.ReceiveMessages(ctx) {
if err != nil {
break
}
// Special handling for init message to show tools
if systemMsg, ok := msg.(*codexsdk.SystemMessage); ok && systemMsg.Subtype == systemMessageSubtypeInit {
tools := extractTools(systemMsg)
fmt.Printf("Tools from system message: %v\n", tools)
fmt.Println()
}
displayMessage(msg)
if _, ok := msg.(*codexsdk.ResultMessage); ok {
break
}
}
fmt.Println()
}
// toolsPresetExample demonstrates using a preset configuration.
func toolsPresetExample() {
fmt.Println("=== Tools Preset Example ===")
fmt.Println("Setting requested Tools={type: 'preset', preset: 'claude_code'}")
fmt.Println("This run compares requested configuration vs observed runtime tools.")
fmt.Println()
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
client := codexsdk.NewClient()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
defer func() {
if err := client.Close(); err != nil {
fmt.Fprintf(os.Stderr, "failed to close client: %v\n", err)
}
}()
if err := client.Start(ctx,
codexsdk.WithLogger(logger),
codexsdk.WithTools(&codexsdk.ToolsPreset{Type: "preset", Preset: "claude_code"}),
); err != nil {
fmt.Printf("Failed to connect: %v\n", err)
return
}
if err := client.Query(ctx, codexsdk.Text("List your currently available tools briefly.")); err != nil {
fmt.Printf("Failed to send query: %v\n", err)
return
}
for msg, err := range client.ReceiveMessages(ctx) {
if err != nil {
break
}
// Special handling for init message to show tools
if systemMsg, ok := msg.(*codexsdk.SystemMessage); ok && systemMsg.Subtype == systemMessageSubtypeInit {
tools := extractTools(systemMsg)
if len(tools) > 5 {
fmt.Printf("Tools from system message (%d tools): %v...\n", len(tools), tools[:5])
} else {
fmt.Printf("Tools from system message (%d tools): %v\n", len(tools), tools)
}
fmt.Println()
}
displayMessage(msg)
if _, ok := msg.(*codexsdk.ResultMessage); ok {
break
}
}
fmt.Println()
}
func main() {
fmt.Println("Tools Option Examples")
fmt.Println()
fmt.Println("This example demonstrates requested tool configuration and observed runtime tool reporting.")
fmt.Println("Note: depending on runtime/backend behavior, requested tool limits may be treated as advisory.")
fmt.Println()
examples := map[string]func(){
"array": toolsArrayExample,
"single": toolsSingleToolExample,
"preset": toolsPresetExample,
}
if len(os.Args) < 2 {
fmt.Println("Usage: go run main.go <example_name>")
fmt.Println("\nAvailable examples:")
fmt.Println(" array - Request a specific tool list (Read, Glob, Grep)")
fmt.Println(" single - Request a single tool (Read)")
fmt.Println(" preset - Request claude_code preset for default tools")
return
}
exampleName := os.Args[1]
if exampleName == "all" {
for _, name := range []string{"array", "single", "preset"} {
examples[name]()
fmt.Println("--------------------------------------------------")
fmt.Println()
}
} else if fn, ok := examples[exampleName]; ok {
fn()
} else {
fmt.Printf("Error: Unknown example '%s'\n", exampleName)
fmt.Println("\nAvailable examples:")
fmt.Println(" array - Request specific tools")
fmt.Println(" single - Request a single tool")
fmt.Println(" preset - Request a preset")
fmt.Println(" all - Run all examples")
os.Exit(1)
}
}