All files / server/services sandbox-runner.ts

84.36% Statements 259/307
72.07% Branches 111/154
88.63% Functions 39/44
87.73% Lines 236/269

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570                                                    21x   75x                             75x     75x               1x     75x 75x 75x 75x   145x 44x     75x 75x 75x 75x 75x 75x 75x 75x   75x   1x     1x     318x               75x         3x       3x   75x 75x     75x                     75x                                                               14x               9x       7x       2x 2x       1x       3x         21x 21x 21x 21x 21x       31x 29x 15x 15x 15x 15x       14x 14x         14x         14x 14x 1x 1x 1x 1x         13x         13x 2x 2x 2x     11x 14x             11x         11x 3x 3x 3x     8x     8x 8x         8x       14x 14x 12x     2x 1x     1x 1x       1x       1x 1x           21x 20x 20x       34x 18x 18x           19x 19x 19x 19x 19x 19x     19x 19x 19x 15x 15x 6x 6x 6x   9x 9x   19x   4x           6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x                 6x 6x 6x 6x       49x 49x         2x 2x 2x 2x 2x 2x 2x 2x       11x 11x 11x           11x       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x           8x 8x 8x           8x       1x 1x 1x             1x                                             33x   33x 33x 33x 33x 6x 6x   27x 27x 27x 27x 27x   33x 33x 33x 33x 33x 33x 33x 33x 33x 33x   33x         33x     33x 33x 33x 33x 33x   33x 9x 2x 2x 2x           27x 27x 27x   27x                 7x 1x 1x   1x       7x 7x 7x 7x 7x 7x 1x 1x   6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x             6x 6x   1x   6x       8x            
// Lean orchestrator for Arduino sketch simulation
// Delegates execution flow to ExecutionManager, manages state transitions and process control
 
import { ProcessController, type IProcessController } from "./process-controller";
import { mkdir } from "node:fs/promises";
import { existsSync } from "node:fs";
import { Logger } from "@shared/logger";
import { sandboxTempDir } from "./temp-artifact-sweep";
import { ArduinoOutputParser as StderrParser } from "./arduino-output-parser";
import { RegistryManager } from "./registry-manager";
import { SimulationTimeoutManager } from "./simulation-timeout-manager";
import { SketchFileBuilder } from "./sketch-file-builder";
import { LocalCompiler } from "./local-compiler";
import type { RunSketchOptions } from "./run-sketch-types";
import { ProcessExecutor } from "./process-executor";
 
// Manager delegation imports
import { DockerManager } from "./sandbox/docker-manager";
import { StreamHandler } from "./sandbox/stream-handler";
import { FilesystemHelper } from "./sandbox/filesystem-helper";
import { ExecutionManager, type ExecutionState, SimulationState, SANDBOX_CONFIG } from "./sandbox/execution-manager";
import { cleanupExecutionContainer, flushMessageQueue } from "./sandbox/execution-phases/cleanup-phase";
import { delegateParsedLineToStreamHandler } from "./sandbox/execution-phases/stream-phase";
import { config } from "../config";
 
export class SandboxRunner {
  private static missingDockerSocketLogEmitted = false;
 
  private readonly logger = new Logger("SandboxRunner");
  private readonly tempDir: string;
  private readonly processController: IProcessController;
  private readonly registryManager: RegistryManager;
  private readonly timeoutManager: SimulationTimeoutManager;
  private readonly fileBuilder: SketchFileBuilder;
  private readonly localCompiler: LocalCompiler;
  private readonly dockerManager: DockerManager;
  private readonly streamHandler: StreamHandler;
  private readonly filesystemHelper: FilesystemHelper;
  private readonly executionManager: ExecutionManager;
  private readonly executionState: ExecutionState;
  private readonly processExecutor: ProcessExecutor;
 
  private controlCompletion?: Promise<boolean>;
  private controlPending = false;
  /** Total time one run may spend paused before the runner ends it. */
  private readonly maxPausedMs: number;
  private pauseBudgetTimer: NodeJS.Timeout | null = null;
 
  /** Completion of the last accepted control; Stop never waits for it. */
  get controlResult(): Promise<boolean> | undefined {
    return this.controlCompletion;
  }
 
  get hasPendingContainerCleanup(): boolean {
    return Boolean(this.executionState.currentContainerName);
  }
 
  private dockerAvailable = false;
  private dockerImageBuilt = false;
  private dockerChecked = false;
  private tempDirCreated = false;
 
  private get state(): SimulationState { return this.executionState?.state ?? SimulationState.STOPPED; }
  private set state(v: SimulationState | string) { this.executionState.state = v as SimulationState; }
 
  constructor(options?: { tempDir?: string; processController?: IProcessController; maxPausedMs?: number }) {
    this.processController = options?.processController ?? new ProcessController();
    this.maxPausedMs = options?.maxPausedMs ?? config.sandbox.maxPausedSeconds * 1_000;
    this.tempDir = options?.tempDir ?? sandboxTempDir();
    this.timeoutManager = new SimulationTimeoutManager();
    this.fileBuilder = new SketchFileBuilder(this.tempDir);
    this.localCompiler = new LocalCompiler();
    this.processExecutor = new ProcessExecutor();
    const stderrParser = new StderrParser();
    
    this.registryManager = new RegistryManager({
      onUpdate: (registry, baudrate, reason) => {
        Iif (this.executionState?.ioRegistryCallback) {
          this.executionState.ioRegistryCallback(registry, baudrate, reason);
        }
        flushMessageQueue(this.executionState);
      },
      onTelemetry: (metrics) => {
        Iif (this.executionState?.telemetryCallback) {
          this.executionState.telemetryCallback(metrics);
        }
      },
      enableTelemetry: true,
    });
 
    // Initialize managers with dependencies
    this.dockerManager = new DockerManager(
      this.processController,
      stderrParser,
      this.timeoutManager,
      // Same routing (and run budget) as the local path.
      (parsed, callbacks) => delegateParsedLineToStreamHandler(parsed, this.executionState, callbacks, {
        registryManager: this.registryManager,
        streamHandler: this.streamHandler,
      }),
      () => { this.executionState.terminationRequested = true; },
    );
    this.streamHandler = new StreamHandler(this.processController);
    this.filesystemHelper = new FilesystemHelper(this.fileBuilder, this.localCompiler);
 
    // Initialize execution manager with dependencies
    this.executionManager = new ExecutionManager(
      this.registryManager,
      this.timeoutManager,
      this.fileBuilder,
      this.localCompiler,
      this.dockerManager,
      this.streamHandler,
      this.filesystemHelper,
    );
 
    // Initialize execution state
    this.executionState = {
      outputBuffer: "",
      outputBufferIndex: 0,
      isSendingOutput: false,
      totalOutputBytes: 0,
      messageQueue: [],
      pauseStartTime: null,
      totalPausedTime: 0,
      isCompiling: false,
      currentSketchDir: null,
      currentRegistryFile: null,
      processStartTime: null,
      onOutputCallback: null,
      pinStateCallback: null,
      errorCallback: null,
      telemetryCallback: null,
      ioRegistryCallback: undefined,
      pinStateBatcher: null,
      serialOutputBatcher: null,
      backpressurePaused: false,
      baudrate: 9600,
      stderrFallbackBuffer: "",
      flushTimer: null,
      state: SimulationState.STOPPED,
      processKilled: false,
      pendingCleanup: false,
      processController: this.processController,
    };
 
  }
 
  get isRunning(): boolean {
    return (
      this.state === SimulationState.STARTING ||
      this.state === SimulationState.RUNNING ||
      this.state === SimulationState.PAUSED
    );
  }
 
  get isPaused(): boolean {
    return this.state === SimulationState.PAUSED;
  }
 
  get simulationState(): SimulationState {
    return this.state;
  }
 
  async initialize(): Promise<void> {
    await this.ensureDockerChecked();
    if (
      config.serverMode === "docker" &&
      (!this.dockerAvailable || !this.dockerImageBuilt)
    ) {
      throw new Error("Docker sandbox is unavailable");
    }
  }
 
  private get pauseStartTime(): number | null { return this.executionState.pauseStartTime; }
 
 
 
  async runSketch(options: RunSketchOptions): Promise<boolean> {
    await this.ensureDockerChecked();
    await this.ensureTempDir();
    this.executionState.dockerAvailable = this.dockerAvailable;
    this.executionState.dockerImageBuilt = this.dockerImageBuilt;
    return this.executionManager.runSketch(options, this.executionState);
  }
 
  private async ensureDockerChecked(): Promise<void> {
    if (this.dockerChecked) return;
    if (config.serverMode === "local") {
      this.dockerAvailable = false;
      this.dockerImageBuilt = false;
      this.dockerChecked = true;
      return;
    }
    
    // Always use async path; ProcessExecutor handles test mocking internally
    try {
      await this.checkDockerAsync();
    } catch {
      this.dockerAvailable = false;
      this.dockerImageBuilt = false;
    } finally {
      this.dockerChecked = true;
    }
  }
 
  private async checkDockerAsync(): Promise<void> {
    const dockerSocketPath = this.getDockerSocketPath();
    if (dockerSocketPath && !existsSync(dockerSocketPath)) {
      this.dockerAvailable = false;
      this.dockerImageBuilt = false;
      this.logMissingDockerSocketOnce(dockerSocketPath);
      return;
    }
 
    // Use ProcessExecutor for all Docker checks
    // docker --version
    const versionResult = await this.processExecutor.execute("docker", ["--version"], {
      timeout: config.sandbox.dockerControlTimeoutMs,
      stdio: "pipe",
    });
 
    if (versionResult.error || versionResult.code !== 0) {
      this.dockerAvailable = false;
      this.dockerImageBuilt = false;
      return;
    }
 
    const versionOutput = versionResult.stdout || "";
    Iif (!versionOutput.includes("Docker")) {
      this.dockerAvailable = false;
      this.dockerImageBuilt = false;
      return;
    }
 
    // docker info
    const infoResult = await this.processExecutor.execute("docker", ["info"], {
      timeout: config.sandbox.dockerControlTimeoutMs,
      stdio: "pipe",
    });
 
    if (infoResult.error || infoResult.code !== 0) {
      this.dockerAvailable = false;
      this.dockerImageBuilt = false;
      return;
    }
 
    this.dockerAvailable = true;
 
    // docker image inspect <image>
    const imageName = SANDBOX_CONFIG.dockerImage;
    const inspectResult = await this.processExecutor.execute("docker", ["image", "inspect", imageName], {
      timeout: config.sandbox.dockerControlTimeoutMs,
      stdio: "pipe",
    });
 
    this.dockerImageBuilt = inspectResult.code === 0;
  }
 
  private getDockerSocketPath(): string | null {
    const dockerHost = config.sandbox.dockerHost.trim();
    if (dockerHost === "unix:///var/run/docker.sock") {
      return "/var/run/docker.sock";
    }
 
    if (!dockerHost.startsWith("unix://")) {
      return null;
    }
 
    const socketPath = dockerHost.slice("unix://".length).trim();
    return socketPath || "/var/run/docker.sock";
  }
 
  private logMissingDockerSocketOnce(socketPath: string): void {
    Iif (SandboxRunner.missingDockerSocketLogEmitted) {
      return;
    }
 
    SandboxRunner.missingDockerSocketLogEmitted = true;
    this.logger.info(
      `Docker socket not available at ${socketPath}`,
    );
  }
 
  private async ensureTempDir(): Promise<void> {
    if (this.tempDirCreated) return;
    this.tempDirCreated = true;
    try { await mkdir(this.tempDir, { recursive: true }); } catch { /* ignore */ }
  }
 
  private async cleanupDockerContainer(containerName?: string): Promise<void> {
    if (!containerName) return;
    const s = this.executionState;
    await cleanupExecutionContainer(s, {
      processExecutor: this.processExecutor, logger: this.logger,
    });
  }
 
  private controlDocker(operation: "pause" | "unpause", commit: () => void): void {
    const s = this.executionState;
    const containerName = s.currentContainerName!;
    const generation = s.runGeneration;
    const expectedState = this.state;
    const abort = s.runAbort;
    const isCurrent = () => s.runGeneration === generation && s.runAbort === abort &&
      !abort?.signal.aborted && !s.processKilled && s.currentContainerName === containerName &&
      !s.terminationRequested && this.state === expectedState && this.processController.hasProcess();
    this.controlPending = true;
    const finish = async (result: Awaited<ReturnType<ProcessExecutor["execute"]>>): Promise<boolean> => {
      if (!isCurrent()) return false;
      this.controlPending = false;
      if (result.code !== 0 || result.error) {
        this.logger.warn(`Docker ${operation} failed for ${containerName} (code ${result.code}): ${String(result.error ?? "nonzero exit")}`);
        await this.stop();
        return false;
      }
      commit();
      return true;
    };
    this.controlCompletion = this.processExecutor.execute("docker", [operation, containerName], {
      timeout: 5000, stdio: "pipe",
    }).then(finish, (error: unknown) => finish({
      code: -1, error: error instanceof Error ? error : new Error(String(error)),
    }));
  }
 
  private commitPause(): void {
    const s = this.executionState;
    this.state = SimulationState.PAUSED;
    this.timeoutManager.pause();
    s.pinStateBatcher?.pause();
    s.serialOutputBatcher?.pause();
    this.registryManager.pauseTelemetry();
    Eif (!s.processKilled) this.processController.writeStdin("[[PAUSE_TIME]]\n");
    s.pauseStartTime = Date.now();
    this.registryManager.markPauseTime(s.pauseStartTime);
    this.startPauseBudget();
    this.logger.info("Simulation paused");
  }
 
  /**
   * The paused time of all pauses of a run is bounded: a paused run keeps its
   * runner, admission and (frozen) container, and `docker pause` also freezes
   * the sandbox's own hard lifetime.
   */
  private startPauseBudget(): void {
    this.clearPauseBudget();
    const remainingMs = Math.max(0, this.maxPausedMs - this.executionState.totalPausedTime);
    this.pauseBudgetTimer = setTimeout(() => this.endPausedRun(), remainingMs);
    this.pauseBudgetTimer.unref?.();
  }
 
  private clearPauseBudget(): void {
    if (this.pauseBudgetTimer) clearTimeout(this.pauseBudgetTimer);
    this.pauseBudgetTimer = null;
  }
 
  /** Ends the run like the runtime timeout does: its exit releases the session. */
  private endPausedRun(): void {
    this.pauseBudgetTimer = null;
    const s = this.executionState;
    Iif (this.state !== SimulationState.PAUSED || s.processKilled || s.terminationRequested) return;
    const limitSeconds = Math.round(this.maxPausedMs / 1_000);
    this.logger.info(`Paused run exceeded its pause budget of ${limitSeconds}s; ending it`);
    s.onOutputCallback?.(`--- Simulation stopped: paused longer than ${limitSeconds} s ---`, true);
    s.terminationRequested = true;
    this.processController.kill("SIGKILL");
  }
 
  pause(): boolean {
    Iif (this.controlPending || this.executionState.terminationRequested || this.state !== SimulationState.RUNNING || !this.processController.hasProcess()) return false;
    if (this.executionState.currentContainerName) {
      this.controlDocker("pause", () => this.commitPause());
    } else E{
      this.processController.kill("SIGSTOP");
      this.commitPause();
      this.controlCompletion = undefined;
    }
    return true;
  }
 
  private commitResume(): void {
    const s = this.executionState;
    this.clearPauseBudget();
    const pauseDuration = Date.now() - (this.pauseStartTime ?? Date.now());
    s.totalPausedTime += pauseDuration;
    Eif (!s.processKilled) this.processController.writeStdin(`[[RESUME_TIME:${pauseDuration}]]\n`);
    s.pauseStartTime = null;
    this.registryManager.markPauseTime(null);
    this.state = SimulationState.RUNNING;
    this.timeoutManager.resume();
    s.pinStateBatcher?.resume();
    s.serialOutputBatcher?.resume();
    this.registryManager.resumeTelemetry();
    this.logger.info(`Simulation resumed after ${pauseDuration}ms`);
    Iif (!s.currentContainerName && !s.processKilled) this.processController.writeStdin("\n");
    Iif (s.outputBuffer.length > 0 && s.onOutputCallback && !s.isSendingOutput) {
      this.sendOutputWithDelay(s.onOutputCallback);
    }
  }
 
  resume(): boolean {
    Iif (this.controlPending || this.executionState.terminationRequested || this.state !== SimulationState.PAUSED || !this.processController.hasProcess()) return false;
    if (this.executionState.currentContainerName) {
      this.controlDocker("unpause", () => this.commitResume());
    } else E{
      this.processController.kill("SIGCONT");
      this.commitResume();
      this.controlCompletion = undefined;
    }
    return true;
  }
 
  sendSerialInput(input: string): void {
    const s = this.executionState;
    if (this.isRunning && !this.isPaused && this.processController.hasProcess() && !s.processKilled) {
      this.processController.writeStdin(input + "\n");
    } else E{
      this.logger.warn("Simulator is not running or is paused — serial input ignored");
    }
  }
 
  setRegistryFile(filePath: string): void { this.executionState.currentRegistryFile = filePath; }
  getSketchDir(): string | null { return this.executionState.currentSketchDir; }
 
  setPinValue(pin: number, value: number): void {
    const s = this.executionState;
    if ((this.isRunning || this.isPaused) && this.processController.hasProcess() && !s.processKilled) {
      this.processController.writeStdin(`[[SET_PIN:${pin}:${value}]]\n`);
    }
  }
 
  // Send output character by character with baudrate delay
  private sendOutputWithDelay(onOutput: (line: string, isComplete?: boolean) => void): void {
    const s = this.executionState;
    if (!this.isRunning || this.isPaused) { s.isSendingOutput = false; return; }
    if (s.outputBufferIndex >= s.outputBuffer.length) { s.isSendingOutput = false; return; }
    s.isSendingOutput = true;
    const char = s.outputBuffer[s.outputBufferIndex++];
    s.totalOutputBytes++;
    if (s.totalOutputBytes > SANDBOX_CONFIG.maxOutputBytes) { void this.stop(); return; }
    onOutput(char, char === "\n");
    setTimeout(() => this.sendOutputWithDelay(onOutput), Math.max(1, 10_000 / s.baudrate));
  }
 
  async stop(): Promise<void> {
    const s = this.executionState;
    // Cancels a run that is still preparing or waiting for a start slot.
    s.runAbort?.abort();
    this.controlPending = false;
    this.clearPauseBudget();
    if (this.state === SimulationState.STOPPED || s.processKilled) {
      await this.cleanupDockerContainer(s.currentContainerName);
      return;
    }
    this.state = SimulationState.STOPPED;
    s.processKilled = true;
    s.pendingCleanup = true;
    s.pauseStartTime = null;
    s.totalPausedTime = 0;
 
    s.pinStateBatcher?.stop(); s.pinStateBatcher?.destroy(); s.pinStateBatcher = null;
    s.serialOutputBatcher?.stop(); s.serialOutputBatcher?.destroy(); s.serialOutputBatcher = null;
    this.registryManager.pauseTelemetry();
    s.onOutputCallback = null; s.errorCallback = null;
    s.telemetryCallback = null; s.pinStateCallback = null; s.ioRegistryCallback = undefined;
    this.registryManager.reset();
    this.timeoutManager.clear();
    this.localCompiler.kill();
    this.processController.kill("SIGKILL");
    this.processController.destroySockets();
 
    const fsState = {
      currentSketchDir: s.currentSketchDir, isCompiling: s.isCompiling,
      pendingCleanup: s.pendingCleanup, cleanupRetries: new Map<string, number>(),
      currentRegistryFile: s.currentRegistryFile,
    };
    const deferredCompileDir = this.filesystemHelper.isCompilationInProgress(fsState)
      ? fsState.currentSketchDir
      : null;
    this.filesystemHelper.markRegistryForCleanup(fsState);
    this.filesystemHelper.markTempDirForCleanup(fsState);
    s.currentSketchDir = fsState.currentSketchDir;
    s.currentRegistryFile = fsState.currentRegistryFile;
    s.pendingCleanup = fsState.pendingCleanup;
 
    for (const dir of this.fileBuilder.getCreatedSketchDirs()) {
      if (dir === deferredCompileDir) continue;
      Iif (!existsSync(dir)) { this.fileBuilder.clearCreatedSketchDir(dir); continue; }
      if (this.filesystemHelper.attemptCleanupDir(dir)) {
        this.fileBuilder.clearCreatedSketchDir(dir);
      } else E{
        this.filesystemHelper.scheduleCleanupRetry(fsState, dir);
      }
    }
 
    s.outputBuffer = ""; s.outputBufferIndex = 0; s.isSendingOutput = false;
    const containerName = s.currentContainerName;
    Iif (s.flushTimer) { clearTimeout(s.flushTimer); s.flushTimer = null; }
 
    await this.cleanupDockerContainer(containerName);
  }
 
  /**
   * Returns the runner to a clean state before the pool hands it to the next
   * user: stops a run still in progress and clears everything the previous run
   * left in the execution state, the process listeners and the I/O registry.
   */
  async resetForReuse(): Promise<void> {
    if (this.isRunning) {
      try {
        await this.stop();
      } catch (error) {
        this.logger.warn(`stop() failed during reset: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
 
    const s = this.executionState;
    s.runAbort?.abort();
    this.controlPending = false;
    this.controlCompletion = undefined;
    this.clearPauseBudget();
    if (s.currentContainerName) {
      await this.cleanupDockerContainer(s.currentContainerName);
      Eif (s.currentContainerName) throw new Error(`Docker cleanup unconfirmed for ${s.currentContainerName}`);
    }
    this.processController.clearListeners();
    s.state = SimulationState.STOPPED;
    s.processKilled = false;
    s.terminationRequested = false;
    s.pauseStartTime = null;
    s.totalPausedTime = 0;
    s.pinStateBatcher = null;
    s.serialOutputBatcher = null;
    s.onOutputCallback = null;
    s.errorCallback = null;
    s.telemetryCallback = null;
    s.pinStateCallback = null;
    s.ioRegistryCallback = undefined;
    s.outputBuffer = "";
    s.outputBufferIndex = 0;
    s.totalOutputBytes = 0;
    s.isSendingOutput = false;
    s.pendingCleanup = false;
    s.messageQueue = [];
    s.stderrFallbackBuffer = "";
    s.backpressurePaused = false;
    Iif (s.flushTimer) {
      clearTimeout(s.flushTimer);
      s.flushTimer = null;
    }
 
    // Reset rather than destroy: the ExecutionManager keeps this instance and its
    // onUpdate callback reads the next run's ioRegistryCallback from the state.
    try {
      this.registryManager.reset();
    } catch (error) {
      this.logger.debug(`RegistryManager reset failed: ${error instanceof Error ? error.message : String(error)}`);
    }
    this.timeoutManager.clear();
  }
 
  getSandboxStatus(): { dockerAvailable: boolean; dockerImageBuilt: boolean } {
    return {
      dockerAvailable: this.dockerAvailable,
      dockerImageBuilt: this.dockerImageBuilt,
    };
  }
}