Skip to content

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

3.9 KB
Raw Blame
// Keep the CLI's private request builders in step with the hosted Apps contract.
import { readFileSync, writeFileSync } from 'node:fs'
import { spawnSync } from 'node:child_process'
import { parse } from 'yaml'

const root = new URL('../../', import.meta.url)
const spec = parse(readFileSync(new URL('openapi/apps.openapi.yaml', root), 'utf8'))
const target = new URL('src/cli/src/commands/app/operations.rs', root)
const methods = []
for (const [path, entry] of Object.entries(spec.paths)) {
  for (const [method, operation] of Object.entries(entry)) {
    if (!operation.operationId) continue
    const names = [...path.matchAll(/{(\w+)}/g)].map(([, name]) => name)
    const parameters = (entry.parameters ?? []).map((p) =>
      p.$ref ? spec.components.parameters[p.$ref.split('/').pop()] : p,
    )
    const typeOf = (name) => (parameters.find((p) => p.name === name)?.schema.type === 'integer' ? 'u64' : '&str')
    const args = names.map((name) => `, ${name}: ${typeOf(name)}`).join('')
    const segments = path
      .slice(1)
      .split('/')
      .map((part) => {
        const name = part.match(/^{(\w+)}$/)?.[1]
        return !name ? JSON.stringify(part) : typeOf(name) === 'u64' ? `&${name}.to_string()` : name
      })
    const rustName = operation.operationId.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase())
    methods.push(`    pub(super) fn ${rustName}(&self${args}) -> Result<RequestBuilder> {
        self.request(Method::${method.toUpperCase()}, &[${segments.join(', ')}])
    }`)
  }
}
// Public result fields consumed by the CLI stay typed; extra server fields
// pass through its JSON output. The declared requirement and type come from the schema.
const schemas = spec.components.schemas
function rustType(schema) {
  if (schema.$ref) return rustType(schemas[schema.$ref.split('/').pop()])
  if (Array.isArray(schema.type))
    return `Option<${rustType({ ...schema, type: schema.type.find((t) => t !== 'null') })}>`
  if (schema.type === 'array') return `Vec<${rustType(schema.items)}>`
  if (schema.type === 'string' || schema.enum?.every((v) => typeof v === 'string')) return 'String'
  if (schema.type === 'integer') return 'u64'
  if (schema.type === 'boolean') return 'bool'
  return 'serde_json::Value'
}
const models = ['Plan', 'Deployment', 'Variable'].map((name) => {
  const schema = schemas[name]
  const fields = schema.required.map((key) => `    pub(super) ${key}: ${rustType(schema.properties[key])},`)
  fields.push('    #[serde(flatten)]', '    pub(super) extra: serde_json::Map<String, serde_json::Value>,')
  return `#[derive(serde::Deserialize, serde::Serialize)]\npub(super) struct ${name} {\n${fields.join('\n')}\n}`
})
const changes = schemas.VariableChange.oneOf.flatMap((variant) => {
  const tag = variant.properties.type
  const fields = variant.required
    .filter((name) => name !== 'type')
    .map((name) => {
      if (variant.properties[name].$ref === '#/components/schemas/StringMap')
        return name + ': std::collections::BTreeMap<String, String>'
      return `${name}: ${rustType(variant.properties[name])}`
    })
  return (tag.enum ?? [tag.const]).map(
    (value) => `    ${value[0].toUpperCase() + value.slice(1)} { ${fields.join(', ')} },`,
  )
})
models.push(
  `#[derive(serde::Serialize)]\n#[serde(tag="type", rename_all="camelCase")]\npub(super) enum VariableChange {\n${changes.join('\n')}\n}`,
)
const source = `//! Private HTTP operations from openapi/apps.openapi.yaml.
use super::Api;
use anyhow::Result;
use reqwest::{Method, RequestBuilder};

${models.join('\n\n')}

impl Api {
${methods.join('\n\n')}
}
`
const formatted = spawnSync('rustfmt', ['--edition', '2024'], { input: source, encoding: 'utf8' })
if (formatted.status !== 0) throw new Error(formatted.error?.message || formatted.stderr)
if (process.argv.includes('--check')) {
  if (readFileSync(target, 'utf8') !== formatted.stdout) {
    throw new Error('Apps operation bindings have drifted. Run make generate:app-operations.')
  }
} else {
  writeFileSync(target, formatted.stdout)
}