Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

14.5 KB
Raw Blame
#!/usr/bin/env node

import { spawnSync } from "node:child_process"
import {
  existsSync,
  lstatSync,
  mkdirSync,
  mkdtempSync,
  readFileSync,
  readdirSync,
  renameSync,
  rmSync,
  unlinkSync,
  writeFileSync,
} from "node:fs"
import { tmpdir } from "node:os"
import { dirname, isAbsolute, join, resolve } from "node:path"
import { fileURLToPath } from "node:url"

const scriptDirectory = dirname(fileURLToPath(import.meta.url))
const driverRoot = resolve(scriptDirectory, "..")
const rustRoot = join(driverRoot, "rust")
const pythonRoot = join(driverRoot, "python")
const typescriptRoot = join(driverRoot, "typescript")
const check = process.argv.includes("--check")

function run(command, args, cwd) {
  const result = spawnSync(command, args, { cwd, stdio: "inherit" })
  if (result.error) throw result.error
  if (result.status !== 0) {
    throw new Error(`${command} exited with status ${result.status}`)
  }
}

function nativeLibraryPath() {
  const file =
    process.platform === "darwin"
      ? "libcua_driver_sdk.dylib"
      : process.platform === "win32"
        ? "cua_driver_sdk.dll"
        : "libcua_driver_sdk.so"
  // Cargo honors CARGO_TARGET_DIR (relative to the workspace) for the build above.
  const targetRoot = process.env.CARGO_TARGET_DIR
    ? resolve(rustRoot, process.env.CARGO_TARGET_DIR)
    : join(rustRoot, "target")
  return join(targetRoot, "release", file)
}

function normalizeWhitespace(source) {
  const output = source
    .replaceAll("\r\n", "\n")
    .split("\n")
    .map((line) => line.replace(/[ \t]+$/u, ""))
    .join("\n")
  return output.endsWith("\n") ? output : `${output}\n`
}

function replaceExact(text, before, after, count = 1) {
  if (text.split(before).length - 1 !== count) {
    throw new Error(`unexpected UniFFI template: ${before}`)
  }
  return text.replaceAll(before, after)
}

function normalizePythonCursorEffects(source) {
  const output = replaceExact(source, ":typing.Optional[CursorEffectSetting]",
    ":typing.Optional[typing.Union[CursorEffectSetting, bool]]", 5)
  return replaceExact(output, "        if value == CursorEffectSetting.ON:\n",
    "        if type(value) is bool:\n            value = CursorEffectSetting.ON if value else CursorEffectSetting.OFF\n        if value == CursorEffectSetting.ON:\n", 2)
}

function normalizeTypeScriptCursorEffects(source) {
  let output = replaceExact(source, "?: CursorEffectSetting", "?: CursorEffectSetting | boolean", 5)
  output = replaceExact(output, "type TypeName = CursorEffectSetting;", "type TypeName = CursorEffectSetting | boolean;")
  output = replaceExact(output, "            switch (value) {\n                case CursorEffectSetting.On:",
    "            if (typeof value === \"boolean\") value = value ? CursorEffectSetting.On : CursorEffectSetting.Off;\n            switch (value) {\n                case CursorEffectSetting.On:")
  return replaceExact(output, "                case CursorEffectSetting.Default: return ordinalConverter.write(3, into);\n",
    "                case CursorEffectSetting.Default: return ordinalConverter.write(3, into);\n                default: throw new UniffiInternalError.UnexpectedEnumCase();\n")
}

function normalizePython(source) {
  const output = normalizeWhitespace(source)
  const unsafe = "eventloop.call_soon(_uniffi_cancel_task, task)"
  const safe = "eventloop.call_soon_threadsafe(_uniffi_cancel_task, task)"
  if (!output.includes("def _uniffi_future_dropped_callback(handle):")) return output
  const matches = output.split(unsafe).length - 1
  const corrected = output.split(safe).length - 1
  if (matches + corrected !== 1) {
    throw new Error("expected one UniFFI Python foreign-future cancellation scheduler")
  }
  // UniFFI 0.31 can drop a foreign future on a Rust worker thread.
  return normalizePythonServiceTransport(
    normalizePythonRemoteChannels(output.replace(unsafe, safe)),
  )
}

function normalizePythonServiceTransport(source) {
  if (!source.includes("class DriverServiceTransport():")) return source
  const lower = "            return _UniffiFfiConverterTypeDriverServiceTransport._handle_map.insert(value)"
  if (source.split(lower).length !== 2) {
    throw new Error("unexpected UniFFI service transport lowering template")
  }
  let output = source.replace(lower, `            eventloop = asyncio.get_running_loop()
            with _UNIFFI_REMOTE_CHANNEL_LOOP_LOCK:
                owner = getattr(value, "_uniffi_foreign_driver_event_loop", eventloop)
                if owner is not eventloop:
                    raise RuntimeError("Driver service transport belongs to a different asyncio event loop")
                value._uniffi_foreign_driver_event_loop = eventloop
            return _UniffiFfiConverterTypeDriverServiceTransport._handle_map.insert(value)`)
  const start = output.indexOf("class _UniffiTraitImplDriverServiceTransportImpl:")
  const end = output.indexOf("class _UniffiFfiConverterTypeDriverServiceTransport:", start)
  if (start < 0 || end < 0) throw new Error("missing service transport vtable")
  const before = "        _uniffi_trait_interface_call_async_with_error(\n            make_call,"
  const vtable = output.slice(start, end)
  if (vtable.split(before).length !== 2) {
    throw new Error("unexpected UniFFI service transport callback template")
  }
  output = output.slice(0, start) + vtable.replace(before,
    "        _uniffi_remote_channel_call_async(\n            uniffi_obj._uniffi_foreign_driver_event_loop,\n            make_call,") + output.slice(end)
  return output
}

function normalizePythonRemoteChannels(source) {
  if (!source.includes("class ForeignDriverEnvelopeChannel():")) return source
  if (source.includes("def _uniffi_remote_channel_call_async(")) {
    if (source.split("def _uniffi_remote_channel_call_async(").length !== 2
        || source.split("        _uniffi_remote_channel_call_async(").length !== 6
        || source.split("            with _UNIFFI_REMOTE_CHANNEL_LOOP_LOCK:").length !== 2) {
      throw new Error("unexpected normalized UniFFI remote callback template")
    }
    return source
  }
  // Each foreign carrier belongs to the loop on which it enters Rust. Rust
  // lifecycle threads must not depend on the process-global callback loop.
  let output = replaceExact(source,
    "            return _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.insert(value)",
    `            eventloop = asyncio.get_running_loop()
            with _UNIFFI_REMOTE_CHANNEL_LOOP_LOCK:
                owner = getattr(value, "_uniffi_foreign_driver_event_loop", eventloop)
                if owner is not eventloop:
                    raise RuntimeError("remote Driver channel belongs to a different asyncio event loop")
                value._uniffi_foreign_driver_event_loop = eventloop
            return _UniffiFfiConverterTypeForeignDriverEnvelopeChannel._handle_map.insert(value)`)
  const start = output.indexOf("def _uniffi_trait_interface_call_async_with_error(")
  const end = output.indexOf("\n_UNIFFI_FOREIGN_FUTURE_HANDLE_MAP =", start)
  if (start < 0 || end < 0) throw new Error("missing UniFFI async callback helper")
  let helper = output.slice(start, end)
  helper = replaceExact(helper,
    "def _uniffi_trait_interface_call_async_with_error(make_call,",
    "def _uniffi_remote_channel_call_async(eventloop, make_call,")
  helper = replaceExact(helper,
    "    eventloop = _uniffi_get_event_loop()\n    task = asyncio.run_coroutine_threadsafe(make_call_and_call_callback(), eventloop)",
    `    coroutine = make_call_and_call_callback()
    try:
        task = asyncio.run_coroutine_threadsafe(coroutine, eventloop)
    except RuntimeError:
        coroutine.close()
        handle = _UNIFFI_FOREIGN_FUTURE_HANDLE_MAP.insert((None, None))
        uniffi_out_dropped_callback[0] = _UniffiForeignFutureDroppedCallbackStruct(handle, _uniffi_future_dropped_callback)
        handle_error(
            _UniffiRustCallStatus.CALL_ERROR,
            lower_error(error_type.Failed("remote Driver channel asyncio event loop is closed")),
        )
        return`)
  output = output.slice(0, end) + "\n_UNIFFI_REMOTE_CHANNEL_LOOP_LOCK = threading.Lock()\n\n" + helper + output.slice(end)
  const vtableStart = output.indexOf("class _UniffiTraitImplForeignDriverEnvelopeChannelImpl:")
  const vtableEnd = output.indexOf("class _UniffiFfiConverterTypeForeignDriverEnvelopeChannel:", vtableStart)
  if (vtableStart < 0 || vtableEnd < 0) throw new Error("missing remote channel vtable")
  const vtable = replaceExact(output.slice(vtableStart, vtableEnd),
    "        _uniffi_trait_interface_call_async_with_error(\n            make_call,",
    "        _uniffi_remote_channel_call_async(\n            uniffi_obj._uniffi_foreign_driver_event_loop,\n            make_call,", 5)
  output = output.slice(0, vtableStart) + vtable + output.slice(vtableEnd)
  return replaceExact(output,
    "    eventloop.call_soon_threadsafe(_uniffi_cancel_task, task)",
    `    if eventloop is None:
        return
    try:
        eventloop.call_soon_threadsafe(_uniffi_cancel_task, task)
    except RuntimeError:
        # The loop owner may have closed it after the callback completed.
        pass`)
}

function normalizeTypeScript(name, source) {
  let output = normalizeWhitespace(source)
  // NodeNext requires emitted relative ESM imports to carry their .js suffix.
  output = output.replace(
    /(from\s+["']\.\/[A-Za-z0-9_-]+)(["'])/g,
    "$1.js$2",
  )
  if (name.endsWith("-ffi.ts")) {
    const needle = 'import lib from "@ubjs/node";'
    const matches = output.split(needle).length - 1
    if (matches !== 1) {
      throw new Error(`expected one Node runtime import in ${name}, found ${matches}`)
    }
    output = output.replace(needle, 'import lib from "./node-runtime.js";')
  }
  if (name === "cua_driver_contract.ts") output = normalizeTypeScriptCursorEffects(output)
  if (name === "cua_driver_contract-ffi.ts") {
    const needle = 'crateName: "cua_driver_contract"'
    const matches = output.split(needle).length - 1
    if (matches !== 1) {
      throw new Error(`expected one contract Node library selector, found ${matches}`)
    }
    // The contract namespace is linked into the SDK cdylib. UBRN 0.31.0-3
    // cannot configure a shared cdylib name for an external component.
    output = output.replace(needle, 'crateName: "cua_driver_sdk"')
  }
  return output
}

function inventoryContents(paths) {
  return [
    "# Generated by scripts/generate-uniffi-bindings.mjs; one owned path per line.",
    ...paths.slice().sort(),
    "",
  ].join("\n")
}

function assertOwnedPath(path) {
  const parts = path.split(/[\\/]/)
  if (
    isAbsolute(path) ||
    parts.some((part) => part === "" || part === "." || part === "..")
  ) {
    throw new Error(`invalid generated ownership path: ${path}`)
  }
  return path
}

function applyGroup(root, inventoryName, files) {
  const inventory = join(root, inventoryName)
  const previous = existsSync(inventory)
    ? readFileSync(inventory, "utf8")
        .split("\n")
        .filter((line) => line && !line.startsWith("#"))
        .map(assertOwnedPath)
    : []
  const expected = Object.keys(files).map(assertOwnedPath).sort()
  const planned = { ...files, [inventoryName]: inventoryContents(expected) }

  if (check) {
    const differences = previous.filter((path) => !expected.includes(path))
    for (const [path, contents] of Object.entries(planned)) {
      const destination = join(root, path)
      if (!existsSync(destination) || readFileSync(destination, "utf8") !== contents) {
        differences.push(path)
      }
    }
    if (differences.length) {
      throw new Error(`stale UniFFI generated files under ${root}: ${differences.join(", ")}`)
    }
    return
  }

  for (const stale of previous.filter((path) => !expected.includes(path))) {
    const destination = join(root, stale)
    if (existsSync(destination)) {
      if (lstatSync(destination).isSymbolicLink()) {
        throw new Error(`refusing to prune generated symlink ${destination}`)
      }
      unlinkSync(destination)
    }
  }
  for (const [path, contents] of Object.entries(planned)) {
    const destination = join(root, path)
    if (existsSync(destination) && lstatSync(destination).isSymbolicLink()) {
      throw new Error(`refusing to overwrite generated symlink ${destination}`)
    }
    mkdirSync(dirname(destination), { recursive: true })
    const temporary = `${destination}.tmp.${process.pid}`
    writeFileSync(temporary, contents)
    renameSync(temporary, destination)
  }
}

const temporaryRoot = mkdtempSync(join(tmpdir(), "cua-driver-uniffi-"))
try {
  run("cargo", ["build", "--locked", "--release", "-p", "cua-driver-sdk"], rustRoot)
  const library = nativeLibraryPath()
  if (!existsSync(library)) throw new Error(`missing built SDK library ${library}`)

  const pythonOutput = join(temporaryRoot, "python")
  run(
    "cargo",
    [
      "run",
      "--locked",
      "-p",
      "cua-driver-bindgen",
      "--bin",
      "cua-driver-bindgen",
      "--",
      "generate",
      "--library",
      library,
      "--language",
      "python",
      "--out-dir",
      pythonOutput,
      "--no-format",
    ],
    rustRoot,
  )

  const typescriptOutput = join(temporaryRoot, "typescript")
  const ubrn = join(
    typescriptRoot,
    "node_modules",
    ".bin",
    process.platform === "win32" ? "ubrn.cmd" : "ubrn",
  )
  if (!existsSync(ubrn)) {
    throw new Error("missing pinned UBRN generator; run npm ci in libs/cua-driver/typescript")
  }
  run(
    ubrn,
    [
      "generate",
      "napi",
      "bindings",
      "--library",
      library,
      "--ts-dir",
      typescriptOutput,
      "--lib-package-base",
      "@trycua/cua-driver",
      "--lib-node-triple",
      "--no-format",
    ],
    rustRoot,
  )

  applyGroup(pythonRoot, ".cua-driver-uniffi-generated-files", {
    "src/cua_driver/_native.py": normalizePython(
      readFileSync(join(pythonOutput, "cua_driver_sdk.py"), "utf8"),
    ),
    "src/cua_driver/_native_contract.py": normalizePythonCursorEffects(normalizePython(
      readFileSync(join(pythonOutput, "cua_driver_contract.py"), "utf8"),
    )),
  })

  const typescriptFiles = {}
  for (const name of readdirSync(typescriptOutput).filter((name) => name.endsWith(".ts"))) {
    typescriptFiles[`src/native/${name}`] = normalizeTypeScript(
      name,
      readFileSync(join(typescriptOutput, name), "utf8"),
    )
  }
  applyGroup(typescriptRoot, ".cua-driver-uniffi-generated-files", typescriptFiles)
  console.log(check ? "UniFFI bindings are up to date." : "Generated UniFFI bindings.")
} finally {
  if (process.argv.includes("--keep-temp")) {
    console.log(`Retained generator scratch output: ${temporaryRoot}`)
  } else {
    rmSync(temporaryRoot, { recursive: true, force: true })
  }
}