-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwith_client.go
More file actions
58 lines (51 loc) · 1.44 KB
/
with_client.go
File metadata and controls
58 lines (51 loc) · 1.44 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
package codexsdk
import (
"context"
"fmt"
)
// WithClient manages client lifecycle with automatic cleanup.
//
// This helper creates a client, starts it with the provided options, executes the
// callback function, and ensures proper cleanup via Close() when done.
//
// The callback receives a fully initialized Client that is ready for use.
// If the callback returns an error, it is returned to the caller.
// If Close() fails, a warning is logged but does not override the callback's error.
//
// Example usage:
//
// err := codexsdk.WithClient(ctx, func(c codexsdk.Client) error {
// if err := c.Query(ctx, Text("Hello")); err != nil {
// return err
// }
// for msg, err := range c.ReceiveResponse(ctx) {
// if err != nil {
// return err
// }
// // process message...
// }
// return nil
// },
// codexsdk.WithLogger(log),
// codexsdk.WithPermissionMode("acceptEdits"),
// )
func WithClient(ctx context.Context, fn func(Client) error, opts ...Option) error {
if ctx.Err() != nil {
return ctx.Err()
}
options := applyAgentOptions(opts)
log := options.Logger
if log == nil {
log = NopLogger()
}
client := NewClient()
if err := client.Start(ctx, opts...); err != nil {
return fmt.Errorf("failed to start client: %w", err)
}
defer func() {
if closeErr := client.Close(); closeErr != nil {
log.Warn("failed to close client", "error", closeErr)
}
}()
return fn(client)
}