77 "strconv"
88 "strings"
99 "sync"
10+ "sync/atomic"
1011 "time"
1112
1213 "github.com/gptscript-ai/gptscript/pkg/runner"
@@ -22,7 +23,8 @@ type Event struct {
2223}
2324
2425type fileFactory struct {
25- file * os.File
26+ file * os.File
27+ runningCount atomic.Int32
2628}
2729
2830// NewFileFactory creates a new monitor factory that writes events to the location specified.
@@ -44,23 +46,26 @@ func NewFileFactory(loc string) (runner.MonitorFactory, error) {
4446
4547 file = os .NewFile (uintptr (fd ), "events" )
4648 } else {
47- file , err = os .OpenFile (loc , os .O_WRONLY | os .O_CREATE , 0 )
49+ file , err = os .OpenFile (loc , os .O_WRONLY | os .O_CREATE , 0644 )
4850 if err != nil {
4951 return nil , err
5052 }
5153 }
5254
5355 return & fileFactory {
54- file : file ,
56+ file : file ,
57+ runningCount : atomic.Int32 {},
5558 }, nil
5659}
5760
58- func (s fileFactory ) Start (_ context.Context , prg * types.Program , env []string , input string ) (runner.Monitor , error ) {
61+ func (s * fileFactory ) Start (_ context.Context , prg * types.Program , env []string , input string ) (runner.Monitor , error ) {
62+ s .runningCount .Add (1 )
5963 fd := & fd {
60- prj : prg ,
61- env : env ,
62- input : input ,
63- file : s .file ,
64+ prj : prg ,
65+ env : env ,
66+ input : input ,
67+ file : s .file ,
68+ factory : s ,
6469 }
6570
6671 fd .event (Event {
@@ -74,12 +79,21 @@ func (s fileFactory) Start(_ context.Context, prg *types.Program, env []string,
7479 return fd , nil
7580}
7681
82+ func (s * fileFactory ) close () {
83+ if count := s .runningCount .Add (- 1 ); count == 0 {
84+ if err := s .file .Close (); err != nil {
85+ log .Errorf ("error closing monitor file: %v" , err )
86+ }
87+ }
88+ }
89+
7790type fd struct {
7891 prj * types.Program
7992 env []string
8093 input string
8194 file * os.File
8295 runLock sync.Mutex
96+ factory * fileFactory
8397}
8498
8599func (f * fd ) Event (event runner.Event ) {
@@ -117,9 +131,7 @@ func (f *fd) Stop(output string, err error) {
117131 }
118132
119133 f .event (e )
120- if err = f .file .Close (); err != nil {
121- log .Errorf ("Failed to close file: %v" , err )
122- }
134+ f .factory .close ()
123135}
124136
125137func (f * fd ) Pause () func () {
0 commit comments