perf(agentruntime): reuse warm Pi worker processes across runs with strict cancel isolation
This commit is contained in:
parent
f76fcdf407
commit
0677d5fa87
|
|
@ -1,18 +1,12 @@
|
|||
package agentruntime
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxRecordBytes = 32 * 1024 * 1024
|
||||
|
|
@ -30,6 +24,7 @@ type runRequest struct {
|
|||
type record struct {
|
||||
Type string `json:"type"`
|
||||
Version int `json:"version,omitempty"`
|
||||
KeepAlive bool `json:"keepAlive,omitempty"`
|
||||
Request *runRequest `json:"request,omitempty"`
|
||||
Event *Event `json:"event,omitempty"`
|
||||
Call *ToolCall `json:"call,omitempty"`
|
||||
|
|
@ -86,7 +81,9 @@ func workerCandidates() []string {
|
|||
return candidates
|
||||
}
|
||||
|
||||
// Run owns one isolated worker and reaps it on every exit. Tool execution stays in the host.
|
||||
// Run reuses a warm pooled worker when one is healthy, otherwise starts a fresh
|
||||
// process. Tool execution stays in the host. A worker only returns to the pool
|
||||
// after a clean result with no cancel, timeout or protocol error.
|
||||
func (p Pi) Run(ctx context.Context, req Request, execute ToolExecutor, emit func(Event), bind func(Control) func()) (*Result, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
|
|
@ -103,7 +100,7 @@ func (p Pi) Run(ctx context.Context, req Request, execute ToolExecutor, emit fun
|
|||
return nil, err
|
||||
}
|
||||
defer release()
|
||||
worker, err := ResolveWorker(p.WorkerPath)
|
||||
workerPath, err := ResolveWorker(p.WorkerPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -111,215 +108,16 @@ func (p Pi) Run(ctx context.Context, req Request, execute ToolExecutor, emit fun
|
|||
if node == "" {
|
||||
node = "node"
|
||||
}
|
||||
scratchParent, err := os.MkdirTemp("", "cyberstrike-pi-host-")
|
||||
w, err := pool.acquire(ctx, node, workerPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer os.RemoveAll(scratchParent)
|
||||
cmd := exec.Command(node, worker)
|
||||
cmd.Env = append(os.Environ(), "CYBERSTRIKE_PI_TMP_PARENT="+scratchParent)
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
stdin.Close()
|
||||
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()
|
||||
return nil, fmt.Errorf("start Pi worker: %w", err)
|
||||
}
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
ioCtx, stopIO := context.WithCancel(context.Background())
|
||||
defer stopIO()
|
||||
var writeMu sync.Mutex
|
||||
write := func(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")
|
||||
}
|
||||
writeMu.Lock()
|
||||
defer writeMu.Unlock()
|
||||
_, err = stdin.Write(append(body, '\n'))
|
||||
return err
|
||||
}
|
||||
incoming := make(chan record, 32)
|
||||
readDone := make(chan error, 1)
|
||||
go func() {
|
||||
scanner := bufio.NewScanner(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 {
|
||||
readDone <- fmt.Errorf("blank Pi protocol line %d", line)
|
||||
} else {
|
||||
readDone <- fmt.Errorf("invalid Pi protocol JSON on line %d: %w", line, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
select {
|
||||
case incoming <- r:
|
||||
case <-ioCtx.Done():
|
||||
readDone <- ioCtx.Err()
|
||||
return
|
||||
}
|
||||
}
|
||||
readDone <- scanner.Err()
|
||||
}()
|
||||
defer func() {
|
||||
cancel()
|
||||
stopIO()
|
||||
stdin.Close()
|
||||
_ = cmd.Process.Kill()
|
||||
_ = cmd.Wait()
|
||||
stdout.Close()
|
||||
}()
|
||||
readyTimeout := time.NewTimer(20 * time.Second)
|
||||
defer readyTimeout.Stop()
|
||||
select {
|
||||
case r := <-incoming:
|
||||
if r.Type != "ready" || r.Version != ProtocolVersion || r.SDKVersion != "1.7.0" {
|
||||
return nil, errors.New("Pi runtime protocol mismatch")
|
||||
}
|
||||
case err := <-readDone:
|
||||
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:
|
||||
return nil, errors.New("Pi worker startup timeout")
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
// Older protocol v1 workers require a profile object. Keep it disabled.
|
||||
run := runRequest{Request: req, LegacyProfile: json.RawMessage(`{"enabled":false}`)}
|
||||
if err = write(record{Type: "run", Version: ProtocolVersion, Request: &run}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if bind != nil {
|
||||
unbind := bind(Control{
|
||||
Steer: func(s string) error { return write(map[string]any{"type": "steer", "message": s}) },
|
||||
Cancel: func() error { cancel(); return 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 := <-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")
|
||||
}
|
||||
go func() {
|
||||
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
|
||||
}
|
||||
res := cached.result
|
||||
if cached.call != string(body) {
|
||||
res = ToolResult{IsError: true, Content: "Tool call ID reused with different arguments"}
|
||||
}
|
||||
_ = 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
|
||||
}
|
||||
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 := <-readDone:
|
||||
// Drain records queued before the reader reported EOF or an error.
|
||||
if len(incoming) > 0 {
|
||||
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
|
||||
_ = write(map[string]any{"type": "cancel"})
|
||||
cancelTimer = time.NewTimer(2 * time.Second)
|
||||
cancelDeadline = cancelTimer.C
|
||||
case <-cancelDeadline:
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
res, runErr := w.run(ctx, req, execute, emit, bind)
|
||||
w.runs++
|
||||
if runErr == nil && ctx.Err() == nil && !w.writeFailed.Load() && w.runs < poolMaxRunsPerWorker {
|
||||
pool.release(node, workerPath, w)
|
||||
} else {
|
||||
w.destroy()
|
||||
}
|
||||
return res, runErr
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ func fixtureWorker(t *testing.T, body string) Pi {
|
|||
if err != nil {
|
||||
t.Skip("Node is unavailable")
|
||||
}
|
||||
t.Cleanup(CloseIdleWorkers)
|
||||
path := filepath.Join(t.TempDir(), "worker.cjs")
|
||||
script := `const readline=require('node:readline');
|
||||
const send=x=>process.stdout.write(JSON.stringify(x)+'\n');
|
||||
|
|
|
|||
|
|
@ -0,0 +1,347 @@
|
|||
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)
|
||||
defer cancel()
|
||||
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")
|
||||
}
|
||||
go func() {
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
package agentruntime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const pidWorkerBody = `input.on('line',line=>{const r=JSON.parse(line);
|
||||
if(r.type==='run')send({type:'result',result:{status:'completed',response:String(process.pid),history:[]}});
|
||||
if(r.type==='cancel')send({type:'result',result:{status:'canceled',response:String(process.pid),history:[]}});});`
|
||||
|
||||
func idleCount() int {
|
||||
pool.mu.Lock()
|
||||
defer pool.mu.Unlock()
|
||||
n := 0
|
||||
for _, list := range pool.idle {
|
||||
n += len(list)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestPoolReusesWarmWorkerAcrossRuns(t *testing.T) {
|
||||
p := fixtureWorker(t, pidWorkerBody)
|
||||
ctx := context.Background()
|
||||
var pids []string
|
||||
for i := 0; i < 3; i++ {
|
||||
res, err := p.Run(ctx, Request{RunID: fmt.Sprintf("reuse-%d", i)}, nil, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pids = append(pids, res.Response)
|
||||
}
|
||||
if pids[0] == "" || pids[0] != pids[1] || pids[1] != pids[2] {
|
||||
t.Fatalf("expected one reused worker PID, got %v", pids)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolCancelDestroysWorkerAndNextRunGetsFreshPID(t *testing.T) {
|
||||
p := fixtureWorker(t, `input.on('line',line=>{const r=JSON.parse(line);
|
||||
if(r.type==='run')send({type:'tool_call',call:{id:'wait',name:'wait',arguments:{}}});
|
||||
if(r.type==='tool_result')send({type:'result',result:{status:'completed',response:String(process.pid),history:[]}});
|
||||
if(r.type==='cancel')send({type:'result',result:{status:'canceled',response:String(process.pid),history:[]}});});`)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
started := make(chan struct{})
|
||||
go func() { <-started; cancel() }()
|
||||
canceled, err := p.Run(ctx, Request{RunID: "cancel-me"}, func(c context.Context, _ ToolCall) (ToolResult, error) {
|
||||
close(started)
|
||||
<-c.Done()
|
||||
return ToolResult{}, c.Err()
|
||||
}, nil, nil)
|
||||
if err == nil || canceled == nil || canceled.Response == "" {
|
||||
t.Fatalf("expected canceled result with old PID, got result=%+v err=%v", canceled, err)
|
||||
}
|
||||
fresh, err := p.Run(context.Background(), Request{RunID: "fresh"}, func(context.Context, ToolCall) (ToolResult, error) {
|
||||
return ToolResult{Content: "ok"}, nil
|
||||
}, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fresh.Response == "" || fresh.Response == canceled.Response {
|
||||
t.Fatalf("expected a fresh worker PID after cancel, old=%q new=%q", canceled.Response, fresh.Response)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolConcurrentRunsRaceFreeAndCloseReapsIdle(t *testing.T) {
|
||||
p := fixtureWorker(t, pidWorkerBody)
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, 64)
|
||||
for i := 0; i < 16; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 3; j++ {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
res, err := p.Run(ctx, Request{RunID: fmt.Sprintf("conc-%d-%d", i, j)}, nil, nil, nil)
|
||||
cancel()
|
||||
if err != nil {
|
||||
errs <- err
|
||||
return
|
||||
}
|
||||
if res.Response == "" {
|
||||
errs <- fmt.Errorf("empty worker PID")
|
||||
return
|
||||
}
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if idleCount() == 0 {
|
||||
t.Fatal("expected pooled idle workers after concurrent runs")
|
||||
}
|
||||
CloseIdleWorkers()
|
||||
if n := idleCount(); n != 0 {
|
||||
t.Fatalf("CloseIdleWorkers left %d idle workers", n)
|
||||
}
|
||||
}
|
||||
|
|
@ -42,15 +42,22 @@ interface RunRequest {
|
|||
}
|
||||
interface ToolReply { content: string; images?: Omit<ImageContent, "type">[]; isError?: boolean; executionId?: string; terminate?: boolean; structuredContent?: Record<string, unknown> }
|
||||
|
||||
let session: AgentSession | undefined;
|
||||
interface ActiveRun {
|
||||
keepAlive: boolean;
|
||||
scratch: string;
|
||||
id: string;
|
||||
session?: AgentSession;
|
||||
canceled: boolean;
|
||||
toolSequence: number;
|
||||
generationAbort: AbortController;
|
||||
steeringBeforeSession?: string[];
|
||||
pending: Map<string, { resolve: (r: ToolReply) => void; reject: (e: Error) => void }>;
|
||||
}
|
||||
|
||||
let activeRun: ActiveRun | undefined;
|
||||
let started = false;
|
||||
let canceled = false;
|
||||
let activeRunId = "";
|
||||
let toolSequence = 0;
|
||||
const generationAbort = new AbortController();
|
||||
let steeringBeforeSession: string[] | undefined = [];
|
||||
const pending = new Map<string, { resolve: (r: ToolReply) => void; reject: (e: Error) => void }>();
|
||||
const scratch = mkdtempSync(join(process.env.CYBERSTRIKE_PI_TMP_PARENT || tmpdir(), "cyberstrike-pi-"));
|
||||
let stdinEnded = false;
|
||||
const scratchRoot = mkdtempSync(join(process.env.CYBERSTRIKE_PI_TMP_PARENT || tmpdir(), "cyberstrike-pi-"));
|
||||
|
||||
function resources(prompt: string): ResourceLoader {
|
||||
return {
|
||||
|
|
@ -63,7 +70,7 @@ function resources(prompt: string): ResourceLoader {
|
|||
};
|
||||
}
|
||||
|
||||
function hostTool(def: RunRequest["tools"][number], imageInput: boolean, recorded?: (name: string, reply: ToolReply) => void, entryFor?: (providerId: string) => string | undefined): ToolDefinition {
|
||||
function hostTool(current: ActiveRun, def: RunRequest["tools"][number], imageInput: boolean, recorded?: (name: string, reply: ToolReply) => void, entryFor?: (providerId: string) => string | undefined): ToolDefinition {
|
||||
return {
|
||||
name: def.name, label: def.name, description: def.description, parameters: def.parameters as never,
|
||||
outputSchema: def.outputSchema as never, annotations: def.annotations, namespace: def.namespace ? { name: def.namespace } : undefined,
|
||||
|
|
@ -72,11 +79,11 @@ function hostTool(def: RunRequest["tools"][number], imageInput: boolean, recorde
|
|||
execute: async (providerId, args, signal) => {
|
||||
// Provider IDs are scoped to a model message and may repeat on later turns.
|
||||
// The host's replay key must identify an actual invocation, not that provider label.
|
||||
const id = activeRunId + ":tool-" + (++toolSequence);
|
||||
const id = current.id + ":tool-" + (++current.toolSequence);
|
||||
if (signal?.aborted) throw new Error("Tool canceled");
|
||||
const reply = await new Promise<ToolReply>((resolve, reject) => {
|
||||
const abort = () => { pending.delete(id); reject(new Error("Tool canceled")); };
|
||||
pending.set(id, {
|
||||
const abort = () => { current.pending.delete(id); reject(new Error("Tool canceled")); };
|
||||
current.pending.set(id, {
|
||||
resolve: (r) => { signal?.removeEventListener("abort", abort); resolve(r); },
|
||||
reject: (e) => { signal?.removeEventListener("abort", abort); reject(e); },
|
||||
});
|
||||
|
|
@ -256,7 +263,7 @@ function openSession(workingDir: string, sessionDir?: string): SessionManager {
|
|||
return SessionManager.open(join(dir, file), dir, workingDir);
|
||||
}
|
||||
|
||||
async function run(req: RunRequest): Promise<void> {
|
||||
async function run(req: RunRequest, current: ActiveRun): Promise<void> {
|
||||
let status = "completed";
|
||||
let failure = "";
|
||||
let manager: SessionManager | undefined;
|
||||
|
|
@ -264,13 +271,13 @@ async function run(req: RunRequest): Promise<void> {
|
|||
let directResult: Record<string, unknown> | undefined;
|
||||
try {
|
||||
if (!req.runId || !req.model?.id || !Array.isArray(req.tools)) throw new Error("Invalid run request");
|
||||
activeRunId = req.runId;
|
||||
const workingDir = req.workingDir ? resolve(req.workingDir) : scratch;
|
||||
current.id = req.runId;
|
||||
const workingDir = req.workingDir ? resolve(req.workingDir) : current.scratch;
|
||||
const names = req.tools.map(t => t.name);
|
||||
if (new Set(names).size !== names.length || names.some(n => !/^[a-zA-Z0-9_.-]+$/.test(n))) throw new Error("Invalid tool catalog");
|
||||
const codemodeEnabled = req.codemode === true && !names.includes("codemode");
|
||||
const runtime = await ModelRuntime.create({ credentials: new InMemoryCredentialStore(), modelsPath: null,
|
||||
modelsStorePath: join(scratch, "models.json"), allowModelNetwork: false, refreshOnCreate: false });
|
||||
modelsStorePath: join(current.scratch, "models.json"), allowModelNetwork: false, refreshOnCreate: false });
|
||||
const configs = [req.model, ...(req.fallbackModels ?? [])];
|
||||
const catalog = runtime.getModels();
|
||||
const physical: Model<Api>[] = [];
|
||||
|
|
@ -341,7 +348,7 @@ async function run(req: RunRequest): Promise<void> {
|
|||
const images: ImageContent[] = imageInput ? (req.images ?? []).map(image => ({ ...image, type: "image" })) : [];
|
||||
const skillPaths = req.skillPaths?.length ? req.skillPaths : req.nativeWorkflow?.skillPaths;
|
||||
const skills = skillPaths?.length
|
||||
? loadSkills({ cwd: workingDir, agentDir: scratch, skillPaths, includeDefaults: false }) : undefined;
|
||||
? loadSkills({ cwd: workingDir, agentDir: current.scratch, skillPaths, includeDefaults: false }) : undefined;
|
||||
// Skill metadata is stable, so it belongs to the cacheable prefix ahead of run context.
|
||||
const skillLoaderTool = req.skillToolName && names.includes(req.skillToolName)
|
||||
? req.skillToolName
|
||||
|
|
@ -354,7 +361,7 @@ async function run(req: RunRequest): Promise<void> {
|
|||
+ (codemodeEnabled ? "\nUse codemode to batch, join, or filter multi-step tool calls in a single sandboxed JavaScript turn when raw tool outputs would be large." : "")
|
||||
+ (req.systemPromptDynamic ?? "");
|
||||
if (req.generateOnly) {
|
||||
const input = SessionManager.inMemory(scratch);
|
||||
const input = SessionManager.inMemory(current.scratch);
|
||||
importHistory(input, req.history ?? [], req.model);
|
||||
if (images.length) {
|
||||
input.appendMessage({ role: "user", content: [{ type: "text", text: req.message }, ...images], timestamp: Date.now() });
|
||||
|
|
@ -365,7 +372,7 @@ async function run(req: RunRequest): Promise<void> {
|
|||
systemPrompt,
|
||||
messages: input.buildSessionContext().messages as Message[],
|
||||
...(req.tools.length ? { tools: req.tools } : {}),
|
||||
}, { maxTokens: req.model.maxTokens, ...(typeof req.model.temperature === "number" ? { temperature: req.model.temperature } : {}), reasoning: (req.model.thinking && req.model.thinking !== "off" ? req.model.thinking : undefined) as any, signal: generationAbort.signal });
|
||||
}, { maxTokens: req.model.maxTokens, ...(typeof req.model.temperature === "number" ? { temperature: req.model.temperature } : {}), reasoning: (req.model.thinking && req.model.thinking !== "off" ? req.model.thinking : undefined) as any, signal: current.generationAbort.signal });
|
||||
if (answer.stopReason === "error" || answer.stopReason === "aborted") throw new Error(answer.errorMessage || answer.stopReason);
|
||||
directResult = { response: answer.content.filter(b => b.type === "text").map(b => b.text).join(""), history: exportHistory([answer]), totalTokens: answer.usage.totalTokens };
|
||||
return;
|
||||
|
|
@ -385,7 +392,7 @@ async function run(req: RunRequest): Promise<void> {
|
|||
const always = new Set(["task", "exit", "transfer_to_agent", "write_todos", "TaskCreate", "TaskUpdate", "TaskGet", "TaskList", "skill", "read_file", "execute", "wait_tool_execution", "get_tool_execution", "cancel_tool_execution", ...(req.alwaysVisibleTools ?? [])]);
|
||||
const loader = resources(systemPrompt + (searchEnabled ? "\nDiscover additional task tools with tool_search. Search results enable matching tools for subsequent calls." : ""));
|
||||
if (searchEnabled || workflow || codemodeEnabled) {
|
||||
const extensions = new DefaultResourceLoader({ cwd: scratch, agentDir: scratch, settingsManager: SettingsManager.inMemory(),
|
||||
const extensions = new DefaultResourceLoader({ cwd: current.scratch, agentDir: current.scratch, settingsManager: SettingsManager.inMemory(),
|
||||
noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
|
||||
extensionFactories: [...(searchEnabled ? [createToolSearchExtension()] : []), ...(codemodeEnabled ? [createCodemodeExtension({
|
||||
mode: req.codemodeMode === "only" ? "only" : "on",
|
||||
|
|
@ -394,7 +401,7 @@ async function run(req: RunRequest): Promise<void> {
|
|||
models: false,
|
||||
})] : []), ...(workflow ? [(pi: any) => {
|
||||
pi.on("agent_before_settle", (event: any) => {
|
||||
if (submitted || canceled || status !== "completed" || event.outcome !== "completed") return;
|
||||
if (submitted || current.canceled || status !== "completed" || event.outcome !== "completed") return;
|
||||
if (wrappingUp && wrapupRemaining <= 0) { status = "yielded"; return; }
|
||||
if (reminders++ >= 2) { status = wrappingUp ? "yielded" : "incomplete"; return; }
|
||||
const promptText = wrappingUp && workflow.wrapupPrompt
|
||||
|
|
@ -410,10 +417,10 @@ async function run(req: RunRequest): Promise<void> {
|
|||
}
|
||||
if (skills) loader.getSkills = () => skills;
|
||||
const inputBudget = Math.max(1024, Math.min(req.model.inputBudget || model.contextWindow - model.maxTokens, model.contextWindow - model.maxTokens));
|
||||
({ session } = await createAgentSession({ cwd: workingDir, agentDir: scratch, modelRuntime: runtime, model,
|
||||
({ session: current.session } = await createAgentSession({ cwd: workingDir, agentDir: current.scratch, modelRuntime: runtime, model,
|
||||
thinkingLevel: (req.model.thinking || "off") as any, sessionManager: manager,
|
||||
settingsManager: SettingsManager.inMemory({ retry: { enabled: true, maxRetries: req.retryMax ?? Math.max(2, configs.length - 1), ...(req.retryMaxDelayMs ? { maxAgentDelayMs: req.retryMaxDelayMs } : {}) }, compaction: { enabled: true, reserveTokens: model.contextWindow - inputBudget, keepRecentTokens: Math.min(20000, Math.floor(inputBudget / 2)) } }),
|
||||
noTools: "builtin", tools: searchEnabled ? (codemodeEnabled ? ["+tool_search", "+codemode"] : ["+tool_search"]) : (codemodeEnabled ? [...names, "codemode"] : names), customTools: req.tools.map(def => ({ ...hostTool(def, imageInput, workflow ? (name, reply) => {
|
||||
noTools: "builtin", tools: searchEnabled ? (codemodeEnabled ? ["+tool_search", "+codemode"] : ["+tool_search"]) : (codemodeEnabled ? [...names, "codemode"] : names), customTools: req.tools.map(def => ({ ...hostTool(current, def, imageInput, workflow ? (name, reply) => {
|
||||
if (name === workflow?.completionTool) submitted = true;
|
||||
if (workflow && (name === workflow.checkpointTool || name === workflow.completionTool)) manager!.appendCustomEntry("assessment-checkpoint", { tool: name, content: reply.content.slice(0,16000), data: reply.structuredContent });
|
||||
} : undefined, workflow ? providerId => {
|
||||
|
|
@ -422,11 +429,11 @@ async function run(req: RunRequest): Promise<void> {
|
|||
} : undefined), exposure: def.exposure ?? (searchEnabled && !always.has(def.name) ? "deferred" : "direct") })),
|
||||
resourceLoader: loader,
|
||||
}));
|
||||
if (searchEnabled || workflow || codemodeEnabled) await session.bindExtensions({});
|
||||
session.agent.toolExecution = "sequential";
|
||||
if (searchEnabled || workflow || codemodeEnabled) await current.session!.bindExtensions({});
|
||||
current.session!.agent.toolExecution = "sequential";
|
||||
let turns = 0;
|
||||
const previousFinish = session.agent.finishTurn;
|
||||
session.agent.finishTurn = async (turn, signal) => {
|
||||
const previousFinish = current.session!.agent.finishTurn;
|
||||
current.session!.agent.finishTurn = async (turn, signal) => {
|
||||
lastAssistant = turn.message;
|
||||
turns++;
|
||||
// The public Agent finishTurn boundary can end natural tool work. An
|
||||
|
|
@ -450,7 +457,7 @@ async function run(req: RunRequest): Promise<void> {
|
|||
wrappingUp = true;
|
||||
wrapupRemaining = wrapupMax;
|
||||
void send({ type: "event", event: { type: "segment_wrapup_start", data: { maxTurns: wrapupMax } } }).catch(() => {});
|
||||
await session!.steer(workflow.wrapupPrompt);
|
||||
await current.session!.steer(workflow.wrapupPrompt);
|
||||
return decision || { action: "continue" };
|
||||
}
|
||||
status = "yielded";
|
||||
|
|
@ -462,10 +469,10 @@ async function run(req: RunRequest): Promise<void> {
|
|||
return (await previousFinish?.(turn, signal)) || undefined;
|
||||
};
|
||||
const metrics = () => {
|
||||
if (!workflow || !session) return;
|
||||
const stats = session.getSessionStats();
|
||||
const active = new Set(session.getActiveToolNames());
|
||||
const declarations = session.getAllTools().filter(t => active.has(t.name)).map(t => ({ name: t.name, description: t.description, parameters: t.parameters }));
|
||||
if (!workflow || !current.session) return;
|
||||
const stats = current.session.getSessionStats();
|
||||
const active = new Set(current.session.getActiveToolNames());
|
||||
const declarations = current.session.getAllTools().filter(t => active.has(t.name)).map(t => ({ name: t.name, description: t.description, parameters: t.parameters }));
|
||||
void send({ type: "event", event: { type: "session_metrics", data: {
|
||||
sessionId: stats.sessionId, tokens: stats.tokens.total, context: stats.contextUsage,
|
||||
toolCount: active.size, toolDefinitionBytes: Buffer.byteLength(JSON.stringify(declarations)),
|
||||
|
|
@ -473,7 +480,7 @@ async function run(req: RunRequest): Promise<void> {
|
|||
} } });
|
||||
};
|
||||
metrics();
|
||||
session.subscribe(event => {
|
||||
current.session.subscribe(event => {
|
||||
const e = event as any;
|
||||
if (e.type === "message_end" || e.type === "compaction_end" || e.type === "agent_settled") metrics();
|
||||
let data: unknown = e;
|
||||
|
|
@ -493,41 +500,55 @@ async function run(req: RunRequest): Promise<void> {
|
|||
if (e.result && Array.isArray(e.result.content)) {
|
||||
data = { ...(data as object), result: { ...e.result, content: withoutImageBlocks(e.result.content) } };
|
||||
}
|
||||
void send({ type: "event", event: { type: e.type, data } }).catch(() => session?.abort());
|
||||
void send({ type: "event", event: { type: e.type, data } }).catch(() => current.session?.abort());
|
||||
});
|
||||
// Pi accepts steering before prompt() and drains it during the run.
|
||||
for (const note of steeringBeforeSession ?? []) await session.steer(note);
|
||||
steeringBeforeSession = undefined;
|
||||
if (canceled) throw new Error("Run canceled before start");
|
||||
await session.prompt(req.message, { expandPromptTemplates: false, images: images.length ? images : undefined });
|
||||
if (canceled || lastAssistant?.stopReason === "aborted") status = "canceled";
|
||||
for (const note of current.steeringBeforeSession ?? []) await current.session!.steer(note);
|
||||
current.steeringBeforeSession = undefined;
|
||||
if (current.canceled) throw new Error("Run canceled before start");
|
||||
await current.session!.prompt(req.message, { expandPromptTemplates: false, images: images.length ? images : undefined });
|
||||
if (current.canceled || lastAssistant?.stopReason === "aborted") status = "canceled";
|
||||
else if (lastAssistant?.stopReason === "error") { status = "failed"; failure = lastAssistant.errorMessage || "Model request failed"; }
|
||||
else if (status === "completed" && lastAssistant?.stopReason === "length") status = "output_truncated";
|
||||
} catch (error) {
|
||||
status = canceled ? "canceled" : "failed";
|
||||
status = current.canceled ? "canceled" : "failed";
|
||||
failure = error instanceof Error ? error.message : String(error);
|
||||
} finally {
|
||||
// Pi may omit a truncated turn from its projected messages. Commit that
|
||||
// fragment before export so the next resume can continue from it.
|
||||
const truncatedText = status === "output_truncated" ? assistantPlainText(lastAssistant) : "";
|
||||
const truncatedReasoning = status === "output_truncated" ? assistantReasoning(lastAssistant) : "";
|
||||
if (manager && truncatedText && !historyHasAssistantFragment(exportHistory(session?.messages ?? []), truncatedText)) {
|
||||
if (manager && truncatedText && !historyHasAssistantFragment(exportHistory(current.session?.messages ?? []), truncatedText)) {
|
||||
const content: AssistantMessage["content"] = [];
|
||||
if (truncatedReasoning && (req.model.api ?? "openai-completions") !== "anthropic-messages") content.push({ type: "thinking", thinking: truncatedReasoning });
|
||||
content.push({ type: "text", text: truncatedText });
|
||||
manager.appendMessage({ role: "assistant", content, api: req.model.api ?? "openai-completions",
|
||||
provider: "cyberstrike", model: req.model.id, usage: emptyUsage(), stopReason: "stop", timestamp: Date.now() });
|
||||
}
|
||||
const response = status === "output_truncated" ? truncatedText : session?.getLastAssistantText() ?? "";
|
||||
let history: unknown = exportHistory(session?.messages ?? []);
|
||||
const response = status === "output_truncated" ? truncatedText : current.session?.getLastAssistantText() ?? "";
|
||||
let history: unknown = exportHistory(current.session?.messages ?? []);
|
||||
if (status === "output_truncated") history = ensureTruncatedAssistantHistory(history as Record<string, unknown>[], truncatedText, truncatedReasoning);
|
||||
const result: Record<string, unknown> = { response, history, ...(directResult ?? {}), status, error: failure, sessionFile: manager?.getSessionFile() };
|
||||
if (status === "output_truncated") {
|
||||
result.response = truncatedText;
|
||||
result.history = history;
|
||||
}
|
||||
session?.dispose();
|
||||
rmSync(scratch, { recursive: true, force: true });
|
||||
current.session?.dispose();
|
||||
current.session = undefined;
|
||||
if (current.keepAlive) {
|
||||
// Reuse the warm process: drop only this run's scratch and state, keep the
|
||||
// loaded ESM modules and undici keep-alive pool, then await the next run.
|
||||
rmSync(current.scratch, { recursive: true, force: true });
|
||||
activeRun = undefined;
|
||||
started = false;
|
||||
await send({ type: "result", result });
|
||||
if (stdinEnded) {
|
||||
rmSync(scratchRoot, { recursive: true, force: true });
|
||||
process.exit(0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
rmSync(scratchRoot, { recursive: true, force: true });
|
||||
await send({ type: "result", result });
|
||||
process.exit(0);
|
||||
}
|
||||
|
|
@ -536,21 +557,35 @@ async function run(req: RunRequest): Promise<void> {
|
|||
async function command(record: any): Promise<void> {
|
||||
if (record.type === "run") {
|
||||
if (started || record.version !== PROTOCOL_VERSION) throw new Error("Invalid protocol state/version");
|
||||
const current: ActiveRun = {
|
||||
keepAlive: record.keepAlive === true,
|
||||
scratch: mkdtempSync(join(scratchRoot, "run-")),
|
||||
id: "",
|
||||
canceled: false,
|
||||
toolSequence: 0,
|
||||
generationAbort: new AbortController(),
|
||||
steeringBeforeSession: [],
|
||||
pending: new Map(),
|
||||
};
|
||||
activeRun = current;
|
||||
started = true;
|
||||
void run(record.request);
|
||||
void run(record.request, current);
|
||||
} else if (record.type === "tool_result") {
|
||||
const call = pending.get(record.id);
|
||||
if (call) { pending.delete(record.id); call.resolve(record.result); }
|
||||
const call = activeRun?.pending.get(record.id);
|
||||
if (call && activeRun) { activeRun.pending.delete(record.id); call.resolve(record.result); }
|
||||
} else if (record.type === "cancel") {
|
||||
canceled = true;
|
||||
generationAbort.abort();
|
||||
for (const p of pending.values()) p.reject(new Error("Run canceled"));
|
||||
pending.clear();
|
||||
await session?.abort();
|
||||
const current = activeRun;
|
||||
if (!current) return;
|
||||
current.canceled = true;
|
||||
current.generationAbort.abort();
|
||||
for (const p of current.pending.values()) p.reject(new Error("Run canceled"));
|
||||
current.pending.clear();
|
||||
await current.session?.abort();
|
||||
} else if (record.type === "steer") {
|
||||
if (canceled || typeof record.message !== "string") throw new Error("Invalid steering request");
|
||||
if (steeringBeforeSession) steeringBeforeSession.push(record.message);
|
||||
else await session!.steer(record.message);
|
||||
const current = activeRun;
|
||||
if (!current || current.canceled || typeof record.message !== "string") throw new Error("Invalid steering request");
|
||||
if (current.steeringBeforeSession) current.steeringBeforeSession.push(record.message);
|
||||
else await current.session!.steer(record.message);
|
||||
} else throw new Error("Unknown protocol command");
|
||||
}
|
||||
|
||||
|
|
@ -558,11 +593,15 @@ const reader = new RecordReader();
|
|||
process.stdin.on("data", (chunk: Buffer) => {
|
||||
try { for (const record of reader.push(chunk)) void command(record).catch(fatal); } catch (e) { void fatal(e); }
|
||||
});
|
||||
process.stdin.on("end", () => { if (started) void command({ type: "cancel" }); else process.exit(0); });
|
||||
process.stdin.on("end", () => {
|
||||
stdinEnded = true;
|
||||
if (activeRun) void command({ type: "cancel" });
|
||||
else { rmSync(scratchRoot, { recursive: true, force: true }); process.exit(0); }
|
||||
});
|
||||
async function fatal(error: unknown): Promise<void> {
|
||||
await send({ type: "fatal", error: error instanceof Error ? error.message : String(error) });
|
||||
session?.dispose();
|
||||
rmSync(scratch, { recursive: true, force: true });
|
||||
activeRun?.session?.dispose();
|
||||
rmSync(scratchRoot, { recursive: true, force: true });
|
||||
process.exit(1);
|
||||
}
|
||||
await send({ type: "ready", version: PROTOCOL_VERSION, runtime: "pi", sdkVersion: "1.7.0" });
|
||||
|
|
|
|||
|
|
@ -727,3 +727,51 @@ test("codemode and tool search coexist without a tool list validation conflict",
|
|||
assert.equal(result.response, "coexistence verified");
|
||||
assert.equal(hostCalls, 1);
|
||||
});
|
||||
|
||||
test("keepAlive worker serves sequential runs with isolated state and exits on stdin end", { timeout: 60000 }, async t => {
|
||||
const fixture = await startFixture(t, (body, res, count) => {
|
||||
if (count === 1) sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "e1", type: "function", function: { name: "echo", arguments: '{"text":"one"}' } }] }, "tool_calls");
|
||||
else if (count === 2) sse(res, { role: "assistant", content: "first done" }, "stop");
|
||||
else if (count === 3) {
|
||||
assert.deepEqual(body.tools.map(tool => tool.function.name), ["shout"]);
|
||||
assert.ok(!JSON.stringify(body.messages).includes("ECHO-ONE"), "run 2 leaked run 1 tool state");
|
||||
sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "s1", type: "function", function: { name: "shout", arguments: '{"text":"two"}' } }] }, "tool_calls");
|
||||
} else sse(res, { role: "assistant", content: "second done" }, "stop");
|
||||
});
|
||||
const worker = spawn(process.execPath, [workerPath], { stdio: ["pipe", "pipe", "pipe"], env: fixtureEnv });
|
||||
t.after(() => worker.kill());
|
||||
const exit = once(worker, "exit");
|
||||
let stderr = "";
|
||||
worker.stderr.on("data", c => stderr += c);
|
||||
const reader = new RecordReader();
|
||||
const send = record => worker.stdin.write(JSON.stringify(record) + "\n");
|
||||
const results = [];
|
||||
const hostCalls = [];
|
||||
const base = request(fixture.url);
|
||||
const run1 = { ...base, runId: "ka-1", message: "first" };
|
||||
const run2 = { ...base, runId: "ka-2", message: "second",
|
||||
model: { ...base.model, id: "fixture-two" },
|
||||
tools: [{ name: "shout", description: "Return text", parameters: { type: "object", properties: { text: { type: "string" } }, required: ["text"] } }] };
|
||||
worker.stdout.on("data", chunk => {
|
||||
for (const r of reader.push(chunk)) {
|
||||
if (r.type === "ready") send({ type: "run", version: 1, keepAlive: true, request: run1 });
|
||||
else if (r.type === "tool_call") {
|
||||
hostCalls.push(r.call.name);
|
||||
send({ type: "tool_result", id: r.call.id, result: { content: r.call.name === "echo" ? "ECHO-ONE" : "SHOUT-TWO" } });
|
||||
} else if (r.type === "result") {
|
||||
results.push(r.result);
|
||||
if (results.length === 1) send({ type: "run", version: 1, keepAlive: true, request: run2 });
|
||||
else worker.stdin.end();
|
||||
}
|
||||
}
|
||||
});
|
||||
const [code] = await exit;
|
||||
assert.equal(code, 0, stderr + JSON.stringify(results));
|
||||
assert.equal(results.length, 2);
|
||||
assert.equal(results[0].status, "completed", results[0].error);
|
||||
assert.equal(results[0].response, "first done");
|
||||
assert.equal(results[1].status, "completed", results[1].error);
|
||||
assert.equal(results[1].response, "second done");
|
||||
assert.deepEqual(hostCalls, ["echo", "shout"]);
|
||||
assert.equal(fixture.requests.length, 4);
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in New Issue