Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

2.7 KB
Raw Blame
/*
 * Copyright 2026 BoxLite AI
 * SPDX-License-Identifier: AGPL-3.0
 */

import type { INestApplication } from '@nestjs/common'
import { SwaggerModule, type OpenAPIObject } from '@nestjs/swagger'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { parse } from 'yaml'

// The Applet contract uses OpenAPI 3.1. Keep its schema constraints when
// rendering it in the platform's OpenAPI 3.0 document.
function platformSchema(_key: unknown, value: unknown): unknown {
  if (!value || typeof value !== 'object') return value
  const schema = value as Record<string, unknown>
  if ('const' in schema) {
    const { const: literal, ...rest } = schema
    return { ...rest, enum: [literal] }
  }
  if (!Array.isArray(schema.type)) return value
  const { type, ...rest } = schema
  if (type.includes('null')) return { ...rest, type: type.find((item) => item !== 'null'), nullable: true }
  // A manifest accepts either TOML text or the documented object.
  const { properties, ...metadata } = rest
  return { ...metadata, oneOf: type.map((item) => (item === 'object' ? { type: item, properties } : { type: item })) }
}

function withApplets(platform: OpenAPIObject, specDirectory: string): OpenAPIObject {
  const apps: OpenAPIObject = parse(readFileSync(join(specDirectory, 'apps.openapi.yaml'), 'utf8'), platformSchema)
  const paths = { ...platform.paths }
  for (const [path, item] of Object.entries(apps.paths)) {
    for (const operation of Object.values(item)) {
      if (operation.operationId) {
        operation.tags = ['Applet']
        operation.security = apps.security
      }
    }
    paths[apps.servers[0].url + path] = {
      ...item,
      servers: [{ url: '/' }],
      parameters: [
        { name: 'organizationId', in: 'path', required: true, schema: { type: 'string' } },
        ...(item.parameters ?? []),
      ],
    }
  }
  return {
    ...platform,
    paths,
    components: {
      ...platform.components,
      parameters: { ...platform.components?.parameters, ...apps.components.parameters },
      responses: { ...platform.components?.responses, ...apps.components.responses },
      schemas: { ...platform.components?.schemas, ...apps.components.schemas },
    },
  }
}

export function setupPlatformSwagger(
  app: INestApplication,
  document: OpenAPIObject,
  oauth: { clientId: string; audience: string },
  specDirectory: string,
) {
  SwaggerModule.setup('api', app, () => withApplets(document, specDirectory), {
    swaggerOptions: {
      initOAuth: {
        clientId: oauth.clientId,
        appName: 'BoxLite AI',
        scopes: ['openid', 'profile', 'email'],
        additionalQueryStringParams: { audience: oauth.audience },
      },
    },
  })
}