Skip to content

Formerly KrillinAI, VideoTranslation and Dubbing Tool for 120+ Languages. Open-source AI workspace for creators, powered by Codex. Video downloader, video translation, create videos, images, audios, and edits with Agents in one place. For your Social Media like YouTube, TikTok, Instagram, etc.

80.7 KB
Raw Blame
import { isDirectTransport } from '../gateway/supplier.js';
import type Database from 'better-sqlite3';
import type { CodexAvailabilityProbe, CodexRuntimeComponentReadiness } from '@opencreator/protocol';
import cors from '@fastify/cors';
import Fastify from 'fastify';
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
  ATTACHMENT_DRAFT_TTL_MS,
  ATTACHMENT_MAX_SIZE_BYTES,
  createAttachmentService
} from '../attachments/service.js';
import {
  createApprovalManager,
  type ApprovalManager
} from '../approvals/manager.js';
import {
  createAgentCapabilityTokenStore,
  type AgentCapabilityTokenStore
} from '../agent-tools/capability-token.js';
import {
  createDefaultAgentScheduleOperations,
  isAgentToolInternalRequest,
  registerAgentToolRoutes,
  type AgentScheduleOperations
} from '../agent-tools/internal-routes.js';
import { createCreatorToolOperations } from '../agent-tools/creator-tools.js';
import { createAgentContextBuilder } from '../creator/agent/context-builder.js';
import { createCreatorAgentService } from '../creator/agent/agent-service.js';
import { createCreatorAgentRepository } from '../creator/agent/repository.js';
import { createCreatorAgentReconciler } from '../creator/agent/reconciler.js';
import {
  createUnavailableAgentRuntimeAdapter,
  type AgentRuntimeAdapter
} from '../creator/agent/runtime-adapter.js';
import { bootstrapCreatorAgentRuntime } from '../creator/agent/bootstrap.js';
import { createCodexCreatorAdapter } from '../creator/agent/codex-adapter.js';
import { createCreatorStageRunner } from '../creator/stage-runner.js';
import { publishCreatorArtifacts } from '../creator/artifact-publisher.js';
import { createCreatorStageScheduler } from '../creator/stage-scheduler.js';
import { createCreatorCommandDispatcher } from '../creator/command-dispatcher.js';
import type { CreatorExecutor } from '../creator/executor.js';
import { createKrillinExecutor } from '../creator/krillin/adapter.js';
import { createKrillinDependencyLoader } from '../creator/krillin/dependency-loader.js';
import { readKrillinRuntimeManifest, resolveInside } from '../creator/krillin/manifest.js';
import {
  hasKrillinRuntimeVerificationWorker,
  startKrillinRuntimeVerification
} from '../creator/krillin/runtime-verifier.js';
import { createKrillinTtsService } from '../creator/krillin/tts-service.js';
import { createSubtitlePreviewService } from '../creator/krillin/subtitle-preview.js';
import { createSubtitleRenderService } from '../creator/krillin/subtitle-render.js';
import {
  createKrillinCodexLlmGateway,
  KRILLIN_LLM_ROUTE_PREFIX
} from '../creator/krillin/codex-llm-gateway.js';
import { createDownloadExecutor } from '../creator/download/executor.js';
import { resolveYtDlpRuntime } from '../creator/yt-dlp/runtime.js';
import {
  createYtDlpUpdateManager,
  type YtDlpUpdateManager
} from '../creator/yt-dlp/update-manager.js';
import { createCoverAnalysisExecutor } from '../creator/cover/executor.js';
import {
  createFfmpegCoverImageNormalizer,
  createImageExecutor
} from '../creator/image/executor.js';
import { createVideoExecutor } from '../creator/video/executor.js';
import { createClipExecutor } from '../creator/clip/executor.js';
import { createSmartDubbingExecutor } from '../creator/smart-dubbing/executor.js';
import { createXiaohongshuPostExecutor } from '../creator/xiaohongshu/executor.js';
import { createShortVideoScriptExecutor } from '../creator/short-video-script/executor.js';
import { createWechatArticleExecutor } from '../creator/article/executor.js';
import { createArticleImageGenerator } from '../creator/article/image-generator.js';
import { createArticleSourceExtractor } from '../creator/article/source-extractor.js';
import { createWechatArticleModel } from '../creator/article/model.js';
import {
  migrateStickmanVisualAssetState,
  purgeLegacyStickmanJobs
} from '../creator/stickman/legacy-migration.js';
import { createStickmanContentExecutor } from '../creator/stickman/content-executor.js';
import { createStickmanCodexJsonCompletion } from '../creator/stickman/codex-json-completion.js';
import { createStickmanAudioExecutor } from '../creator/stickman/audio-executor.js';
import { createStickmanImageExecutor } from '../creator/stickman/image-executor.js';
import { createStickmanVisualAssetRegistry } from '../creator/stickman/visual-assets.js';
import { createStickmanValidationExecutor } from '../creator/stickman/validation-executor.js';
import { createStickmanTimelineExecutor } from '../creator/stickman/timeline-executor.js';
import { createStickmanRemotionExecutor } from '../creator/stickman/remotion-executor.js';
import { createRemotionComponentManager } from '../creator/stickman/remotion-component.js';
import { createStickmanMediaValidationExecutor } from '../creator/stickman/media-validation-executor.js';
import { createStickmanDeliveryExecutor } from '../creator/stickman/delivery-executor.js';
import { CreatorProviderRequestLedger } from '../creator/provider-requests.js';
import { createCreatorProjectCoverService } from '../creator/project-cover.js';
import { createVideoGenerationService } from '../video-generation/service.js';
import { createImageGenerationService } from '../image-generation/service.js';
import { inspectCodexImageRuntime } from '../image-generation/codex-runtime.js';
import {
  createCreatorReferenceImageUploadService,
  type CreatorReferenceImageUploadService
} from '../creator/reference-image-upload.js';
import {
  createCreatorSourceUploadService,
  type CreatorSourceUploadService
} from '../creator/source-upload.js';
import {
  createCreatorDocumentUploadService,
  type CreatorDocumentUploadService
} from '../creator/document-upload.js';
import { createCreatorArtifactImportService } from '../creator/artifact-import.js';
import { createCreatorPreflight } from '../creator/preflight.js';
import { validateMediaFile, type MediaProbe } from '../creator/validators/media.js';
import {
  createCoverWorkflow,
  type CoverWorkflow
} from '../creator/templates/cover-actions.js';
import {
  createVideoTranslationWorkflow,
  type VideoTranslationWorkflow
} from '../creator/templates/video-translation-actions.js';
import {
  createAutoClipWorkflow,
  type AutoClipWorkflow
} from '../creator/templates/auto-clip-actions.js';
import {
  createStickmanVideoWorkflow,
  type StickmanVideoWorkflow
} from '../creator/templates/stickman-video-actions.js';
import {
  registerCreatorMcpRoute,
  registerAgentScheduleMcpRoute
} from '../agent-tools/mcp-routes.js';
import {
  createAgentScheduleProcessInjector,
  createAgentScheduleRunInjector,
  type AgentToolRunInjection,
  type RunMcpInjector
} from '../agent-tools/run-injection.js';
import {
  createUnknownCapabilityMatrix,
  isResumeExecutionSupported,
  withRuntimeSkillCapabilities,
  type RuntimeCapabilityMatrix
} from '../codex/capabilities.js';
import { createCodexAppServerClient } from '../codex/app-server-client.js';
import {
  createAppServerRuntimeManager,
  type AppServerRuntimeManager
} from '../codex/app-server-runtime-manager.js';
import { createCodexRuntimeReadiness } from '../codex/runtime-readiness.js';
import { createCodexProviderConfigService } from '../codex/provider-config.js';
import {
  createFileCodexProviderCredentialStore,
  createOpenCreatorCodexProviderCredentialStore,
  readCodexProviderApiKey,
  type CodexProviderCredentialStore
} from '../codex/provider-credential-store.js';
import {
  ensureCodexFileCredentialStore,
  isCodexCredentialStoreConfigurationDiagnostic
} from '../codex/credential-storage.js';
import { resolveCodexHome } from '../codex/home.js';
import { createFollowingLocalCodexHome, synchronizeLocalCodexConfiguration } from '../codex/probe-home.js';
import { readLocalCodexModelConfiguration } from '../codex/local-provider.js';
import {
  createCodexModelCatalog,
  type CodexModelCatalog
} from '../codex/model-catalog-2026-08-05.js';
import { createMcpManager } from '../codex/mcp/manager.js';
import {
  createCodexMcpRuntimeInjector
} from '../codex/mcp/runtime-injector-2026-08-12.js';
import { createMemoryService } from '../memory/service.js';
import { createNotificationService } from '../notifications/service.js';
import { createProjectManager } from '../projects/manager.js';
import { createProfileManager } from '../codex/profiles/manager.js';
import {
  createCodexSessionProvider,
  type CodexSessionProvider
} from '../codex/sessions/app-server-provider.js';
import { createSkillManager } from '../codex/skills/manager.js';
import { createSkillMarketManager } from '../codex/skills/market-manager.js';
import { createSkillMarketRecordRepository } from '../codex/skills/market-records.js';
import {
  createCodexSkillSourceInstaller,
  type CodexSkillSourceInstaller
} from '../codex/skills/source-installer.js';
import { buildCodexStatusResponse } from '../codex/status.js';
import { createCleanupService } from '../cleanup/service.js';
import {
  createCreatorServicesConfigStoreWithTextModelFallback,
  createFileCreatorServicesConfigStore,
  createOpenCreatorCreatorServicesConfigStore,
  type CreatorServicesConfigStore
} from '../creator-services/config-store.js';
import { createLocalCodexTextModelDefaults } from '../creator-services/local-codex-defaults.js';
import { createSmartDubbingService } from '../smart-dubbing/service.js';
import {
  createCreatorEventHub,
  creatorAgentEventKind,
  creatorIssueEventId,
  creatorStageEventId
} from '../creator/events.js';
import { createCreatorRepository } from '../creator/repository.js';
import { createCreatorTelemetryOutbox } from '../telemetry/outbox.js';
import { createCreatorTelemetrySink } from '../telemetry/creator.js';
import { registerTelemetryRoutes } from '../telemetry/routes.js';
import { createCreatorIssueService } from '../creator/issues.js';
import { createCreatorService, type CreatorService } from '../creator/service.js';
import {
  loadCreatorPresetCatalog,
  resolveCreatorPresetCatalogRoot
} from '../creator/presets/catalog.js';
import { assertCreatorPresetStageRequirement } from '../creator/presets/requirements.js';
import type { CreatorPresetRegistry } from '../creator/presets/types.js';
import { createDefaultCreatorTemplateRegistry } from '../creator/templates/registry.js';
import { createRunManager, type RunManager } from '../runs/manager.js';
import { createPersistentAppServerExecutor } from '../runs/persistent-app-server-executor-2026-07-28.js';
import {
  createScheduleCoordinator,
  type ScheduleCoordinator
} from '../scheduler/coordinator.js';
import { ScheduleRepository } from '../scheduler/repository.js';
import { createSchedulerService, type SchedulerService } from '../scheduler/service.js';
import { openRuntimeDatabase } from '../storage/database.js';
import { createRunRepository, createThreadRepository } from '../storage/repositories.js';
import { createThreadManager } from '../threads/manager.js';
import { createTaskService } from '../tasks/service.js';
import { createOpenCreatorSettingsStore } from '../settings/store.js';
import { createDefaultRevealExecutor } from '../workspace-files/reveal.js';
import { createWorkspaceFileService } from '../workspace-files/service.js';
import {
  createVideoMetadataService,
  type VideoMetadataService
} from '../video-metadata/service.js';
import { prepareSchedulerStartup } from '../startup.js';
import { requireAuth } from './auth.js';
import { apiError } from './errors.js';
import { registerAttachmentRoutes } from './routes.attachments.js';
import { registerApprovalRoutes } from './routes.approvals.js';
import { registerCodexRoutes } from './routes.codex.js';
import { registerCleanupRoutes } from './routes.cleanup.js';
import { registerCreatorServicesRoutes } from './routes.creator-services.js';
import { registerGatewayAccountRoutes } from './routes.gateway-account.js';
import { createGatewayAccountService, type GatewayAccountService } from '../gateway/account-service.js';
import { createGatewayClient, GatewayError, type GatewayClient } from '../gateway/client.js';
import { createOfficialVoicePreview, createOfficialVoicePreviewLanguages } from '../gateway/voice-preview.js';
import { createGatewayRuntimeBindings } from '../gateway/runtime-bindings.js';
import { createOfficialFetch } from '../gateway/official-fetch.js';
import { createOfficialModelAccess } from '../gateway/model-access.js';
import { createModelSelectionProbe } from '../gateway/model-selection-probe.js';
import { prepareOfficialRuntimeProbe } from '../gateway/runtime-probe.js';
import { createRuntimeSource } from '../gateway/runtime-source.js';
import { createGatewayCreatorSource } from '../gateway/creator-service-source.js';
import { createCodexAppServerHost } from '../codex/app-server-host-2026-07-28.js';
import { registerCreatorRoutes } from './routes.creator.js';
import { registerCreatorRuntimeRoutes } from './routes.creator-runtime.js';
import { registerDiagnosticsRoutes } from './routes.diagnostics.js';
import { registerImageGenerationRoutes } from './routes.image-generation.js';
import { registerMcpRoutes } from './routes.mcp.js';
import { registerMemoryRoutes } from './routes.memory.js';
import { registerNotificationRoutes } from './routes.notifications.js';
import { registerProfileRoutes } from './routes.profiles.js';
import { registerProjectRoutes } from './routes.projects.js';
import { registerRunRoutes } from './routes.runs.js';
import { registerSearchRoutes } from './routes.search.js';
import { registerSettingsRoutes } from './routes.settings.js';
import { registerScheduleRoutes } from './routes.schedules.js';
import { registerSkillMarketRoutes } from './routes.skill-market.js';
import { registerSkillRoutes } from './routes.skills.js';
import { registerSmartDubbingRoutes } from './routes.smart-dubbing.js';
import { registerTaskRoutes } from './routes.tasks.js';
import { registerThreadRoutes } from './routes.threads.js';
import { registerWorkspaceFileRoutes } from './routes.workspace-files.js';
import { registerVideoMetadataRoutes } from './routes.video-metadata.js';
import { PlatformConnectionService } from '../platform-connections/service.js';
import { supportedVideoSourcePlatform, gatewayModelReady } from '@opencreator/protocol';
import { registerPlatformConnectionRoutes } from './routes.platform-connections.js';

export type BuildServerInput = {
  token: string;
  appHome?: string;
  dataDir?: string;
  configFile?: string;
  credentialsFile?: string;
  gatewayOrigin?: string;
  runtimeDir?: string;
  creatorDir?: string;
  db?: Database.Database;
  codexBin?: string;
  codexHome?: string;
  localCodexHome?: string;
  defaultCwd?: string;
  defaultProjectRoot?: string;
  runManager?: RunManager;
  scheduler?: SchedulerService;
  scheduleCoordinator?: ScheduleCoordinator;
  schedulerAutostart?: boolean;
  startupSessionClassifier?(): void;
  sseHeartbeatMs?: number;
  resumeCapabilityVerified?: boolean;
  capabilities?: RuntimeCapabilityMatrix;
  skillMarketSourceInstaller?: CodexSkillSourceInstaller;
  attachmentMaxSizeBytes?: number;
  attachmentDraftTtlMs?: number;
  approvalManager?: ApprovalManager;
  agentCapabilityTokens?: AgentCapabilityTokenStore;
  agentScheduleOperations?: AgentScheduleOperations;
  agentToolsEnabled?: boolean;
  persistentAppServerEnabled?: boolean;
  runtimeTransport?: 'exec' | 'app-server';
  codexThreadRotationRunThreshold?: number;
  codexSessionProvider?: CodexSessionProvider;
  codexModelCatalog?: CodexModelCatalog;
  getCodexAvailabilityProbe?(): CodexAvailabilityProbe | undefined;
  onPrepareAvailabilityProbe?(prepare: () => ReturnType<typeof prepareOfficialRuntimeProbe>): void;
  memoryHistoryReader?(threadId: string): { items: import('@opencreator/protocol').ThreadHistoryItem[] } | undefined;
  creatorServicesConfigStore?: CreatorServicesConfigStore;
  videoMetadataService?: VideoMetadataService;
  codexProviderCredentialStore?: CodexProviderCredentialStore;
  creatorService?: CreatorService;
  creatorPresetRegistry?: CreatorPresetRegistry;
  creatorPresetCatalogRoot?: string;
  creatorPresetAssetsRoot?: string;
  creatorReferenceImageUploadService?: CreatorReferenceImageUploadService;
  creatorReferenceImageMaxSizeBytes?: number;
  creatorSourceUploadService?: CreatorSourceUploadService;
  creatorDocumentUploadService?: CreatorDocumentUploadService;
  creatorDocumentMaxSizeBytes?: number;
  creatorSourceMediaProbe?(path: string): Promise<MediaProbe>;
  creatorSourceMaxSizeBytes?: number;
  creatorYtDlpPath?: string;
  creatorYtDlpUpdateManager?: YtDlpUpdateManager;
  creatorRuntimePlatform?: NodeJS.Platform;
  creatorRuntimeArch?: string;
  creatorExecutors?: CreatorExecutor[];
  creatorAgentRuntime?: AgentRuntimeAdapter;
  allowedWebOrigins?: string[];
};

const ATTACHMENT_CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
const KRILLIN_VERIFICATION_BACKGROUND_DELAY_MS = 500;

export async function buildServer(input: BuildServerInput) {
  const server = Fastify({
    logger: false,
    forceCloseConnections: true
  });
  const allowedWebOrigins = new Set(
    input.allowedWebOrigins ?? ['http://127.0.0.1:19861']
  );
  await server.register(cors, {
    origin(origin, callback) {
      if (origin === undefined) return callback(null, false);
      if (allowedWebOrigins.has(origin)) return callback(null, true);
      return callback(null, false);
    },
    methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Authorization', 'Content-Type', 'Last-Event-ID'],
    credentials: false,
    maxAge: 600
  });
  const auth = requireAuth(input.token);
  const dataDir = resolve(input.dataDir ?? '.runtime');
  const appHome = resolve(input.appHome ?? dataDir);
  const configFile = resolve(input.configFile ?? join(appHome, 'config.toml'));
  const runtimeDir = resolve(input.runtimeDir ?? join(dataDir, 'creator-runtime'));
  const creatorDir = resolve(input.creatorDir ?? join(dataDir, 'creator'));
  const defaultManagedProjectRoot = join(
    input.defaultProjectRoot ?? join(homedir(), 'Documents'),
    'OpenCreator'
  );
  const openCreatorSettingsStore = createOpenCreatorSettingsStore(configFile, {
    defaultProjectRoot: defaultManagedProjectRoot,
    outputRoot: join(defaultManagedProjectRoot, 'Exports')
  });
  const codexBin = input.codexBin ?? 'codex';
  const defaultCwd = input.defaultCwd ?? process.cwd();
  const resolvedCodexHome =
    input.codexHome === undefined
      ? resolveCodexHome()
      : resolveCodexHome({ isolatedHome: input.codexHome });
  const codexHome = resolvedCodexHome.path;
  const localCodexHome = resolve(input.localCodexHome ?? codexHome);
  if (
    input.localCodexHome !== undefined
    && resolvedCodexHome.mode === 'isolated'
    && localCodexHome !== codexHome
  ) {
    try {
      synchronizeLocalCodexConfiguration(localCodexHome, codexHome);
    } catch {
      console.warn('Local Codex configuration could not be synchronized. The assistant will check it again before use.');
    }
  }
  try {
    await ensureCodexFileCredentialStore(codexHome);
  } catch (error) {
    if (!isCodexCredentialStoreConfigurationDiagnostic(error)) throw error;
  }
  const resumeCapabilityVerified =
    input.resumeCapabilityVerified ?? (
      input.capabilities === undefined ? undefined : isResumeExecutionSupported(input.capabilities)
    );
  const capabilities = withRuntimeSkillCapabilities(
    input.capabilities ?? createUnknownCapabilityMatrix()
  );
  const db = input.db ?? openRuntimeDatabase(join(dataDir, 'app.sqlite'));
  const ownsDb = input.db === undefined;
  const creatorTelemetryOutbox = createCreatorTelemetryOutbox(db);
  const runRepository = createRunRepository(db);
  const threadRepository = createThreadRepository(db);
  const scheduleRepository = new ScheduleRepository(db);
  const projectManager = createProjectManager({
    db,
    managedProjectRoot: defaultManagedProjectRoot,
    resolveManagedProjectRoot: () => (
      openCreatorSettingsStore.readStorage().settings.defaultProjectRoot
    )
  });
  const threadManager = createThreadManager({ db, dataDir, projectManager });
  const codexControlClient = createCodexAppServerClient({
    codexBin,
    codexHome
  });
  const codexSessionProvider = input.codexSessionProvider ?? createCodexSessionProvider({
    client: createCodexAppServerClient({
      codexBin,
      codexHome
    })
  });
  const codexModelCatalog = input.codexModelCatalog ?? createCodexModelCatalog({
    client: createCodexAppServerClient({
      codexBin,
      codexHome
    })
  });
  const workspaceFileService = createWorkspaceFileService({
    getThread: (id) => threadManager.getPublicThread(id),
    revealExecutor: createDefaultRevealExecutor()
  });
  const profileManager = createProfileManager({ codexHome: resolvedCodexHome });
  const skillManager = createSkillManager({ codexHome: resolvedCodexHome, db });
  const skillMarketRecords = createSkillMarketRecordRepository(db);
  const skillMarketManager = createSkillMarketManager({
    dataDir,
    skillManager,
    records: skillMarketRecords,
    sourceInstaller:
      input.skillMarketSourceInstaller ?? createCodexSkillSourceInstaller({ codexHome })
  });
  let persistentAppServerExecutor:
    | ReturnType<typeof createPersistentAppServerExecutor>
    | undefined;
  let appServerRuntimeManager: AppServerRuntimeManager | undefined;
  let creatorAppServerRuntimeManager: AppServerRuntimeManager | undefined;
  let stickmanContentRuntimeManager = input.creatorExecutors === undefined
    ? createAppServerRuntimeManager({ codexBin, codexHome })
    : undefined;
  const invalidatePersistentRuntime = (reason: string): Promise<void> => {
    const work = Promise.all([
      appServerRuntimeManager?.invalidate(reason)
        ?? persistentAppServerExecutor?.invalidate(reason)
        ?? Promise.resolve(),
      creatorAppServerRuntimeManager?.invalidate(reason) ?? Promise.resolve(),
      stickmanContentRuntimeManager?.invalidate(reason) ?? Promise.resolve()
    ]).then(() => undefined);
    void work.catch(error => {
      console.warn(
        `Persistent app-server invalidation failed: ${formatError(error)}`
      );
    });
    return work;
  };
  const mcpManager = createMcpManager({
    codexBin,
    codexHome: resolvedCodexHome,
    db,
    capabilities,
    onConfigurationChanged: invalidatePersistentRuntime
  });
  const notificationService = createNotificationService({ db });
  const approvalManager = input.approvalManager ?? createApprovalManager({ db });
  const unsubscribeApprovalNotifications = approvalManager.subscribe(approval => {
    if (approval.status === 'pending') {
      notificationService.enqueueApproval(approval.id);
    }
  });
  const memoryService = createMemoryService({ db });
  const storedCreatorServicesConfigStore =
    input.creatorServicesConfigStore ?? (
      input.credentialsFile === undefined
        ? createFileCreatorServicesConfigStore(
            join(dataDir, 'config', 'creator-services.json')
          )
        : createOpenCreatorCreatorServicesConfigStore({
            configFile,
            credentialsFile: input.credentialsFile
          })
    );
  const codexProviderCredentialStore =
    input.codexProviderCredentialStore ?? (
      input.credentialsFile === undefined
        ? createFileCodexProviderCredentialStore(
            join(dataDir, 'config', 'codex-provider.json')
          )
        : createOpenCreatorCodexProviderCredentialStore(input.credentialsFile)
    );
  const resolveCodexProviderApiKey = async (provider: {
    baseUrl: string;
    model: string;
  }): Promise<string | undefined> => readCodexProviderApiKey({
    store: codexProviderCredentialStore,
    provider,
    async readLegacy() {
      return (await storedCreatorServicesConfigStore.read()).llm;
    }
  });
  const creatorEvents = createCreatorEventHub();
  const creatorJobsRoot = join(creatorDir, 'jobs');
  await purgeLegacyStickmanJobs({ db, jobsRoot: creatorJobsRoot });
  migrateStickmanVisualAssetState({ db });
  let gatewayCreatorSource: ReturnType<typeof createGatewayCreatorSource> | undefined;
  const creatorRepository = createCreatorRepository(db, { serviceBinding: templateId => gatewayCreatorSource?.snapshot(templateId) ?? { source: 'manual' } });
  const creatorIssueService = createCreatorIssueService(creatorRepository, {
    onChanged(issue) {
      if (issue.scope.kind !== 'creator-job') return;
      const job = creatorRepository.getJob(issue.scope.jobId);
      if (job === undefined) return;
      creatorEvents.publish({
        id: creatorIssueEventId(issue),
        jobId: job.id,
        revision: job.revision,
        kind: 'issue_changed',
        payload: JSON.parse(JSON.stringify({ issue })) as Record<string, import('@opencreator/protocol').CreatorJson>,
        createdAt: issue.lastOccurredAt
      });
    }
  });
  const creatorProviderRequestLedger = new CreatorProviderRequestLedger(
    creatorRepository,
    creatorIssueService
  );
  const officialManagers = new Map<string, AppServerRuntimeManager>();
  let officialBindings: ReturnType<typeof createGatewayRuntimeBindings> | undefined;
  let officialRuntimeIdentity: string | undefined;
  const gatewayOrigin = input.gatewayOrigin ?? process.env.OPENCREATOR_GATEWAY_ORIGIN;
  const unavailable = async (): Promise<never> => { throw new GatewayError('services_not_ready'); };
  const readCommonProxy = async () => (await storedCreatorServicesConfigStore.read()).proxy;
  const gatewayClient: GatewayClient = gatewayOrigin ? createGatewayClient(gatewayOrigin, createOfficialFetch({ readProxy: readCommonProxy })) : {
    origin: '', startDevice: unavailable, pollDevice: unavailable, cancelDevice: unavailable,
    refresh: unavailable, bootstrap: unavailable, avatar: unavailable, logout: unavailable, request: unavailable
  };
  let officialInjectors: Record<string, import('../agent-tools/run-injection.js').AgentScheduleProcessInjector> = {};
  const modelSelectionProbe = createModelSelectionProbe({ dataDir,
    fetcher: createOfficialFetch({ readProxy: readCommonProxy }), readProxy: readCommonProxy
  });
  const gatewayAccount: GatewayAccountService = createGatewayAccountService({
    dataDir, client: gatewayClient,
    probeModel: modelSelectionProbe.probe,
    deferStartupActivation: true,
    modelAccess: createOfficialModelAccess({
      dataDir, fetcher: createOfficialFetch({ readProxy: readCommonProxy }), readProxy: readCommonProxy
    }),
    hasActiveTasks: () => [appServerRuntimeManager, creatorAppServerRuntimeManager, stickmanContentRuntimeManager]
      .some(manager => manager?.listScopes().some(scope => scope.active || scope.pending > 0))
      || creatorRepository.listJobs().some(job => job.status === 'running' || job.stages.some(stage => stage.status === 'queued')) || gatewayCreatorSource?.isBusy() === true,
    hasPendingTasks: () => creatorRepository.listJobs().some(job => job.providerRequests.some(request => request.billingSideEffect && ['submitting', 'waiting_remote', 'unknown_remote_acceptance'].includes(request.status))),
    async closeRuntime() {
      await gatewayCreatorSource?.revoke();
      officialBindings?.beginLogout();
      await officialBindings?.close();
      officialBindings = undefined;
      officialRuntimeIdentity = undefined;
      officialManagers.clear();
    },
    async activateRuntime(bootstrap) {
      if (runtimeTransport !== 'app-server') throw new GatewayError('services_not_ready');
      const model = bootstrap.models.find(value => value.id === bootstrap.defaults.text && value.modality === 'text' && value.capabilities.includes('responses') && gatewayModelReady(value));
      if (!model) throw new GatewayError('services_not_ready');
      const identity = JSON.stringify([bootstrap.account.id, bootstrap.baseUrl, bootstrap.transport,
        ...(isDirectTransport(bootstrap.transport) ? [] : [bootstrap.bindingVersion, bootstrap.keyVersion])]);
      if (officialBindings && officialRuntimeIdentity === identity) {
        // Turns already carry their own model; changing the default must keep live hosts and streams.
        await officialBindings.updateModel(model.id);
        return;
      }
      officialRuntimeIdentity = undefined;
      await officialBindings?.close(); officialManagers.clear();
      const home = join(runtimeDir, 'gateway-codex');
      const bootstrapResult = bootstrapCreatorAgentRuntime({ ...creatorAgentBootstrapInput, codexHome: home, source: 'gateway' });
      if (!bootstrapResult.available) throw new GatewayError('services_not_ready');
      officialBindings = createGatewayRuntimeBindings({
        codexHome: home, baseUrl: bootstrap.baseUrl, model: model.id, direct: isDirectTransport(bootstrap.transport), gateway: bootstrap.transport === 'gateway',
        readProxy: readCommonProxy,
        beginUse: async () => { const use = await gatewayAccount.beginModelUse(); return { key: use.credentials.modelKey, keyVersion: use.credentials.keyVersion, baseUrl: use.credentials.baseUrl, release: use.release, models: use.credentials.models,
          onModelFailure: (id, modality, facts) => gatewayAccount.reportModelFailure(use.credentials, id, modality, facts),
          onModelSuccess: (id, modality, operation) => gatewayAccount.reportModelSuccess(use.credentials, id, modality, operation) }; },
        recoverKey: async keyVersion => { const updated = await gatewayAccount.recoverModelCredentials(keyVersion); if (updated.baseUrl !== bootstrap.baseUrl) throw new GatewayError('supplier_binding_changed', 409); return { key: updated.modelKey, keyVersion: updated.keyVersion }; },
        readCredentials: async () => {
          if (bootstrap.transport !== 'gateway' && bootstrap.modelKey) return { accountId: bootstrap.account.id, modelKey: bootstrap.modelKey, keyVersion: bootstrap.keyVersion };
          const use = await gatewayAccount.beginModelUse({ recovery: true });
          try { return use.credentials; } finally { await use.release(); }
        },
        closeRuntime: async () => { await Promise.all([...officialManagers.values()].map(manager => manager.close())); }
      });
      const prepared = await officialBindings.prepare();
      const probe = createCodexAppServerHost({ codexBin, codexHome: home, cwd: dataDir, profile: 'default', baseEnvironment: prepared.env, spawnTimeoutMs: 15_000 });
      try { await probe.ready; } finally { await probe.close('gateway-activation-probe'); }
      for (const name of ['general', 'creator', 'stickman']) {
        officialManagers.set(name, createAppServerRuntimeManager({
          codexBin, codexHome: home, processInjector: officialInjectors[name],
          createHost(host) { return createCodexAppServerHost({ ...host, codexHome: home, baseEnvironment: prepared.env }); }
        }));
      }
      officialRuntimeIdentity = identity;
    }
  });
  await gatewayAccount.initialize();
  const creatorTelemetry = createCreatorTelemetrySink({
    outbox: creatorTelemetryOutbox,
    readAccount() {
      const account = gatewayAccount.peekState();
      const recharge = gatewayAccount.peekTelemetryRechargeState();
      return {
        authState: account.authState === 'signed_in'
          ? 'signed_in'
          : account.authState === 'signed_out' ? 'signed_out' : 'unknown',
        rechargeState: recharge.state,
        accountStateObservedAt: recharge.observedAt
      };
    }
  });
  const creatorAgentRepository = createCreatorAgentRepository(db);
  const creatorAgentReconciler = createCreatorAgentReconciler({
    repository: creatorAgentRepository
  });
  creatorAgentReconciler.reconcileAfterDaemonRestart();
  const creatorTemplates = createDefaultCreatorTemplateRegistry();
  for (const stage of creatorRepository.listRecoveredInterruptedStageRuns?.() ?? []) {
    const job = creatorRepository.getJob(stage.jobId);
    if (job === undefined) continue;
    const template = creatorTemplates.get(job.templateId, job.templateVersion);
    creatorTelemetry.stageFinished(job, stage, template.id, 'interrupted');
  }
  const creatorPresetCatalogRoot = resolve(
    input.creatorPresetCatalogRoot ?? resolveCreatorPresetCatalogRoot()
  );
  const creatorPresetAssetsRoot = resolve(
    input.creatorPresetAssetsRoot
      ?? (process.env.OPENCREATOR_PRESET_ASSETS_ROOT?.trim()
        || join(creatorPresetCatalogRoot, 'assets'))
  );
  const creatorPresetRegistry = input.creatorPresetRegistry
    ?? await loadCreatorPresetCatalog({
      root: creatorPresetCatalogRoot,
      assetsRoot: creatorPresetAssetsRoot,
      templates: creatorTemplates,
      verificationCachePath: join(
        dataDir,
        'runtime-verification',
        'creator-presets.json'
      )
    });
  const agentCapabilityTokens =
    input.agentCapabilityTokens ?? createAgentCapabilityTokenStore();
  const runtimeTransport = input.runtimeTransport ?? 'app-server';
  const getAgentToolBaseUrl = () =>
    resolveListeningOrigin(server.server.address());
  const krillinCodexLlmGateway = createKrillinCodexLlmGateway({
    codexBin,
    codexHome,
    cwd: dataDir,
    readLocalConfiguration: () => readLocalCodexModelConfiguration({ codexHome: localCodexHome }),
    readProxy: async () => (await storedCreatorServicesConfigStore.read()).proxy,
    readConfiguration: createFollowingLocalCodexHome(localCodexHome,
      join(runtimeDir, 'creator-text-codex'))
  });
  const creatorAgentBootstrapInput = {
    sourceCodexHome: localCodexHome,
    runtimeRoot: runtimeDir,
    ...(input.appHome === undefined
      ? {}
      : { codexHome: join(runtimeDir, 'creator-codex') }),
    bundledSkillDir: join(
      dirname(fileURLToPath(import.meta.url)),
      '..',
      '..',
      'runtime',
      'opencreator-runtime'
    )
  };
  let creatorAgentBootstrap = bootstrapCreatorAgentRuntime(creatorAgentBootstrapInput);
  const codexRuntimeReadiness = createCodexRuntimeReadiness({
    client: codexControlClient,
    mode: process.env.OPENCREATOR_CODEX_RUNTIME_MODE === 'external'
      ? 'external'
      : 'bundled',
    version: capabilities.codexVersion.replace(/^codex-cli\s+/, ''),
    commit: process.env.OPENCREATOR_CODEX_RUNTIME_MODE === 'external'
      ? null
      : '758ef40f50c1a458425c7cfbf1eb12cbc07af0b0',
    binaryPath: codexBin,
    codexHome,
    cwd: dataDir,
    binary: readCodexBinaryReadiness(
      process.env.OPENCREATOR_CODEX_RUNTIME_MODE === 'external'
        ? undefined
        : process.env.OPENCREATOR_CODEX_RUNTIME_ROOT
    ),
    checkToolServer: () => creatorAgentBootstrap.available
      ? { status: 'ready' }
      : {
          status: 'unavailable',
          errorCode: 'creator_agent_unavailable',
          message: creatorAgentBootstrap.error ?? 'Creator Tool Server is unavailable'
        }
  });
  const codexProviderConfig = createCodexProviderConfigService({
    client: codexControlClient,
    readiness: codexRuntimeReadiness,
    async readStoredApiKey(provider) {
      return resolveCodexProviderApiKey(provider);
    },
    async onProviderUpdated(provider) {
      if (provider.apiKey !== undefined) {
        await codexProviderCredentialStore.writeApiKey(provider.apiKey, provider);
      }
    },
    async onConfigurationChanged() {
      await Promise.all([
        codexModelCatalog.restart?.(),
        codexSessionProvider.restart?.(),
        invalidatePersistentRuntime('codex_provider_config_changed')
      ]);
      for (const thread of threadManager.listThreads({
        status: 'active',
        purpose: 'creator_agent'
      })) {
        threadManager.setCodexThreadId(thread.id, null);
      }
      creatorAgentBootstrap = bootstrapCreatorAgentRuntime(creatorAgentBootstrapInput);
      if (!creatorAgentBootstrap.available) {
        throw new Error(creatorAgentBootstrap.error ?? 'Creator Agent bootstrap failed');
      }
    }
  });
  const localCodexTextModelDefaults = createLocalCodexTextModelDefaults({
    codexHome: localCodexHome,
    readGatewayConfig() {
      const baseUrl = resolveListeningOrigin(server.server.address());
      return baseUrl === undefined ? undefined : krillinCodexLlmGateway.config(baseUrl);
    }
  });
  const manualCreatorServicesConfigStore =
    createCreatorServicesConfigStoreWithTextModelFallback(
      storedCreatorServicesConfigStore,
      localCodexTextModelDefaults
    );
  gatewayCreatorSource = createGatewayCreatorSource({ account: gatewayAccount, manual: manualCreatorServicesConfigStore, getLocalOrigin: getAgentToolBaseUrl, readJobBinding: creatorRepository.getServiceBinding, readJobState: id => creatorRepository.getJob(id)?.state, readJobTemplateId: id => creatorRepository.getJob(id)?.templateId, readStageRun: creatorRepository.getStageRun, ledger: creatorProviderRequestLedger, directRequestsRoot: join(dataDir, 'gateway', 'requests') });
  const creatorServicesConfigStore = gatewayCreatorSource.store;
  // Validation must resolve the same frozen binding and task model choices as execution.
  const readCreatorConfigForJob = (jobId: string) => gatewayCreatorSource!.runForJob(
    jobId, `preflight:${jobId}`, () => creatorServicesConfigStore.read()
  );
  if (stickmanContentRuntimeManager) stickmanContentRuntimeManager = createRuntimeSource(stickmanContentRuntimeManager, gatewayAccount.peekState, () => officialManagers.get('stickman'));
  let getCreatorYtDlpRuntime: ((sourceUrl?: string) => ReturnType<typeof resolveYtDlpRuntime>) | undefined;
  const youtubeConnection = new PlatformConnectionService({
    root: join(dataDir, 'platform-connections', 'youtube'),
    getRuntime: () => getCreatorYtDlpRuntime?.()
  });
  const douyinConnection = new PlatformConnectionService({
    platform: 'douyin',
    root: join(dataDir, 'platform-connections', 'douyin'),
    getRuntime: () => getCreatorYtDlpRuntime?.()
  });
  await youtubeConnection.initialize();
  await douyinConnection.initialize();
  await registerPlatformConnectionRoutes(server, youtubeConnection, douyinConnection);
  const videoMetadataService = input.videoMetadataService ?? createVideoMetadataService({
    getProxy: async () => (await readCommonProxy()).trim(),
    getYtDlpRuntime: sourceUrl => getCreatorYtDlpRuntime?.(sourceUrl),
    isYouTubeConnected: () => youtubeConnection.hasAuthentication(),
    withYouTubeCookies: operation => youtubeConnection.withCookies(operation),
    withDouyinCookies: operation => douyinConnection.withCookies(operation)
  });
  const creatorService = input.creatorService ?? createCreatorService({
    jobsRoot: creatorJobsRoot,
    repository: creatorRepository,
    templates: creatorTemplates,
    providerRequestLedger: creatorProviderRequestLedger,
    presets: creatorPresetRegistry,
    creatorServicesConfig: creatorServicesConfigStore,
    telemetry: creatorTelemetry
  });
  const creatorRuntimeRoot = process.env.OPENCREATOR_CREATOR_RUNTIME_ROOT
    ?? join(runtimeDir, 'krillinai');
  const krillinVerificationCachePath = join(
    dataDir,
    'runtime-verification',
    'krillinai.json'
  );
  let krillinVerificationTimer: NodeJS.Timeout | undefined;
  let startKrillinVerification: (() => ReturnType<typeof startKrillinRuntimeVerification>) | undefined;
  let ensureKrillinRuntimeReady = async () => {};
  const krillinDependencyLoader = createKrillinDependencyLoader({
    root: join(runtimeDir, 'krillinai', 'dependencies'),
    ...(input.creatorRuntimePlatform === undefined
      ? {}
      : { platform: input.creatorRuntimePlatform }),
    ...(input.creatorRuntimeArch === undefined ? {} : { arch: input.creatorRuntimeArch })
  });
  const krillinTtsService = createKrillinTtsService({
    resourceRoot: creatorRuntimeRoot,
    workRoot: join(creatorJobsRoot, '.tts'),
    configStore: creatorServicesConfigStore,
    officialPreviewLanguages: createOfficialVoicePreviewLanguages({ origin: gatewayClient.origin,
      fetcher: createOfficialFetch({ readProxy: readCommonProxy }) }),
    officialPreview: createOfficialVoicePreview({ origin: gatewayClient.origin,
      getState: () => gatewayAccount.peekState(),
      fetcher: createOfficialFetch({ readProxy: readCommonProxy }) }),
    verificationCachePath: krillinVerificationCachePath,
    ensureRuntimeReady: () => ensureKrillinRuntimeReady()
  });
  const smartDubbingService = createSmartDubbingService({
    dataDir,
    ttsService: krillinTtsService
  });
  const videoGenerationService = createVideoGenerationService({
    dataDir,
    configStore: creatorServicesConfigStore,
    gatewaySource: gatewayCreatorSource
  });
  // Image generation follows the user's local Codex login, independently of Agent settings.
  const codexImageRuntime = { codexHome: localCodexHome, codexBin };
  const readCodexImageStatus = () => inspectCodexImageRuntime(codexImageRuntime);
  const imageGenerationService = createImageGenerationService({
    dataDir,
    configStore: creatorServicesConfigStore,
    codexNative: codexImageRuntime
  });
  const packagedRemotionReleasePath = resolve(
    dirname(fileURLToPath(import.meta.url)),
    '../../runtime/remotion-component.json'
  );
  const stickmanRuntimeRoot = process.env.OPENCREATOR_STICKMAN_RUNTIME_ROOT
    ?? join(dataDir, 'creator-runtime', 'stickman');
  const developmentRemotionReleasePath = resolve(dirname(fileURLToPath(import.meta.url)), '../../../desktop/.pack/components/remotion-component.json');
  const remotionReleasePath = process.env.OPENCREATOR_REMOTION_COMPONENT_MANIFEST
    ?? (existsSync(packagedRemotionReleasePath) ? packagedRemotionReleasePath : developmentRemotionReleasePath);
  const remotionComponent = createRemotionComponentManager({
    root: stickmanRuntimeRoot,
    releasePath: remotionReleasePath,
    archivePath: process.env.OPENCREATOR_REMOTION_COMPONENT_ARCHIVE,
    developmentArchiveRoot: !existsSync(packagedRemotionReleasePath) && process.env.OPENCREATOR_RUNTIME_CHANNEL === 'development' ? dirname(remotionReleasePath) : undefined,
    readProxy: async () => (await creatorServicesConfigStore.read()).proxy.trim()
  });
  const packagedStickmanAssetsRoot = process.env.OPENCREATOR_STICKMAN_ASSETS_ROOT
    ?? resolve(dirname(fileURLToPath(import.meta.url)), '../../runtime/stickman-assets');
  const packagedStickmanCatalog = join(packagedStickmanAssetsRoot, 'visual-assets', 'catalog.json');
  const developmentStickmanCatalog = resolve(
    dirname(fileURLToPath(import.meta.url)),
    '../../../../resources/stickman/visual-assets/catalog.json'
  );
  const developmentStickmanVisualAssetRoot = resolve(
    dirname(fileURLToPath(import.meta.url)),
    '../../../web/public/dashboard'
  );
  const stickmanVisualAssetOptions = existsSync(packagedStickmanCatalog)
    ? {
        root: packagedStickmanAssetsRoot,
        catalogPath: packagedStickmanCatalog
      }
    : existsSync(developmentStickmanCatalog)
      ? {
          root: developmentStickmanVisualAssetRoot,
          catalogPath: developmentStickmanCatalog
        }
      : undefined;
  const stickmanVisualAssets = stickmanVisualAssetOptions !== undefined
    ? createStickmanVisualAssetRegistry(stickmanVisualAssetOptions)
    : undefined;
  const creatorTesseractPath = [
    process.env.OPENCREATOR_TESSERACT_PATH,
    process.platform === 'win32' ? 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe' : undefined,
    process.platform === 'win32' ? 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe' : undefined
  ].find(candidate => candidate !== undefined && existsSync(candidate));
  const creatorExecutors: CreatorExecutor[] = input.creatorExecutors ?? [];
  if (input.creatorExecutors === undefined) {
    if (stickmanVisualAssets !== undefined) {
      creatorExecutors.push(createStickmanContentExecutor({
        configStore: creatorServicesConfigStore,
        codexCompleteJson: createStickmanCodexJsonCompletion({
          runtimeManager: stickmanContentRuntimeManager!
        }),
        visualAssets: stickmanVisualAssets
      }));
      creatorExecutors.push(createStickmanImageExecutor({
        configStore: creatorServicesConfigStore,
        ledger: creatorProviderRequestLedger,
        codexNative: codexImageRuntime,
        ...(creatorTesseractPath === undefined ? {} : { tesseractPath: creatorTesseractPath })
      }));
    }
    creatorExecutors.push(
      createStickmanValidationExecutor({
        ...(creatorTesseractPath === undefined ? {} : { tesseractPath: creatorTesseractPath })
      }),
      createStickmanTimelineExecutor()
    );
  }
  let creatorFfmpegPath: string | undefined;
  let creatorFfprobePath: string | undefined;
  let creatorYtDlpUpdateManager = input.creatorYtDlpUpdateManager;
  let getYtDlpRuntime: ((sourceUrl?: string) => ReturnType<typeof resolveYtDlpRuntime>) | undefined;
  try {
    const runtimeManifest = readKrillinRuntimeManifest(creatorRuntimeRoot);
    let runtimeVerification: ReturnType<typeof startKrillinRuntimeVerification> | undefined;
    startKrillinVerification = () => {
      if (krillinVerificationTimer !== undefined) {
        clearTimeout(krillinVerificationTimer);
        krillinVerificationTimer = undefined;
      }
      if (runtimeVerification === undefined) {
        runtimeVerification = startKrillinRuntimeVerification({
          resourceRoot: creatorRuntimeRoot,
          cachePath: krillinVerificationCachePath
        });
        void runtimeVerification.catch(error => {
          console.warn(`Creator runtime verification failed: ${formatError(error)}`);
        });
      }
      return runtimeVerification;
    };
    ensureKrillinRuntimeReady = async () => {
      await startKrillinVerification!();
    };
    const executable = (pattern: RegExp) => {
      const resource = runtimeManifest.resources.find(candidate => (
        candidate.kind === 'executable' && pattern.test(candidate.path)
      ));
      return resource === undefined ? undefined : resolveInside(creatorRuntimeRoot, resource.path);
    };
    creatorFfmpegPath = executable(/(?:^|\/)ffmpeg(?:\.exe)?$/i);
    creatorFfprobePath = executable(/(?:^|\/)ffprobe(?:\.exe)?$/i);
    const ytDlp = resolveYtDlpRuntime({
      resourceRoot: creatorRuntimeRoot,
      manifest: runtimeManifest,
      ...(input.creatorYtDlpPath === undefined
        ? {}
        : { overridePath: input.creatorYtDlpPath })
    });
    if (
      creatorYtDlpUpdateManager === undefined
      && input.creatorYtDlpPath === undefined
      && ytDlp?.script !== undefined
    ) {
      try {
        creatorYtDlpUpdateManager = await createYtDlpUpdateManager({
          root: join(runtimeDir, 'yt-dlp'),
          bundledRuntime: ytDlp,
          async readProxy() {
            return (await creatorServicesConfigStore.read()).proxy.trim();
          }
        });
      } catch (error) {
        console.warn(`yt-dlp updater is unavailable: ${formatError(error)}`);
      }
    }
    getYtDlpRuntime = sourceUrl => (sourceUrl && supportedVideoSourcePlatform(sourceUrl) === 'douyin'
      ? douyinConnection : youtubeConnection).authenticatedRuntime(creatorYtDlpUpdateManager?.getRuntime() ?? ytDlp);
    getCreatorYtDlpRuntime = getYtDlpRuntime;
    if (input.creatorExecutors === undefined) {
      creatorExecutors.push(createKrillinExecutor({
        resourceRoot: creatorRuntimeRoot,
        jobsRoot: creatorJobsRoot,
        dependencyLoader: krillinDependencyLoader,
        configStore: creatorServicesConfigStore,
        getYtDlpRuntime,
        verificationCachePath: krillinVerificationCachePath,
        ensureRuntimeReady: () => ensureKrillinRuntimeReady()
      }));
    }
    if (
      input.creatorExecutors === undefined
      && ytDlp
      && creatorFfmpegPath
      && creatorFfprobePath
    ) {
      creatorExecutors.push(createDownloadExecutor({
        configStore: creatorServicesConfigStore,
        ytDlpPath: ytDlp.executable,
        ytDlpPrefixArgs: ytDlp.prefixArgs,
        ytDlpEnv: ytDlp.env,
        getYtDlpRuntime: sourceUrl => getYtDlpRuntime!(sourceUrl)!,
        ffmpegPath: creatorFfmpegPath,
        ffprobePath: creatorFfprobePath
      }));
    }
    if (input.creatorExecutors === undefined && ytDlp) {
      creatorExecutors.push(createCoverAnalysisExecutor({
        configStore: creatorServicesConfigStore,
        ytDlpPath: ytDlp.executable,
        ytDlpPrefixArgs: ytDlp.prefixArgs,
        ytDlpEnv: ytDlp.env,
        getYtDlpRuntime: () => getYtDlpRuntime!()!
      }));
    }
    if (input.creatorExecutors === undefined && creatorFfmpegPath && creatorFfprobePath) {
      creatorExecutors.push(createClipExecutor({
        configStore: creatorServicesConfigStore,
        ffmpegPath: creatorFfmpegPath,
        ffprobePath: creatorFfprobePath
      }));
    }
    if (input.creatorExecutors === undefined && creatorFfprobePath) {
      creatorExecutors.push(createStickmanAudioExecutor({
        configStore: creatorServicesConfigStore,
        ttsService: krillinTtsService,
        ledger: creatorProviderRequestLedger,
        ffprobePath: creatorFfprobePath
      }));
      creatorExecutors.push(createStickmanRemotionExecutor({
        ffprobePath: creatorFfprobePath,
        runtimeRoot: stickmanRuntimeRoot,
        ensureRuntime: stage => remotionComponent.ensure(stage)
      }));
      if (creatorFfmpegPath) {
        creatorExecutors.push(createStickmanMediaValidationExecutor({
          ffprobePath: creatorFfprobePath,
          ffmpegPath: creatorFfmpegPath
        }));
      }
      creatorExecutors.push(createStickmanDeliveryExecutor({
        ffprobePath: creatorFfprobePath,
        ffmpegPath: creatorFfmpegPath
      }));
    }
  } catch (error) {
    console.warn(`Creator optional runtime executors are unavailable: ${formatError(error)}`);
  }
  if (input.creatorExecutors === undefined) {
    creatorExecutors.push(createXiaohongshuPostExecutor({
      configStore: creatorServicesConfigStore
    }));
    creatorExecutors.push(createShortVideoScriptExecutor({
      configStore: creatorServicesConfigStore
    }));
    creatorExecutors.push(createSmartDubbingExecutor({
      ttsService: krillinTtsService,
      isOfficial: () => gatewayAccount.peekState().source === 'gateway'
    }));
    creatorExecutors.push(createImageExecutor({
      ledger: creatorProviderRequestLedger,
      configStore: creatorServicesConfigStore,
      codexNative: codexImageRuntime,
      ...(creatorFfmpegPath === undefined
        ? {}
        : {
            normalizeCoverImage: createFfmpegCoverImageNormalizer(
              creatorFfmpegPath
            )
          })
    }));
    if (creatorFfprobePath !== undefined) {
      creatorExecutors.push(createVideoExecutor({
        ledger: creatorProviderRequestLedger,
        service: videoGenerationService,
        probeVideo: path => validateMediaFile(path, creatorFfprobePath!)
      }));
    }
    creatorExecutors.push(createWechatArticleExecutor({
      sourceExtractor: createArticleSourceExtractor({
        configStore: creatorServicesConfigStore,
        getYtDlpRuntime: getCreatorYtDlpRuntime
      }),
      model: createWechatArticleModel({ configStore: creatorServicesConfigStore }),
      imageGenerator: createArticleImageGenerator({
        configStore: creatorServicesConfigStore,
        codexNative: codexImageRuntime
      })
    }));
  }
  const creatorPreflight = createCreatorPreflight({
    assertServiceSource: gatewayCreatorSource.assertJob,
    readConfigForJob: readCreatorConfigForJob,
    validateOfficialModel: gatewayAccount.validateModel,
    readCodexImageStatus,
    videoMetadataService,
    configStore: creatorServicesConfigStore,
    readCapabilities: () => krillinDependencyLoader.capabilities(),
    resourceRoot: creatorRuntimeRoot,
    jobsRoot: creatorJobsRoot,
    ffmpegPath: creatorFfmpegPath,
    ffprobePath: creatorFfprobePath,
    stickmanRuntimeRoot,
    remotionComponent,
    ...(getYtDlpRuntime === undefined ? {} : { getYtDlpRuntime }),
    runtimeVerificationCachePath: krillinVerificationCachePath,
    ensureRuntimeReady: () => ensureKrillinRuntimeReady(),
    executorIds: creatorExecutors.map(executor => executor.id),
    validateRuntimeAssets: input.creatorExecutors === undefined
  });
  const creatorProjectCoverService = createCreatorProjectCoverService({
    jobsRoot: creatorJobsRoot,
    ensureRuntimeReady: () => ensureKrillinRuntimeReady(),
    ...(creatorFfmpegPath === undefined ? {} : { ffmpegPath: creatorFfmpegPath })
  });
  const creatorSourceMediaProbe = input.creatorSourceMediaProbe
    ?? (creatorFfprobePath === undefined
      ? undefined
      : async (path: string) => {
          await ensureKrillinRuntimeReady();
          return await validateMediaFile(path, creatorFfprobePath!);
        });
  const creatorSourceUploadService = input.creatorSourceUploadService
    ?? (creatorSourceMediaProbe === undefined
      ? undefined
      : createCreatorSourceUploadService({
          jobsRoot: creatorJobsRoot,
          creator: creatorService,
          probeMedia: creatorSourceMediaProbe,
          maxSizeBytes: input.creatorSourceMaxSizeBytes
        }));
  const creatorReferenceImageUploadService = input.creatorReferenceImageUploadService
    ?? createCreatorReferenceImageUploadService({
        jobsRoot: creatorJobsRoot,
        creator: creatorService,
        maxSizeBytes: input.creatorReferenceImageMaxSizeBytes
      });
  const creatorDocumentUploadService = input.creatorDocumentUploadService
    ?? createCreatorDocumentUploadService({
      jobsRoot: creatorJobsRoot,
      creator: creatorService,
      ...(input.creatorDocumentMaxSizeBytes === undefined
        ? {}
        : { maxSizeBytes: input.creatorDocumentMaxSizeBytes })
    });
  const creatorArtifactImportService = createCreatorArtifactImportService({
    jobsRoot: creatorJobsRoot,
    creator: creatorService
  });
  let coverWorkflow: CoverWorkflow | undefined;
  let videoTranslationWorkflow: VideoTranslationWorkflow | undefined;
  let stickmanVideoWorkflow: StickmanVideoWorkflow | undefined;
  let autoClipWorkflow: AutoClipWorkflow | undefined;
  const creatorStageRunner = input.creatorService === undefined
    ? createCreatorStageRunner({
        repository: creatorRepository,
        issueService: creatorIssueService,
        templates: creatorService.templates,
        workRoot: creatorJobsRoot,
        telemetry: creatorTelemetry,
        executors: creatorExecutors.map(executor => ({
          id: executor.id,
          supportsProcessPause: executor.supportsProcessPause,
          run: stage => gatewayCreatorSource!.runForJob(stage.job.id, stage.stageRun.id, () =>
            ['download', 'krillinai', 'cover-analysis', 'wechat-article'].includes(executor.id)
              ? youtubeConnection.withCookies(() => douyinConnection.withCookies(() => executor.run(stage)))
              : executor.run(stage))
        })),
        async beforeRun(job, stageId) {
          gatewayCreatorSource!.assertJob(job.id);
          assertCreatorPresetStageRequirement({
            job,
            stageId,
            services: await readCreatorConfigForJob(job.id)
          });
        },
        onJobChanged(job) {
          creatorEvents.publish({
            id: `snapshot:${job.revision}`,
            jobId: job.id,
            revision: job.revision,
            kind: 'snapshot_changed',
            payload: { revision: job.revision }
          });
        },
        onStageChanged(stage) {
          const job = creatorService.getJob(stage.jobId);
          if (job === undefined) return;
          creatorEvents.publish({
            id: creatorStageEventId(stage),
            jobId: stage.jobId,
            revision: job.revision,
            kind: 'stage_progress',
            payload: { stage }
          });
          if ((stage.stageId === 'subtitle' && stage.status === 'running')
            || (stage.progress.backgroundSourceDownload === true && ['failed', 'canceled', 'interrupted'].includes(stage.status))) {
            void videoTranslationWorkflow?.handleStageChanged(stage).catch(error => {
              console.warn(`Video translation source download failed to start: ${formatError(error)}`);
            });
          }
          if (['failed', 'canceled', 'interrupted'].includes(stage.status)) {
            void stickmanVideoWorkflow?.handleStageChanged(stage).catch(error => {
              console.warn(`Stickman video workflow reconciliation failed: ${formatError(error)}`);
            });
          }
        },
        onStageSucceeded(stage) {
          const completedJob = creatorService.getJob(stage.jobId);
          if (completedJob !== undefined) {
            const project = projectManager.getProject(completedJob.projectId);
            if (project !== undefined) {
              void publishCreatorArtifacts({
                job: completedJob,
                project,
                outputRoot: openCreatorSettingsStore.readStorage().settings.outputRoot
              }).catch(error => {
                console.warn(`Creator artifact publication failed: ${formatError(error)}`);
              });
            }
          }
          void coverWorkflow?.handleStageChanged(stage).catch(error => {
            console.warn(`Cover workflow continuation failed: ${formatError(error)}`);
          });
          void videoTranslationWorkflow?.handleStageChanged(stage).catch(error => {
            console.warn(`Video translation workflow continuation failed: ${formatError(error)}`);
          });
          void stickmanVideoWorkflow?.handleStageChanged(stage).catch(error => {
            console.warn(`Stickman video workflow continuation failed: ${formatError(error)}`);
          });
          void autoClipWorkflow?.handleStageChanged(stage).catch(error => {
            console.warn(`Video clip workflow continuation failed: ${formatError(error)}`);
          });
        }
      })
    : undefined;
  const creatorStageScheduler = creatorStageRunner === undefined
    ? undefined
    : createCreatorStageScheduler({
        repository: creatorRepository,
        runner: creatorStageRunner
      });
  const creatorCommandDispatcher = createCreatorCommandDispatcher({
    service: creatorService,
    repository: creatorRepository,
    receipts: creatorAgentRepository,
    queryProviderRequest: request => gatewayCreatorSource!.queryProviderRequest(request),
    onQueuedStage: () => creatorStageScheduler?.wake(),
    onCommitted(result) {
      const activity = result.job.activities.find(candidate => (
        candidate.revision === result.job.revision
      ));
      if (activity !== undefined) {
        creatorEvents.publish({
          id: `activity:${activity.id}`,
          jobId: result.job.id,
          revision: result.job.revision,
          kind: 'activity_changed',
          payload: { activity },
          createdAt: activity.createdAt
        });
      }
      const stageRunId = result.commandReceipt.stageRunId;
      const stage = stageRunId === null
        ? undefined
        : result.job.stages.find(candidate => candidate.id === stageRunId)
          ?? creatorRepository.getStageRun(stageRunId);
      if (stage !== undefined) {
        creatorEvents.publish({
          id: creatorStageEventId(stage),
          jobId: result.job.id,
          revision: result.job.revision,
          kind: 'stage_progress',
          payload: { stage }
        });
      }
      creatorEvents.publish({
        id: `snapshot:${result.job.revision}`,
        jobId: result.job.id,
        revision: result.job.revision,
        kind: 'snapshot_changed',
        payload: { revision: result.job.revision }
      });
      void stickmanVideoWorkflow?.handleAction(
        result.job,
        result.commandReceipt.command
      ).catch(error => {
        console.warn(`Stickman video action continuation failed: ${formatError(error)}`);
      });
    }
  });
  videoTranslationWorkflow = creatorStageRunner === undefined
    ? undefined
    : createVideoTranslationWorkflow({
        creator: creatorService,
        dispatcher: creatorCommandDispatcher,
        configStore: creatorServicesConfigStore,
        readConfigForJob: readCreatorConfigForJob,
        videoMetadataService
      });
  coverWorkflow = creatorStageRunner === undefined
    ? undefined
    : createCoverWorkflow({
        creator: creatorService,
        dispatcher: creatorCommandDispatcher,
        configStore: creatorServicesConfigStore,
        readConfigForJob: readCreatorConfigForJob
      });
  stickmanVideoWorkflow = creatorStageRunner === undefined
    ? undefined
    : createStickmanVideoWorkflow({
        creator: creatorService,
        dispatcher: creatorCommandDispatcher,
        configStore: creatorServicesConfigStore,
        readConfigForJob: readCreatorConfigForJob,
        repository: creatorRepository,
        providerLedger: creatorProviderRequestLedger
      });
  autoClipWorkflow = creatorStageRunner === undefined
    ? undefined
    : createAutoClipWorkflow({
        creator: creatorService,
        dispatcher: creatorCommandDispatcher
      });
  const scheduleRunInjector = createAgentScheduleRunInjector({
    capabilities: agentCapabilityTokens,
    getBaseUrl: getAgentToolBaseUrl,
    scheduleToolsEnabled: input.agentToolsEnabled === true
  });
  const agentToolProcessInjector = createAgentScheduleProcessInjector({
    capabilities: agentCapabilityTokens,
    getBaseUrl: getAgentToolBaseUrl,
    includeCreator: false
  });
  const creatorAgentToolProcessInjector = createAgentScheduleProcessInjector({
    capabilities: agentCapabilityTokens,
    getBaseUrl: getAgentToolBaseUrl,
    includeSchedule: false
  });
  appServerRuntimeManager = createAppServerRuntimeManager({
    codexBin,
    codexHome,
    processInjector: agentToolProcessInjector
  });
  const readCreatorLocalConfiguration = localCodexHome === codexHome
    ? undefined
    : createFollowingLocalCodexHome(localCodexHome, codexHome);
  creatorAppServerRuntimeManager = createAppServerRuntimeManager({
    codexBin,
    codexHome,
    // Keep existing rollouts while following the same local configuration as AI Services.
    readConfiguration: readCreatorLocalConfiguration,
    processInjector: creatorAgentToolProcessInjector
  });
  officialInjectors = { general: agentToolProcessInjector, creator: creatorAgentToolProcessInjector };
  appServerRuntimeManager = createRuntimeSource(appServerRuntimeManager, gatewayAccount.peekState, () => officialManagers.get('general'));
  creatorAppServerRuntimeManager = createRuntimeSource(creatorAppServerRuntimeManager, gatewayAccount.peekState, () => officialManagers.get('creator'));
  const creatorAgentRuntime = input.creatorAgentRuntime ?? (creatorAgentBootstrap.available
    ? createCodexCreatorAdapter({
        runtimeManager: creatorAppServerRuntimeManager,
        threads: threadManager,
        skillPath: creatorAgentBootstrap.skillPath,
        guideVersion: creatorAgentBootstrap.guideVersion,
        guideHash: creatorAgentBootstrap.hash,
        async recheckConfigurationAfterFailure() {
          if (gatewayAccount.peekState().source !== 'manual' || readCreatorLocalConfiguration === undefined) return false;
          const checked = readCreatorLocalConfiguration({ verifyRuntime: true });
          if (checked.repaired) await creatorAppServerRuntimeManager?.invalidate('local_codex_configuration_repaired');
          return checked.repaired;
        },
        available: true
      })
    : createUnavailableAgentRuntimeAdapter(creatorAgentBootstrap.error));
  const creatorAgentContextBuilder = createAgentContextBuilder({ templates: creatorService.templates });
  const creatorAgentService = createCreatorAgentService({
    creator: creatorService,
    dispatcher: creatorCommandDispatcher,
    repository: creatorAgentRepository,
    threads: threadManager,
    contextBuilder: creatorAgentContextBuilder,
    runtime: creatorAgentRuntime,
    issueService: creatorIssueService,
    preflight: creatorPreflight,
    onEvent(event) {
      const job = creatorService.getJob(event.jobId);
      if (job === undefined) return;
      creatorEvents.publish({
        id: `agent:${event.sequence}`,
        jobId: event.jobId,
        revision: job.revision,
        kind: creatorAgentEventKind(event),
        payload: { event },
        createdAt: event.createdAt
      });
    }
  });
  const codexMcpRuntimeInjector = createCodexMcpRuntimeInjector({
    codexHome
  });
  const agentToolInjector = combineRunInjectors(
    scheduleRunInjector,
    codexMcpRuntimeInjector
  );
  persistentAppServerExecutor =
    input.runManager === undefined
    && input.persistentAppServerEnabled !== false
    && runtimeTransport === 'app-server'
      ? createPersistentAppServerExecutor({
          codexBin,
          codexHome,
          runtimeManager: appServerRuntimeManager,
          runtimeInjector: codexMcpRuntimeInjector
        })
      : undefined;
  const runManager =
    input.runManager ??
    createRunManager({
      db,
      dataDir,
      codexBin,
      codexHome,
      threadAccess: threadManager,
      resumeCapabilityVerified,
      profileValidator: profileManager,
      runtimeTransport,
      approvalManager,
      persistentAppServerExecutor,
      codexThreadRotationRunThreshold:
        input.codexThreadRotationRunThreshold
        ?? parseNonNegativeInteger(process.env.OPENCREATOR_CODEX_THREAD_ROTATION_RUN_THRESHOLD),
      prepareThreadRotationContext: context =>
        memoryService.prepareThreadRotationContext(context),
      agentToolInjector,
      recordRunContext: (runId, items) => memoryService.recordRunContext(runId, items),
      onRunTerminal(runId) {
        agentCapabilityTokens.revokeRun(runId);
        notificationService.enqueueRunTerminal(runId);
      }
    });
  let scheduler = input.scheduler;
  const scheduleCoordinator = input.scheduleCoordinator ?? createScheduleCoordinator({
    db,
    repository: scheduleRepository,
    threadManager,
    runManager,
    defaultCwd,
    profileValidator: profileManager,
    onSchedulesChanged: () => scheduler?.refreshTimer()
  });
  prepareSchedulerStartup({
    coordinator: scheduleCoordinator,
    classifySessions: input.schedulerAutostart === true
      ? input.startupSessionClassifier
      : undefined
  });
  scheduler ??= createSchedulerService({
    repository: scheduleRepository,
    runManager,
    autostart: false
  });
  const agentScheduleOperations =
    input.agentScheduleOperations
    ?? createDefaultAgentScheduleOperations({
      coordinator: scheduleCoordinator,
      scheduler,
      threadManager
    });
  const taskService = createTaskService({
    db,
    approvals: approvalManager,
    runs: runManager
  });
  const cleanupService = createCleanupService({
    dataDir,
    runs: runRepository,
    threads: threadRepository
  });
  const attachmentService = createAttachmentService({
    db,
    dataDir,
    maxSizeBytes: input.attachmentMaxSizeBytes ?? ATTACHMENT_MAX_SIZE_BYTES,
    draftTtlMs: input.attachmentDraftTtlMs ?? ATTACHMENT_DRAFT_TTL_MS
  });
  const initialAttachmentCleanup = attachmentService.cleanupExpiredDrafts()
    .then(() => undefined)
    .catch(error => {
      console.warn(`Initial attachment cleanup failed: ${formatError(error)}`);
    });
  const attachmentCleanupTimer = setInterval(() => {
    void attachmentService.cleanupExpiredDrafts().catch(error => {
      console.warn(`Attachment cleanup failed: ${formatError(error)}`);
    });
  }, ATTACHMENT_CLEANUP_INTERVAL_MS);
  attachmentCleanupTimer.unref();

  server.setErrorHandler((error, request, reply) => {
    if ((error as { code?: string }).code === 'FST_ERR_CTP_INVALID_JSON_BODY') {
      return reply
        .code(400)
        .send(apiError('VALIDATION_FAILED', 'body must be valid JSON'));
    }
    if ((error as { code?: string }).code === 'FST_ERR_CTP_BODY_TOO_LARGE') {
      return reply
        .code(413)
        .send(apiError('ATTACHMENT_TOO_LARGE', 'Attachment exceeds the configured size limit'));
    }
    throw error;
  });

  let closing = false;
  let backgroundStartup: Promise<void> | undefined;
  server.addHook('onListen', () => {
    backgroundStartup = (async () => {
      await gatewayAccount.startBackgroundRestore();
      if (closing) return;
      void coverWorkflow?.recover().catch(error => {
        console.warn(`Cover workflow recovery failed: ${formatError(error)}`);
      });
      void videoTranslationWorkflow?.recover().catch(error => {
        console.warn(`Video translation workflow recovery failed: ${formatError(error)}`);
      });
      void stickmanVideoWorkflow?.recover().catch(error => {
        console.warn(`Stickman video workflow recovery failed: ${formatError(error)}`);
      });
      void autoClipWorkflow?.recover().catch(error => {
        console.warn(`Video clip workflow recovery failed: ${formatError(error)}`);
      });
      if (input.schedulerAutostart === true) scheduler.start();
    })().catch(error => {
      console.warn(`Background startup failed: ${formatError(error)}`);
    });
    if (
      startKrillinVerification === undefined
      || !hasKrillinRuntimeVerificationWorker()
    ) return;
    krillinVerificationTimer = setTimeout(() => {
      krillinVerificationTimer = undefined;
      void startKrillinVerification?.();
    }, KRILLIN_VERIFICATION_BACKGROUND_DELAY_MS);
    krillinVerificationTimer.unref();
  });

  server.addHook('onClose', async () => {
    closing = true;
    await youtubeConnection.close();
    await douyinConnection.close();
    await modelSelectionProbe.close();
    await gatewayAccount.close();
    await backgroundStartup;
    let firstError: unknown;
    const capture = async (operation: () => void | Promise<void>) => {
      try {
        await operation();
      } catch (error) {
        firstError ??= error;
      }
    };

    await capture(() => clearInterval(attachmentCleanupTimer));
    await capture(() => {
      if (krillinVerificationTimer !== undefined) clearTimeout(krillinVerificationTimer);
    });
    await capture(() => initialAttachmentCleanup);
    await capture(() => unsubscribeApprovalNotifications());
    await capture(() => scheduler.stop());
    await capture(() => runManager.close());
    await capture(() => appServerRuntimeManager?.close());
    await capture(() => creatorAppServerRuntimeManager?.close());
    await capture(() => stickmanContentRuntimeManager?.close());
    await capture(() => krillinCodexLlmGateway.close());
    await capture(() => codexSessionProvider.close());
    await capture(() => codexModelCatalog.close());
    await capture(() => codexControlClient.close());
    await Promise.all([
      capture(() => creatorStageScheduler?.close()),
      capture(() => creatorStageRunner?.close())
    ]);
    await capture(() => agentCapabilityTokens.close());
    if (ownsDb) {
      await capture(() => {
        if (db.open) db.close();
      });
    }
    if (firstError !== undefined) throw firstError;
  });

  server.get('/healthz', async () => ({ ok: true }));

  server.addHook('preHandler', async (request, reply) => {
    if (request.url === '/healthz') return;
    if (isAgentToolInternalRequest(request.url)) return;
    if (request.url.startsWith(`${KRILLIN_LLM_ROUTE_PREFIX}/`)) return;
    await auth(request, reply);
  });

  await registerCodexRoutes(server, {
    codexBin,
    codexHome: resolvedCodexHome,
    capabilities,
    modelCatalog: {
      ...codexModelCatalog,
      async listModels() {
        const gateway = gatewayAccount.peekState();
        if (gateway.source === 'manual') return codexModelCatalog.listModels();
        return { models: gateway.models.filter(model => model.modality === 'text' && model.capabilities.includes('responses') && gatewayModelReady(model)).map((model, index) => ({ id: model.id, model: model.id, displayName: /openrouter/i.test(model.id) ? 'Auto' : model.id.split('/').pop()!, description: '', supportedReasoningEfforts: [], defaultReasoningEffort: null, inputModalities: ['text' as const], isDefault: gateway.selectedModels?.text ? model.id === gateway.selectedModels.text : index === 0 })) };
      }
    },
    readiness: codexRuntimeReadiness,
    providerConfig: {
      ...codexProviderConfig,
      async read() {
        const state = gatewayAccount.peekState();
        if (state.source === 'gateway') return { authentication: 'api_key' as const, apiKeyConfigured: false, baseUrl: '', model: state.selectedModels?.text ?? '' };
        return codexProviderConfig.read();
      },
      async update(update) {
        await gatewayAccount.setSource('manual');
        return codexProviderConfig.update(update);
      }
    },
    getAvailabilityProbe: input.getCodexAvailabilityProbe
  });
  await registerProfileRoutes(server, {
    codexHome: resolvedCodexHome,
    profileManager,
    getProfileUsage(name) {
      return {
        threads: threadRepository.listProfileReferences(name),
        schedules: scheduleRepository.listProfileReferences(name)
      };
    }
  });
  await registerVideoMetadataRoutes(server, videoMetadataService);
  await registerProjectRoutes(server, projectManager, runManager);
  await registerSkillRoutes(server, { skillManager });
  await registerSkillMarketRoutes(server, { skillMarketManager });
  await registerMcpRoutes(server, { mcpManager });
  await registerRunRoutes(server, runManager, {
    sseHeartbeatMs: input.sseHeartbeatMs,
    threadManager,
    profileValidator: profileManager,
    attachmentService,
    capabilities,
    memoryService
  });
  await registerScheduleRoutes(server, scheduleCoordinator, scheduler);
  await registerAgentToolRoutes(server, {
    capabilities: agentCapabilityTokens,
    schedules: agentScheduleOperations,
    creator: createCreatorToolOperations({
      service: creatorService,
      dispatcher: creatorCommandDispatcher,
      contextBuilder: creatorAgentContextBuilder
    })
  });
  await krillinCodexLlmGateway.register(server);
  if (input.agentToolsEnabled === true) {
    await registerAgentScheduleMcpRoute(server, {
      capabilities: agentCapabilityTokens,
      getBaseUrl: () => resolveListeningOrigin(server.server.address())
    });
  }
  await registerCreatorMcpRoute(server, {
    capabilities: agentCapabilityTokens,
    getBaseUrl: () => resolveListeningOrigin(server.server.address())
  });
  await registerCleanupRoutes(server, cleanupService);
  await registerSettingsRoutes(server, openCreatorSettingsStore);
  await registerCreatorServicesRoutes(
    server,
    creatorServicesConfigStore,
    () => krillinDependencyLoader.capabilities(),
    krillinTtsService,
    async () => {
      await videoTranslationWorkflow?.resumeConfiguredJobs();
      await coverWorkflow?.resumeConfiguredJobs();
      await stickmanVideoWorkflow?.resumeConfiguredJobs();
    },
    readCodexImageStatus,
    async () => gatewayAccount.peekState().source === 'gateway'
      ? { authentication: 'api_key' as const, apiKeyConfigured: false, baseUrl: '', model: gatewayAccount.peekState().selectedModels?.text ?? '' }
      : localCodexTextModelDefaults.readStatus(),
    storedCreatorServicesConfigStore
  );
  await registerGatewayAccountRoutes(server, gatewayAccount);
  await gatewayCreatorSource.register(server);
  await registerSmartDubbingRoutes(server, smartDubbingService);
  await registerCreatorRuntimeRoutes(server, creatorYtDlpUpdateManager, {
    loader: krillinDependencyLoader,
    remotion: remotionComponent,
    readConfig: () => creatorServicesConfigStore.read()
  });
  await registerImageGenerationRoutes(server, imageGenerationService);
  await registerCreatorRoutes(server, creatorService, creatorEvents, {
    sseHeartbeatMs: input.sseHeartbeatMs,
    jobsRoot: creatorJobsRoot,
    agentService: creatorAgentService,
    coverWorkflow,
    videoTranslationWorkflow,
    stickmanVideoWorkflow,
    stickmanVisualAssets,
    projectCoverService: creatorProjectCoverService,
    referenceImageUploadService: creatorReferenceImageUploadService,
    sourceUploadService: creatorSourceUploadService,
    documentUploadService: creatorDocumentUploadService,
    artifactImportService: creatorArtifactImportService,
    dispatcher: creatorCommandDispatcher,
    stageRunner: creatorStageRunner,
    presets: creatorPresetRegistry,
    presetCatalogRoot: creatorPresetCatalogRoot,
    presetAssetsRoot: creatorPresetAssetsRoot,
    readServicesConfig: () => creatorServicesConfigStore.read(),
    codexImageRuntime,
    preflight: creatorPreflight,
    issueService: creatorIssueService,
    subtitlePreviewService: createSubtitlePreviewService({
      resourceRoot: creatorRuntimeRoot,
      workRoot: join(creatorJobsRoot, '.previews'),
      ensureRuntimeReady: () => ensureKrillinRuntimeReady(),
      getYtDlpRuntime: () => getCreatorYtDlpRuntime?.()
    }),
    subtitleRenderService: createSubtitleRenderService({
      resourceRoot: creatorRuntimeRoot,
      workRoot: join(creatorJobsRoot, '.previews'),
      ensureRuntimeReady: () => ensureKrillinRuntimeReady()
    })
  });
  await registerAttachmentRoutes(server, attachmentService, {
    maxSizeBytes: input.attachmentMaxSizeBytes
  });
  await registerApprovalRoutes(server, approvalManager);
  await registerTelemetryRoutes(server, creatorTelemetryOutbox);
  await registerNotificationRoutes(server, notificationService);
  await registerTaskRoutes(server, taskService);
  await registerMemoryRoutes(server, memoryService, {
    async readThreadHistory(threadId) {
      if (input.memoryHistoryReader !== undefined) {
        return input.memoryHistoryReader(threadId);
      }
      const thread = threadManager.getThread(threadId);
      if (thread === undefined) return undefined;
      if (thread.codexThreadId === undefined || thread.codexThreadId === null) {
        return { items: [] };
      }
      return {
        items: await readAllCodexHistory(codexSessionProvider, thread.codexThreadId)
      };
    }
  });
  await registerDiagnosticsRoutes(server, {
    dataDir,
    runs: runRepository,
    schedules: scheduleRepository,
    getCodexStatusSnapshot: () =>
      buildCodexStatusResponse({
        codexBin,
        codexHome: resolvedCodexHome,
        capabilities,
        availabilityProbe: input.getCodexAvailabilityProbe?.()
      })
  });
  await registerWorkspaceFileRoutes(server, workspaceFileService);
  await registerSearchRoutes(server, {
    provider: codexSessionProvider,
    threadManager
  });
  await registerThreadRoutes(server, threadManager, runManager, {
    profileValidator: profileManager,
    attachmentService,
    readThreadHistory(codexThreadId, options) {
      return codexSessionProvider.listTurns({
        codexThreadId,
        limit: options.limit,
        ...(options.cursor === undefined ? {} : { cursor: options.cursor })
      });
    }
  });

  input.onPrepareAvailabilityProbe?.(() => prepareOfficialRuntimeProbe({ account: gatewayAccount, readProxy: readCommonProxy }));
  return server;
}

function readCodexBinaryReadiness(runtimeRoot: string | undefined): CodexRuntimeComponentReadiness {
  if (runtimeRoot === undefined) return { status: 'ready' };
  try {
    const manifest = JSON.parse(readFileSync(join(runtimeRoot, 'manifest.json'), 'utf8')) as {
      binary?: { sha256?: unknown };
      appServerProtocol?: { schemaSha256?: unknown };
    };
    if (typeof manifest.binary?.sha256 !== 'string') {
      return {
        status: 'invalid',
        errorCode: 'codex_runtime_hash_mismatch',
        message: 'The Codex Runtime manifest is missing the executable SHA-256'
      };
    }
    return {
      status: 'ready',
      details: {
        sha256: manifest.binary.sha256,
        ...(typeof manifest.appServerProtocol?.schemaSha256 === 'string'
          ? { protocolSchemaSha256: manifest.appServerProtocol.schemaSha256 }
          : {})
      }
    };
  } catch (cause) {
    return {
      status: 'invalid',
      errorCode: 'codex_runtime_hash_mismatch',
      message: cause instanceof Error ? cause.message : String(cause)
    };
  }
}

function combineRunInjectors(
  ...injectors: Array<RunMcpInjector | undefined>
): RunMcpInjector | undefined {
  const active = injectors.filter(
    (injector): injector is RunMcpInjector => injector !== undefined
  );
  if (active.length === 0) return undefined;
  return {
    async prepare(run) {
      const prepared = (
        await Promise.all(active.map(injector => injector.prepare(run)))
      ).filter(
        (injection): injection is AgentToolRunInjection =>
          injection !== undefined
      );
      if (prepared.length === 0) return undefined;
      return {
        mcpServers: prepared.flatMap(injection => injection.mcpServers),
        env: Object.assign({}, ...prepared.map(injection => injection.env)),
        builtInTools: prepared.find(
          injection => injection.builtInTools !== undefined
        )?.builtInTools,
        configurationFingerprint: prepared
          .map(injection => injection.configurationFingerprint)
          .filter((value): value is string => value !== undefined)
          .join(':')
      };
    }
  };
}

async function readAllCodexHistory(
  provider: CodexSessionProvider,
  codexThreadId: string
): Promise<import('@opencreator/protocol').ThreadHistoryItem[]> {
  let cursor: string | undefined;
  const seenCursors = new Set<string>();
  let items: import('@opencreator/protocol').ThreadHistoryItem[] = [];
  do {
    const page = await provider.listTurns({
      codexThreadId,
      limit: 100,
      ...(cursor === undefined ? {} : { cursor })
    });
    items = [...page.items, ...items];
    cursor = page.nextCursor;
    if (cursor !== undefined && seenCursors.has(cursor)) {
      throw new Error('Codex app-server returned a repeated history cursor');
    }
    if (cursor !== undefined) seenCursors.add(cursor);
  } while (cursor !== undefined);
  return items;
}

function formatError(error: unknown): string {
  return error instanceof Error ? error.message : String(error);
}

function parseNonNegativeInteger(value: string | undefined): number | undefined {
  if (value === undefined || !/^\d+$/.test(value)) return undefined;
  const parsed = Number(value);
  return Number.isSafeInteger(parsed) ? parsed : undefined;
}

function resolveListeningOrigin(
  address: ReturnType<typeof import('node:net').Server.prototype.address>
): string | undefined {
  if (address === null || typeof address === 'string') return undefined;
  const host = address.address === '::' || address.address === '0.0.0.0'
    ? '127.0.0.1'
    : address.address.includes(':')
      ? `[${address.address}]`
      : address.address;
  return `http://${host}:${address.port}`;
}