Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

13.6 KB
Raw Blame
#!/usr/bin/env node
// anymodel bot: stdio MCP front for the bundled Cua Driver (MIT, part of anymodel bot).
//
// DSH's mcp-client launches this script instead of `cua-driver mcp` directly. It:
//  0. answers the MCP handshake itself right away and brings the driver up in the background, so
//     the agent's startup never waits for (or crash-loops on) the driver (see createFront),
//  1. asks the bundled binary which tools exist on this platform (`cua-driver list-tools`),
//  2. writes a bounded-mode capability manifest (v3) allowing only our reviewed tool set
//     (intersected with what exists; unknown names would make the driver refuse to start),
//  3. runs `cua-driver mcp` with CUA_DRIVER_PERMISSION_MODE=bounded + that manifest,
//  4. hides every other tool from tools/list (the full list is ~230 KB of schemas) and
//     refuses calls to them before they reach the driver,
//  5. restarts the driver transparently before the manifest's 24 h lifetime runs out.
// Never passes --dangerously-bypass-approvals; telemetry and update checks are off.
// Config comes from the JSON file named by AMB_CUA_CONFIG (written by the host):
//   { bin, manifest, tools: string[], apps: [{executable}|{bundle_id}], display: boolean, direct?: boolean }
import { spawn, execFile } from 'node:child_process'
import fs from 'node:fs'
import readline from 'node:readline'
import { fileURLToPath } from 'node:url'

const LIFETIME_MS = 23 * 3600_000

const yq = (s) => JSON.stringify(String(s))

/**
 * One entry per application identity. cua-driver refuses to start ("application resources repeat
 * an identity") when the same app appears twice, and Windows paths differ only in case surprisingly
 * often (C:\Windows\System32\notepad.exe vs a Start-menu shortcut's C:\WINDOWS\system32\notepad.exe).
 */
export function uniqueApps(apps = [], platform = process.platform) {
  const seen = new Set()
  return apps.filter((a) => {
    const key = a.bundle_id ? `b:${String(a.bundle_id).toLowerCase()}` : `x:${platform === 'win32' || platform === 'darwin' ? String(a.executable).toLowerCase() : String(a.executable)}`
    if (seen.has(key)) return false
    seen.add(key)
    return true
  })
}

/** Bounded-mode capability manifest (YAML, version 3). */
export function manifestYaml({ tools, apps = [], display = false }) {
  apps = uniqueApps(apps)
  const lines = ['# generated by anymodel bot; do not edit', 'version: 3', 'expires_after: 24h', 'idle_timeout: 24h', 'allow:', '  tools:']
  for (const t of tools) lines.push(`    - ${yq(t)}`)
  lines.push('resources:')
  if (apps.length) {
    lines.push('  apps:')
    for (const a of apps) {
      lines.push(a.bundle_id ? `    - bundle_id: ${yq(a.bundle_id)}` : `    - executable: ${yq(a.executable)}`)
      lines.push('      launch: true', '      windows: all', '      terminate: driver_launched')
    }
  }
  lines.push('  desktop:', `    display: ${display ? 'true' : 'false'}`)
  return lines.join('\n') + '\n'
}

/** Parse `cua-driver list-tools` output ("name: description" per line). */
export function parseToolList(text) {
  const out = new Set()
  for (const line of String(text).split(/\r?\n/)) {
    const m = /^([a-z][a-z0-9_]*):\s/.exec(line)
    if (m) out.add(m[1])
  }
  return out
}

/** Environment for the driver: what we were given, minus our own config, plus the hard settings. */
export function childEnv(base, cfg) {
  const env = { ...base }
  for (const k of Object.keys(env)) {
    if (k.startsWith('AMB_') || k === 'ELECTRON_RUN_AS_NODE' || /KEY|PASSWORD|SECRET|TOKEN/i.test(k)) delete env[k]
  }
  delete env.CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS
  Object.assign(env, {
    CUA_DRIVER_PERMISSION_MODE: 'bounded',
    CUA_DRIVER_CAPABILITY_MANIFEST_FILE: cfg.manifest,
    CUA_DRIVER_CAPABILITY_MANIFEST_APPROVED: '1',
    CUA_DRIVER_DISABLE_RUN_SCRIPT: '1',
    DO_NOT_TRACK: '1',
    CUA_TELEMETRY_ENABLED: '0',
    CUA_DRIVER_RS_TELEMETRY_ENABLED: '0',
    // no update check either: it is a network request at every start and prints a notice to stderr
    CUA_DRIVER_RS_UPDATE_CHECK: '0',
  })
  return env
}

/** Line filter between the MCP client and the driver. Pure (no I/O) so it can be unit-tested. */
export function createFilter(allowed) {
  const listIds = new Set()
  return {
    /** client → driver: returns { forward?: msg, reply?: msg } */
    fromClient(msg) {
      if (msg && msg.method === 'tools/list' && msg.id !== undefined) listIds.add(msg.id)
      if (msg && msg.method === 'tools/call' && msg.id !== undefined) {
        const name = String(msg.params?.name ?? '')
        if (!allowed.has(name)) {
          return { reply: { jsonrpc: '2.0', id: msg.id, result: { isError: true, content: [{ type: 'text', text: `Tool '${name}' is not enabled in anymodel bot's Computer Use (Cua Driver).` }] } } }
        }
      }
      return { forward: msg }
    },
    /** driver → client */
    fromDriver(msg) {
      if (msg && msg.id !== undefined && listIds.has(msg.id) && msg.result && Array.isArray(msg.result.tools)) {
        listIds.delete(msg.id)
        return { ...msg, result: { ...msg.result, tools: msg.result.tools.filter((t) => allowed.has(t.name)) } }
      }
      return msg
    },
  }
}

/** `cua-driver list-tools`, asynchronously (never blocks the MCP channel). */
function listTools(cfg, env, timeoutMs = 30_000) {
  return new Promise((resolve, reject) => {
    execFile(cfg.bin, ['list-tools'], { env, encoding: 'utf8', timeout: timeoutMs, windowsHide: true, maxBuffer: 16 * 1024 * 1024 }, (err, stdout) => {
      if (err) reject(new Error(`cua-driver list-tools failed: ${err.message}`))
      else resolve(parseToolList(stdout))
    })
  })
}

const START_TIMEOUT_MS = 60_000
const RETRY_AFTER_MS = 60_000
const LIST_WAIT_MS = 3_000

/**
 * The MCP front. It answers `initialize` itself and starts the driver in the background, so DSH's
 * startup (which waits for every MCP server's first connection) never waits for cua-driver. Until
 * the driver is up, tools/list is empty; when it comes up the client gets
 * notifications/tools/list_changed and re-lists. A driver that fails to start is NOT a reason to
 * exit: exiting makes the MCP client relaunch this process (and the driver, and on Windows a
 * console for each) again and again. Instead calls report the failure, and the driver is retried
 * at most once a minute, on demand.
 */
export function createFront({ cfg, env, send, log, spawnDriver, listTools: list = () => listTools(cfg, env), now = Date.now }) {
  let allowed = new Set()
  let filter = createFilter(allowed)
  let child
  let ready = false
  let starting
  let startedAt = 0
  let lastAttempt = 0
  let lastFailure = ''
  let clientInit
  let owedListChanged = false
  let initSeq = 0
  const pending = new Set()
  const waiters = new Set()
  const settleWaiters = () => {
    for (const w of waiters) w()
    waiters.clear()
  }
  const whenReady = (ms) =>
    ready
      ? Promise.resolve(true)
      : new Promise((resolve) => {
          const done = () => {
            clearTimeout(t)
            waiters.delete(done)
            resolve(ready)
          }
          const t = setTimeout(done, ms)
          waiters.add(done)
        })

  const fail = (why) => {
    lastFailure = why
    log(why)
    settleWaiters()
  }

  const onDriverLine = (c, initId, line) => {
    if (!line.trim()) return
    let msg
    try { msg = JSON.parse(line) } catch { return }
    if (msg.id === initId) {
      if (msg.error) return fail(`cua-driver refused initialize: ${msg.error.message ?? JSON.stringify(msg.error)}`)
      c.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n')
      ready = true
      startedAt = now()
      lastFailure = ''
      log('cua-driver ready')
      settleWaiters()
      if (owedListChanged) {
        owedListChanged = false
        send({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' })
      }
      return
    }
    if (typeof msg.id === 'string' && msg.id.startsWith('amb-')) return
    if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) pending.delete(msg.id)
    send(filter.fromDriver(msg))
  }

  const start = () => {
    if (starting) return starting
    starting = (async () => {
      lastAttempt = now()
      let available
      try {
        available = await list()
      } catch (e) {
        return fail(String(e?.message ?? e))
      }
      const tools = cfg.tools.filter((t) => available.has(t))
      allowed = new Set(tools)
      filter = createFilter(allowed)
      fs.writeFileSync(cfg.manifest, manifestYaml({ tools, apps: cfg.apps ?? [], display: !!cfg.display }), { mode: 0o600 })
      const c = spawnDriver()
      child = c
      const initId = `amb-init-${++initSeq}`
      readline.createInterface({ input: c.stdout }).on('line', (line) => onDriverLine(c, initId, line))
      c.stderr?.on('data', (d) => process.stderr.write(d))
      // A driver that already exited must not take this process down with EPIPE on the next write.
      c.stdin.on('error', () => {})
      c.on('error', (e) => fail(`cua-driver could not start: ${e.message}`))
      c.on('exit', (code) => {
        if (child !== c) return
        child = undefined
        ready = false
        for (const id of pending) send({ jsonrpc: '2.0', id, error: { code: -32603, message: `cua-driver exited (${code})` } })
        pending.clear()
        fail(`cua-driver mcp exited (${code})`)
      })
      const params = clientInit?.params ?? { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'amb-cua-mcp', version: '1' } }
      c.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: initId, method: 'initialize', params }) + '\n')
      if (!(await whenReady(START_TIMEOUT_MS)) && child === c) {
        fail(`cua-driver did not answer initialize within ${START_TIMEOUT_MS / 1000} s`)
        c.kill()
      }
    })().finally(() => {
      starting = undefined
    })
    return starting
  }

  /** Driver is up, or try once more if the last attempt is old enough; resolves to readiness. */
  const ensure = async (waitMs) => {
    if (ready) return true
    if (!starting) {
      // failed less than a minute ago: answer right away instead of waiting for nothing
      if (now() - lastAttempt < RETRY_AFTER_MS) return false
      void start()
    }
    return whenReady(waitMs)
  }

  const forward = (msg) => {
    if (msg.id !== undefined && msg.method) pending.add(msg.id)
    child.stdin.write(JSON.stringify(msg) + '\n')
  }

  const onClient = async (msg) => {
    if (msg.method === 'initialize' && msg.id !== undefined) {
      clientInit = msg
      send({ jsonrpc: '2.0', id: msg.id, result: { protocolVersion: msg.params?.protocolVersion ?? '2025-06-18', capabilities: { tools: { listChanged: true } }, serverInfo: { name: 'amb-cua-mcp', version: '1.0.0' } } })
      void start()
      return
    }
    if (msg.method === 'notifications/initialized') return // the driver gets its own
    if (msg.method === 'ping' && msg.id !== undefined) return send({ jsonrpc: '2.0', id: msg.id, result: {} })
    if (msg.method === 'tools/list' && msg.id !== undefined) {
      if (await ensure(LIST_WAIT_MS)) return forward(filter.fromClient(msg).forward)
      owedListChanged = true
      return send({ jsonrpc: '2.0', id: msg.id, result: { tools: [] } })
    }
    if (msg.method === 'tools/call' && msg.id !== undefined) {
      // The manifest lives at most 24 h: start a fresh driver (same manifest) before it expires.
      if (ready && now() - startedAt > LIFETIME_MS) {
        const old = child
        child = undefined
        ready = false
        for (const id of pending) send({ jsonrpc: '2.0', id, error: { code: -32603, message: 'cua-driver restarted' } })
        pending.clear()
        old?.kill()
        lastAttempt = 0
      }
      if (!(await ensure(START_TIMEOUT_MS))) {
        return send({ jsonrpc: '2.0', id: msg.id, result: { isError: true, content: [{ type: 'text', text: `Computer Use is unavailable on this computer right now (${lastFailure || 'the Cua Driver is still starting'}). Tell the user instead of retrying.` }] } })
      }
      const r = filter.fromClient(msg)
      return r.reply ? send(r.reply) : forward(r.forward)
    }
    if (ready) return forward(msg)
    if (msg.id !== undefined && msg.method) send({ jsonrpc: '2.0', id: msg.id, error: { code: -32603, message: lastFailure || 'cua-driver is starting' } })
  }

  return {
    onClient,
    stop: () => child?.kill(),
    get ready() {
      return ready
    },
  }
}

function main() {
  const cfg = JSON.parse(fs.readFileSync(process.env.AMB_CUA_CONFIG, 'utf8'))
  const env = childEnv(process.env, cfg)
  const args = ['mcp', ...(cfg.direct ? ['--direct'] : [])]
  for (const s of [process.stdout, process.stderr]) s.on('error', () => {})
  const front = createFront({
    cfg,
    env,
    send: (msg) => process.stdout.write(JSON.stringify(msg) + '\n'),
    log: (s) => process.stderr.write(`amb-cua-mcp: ${s}\n`),
    // stdio all piped (stderr forwarded): with windowsHide that also means CREATE_NO_WINDOW, so
    // no console window exists at all (SW_HIDE alone is not enough when Windows Terminal is the
    // default console host).
    spawnDriver: () => spawn(cfg.bin, args, { env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }),
  })
  const rl = readline.createInterface({ input: process.stdin })
  rl.on('line', (line) => {
    if (!line.trim()) return
    let msg
    try { msg = JSON.parse(line) } catch { return }
    front.onClient(msg).catch((e) => process.stderr.write(`amb-cua-mcp: ${e?.message ?? e}\n`))
  })
  rl.on('close', () => { front.stop(); process.exit(0) })
  for (const s of ['SIGTERM', 'SIGINT']) process.on(s, () => { front.stop(); process.exit(0) })
}

if (process.argv[1] && fileURLToPath(import.meta.url) === fs.realpathSync(process.argv[1])) main()