| 1 | package engine |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "runtime" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | // DefaultPythonBinary is preferred when its version meets MinPythonVersion. |
| 17 | const DefaultPythonBinary = "python3" |
| 18 | |
| 19 | // MinPythonVersion mirrors the engine's MIN_PYTHON constant in |
| 20 | // last30days.py. Surfaced in errors so users know what they're missing. |
| 21 | const MinPythonVersion = "3.12" |
| 22 | |
| 23 | // PythonInstallURL is included in the missing-interpreter error so users |
| 24 | // have a direct route from the failure to a fix. |
| 25 | const PythonInstallURL = "https://www.python.org/downloads/" |
| 26 | |
| 27 | // DefaultTimeout caps a single research subprocess. The engine's deep-tier |
| 28 | // resume enrichment alone budgets 450s, so ten minutes is the floor that lets |
| 29 | // a full run finish; the per-stream and X-chain deadlines inside the pipeline |
| 30 | // still fail fast when something hangs. |
| 31 | const DefaultTimeout = 10 * time.Minute |
| 32 | |
| 33 | // TimeoutEnvOverride lets operators override DefaultTimeout per install |
| 34 | // (seconds, integer). Honored by Run when RunOptions.Timeout is zero. |
| 35 | const TimeoutEnvOverride = "LAST30DAYS_MCP_TIMEOUT" |
| 36 | |
| 37 | // termGracePeriod bounds the SIGTERM phase of the deadline path: the |
| 38 | // python SIGTERM handler needs a moment to killpg() the setsid'd |
| 39 | // descendant groups before the SIGKILL backstop fires. |
| 40 | const termGracePeriod = 2 * time.Second |
| 41 | |
| 42 | // pipeGracePeriod bounds output draining after the engine exits even if |
| 43 | // an unregistered detached descendant still holds its output pipes. |
| 44 | const pipeGracePeriod = time.Second |
| 45 | |
| 46 | // RunOptions configures one invocation of the embedded Python engine. |
| 47 | // PythonPath is exposed so tests can substitute a stub interpreter without |
| 48 | // manipulating the process PATH. |
| 49 | type RunOptions struct { |
| 50 | PythonPath string // resolved test/caller override; empty honors PythonEnvOverride, then DefaultPythonBinary |
| 51 | CacheDir string // engine.Ensure result; lib/ here is added to PYTHONPATH |
| 52 | Args []string // arguments after last30days.py (topic, --emit=..., etc.) |
| 53 | ExtraEnv []string // appended to os.Environ() for the child process |
| 54 | Timeout time.Duration // zero means DefaultTimeout or TimeoutEnvOverride |
| 55 | MaxStdoutBytes int // zero means DefaultMaxStdoutBytes |
| 56 | MaxStderrBytes int // zero means DefaultMaxStderrBytes |
| 57 | } |
| 58 | |
| 59 | // RunResult captures the engine's bounded output. Stdout is what we surface to |
| 60 | // the agent; Stderr is included in error messages so users can diagnose |
| 61 | // engine failures without leaving Claude Desktop. |
| 62 | type RunResult struct { |
| 63 | Stdout []byte |
| 64 | Stderr []byte |
| 65 | StdoutTruncated bool |
| 66 | StderrTruncated bool |
| 67 | ExitCode int |
| 68 | TimedOut bool |
| 69 | } |
| 70 | |
| 71 | // Run shells out to python3 with last30days.py inside cacheDir. The child |
| 72 | // receives the parent environment (so MCPB user_config env-injection |
| 73 | // reaches the engine) plus ExtraEnv and a PYTHONPATH that points at the |
| 74 | // cache so the engine's `from lib import ...` statements resolve. |
| 75 | // |
| 76 | // A missing interpreter, a non-zero exit, and a timeout each surface as |
| 77 | // distinct errors so the tool handler can map them to user-facing |
| 78 | // messages without re-parsing stderr. |
| 79 | func Run(ctx context.Context, opts RunOptions) (*RunResult, error) { |
| 80 | if opts.CacheDir == "" { |
| 81 | return nil, errors.New("engine: CacheDir is required") |
| 82 | } |
| 83 | pythonPath, err := resolvePythonContext(ctx, opts.PythonPath) |
| 84 | if err != nil { |
| 85 | return nil, err |
| 86 | } |
| 87 | |
| 88 | scriptPath := filepath.Join(opts.CacheDir, "last30days.py") |
| 89 | if _, err := os.Stat(scriptPath); err != nil { |
| 90 | return nil, fmt.Errorf("engine: last30days.py not found in cache %s: %w", opts.CacheDir, err) |
| 91 | } |
| 92 | |
| 93 | timeout := resolveTimeout(opts.Timeout) |
| 94 | subCtx, cancel := context.WithTimeout(ctx, timeout) |
| 95 | defer cancel() |
| 96 | |
| 97 | args := append([]string{scriptPath}, opts.Args...) |
| 98 | cmd := exec.Command(pythonPath, args...) |
| 99 | cmd.Env = buildEnv(opts.CacheDir, opts.ExtraEnv) |
| 100 | // Own process group so cancellation SIGTERM reaches same-group helpers on |
| 101 | // the primary unreaped wait path while Python's SIGTERM handler cleans up |
| 102 | // registered setsid'd descendant groups (including grok CLI via lib/subproc.py) |
| 103 | // on both primary and direct-child fallback paths. exec.CommandContext would |
| 104 | // SIGKILL only Python directly and skip its SIGTERM/atexit cleanup. |
| 105 | setProcessGroup(cmd) |
| 106 | |
| 107 | maxStdout := resolveOutputLimit(opts.MaxStdoutBytes, DefaultMaxStdoutBytes) |
| 108 | maxStderr := resolveOutputLimit(opts.MaxStderrBytes, DefaultMaxStderrBytes) |
| 109 | stdout := newHeadBuffer(maxStdout) |
| 110 | stderr := newTailBuffer(maxStderr) |
| 111 | |
| 112 | if err := subCtx.Err(); err != nil { |
| 113 | return &RunResult{ |
| 114 | ExitCode: -1, |
| 115 | TimedOut: errors.Is(err, context.DeadlineExceeded), |
| 116 | }, fmt.Errorf("engine: subprocess not started: %w", err) |
| 117 | } |
| 118 | pipes, err := newOutputPipes() |
| 119 | if err != nil { |
| 120 | return &RunResult{ |
| 121 | ExitCode: -1, |
| 122 | TimedOut: errors.Is(subCtx.Err(), context.DeadlineExceeded), |
| 123 | }, fmt.Errorf("engine: failed to create subprocess pipes: %w", err) |
| 124 | } |
| 125 | cmd.Stdout = pipes.stdoutW |
| 126 | cmd.Stderr = pipes.stderrW |
| 127 | |
| 128 | if err := cmd.Start(); err != nil { |
| 129 | pipes.closeAll() |
| 130 | res := &RunResult{ |
| 131 | Stdout: stdout.Bytes(), |
| 132 | Stderr: stderr.Bytes(), |
| 133 | StdoutTruncated: stdout.Truncated(), |
| 134 | StderrTruncated: stderr.Truncated(), |
| 135 | ExitCode: 0, |
| 136 | TimedOut: errors.Is(subCtx.Err(), context.DeadlineExceeded), |
| 137 | } |
| 138 | return res, fmt.Errorf("engine: subprocess failed to start: %w", err) |
| 139 | } |
| 140 | pipes.startDraining(stdout, stderr) |
| 141 | |
| 142 | err = waitCommandWithDrain(subCtx, cmd, termGracePeriod, pipeGracePeriod, pipes.drainDone, pipes.closeReadPipes) |
| 143 | |
| 144 | ctxErr := subCtx.Err() |
| 145 | res := &RunResult{ |
| 146 | Stdout: stdout.Bytes(), |
| 147 | Stderr: stderr.Bytes(), |
| 148 | StdoutTruncated: stdout.Truncated(), |
| 149 | StderrTruncated: stderr.Truncated(), |
| 150 | ExitCode: 0, |
| 151 | TimedOut: errors.Is(ctxErr, context.DeadlineExceeded), |
| 152 | } |
| 153 | if cmd.ProcessState != nil { |
| 154 | res.ExitCode = cmd.ProcessState.ExitCode() |
| 155 | } |
| 156 | if res.TimedOut { |
| 157 | return res, fmt.Errorf("engine: subprocess exceeded %s timeout: %w", timeout, ctxErr) |
| 158 | } |
| 159 | if ctxErr != nil { |
| 160 | return res, fmt.Errorf("engine: subprocess canceled: %w", ctxErr) |
| 161 | } |
| 162 | if res.StdoutTruncated { |
| 163 | if err != nil { |
| 164 | var exitErr *exec.ExitError |
| 165 | if errors.As(err, &exitErr) { |
| 166 | return res, fmt.Errorf("%w (%d byte limit, received %d bytes; exit code %d)", ErrStdoutLimitExceeded, maxStdout, stdout.Total(), res.ExitCode) |
| 167 | } |
| 168 | return res, fmt.Errorf("%w (%d byte limit, received %d bytes; %v)", ErrStdoutLimitExceeded, maxStdout, stdout.Total(), err) |
| 169 | } |
| 170 | return res, fmt.Errorf("%w (%d byte limit, received %d bytes)", ErrStdoutLimitExceeded, maxStdout, stdout.Total()) |
| 171 | } |
| 172 | if err == nil { |
| 173 | return res, nil |
| 174 | } |
| 175 | |
| 176 | var exitErr *exec.ExitError |
| 177 | if errors.As(err, &exitErr) { |
| 178 | return res, fmt.Errorf("engine: subprocess exited with code %d", res.ExitCode) |
| 179 | } |
| 180 | return res, fmt.Errorf("engine: subprocess failed: %w", err) |
| 181 | } |
| 182 | |
| 183 | func resolveTimeout(explicit time.Duration) time.Duration { |
| 184 | if explicit > 0 { |
| 185 | return explicit |
| 186 | } |
| 187 | if raw := os.Getenv(TimeoutEnvOverride); raw != "" { |
| 188 | if d, err := time.ParseDuration(raw); err == nil && d > 0 { |
| 189 | return d |
| 190 | } |
| 191 | // Accept bare integer seconds (e.g. "300") as documented. |
| 192 | if secs, err := strconv.Atoi(raw); err == nil && secs > 0 { |
| 193 | return time.Duration(secs) * time.Second |
| 194 | } |
| 195 | } |
| 196 | return DefaultTimeout |
| 197 | } |
| 198 | |
| 199 | // buildEnv stitches PYTHONPATH onto os.Environ + ExtraEnv. Any pre-existing |
| 200 | // PYTHONPATH, PYTHONDONTWRITEBYTECODE, or key overridden by ExtraEnv in the |
| 201 | // parent environment is dropped before appending; otherwise the child sees |
| 202 | // duplicate entries and POSIX getenv returns the first one, shadowing our |
| 203 | // cache-dir or MCP-level overrides. |
| 204 | func buildEnv(cacheDir string, extra []string) []string { |
| 205 | const ( |
| 206 | pyKey = "PYTHONPATH=" |
| 207 | bytecodeKey = "PYTHONDONTWRITEBYTECODE=" |
| 208 | ) |
| 209 | overrides := make(map[string]struct{}, len(extra)) |
| 210 | for _, kv := range extra { |
| 211 | if key, ok := envKey(kv); ok { |
| 212 | overrides[key] = struct{}{} |
| 213 | } |
| 214 | } |
| 215 | parent := os.Environ() |
| 216 | base := make([]string, 0, len(parent)+2+len(extra)) |
| 217 | for _, kv := range parent { |
| 218 | if strings.HasPrefix(kv, pyKey) || strings.HasPrefix(kv, bytecodeKey) { |
| 219 | continue |
| 220 | } |
| 221 | if key, ok := envKey(kv); ok { |
| 222 | if _, replaced := overrides[key]; replaced { |
| 223 | continue |
| 224 | } |
| 225 | } |
| 226 | base = append(base, kv) |
| 227 | } |
| 228 | base = append(base, pyKey+cacheDir, bytecodeKey+"1") |
| 229 | base = append(base, extra...) |
| 230 | return base |
| 231 | } |
| 232 | |
| 233 | func envKey(kv string) (string, bool) { |
| 234 | eq := strings.IndexByte(kv, '=') |
| 235 | if eq <= 0 { |
| 236 | return "", false |
| 237 | } |
| 238 | key := kv[:eq] |
| 239 | if runtime.GOOS == "windows" { |
| 240 | return strings.ToUpper(key), true |
| 241 | } |
| 242 | return key, true |
| 243 | } |
| 244 |