Skip to content

VIP-81: Built-In Zero-Dependency Multi-Language Native FFI (vibe:ffi & foreign)

Status: accepted by Will, 2026-11-30. Will: "I accept 76 to 81". (Previously open, 2026-11-28.)

Will's words

"One thing unrelated while talking about it is I want a really good VIP for a bun like FFI api that works with multiple supported languages. Like a built in napi but zero deps we are replacing napi not using napi"

Motivation

Calling native code (C, Zig, Rust, Go, Swift, C++, Odin) from JavaScript/TypeScript today is broken in three ways:

  1. N-API (node-gyp / cmake-js / napi-rs) is heavy, coupled, and painful: It requires C++ build toolchains on end-user machines, node_api.h version matrices, per-runtime engine boxing (napi_value handle scopes on every single call), and language-specific proc-macro ecosystems (napi-rs for Rust, separate bindings for Zig/C/Go).
  2. bun:ffi is fast and ergonomic, but runtime-locked and untyped at the boundary: bun:ffi only exists in Bun, requires manually duplicating C signatures in JS objects (drift = segfault), offers no Effect error/cancellation/capability integration, and doesn't compile .zig/.rs/.c/.go sources directly.
  3. Security & Effect soundness disappear at the FFI boundary: Native calls can crash the process, block the JS event loop, leak dlopen handles or callback trampolines, or bypass VIP-58 Capabilities.

VIP-81 replaces N-API with a built-in, zero-dependency, multi-language FFI system consisting of:

  • Vibe ABI v1 — a minimal, engine-independent C-ABI calling convention (NO node_api.h, NO V8/JSC handle boxing, NO node-gyp).
  • vibe:ffi (vibelang-runtime/ffi) — a Bun-like ergonomic runtime FFI API that works across vibe run, Bun, Node, and Deno.
  • First-class foreign declarations & multi-language source imports (import { ... } from "./hash.zig" with { type: "ffi" }) checked by the Vibe compiler for C, Zig, Rust, Go, and any C-ABI language, integrated with Effect Scope, defer, schema, fiber cancellation, and VIP-58 Capability.Ffi.

Decision

1. Replacing N-API: Vibe ABI v1 (Zero External Dependencies)

Instead of binding to V8/Node's N-API C API, VibeLang defines a tiny, stable C-ABI contract (vibe_abi_v1) built strictly on the host CPU's native C calling convention (System V AMD64, AAPCS64 ARM64, Win64):

  • Primitive scalar types passed directly in CPU registers: void, bool, i8, u8, i16, u16, i32, u32, i64, u64, isize, usize, f32, f64, ptr<T>, mut ptr<T>, cstring.
  • Fat slices (VibeSlice<T>): { ptr: *const T, len: usize } (2 registers, zero-copy pinned Uint8Array / ArrayBufferView — eliminates out-of-bounds buffer reads by passing length explicitly).
  • Flat C-layout structs (@repr("C") schema): Compiler computes exact sizeof, alignof, and field byte offsets per target triple (matching C11 / Rust #[repr(C)] / Zig extern struct) and generates zero-copy DataView / TypedArray accessors — zero JSON serialization, zero N-API object allocation.
  • Structured error return convention (VibeResult): Optional throws foreign functions take a trailing out_err: *mut VibeError ({ code: i32, msg_ptr: *const u8, msg_len: usize }) so native errors surface as typed Effect failures (FfiCallError or mapped schema error) instead of crashing or returning magic -1 sentinels.
  • Cooperative fiber cancellation (VibeCancelToken): Async/effect foreign functions may accept an implicit *const atomic_u8 cancel flag so Effect fiber interruption cleanly aborts long-running native work.

How Zero-Dep Execution Works Across Runtimes (No N-API, No node-gyp)

RuntimeDispatch Backend (Zero npm Native Build Dependencies)
vibe run (native Vibe runner)Built directly into the vibe Go binary using direct native calling-convention trampolines (ARM64/x86-64 assembly stubs — zero libffi, zero cgo required at user install time).
BunLowers directly to Bun's built-in dlopen / CString / ptr fast path with zero wrapper overhead.
Node.js & DenoShips a single prebuilt, tiny (~25 KB) pure-C/Zig Vibe FFI Bridge per platform triple (darwin-arm64, linux-x64, linux-arm64, windows-x64) bundled inside vibelang-runtime (using the runtime's own minimal loader — or Deno's built-in Deno.dlopen — with zero user-side node-gyp, zero Python, zero C++ compiler, and zero napi headers in user packages!).

2. Layer 1 — Bun-Like Runtime API (vibe:ffi)

For dynamic loading of existing system or third-party shared libraries (.dylib, .so, .dll), vibe:ffi provides an ergonomic Bun-inspired API with full TypeScript/Vibe type inference and Effect Scope + Capability.Ffi safety:

import { FFI } from "vibe:ffi"
 
export effect function hashBytes(data: Uint8Array) {
  const lib = try FFI.dlopen(`libblake3.${FFI.suffix}`, {
    blake3_hash: {
      args: ["slice<u8>", "mut slice<u8>"],
      returns: "i32"
    }
  })
  // lib is automatically closed when the enclosing Scope ends!
 
  const out = new Uint8Array(32)
  const rc = lib.symbols.blake3_hash(data, out)
  if (rc !== 0) throw new HashFailed({ code: rc })
  return out
}

Core vibe:ffi primitives:

  • FFI.dlopen(path, symbols) → Effect<Library<S>, FfiLoadError, Scope | Capability.Ffi> (auto-unloads on Scope exit; supports defer cleanup).
  • FFI.suffix → "dylib" | "so" | "dll".
  • FFI.ptr(typedArray) / FFI.toArrayBuffer(ptr, byteLength) / FFI.CString(ptr) / FFI.read.{i32,u64,f64,ptr}(ptr, offset).
  • FFI.callback(signature, fn) → Effect<CallbackHandle, never, Scope | Capability.Ffi> (creates a C-callable function pointer for native->JS callbacks and deterministically frees the trampoline when the Scope closes).
  • FFI.struct(CReprSchema) → zero-copy typed view over native struct memory (size, align, offsets, view(buf)).

3. Layer 2 — First-Class foreign Declarations & Multi-Language Source Imports

Manually mirroring C signatures in FFI.dlopen(...) is still error-prone. VibeLang adds two compiler-checked forms:

A. Declarative foreign Blocks (for Prebuilt Libraries)

@repr("C")
export schema ImageHeader {
  readonly width: u32
  readonly height: u32
  readonly channels: u8
}
 
export foreign "c" from "libimage" {
  // Pure sync call: runs inline in nanoseconds, marked @throws {never}
  pure fn image_pixel_count(hdr: ptr<ImageHeader>): u64
 
  // Effect call: automatically runs off the main thread on the FFI worker pool,
  // supports fiber cancellation, and maps non-zero status to typed error!
  effect fn image_decode(
    input: slice<u8>,
    out_hdr: mut ptr<ImageHeader>,
    out_pixels: mut slice<u8>
  ): void ! ImageDecodeError
}
  • pure fn executes synchronously on the calling thread (hot path: ~5–15ns call overhead) and requires Capability.Ffi at library load time.
  • effect fn dispatches to a bounded native worker pool so blocking I/O or heavy CPU work never freezes the JS/Effect event loop, propagates fiber interruption via VibeCancelToken, and returns Effect<A, E | FfiCallError, Capability.Ffi>.

B. Direct Multi-Language Source Imports (Zero Glue, Zero napi-rs)

VibeLang compiles native source files directly into content-addressed, target-tripled shared libraries and extracts and verifies the exported ABI signatures at compile time — eliminating signature drift completely:

// Zig: direct `export fn` — zero bindings!
import { fastHash, verifyEd25519 } from "./crypto.zig" with { type: "ffi" }
 
// Rust: direct `pub extern "C" fn` — zero napi-rs, zero proc-macros!
import { parseMarkdown } from "./markdown.rs" with { type: "ffi" }
 
// C / C++: direct `extern "C"` functions!
import { compressZstd } from "./zstd_wrap.c" with { type: "ffi" }
 
// Go: `//export` functions built with `-buildmode=c-shared`!
import { verifyZkProof } from "./prover.go" with { type: "ffi" }

Supported Language Matrix

LanguageExport Convention in SourceCompiler Toolchain Invoked by vibe buildHeader / Signature Verification
C / C++VIBE_EXPORT / extern "C"cc / clang (or bundled zig cc for zero-setup cross-compile!)AST/header signature extractor verifies exact param & return types
Zigexport fn name(...) callconv(.c)zig build-lib -dynamic -OReleaseFastZig AST parser extracts export fn and extern struct layouts directly
Rust#[unsafe(no_mangle)] pub extern "C" fnrustc --crate-type cdylib / cargoRust item parser extracts extern "C" fn and #[repr(C)] struct directly
Go//export Namego build -buildmode=c-sharedGo's go/ast (already in Vibe's compiler!) parses //export directly
Swift / Odin / C3 / Any C-ABI@_cdecl / @(export) / externConfigured via vibe.config.json ffi.compilers or prebuilt foreign "c"Verified against foreign "c" declaration or emitted .h header

4. Security, Capabilities & Memory Safety

  1. VIP-58 Capability Gate (Capability.Ffi): Every FFI.dlopen, foreign library load, and with { type: "ffi" } import requires Capability.Ffi (optionally scoped to allowed library paths/hashes in vibe.config.json). Sandboxed VIP-55 task/workflow or VIP-63 coding-agent runs without ffi capability fail at compile/plan time (EK5801).
  2. Safe Slices by Default: slice<u8> / mut slice<T> pins the JS Uint8Array for the duration of the call and passes (ptr, len) together. Raw pointer arithmetic (ptr<T> dereference / arbitrary address FFI.read) requires explicit FFI.unsafe opt-in so static analysis and code review can audit every unsafe touchpoint.
  3. Deterministic Lifetimes: FFI.dlopen and FFI.callback are Scope-bound (Effect<..., Scope | Capability.Ffi>), guaranteeing handles and callback trampolines are never leaked and never use-after-free while an in-flight effect fn worker holds a reference (refcounted pin until worker completion).
  4. Cross-Compilation & Caching: vibe build caches compiled .dylib/.so/.dll artifacts by (sourceHash, compilerVersion, targetTriple) under .vibe/ffi-cache/ and supports multi-target packaging (vibe build --target darwin-arm64,linux-x64,linux-arm64) using zig cc as an optional zero-config cross-compiler.

5. Static Rules

MistakeCode
Non-ABI-safe type (e.g., JS function, Map, unboxed union) in a foreign signature or @repr("C") schemaEK8101
@repr("C") schema contains recursive or dynamically-sized field without ptr<T>/slice<T>EK8102
Signature mismatch between import ... with { type: "ffi" } call site and extracted native export, at a call through the import or any value that holds the function; an imported name the source does not define; a default or namespace import of a native source; a source that does not buildEK8103
pure fn foreign call attempts to declare typed Effect error (! E) without effect fnEK8104
Passing immutable Readonly<Uint8Array> to mut slice<u8> / mut ptr<T> parameterEK8105
Calling native FFI inside a capability-restricted task/workflow lacking Capability.FfiEK5801

Testing & Verification Plan

  • ABI Layout Verification (Z3 + Differential C/Zig/Rust/Go Harness): Compile the same @repr("C") schema structs across C (clang), Zig, Rust, and Go and assert byte-for-byte identical sizeof, alignof, and offsetof against Vibe's Go compiler layout engine.
  • Cross-Language Round-Trip Matrix: End-to-end tests in typescript/vibelang/cases/vip81-* calling identical test suites implemented in C, Zig, Rust, and Go across:
    • Scalar math (i32, u64, f64, bool)
    • Zero-copy slice<u8> / mut slice<u8> buffers
    • @repr("C") schema struct passing & mutation
    • effect fn off-thread execution + fiber interruption cancellation (VibeCancelToken)
    • FFI.callback native-to-Vibe callbacks + Scope cleanup (AddressSanitizer / Valgrind leak-free verification)
    • Capability.Ffi denial in sandboxed tasks (EK5801)
  • Fuzzing: FuzzFfiParserAndLayout (arbitrary foreign blocks and @repr("C") schema layouts) + differential fuzzing of vibe:ffi dispatch across vibe run, Bun, and Node.

Open Questions for Will

  1. Keyword choice: Do you prefer foreign "c" from "libfoo" { ... } or extern "c" from "libfoo" { ... } (closer to Rust/Zig/C)?
  2. Async/off-thread default: Should functions in foreign default to effect fn (safe off-thread dispatch) with explicit pure fn opt-in for inline hot-path calls, or the reverse? (Recommendation: effect fn safe default, pure fn explicit opt-in for nanosecond math!)
  3. Node/Deno bridge strategy: Should vibelang-runtime bundle the ~25 KB prebuilt zero-dep Vibe ABI bridge binaries per platform (published as optional platform packages like @vibelang/ffi-darwin-arm64, zero node-gyp), AND automatically use Bun's native FFI when running under Bun and Go's native trampoline when running under vibe run?