Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

9.4 KB
Raw Blame
import { Router } from 'express';
import { runSchema, validate, sanitizeScreenshotRefs } from '../validation.js';
import { ToolkitHttpError, defaultAsyncHandler } from '../internal/httpError.js';

export function createRunsRoutes(runnerService, options = {}) {
  const router = Router();
  // `asyncHandler`/`ServerError` are injected by the host (PortOS passes its
  // real ServerError + asyncHandler so thrown errors normalize into
  // `{ error, code, timestamp, context? }` and route to errorMiddleware).
  // Standalone, the toolkit's own defaults serialize the same envelope.
  const { asyncHandler = defaultAsyncHandler, io = null, ServerError = ToolkitHttpError, withRunAdmission = handler => handler } = options;

  router.get('/', asyncHandler(async (req, res) => {
    const limit = parseInt(req.query.limit) || 50;
    const offset = parseInt(req.query.offset) || 0;
    const source = req.query.source || 'all';

    const result = await runnerService.listRuns(limit, offset, source);
    res.json(result);
  }));

  router.post('/', asyncHandler(withRunAdmission(async (req, res) => {
    // Validate up front so invalid types (timeout: "abc", screenshots: "x")
    // can't reach the runner — setTimeout would treat "abc" as 0 and kill
    // the run immediately, and iterating a string `screenshots` would walk
    // characters as individual paths.
    const result = validate(runSchema, req.body);
    if (!result.success) {
      throw new ServerError('Invalid run data', { status: 400, code: 'VALIDATION_ERROR', context: { details: result.errors } });
    }
    const { providerId, model, prompt, workspacePath, workspaceName, timeout, screenshots } = result.data;
    console.log(`🚀 POST /runs - provider: ${providerId}, model: ${model}, workspace: ${workspaceName}`);

    if (!providerId) {
      throw new ServerError('providerId is required', { status: 400 });
    }
    if (!prompt) {
      throw new ServerError('prompt is required', { status: 400 });
    }

    // A workspace NAME with no PATH means the caller picked an app whose
    // Repository Path is unset — distinct from picking no app at all, which
    // sends neither. Downstream both arrive as an absent `workspacePath` and
    // the run falls back to the host's own directory, so a prompt naming a
    // relative file writes there instead of into the chosen app (#3180). The
    // name is the only signal that a choice was made, and it is already on the
    // wire, so reject here rather than letting the two cases collapse.
    if (workspaceName && !(typeof workspacePath === 'string' && workspacePath.trim())) {
      throw new ServerError(
        `Workspace '${workspaceName}' has no Repository Path — set it for this app, then run again.`,
        { status: 400, code: 'WORKSPACE_PATH_MISSING' }
      );
    }

    // `screenshots[]` is untrusted user input that the vision loader
    // base64-encodes and forwards to the external provider — constrain it to
    // safe screenshots-dir basenames here so a `../` traversal or absolute path
    // can't exfiltrate an arbitrary file (issue #1870). A non-image / traversal
    // entry is rejected loudly rather than silently dropped.
    const { safe: safeScreenshots, rejected } = sanitizeScreenshotRefs(screenshots);
    if (rejected.length > 0) {
      throw new ServerError('Invalid screenshot path', {
        status: 400,
        code: 'VALIDATION_ERROR',
        context: { details: `Disallowed screenshot reference(s): ${rejected.join(', ')}` },
      });
    }

    const runData = await runnerService.createRun({
      providerId,
      model,
      prompt,
      workspacePath,
      workspaceName,
      timeout,
      screenshots: safeScreenshots
    });

    const { runId, provider, metadata, timeout: effectiveTimeout } = runData;
    console.log(`🚀 Run created: ${runId}, provider type: ${provider.type}`);

    // When createRun proactively swapped to a fallback (the requested provider
    // was benched), the request `model` was resolved against the now-benched
    // PRIMARY and almost never exists on the fallback — running it would leak
    // a bad model id onto the fallback (the same bug as the staged-LLM path).
    // Use the fallback's configured model (or its own default) instead; for
    // non-fallback runs keep honoring the request `model`.
    const runModel = runData.usedFallback
      ? (runData.fallbackModel || provider.defaultModel || null)
      : model;
    // CLI/TUI executors read defaultModel for their argv and run-started hooks.
    // Pin the requested (or fallback) model without changing the saved provider.
    const executionProvider = (runModel && runModel !== provider.defaultModel)
      ? { ...provider, defaultModel: runModel }
      : provider;
    // Gateway credentials are attached non-enumerably on provider reads. A
    // spread drops them; retain that execution-only key without exposing it to
    // JSON serialization or persistence (same contract as the host prompt runner).
    if (executionProvider !== provider && !executionProvider.apiKey && provider.apiKey) {
      Object.defineProperty(executionProvider, 'apiKey', {
        value: provider.apiKey,
        enumerable: false,
        configurable: true,
      });
    }

    if (provider.type === 'cli') {
      void Promise.resolve(runnerService.executeCliRun({
        runId,
        provider: executionProvider,
        prompt,
        workspacePath,
        onData: (data) => {
          io?.emit(`run:${runId}:data`, data);
        },
        onComplete: (finalMetadata) => {
          console.log(`✅ Run complete: ${runId}, success: ${finalMetadata.success}`);
          io?.emit(`run:${runId}:complete`, finalMetadata);
        },
        timeout: effectiveTimeout,
      })).catch(error => {
        console.error(`❌ Run ${runId} executor failed: ${error.message}`);
        io?.emit(`run:${runId}:complete`, { id: runId, success: false, error: error.message });
      });
    } else if (provider.type === 'api') {
      void Promise.resolve(runnerService.executeApiRun({
        runId,
        provider,
        model: runModel,
        prompt,
        workspacePath,
        screenshots: safeScreenshots,
        onData: (data) => {
          io?.emit(`run:${runId}:data`, data);
        },
        onComplete: (finalMetadata) => {
          io?.emit(`run:${runId}:complete`, finalMetadata);
        },
        timeout: effectiveTimeout,
      })).catch(error => {
        console.error(`❌ Run ${runId} executor failed: ${error.message}`);
        io?.emit(`run:${runId}:complete`, { id: runId, success: false, error: error.message });
      });
    } else if (provider.type === 'tui' && typeof runnerService.executeTuiRun === 'function') {
      void Promise.resolve(runnerService.executeTuiRun({
        runId,
        provider: executionProvider,
        prompt,
        workspacePath,
        onData: (data) => {
          io?.emit(`run:${runId}:data`, data);
        },
        onComplete: (finalMetadata) => {
          console.log(`✅ Run complete: ${runId}, success: ${finalMetadata.success}`);
          io?.emit(`run:${runId}:complete`, finalMetadata);
        },
        timeout: effectiveTimeout,
      })).catch(error => {
        console.error(`❌ Run ${runId} executor failed: ${error.message}`);
        io?.emit(`run:${runId}:complete`, { id: runId, success: false, error: error.message });
      });
    } else {
      throw new ServerError(`Unsupported provider type: ${provider.type}`, {
        status: 400,
        context: {
          details: provider.type === 'tui'
            ? 'TUI executor not attached to runner — check that setTuiRunner() was called in index.js'
            : `Known types: cli, api, tui (received: ${provider.type})`,
        },
      });
    }

    res.status(202).json({
      runId,
      status: 'started',
      metadata
    });
  })));

  router.get('/:id', asyncHandler(async (req, res) => {
    const metadata = await runnerService.getRun(req.params.id);

    if (!metadata) {
      throw new ServerError('Run not found', { status: 404 });
    }

    const isActive = await runnerService.isRunActive(req.params.id);
    res.json({
      ...metadata,
      isActive
    });
  }));

  router.get('/:id/output', asyncHandler(async (req, res) => {
    const output = await runnerService.getRunOutput(req.params.id);

    if (output === null) {
      throw new ServerError('Run not found', { status: 404 });
    }

    res.type('text/plain').send(output);
  }));

  router.get('/:id/prompt', asyncHandler(async (req, res) => {
    const prompt = await runnerService.getRunPrompt(req.params.id);

    if (prompt === null) {
      throw new ServerError('Run not found', { status: 404 });
    }

    res.type('text/plain').send(prompt);
  }));

  router.post('/:id/stop', asyncHandler(async (req, res) => {
    const stopped = await runnerService.stopRun(req.params.id);

    if (!stopped) {
      throw new ServerError('Run not found or not active', { status: 404 });
    }

    res.json({ success: true });
  }));

  router.delete('/:id', asyncHandler(async (req, res) => {
    const deleted = await runnerService.deleteRun(req.params.id);

    if (!deleted) {
      throw new ServerError('Run not found', { status: 404 });
    }

    res.status(204).send();
  }));

  router.delete('/', asyncHandler(async (req, res) => {
    if (req.query.filter !== 'failed') {
      throw new ServerError('Only filter=failed is supported for bulk delete', { status: 400 });
    }

    const deletedCount = await runnerService.deleteFailedRuns();
    res.json({ deletedCount });
  }));

  return router;
}