package agentruntime import ( "context" "encoding/json" "errors" "fmt" "os" "path/filepath" ) const maxRecordBytes = 32 * 1024 * 1024 type Pi struct { NodePath string WorkerPath string } type runRequest struct { Request LegacyProfile json.RawMessage `json:"profile"` } 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"` Result *Result `json:"result,omitempty"` Error string `json:"error,omitempty"` SDKVersion string `json:"sdkVersion,omitempty"` } // ResolveWorker supports source installs and release bundles without relying on PATH for scripts. func ResolveWorker(configured string) (string, error) { if configured != "" { path, err := filepath.Abs(configured) if err != nil { return "", err } if st, err := os.Stat(path); err != nil || !st.Mode().IsRegular() { return "", fmt.Errorf("Pi worker does not exist: %s", path) } return path, nil } for _, path := range workerCandidates() { root := filepath.Dir(filepath.Dir(path)) if fingerprint, err := SourceFingerprint(root); err == nil { bundle := filepath.Join(root, ".builds", fingerprint) if _, err = os.Stat(filepath.Join(bundle, ".ready")); err == nil { if _, err = os.Stat(filepath.Join(bundle, "dist", "worker.js")); err == nil { return filepath.Join(bundle, "dist", "worker.js"), nil } } continue } if st, err := os.Stat(path); err == nil && st.Mode().IsRegular() { return path, nil } } return "", errors.New("Pi worker missing; run bash scripts/build-pi-runtime.sh, or configure agent_runtime.worker_path") } func workerCandidates() []string { var candidates []string if exe, err := os.Executable(); err == nil { candidates = append(candidates, filepath.Join(filepath.Dir(exe), "runtime/pi/dist/worker.js")) } if cwd, err := os.Getwd(); err == nil { candidates = append(candidates, filepath.Join(cwd, "runtime/pi/dist/worker.js")) // Package tests and developer commands may run below the repository root. for dir := cwd; dir != filepath.Dir(dir); dir = filepath.Dir(dir) { if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { candidates = append(candidates, filepath.Join(dir, "runtime/pi/dist/worker.js")) break } } } return candidates } // 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 } if req.WorkingDir == "" { var err error req.WorkingDir, err = os.Getwd() if err != nil { return nil, err } } release, err := acquireSession(ctx, req.SessionDir) if err != nil { return nil, err } defer release() workerPath, err := ResolveWorker(p.WorkerPath) if err != nil { return nil, err } node := p.NodePath if node == "" { node = "node" } w, err := pool.acquire(ctx, node, workerPath) if err != nil { return nil, err } res, runErr := w.run(ctx, req, execute, emit, bind) w.runs++ if runErr == nil && ctx.Err() == nil && !w.writeFailed.Load() && len(w.incoming) == 0 && w.runs < poolMaxRunsPerWorker { pool.release(node, workerPath, w) } else { w.destroy() } return res, runErr }