package agentruntime import ( "bufio" "bytes" "context" "encoding/json" "errors" "fmt" "io" "os" "os/exec" "sync" "sync/atomic" "time" ) const ( poolMaxIdle = 4 poolIdleTTL = 2 * time.Minute poolMaxRunsPerWorker = 64 ) type poolKey struct { node string worker string } // piWorker owns one warm Node process and its protocol pipes across serial runs. type piWorker struct { cmd *exec.Cmd stdin io.WriteCloser stdout io.ReadCloser incoming chan record readDone chan error writeMu sync.Mutex writeFailed atomic.Bool ioCancel context.CancelFunc scratchParent string runs int lastUsed time.Time destroyOnce sync.Once } type workerPool struct { mu sync.Mutex idle map[poolKey][]*piWorker } var pool = &workerPool{idle: map[poolKey][]*piWorker{}} func startPiWorker(ctx context.Context, node, workerPath string) (*piWorker, error) { scratchParent, err := os.MkdirTemp("", "cyberstrike-pi-host-") if err != nil { return nil, err } cmd := exec.Command(node, workerPath) cmd.Env = append(os.Environ(), "CYBERSTRIKE_PI_TMP_PARENT="+scratchParent) stdin, err := cmd.StdinPipe() if err != nil { os.RemoveAll(scratchParent) return nil, err } stdout, err := cmd.StdoutPipe() if err != nil { stdin.Close() os.RemoveAll(scratchParent) return nil, err } // Worker protocol carries failures. Never forward arbitrary stderr (which may include provider secrets). cmd.Stderr = io.Discard if err = cmd.Start(); err != nil { stdin.Close() stdout.Close() os.RemoveAll(scratchParent) return nil, fmt.Errorf("start Pi worker: %w", err) } ioCtx, ioCancel := context.WithCancel(context.Background()) w := &piWorker{cmd: cmd, stdin: stdin, stdout: stdout, incoming: make(chan record, 32), readDone: make(chan error, 1), ioCancel: ioCancel, scratchParent: scratchParent} go w.readLoop(ioCtx) readyTimeout := time.NewTimer(20 * time.Second) defer readyTimeout.Stop() select { case r := <-w.incoming: if r.Type != "ready" || r.Version != ProtocolVersion || r.SDKVersion != "1.7.0" { w.destroy() return nil, errors.New("Pi runtime protocol mismatch") } case err := <-w.readDone: w.destroy() if err != nil { return nil, fmt.Errorf("read Pi worker handshake: %w", err) } return nil, errors.New("Pi worker closed stdout before handshake") case <-readyTimeout.C: w.destroy() return nil, errors.New("Pi worker startup timeout") case <-ctx.Done(): w.destroy() return nil, ctx.Err() } return w, nil } func (w *piWorker) readLoop(ioCtx context.Context) { scanner := bufio.NewScanner(w.stdout) scanner.Buffer(make([]byte, 64*1024), maxRecordBytes+1) for line := 1; scanner.Scan(); line++ { data := scanner.Bytes() var r record if err := json.Unmarshal(data, &r); err != nil { if len(bytes.TrimSpace(data)) == 0 { w.readDone <- fmt.Errorf("blank Pi protocol line %d", line) } else { w.readDone <- fmt.Errorf("invalid Pi protocol JSON on line %d: %w", line, err) } return } select { case w.incoming <- r: case <-ioCtx.Done(): w.readDone <- ioCtx.Err() return } } w.readDone <- scanner.Err() } func (w *piWorker) write(v any) error { body, err := json.Marshal(v) if err != nil { return err } if len(body) > maxRecordBytes { return errors.New("Pi request exceeds protocol record limit") } w.writeMu.Lock() defer w.writeMu.Unlock() _, err = w.stdin.Write(append(body, '\n')) if err != nil { w.writeFailed.Store(true) } return err } func (w *piWorker) alive() bool { select { case <-w.readDone: return false default: return true } } func (w *piWorker) destroy() { w.destroyOnce.Do(func() { w.ioCancel() w.stdin.Close() if w.cmd.Process != nil { _ = w.cmd.Process.Kill() } _ = w.cmd.Wait() w.stdout.Close() os.RemoveAll(w.scratchParent) }) } func (p *workerPool) acquire(ctx context.Context, node, workerPath string) (*piWorker, error) { key := poolKey{node, workerPath} p.mu.Lock() list := p.idle[key] var chosen *piWorker var dead []*piWorker for len(list) > 0 { w := list[len(list)-1] list = list[:len(list)-1] if time.Since(w.lastUsed) > poolIdleTTL || !w.alive() { dead = append(dead, w) continue } chosen = w break } p.idle[key] = list p.mu.Unlock() for _, w := range dead { w.destroy() } if chosen != nil { return chosen, nil } return startPiWorker(ctx, node, workerPath) } func (p *workerPool) release(node, workerPath string, w *piWorker) { key := poolKey{node, workerPath} w.lastUsed = time.Now() p.mu.Lock() list := p.idle[key] if len(list) >= poolMaxIdle { p.mu.Unlock() w.destroy() return } p.idle[key] = append(list, w) p.mu.Unlock() } // CloseIdleWorkers reaps every pooled idle process for tests and graceful shutdown. func CloseIdleWorkers() { pool.mu.Lock() all := pool.idle pool.idle = map[poolKey][]*piWorker{} pool.mu.Unlock() for _, list := range all { for _, w := range list { w.destroy() } } } // run drives one keepAlive run over the worker. The caller decides whether the // worker returns to the pool; any cancel, timeout or protocol error destroys it. func (w *piWorker) run(ctx context.Context, req Request, execute ToolExecutor, emit func(Event), bind func(Control) func()) (*Result, error) { runCtx, cancel := context.WithCancel(ctx) var toolWG sync.WaitGroup var inFlightTools atomic.Int32 defer func() { cancel() toolWG.Wait() }() run := runRequest{Request: req, LegacyProfile: json.RawMessage(`{"enabled":false}`)} if err := w.write(record{Type: "run", Version: ProtocolVersion, KeepAlive: true, Request: &run}); err != nil { return nil, err } if bind != nil { unbind := bind(Control{ Steer: func(s string) error { return w.write(map[string]any{"type": "steer", "message": s}) }, Cancel: func() error { cancel(); return w.write(map[string]any{"type": "cancel"}) }, }) if unbind != nil { defer unbind() } } type executed struct { call string result ToolResult done chan struct{} } var toolMu sync.Mutex toolCache := map[string]*executed{} toolSlots := make(chan struct{}, 32) ctxDone := ctx.Done() var cancelDeadline <-chan time.Time var cancelTimer *time.Timer defer func() { if cancelTimer != nil { cancelTimer.Stop() } }() for { select { case r := <-w.incoming: switch r.Type { case "event": if emit != nil && r.Event != nil { emit(*r.Event) } case "tool_call": if r.Call == nil || r.Call.ID == "" { return nil, errors.New("Pi tool call has no identity") } call := *r.Call select { case toolSlots <- struct{}{}: default: return nil, errors.New("Pi tool concurrency limit exceeded") } toolWG.Add(1) inFlightTools.Add(1) go func() { defer toolWG.Done() defer inFlightTools.Add(-1) defer func() { <-toolSlots }() body, _ := json.Marshal(call) toolMu.Lock() cached := toolCache[call.ID] if cached == nil { cached = &executed{call: string(body), done: make(chan struct{})} toolCache[call.ID] = cached toolMu.Unlock() res := ToolResult{IsError: true, Content: "No host tool executor"} if execute != nil { var invokeErr error res, invokeErr = execute(runCtx, call) if invokeErr != nil { res.IsError = true res.Content = invokeErr.Error() } } cached.result = res close(cached.done) } else { toolMu.Unlock() } select { case <-cached.done: case <-runCtx.Done(): return } if runCtx.Err() != nil { return } res := cached.result if cached.call != string(body) { res = ToolResult{IsError: true, Content: "Tool call ID reused with different arguments"} } _ = w.write(map[string]any{"type": "tool_result", "id": call.ID, "result": res}) }() case "result": if r.Result == nil { return nil, errors.New("Pi returned an empty result") } if ctx.Err() != nil { return r.Result, ctx.Err() } if r.Result.Error != "" { return r.Result, fmt.Errorf("Pi runtime error: %s", r.Result.Error) } if r.Result.Status == "canceled" { return r.Result, context.Canceled } if inFlightTools.Load() > 0 { // A run that settled while sibling tool calls were still in flight cannot // safely share its stdio stream with a subsequent run; mark it non-reusable. w.writeFailed.Store(true) } return r.Result, nil case "fatal": return nil, fmt.Errorf("Pi protocol failure: %s", r.Error) default: return nil, fmt.Errorf("unexpected Pi record: %s", r.Type) } case err := <-w.readDone: // Drain records queued before the reader reported EOF or an error. if len(w.incoming) > 0 { w.readDone <- err continue } if err != nil { return nil, fmt.Errorf("read Pi worker output: %w", err) } return nil, errors.New("Pi worker closed stdout without a result") case <-ctxDone: ctxDone = nil _ = w.write(map[string]any{"type": "cancel"}) cancelTimer = time.NewTimer(2 * time.Second) cancelDeadline = cancelTimer.C case <-cancelDeadline: return nil, ctx.Err() } } }