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:
- N-API (
node-gyp/cmake-js/napi-rs) is heavy, coupled, and painful: It requires C++ build toolchains on end-user machines,node_api.hversion matrices, per-runtime engine boxing (napi_valuehandle scopes on every single call), and language-specific proc-macro ecosystems (napi-rsfor Rust, separate bindings for Zig/C/Go). bun:ffiis fast and ergonomic, but runtime-locked and untyped at the boundary:bun:ffionly 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/.gosources directly.- Security & Effect soundness disappear at the FFI boundary: Native calls can crash the process, block the JS event loop, leak
dlopenhandles or callback trampolines, or bypass VIP-58Capabilities.
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, NOnode-gyp). vibe:ffi(vibelang-runtime/ffi) — a Bun-like ergonomic runtime FFI API that works acrossvibe run, Bun, Node, and Deno.- First-class
foreigndeclarations & 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 EffectScope,defer,schema, fiber cancellation, and VIP-58Capability.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 pinnedUint8Array/ArrayBufferView— eliminates out-of-bounds buffer reads by passing length explicitly). - Flat C-layout structs (
@repr("C") schema): Compiler computes exactsizeof,alignof, and field byte offsets per target triple (matching C11 / Rust#[repr(C)]/ Zigextern struct) and generates zero-copyDataView/TypedArrayaccessors — zero JSON serialization, zero N-API object allocation. - Structured error return convention (
VibeResult): Optionalthrowsforeign functions take a trailingout_err: *mut VibeError({ code: i32, msg_ptr: *const u8, msg_len: usize }) so native errors surface as typed Effect failures (FfiCallErroror mappedschema error) instead of crashing or returning magic-1sentinels. - Cooperative fiber cancellation (
VibeCancelToken): Async/effect foreign functions may accept an implicit*const atomic_u8cancel flag so Effect fiber interruption cleanly aborts long-running native work.
How Zero-Dep Execution Works Across Runtimes (No N-API, No node-gyp)
| Runtime | Dispatch 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). |
| Bun | Lowers directly to Bun's built-in dlopen / CString / ptr fast path with zero wrapper overhead. |
| Node.js & Deno | Ships 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 onScopeexit; supportsdefercleanup).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 theScopecloses).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 fnexecutes synchronously on the calling thread (hot path: ~5–15ns call overhead) and requiresCapability.Ffiat library load time.effect fndispatches to a bounded native worker pool so blocking I/O or heavy CPU work never freezes the JS/Effect event loop, propagates fiber interruption viaVibeCancelToken, and returnsEffect<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
| Language | Export Convention in Source | Compiler Toolchain Invoked by vibe build | Header / 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 |
| Zig | export fn name(...) callconv(.c) | zig build-lib -dynamic -OReleaseFast | Zig AST parser extracts export fn and extern struct layouts directly |
| Rust | #[unsafe(no_mangle)] pub extern "C" fn | rustc --crate-type cdylib / cargo | Rust item parser extracts extern "C" fn and #[repr(C)] struct directly |
| Go | //export Name | go build -buildmode=c-shared | Go's go/ast (already in Vibe's compiler!) parses //export directly |
| Swift / Odin / C3 / Any C-ABI | @_cdecl / @(export) / extern | Configured via vibe.config.json ffi.compilers or prebuilt foreign "c" | Verified against foreign "c" declaration or emitted .h header |
4. Security, Capabilities & Memory Safety
- VIP-58 Capability Gate (
Capability.Ffi): EveryFFI.dlopen,foreignlibrary load, andwith { type: "ffi" }import requiresCapability.Ffi(optionally scoped to allowed library paths/hashes invibe.config.json). Sandboxed VIP-55task/workflowor VIP-63 coding-agent runs withoutfficapability fail at compile/plan time (EK5801). - Safe Slices by Default:
slice<u8>/mut slice<T>pins the JSUint8Arrayfor the duration of the call and passes(ptr, len)together. Raw pointer arithmetic (ptr<T>dereference / arbitrary addressFFI.read) requires explicitFFI.unsafeopt-in so static analysis and code review can audit every unsafe touchpoint. - Deterministic Lifetimes:
FFI.dlopenandFFI.callbackareScope-bound (Effect<..., Scope | Capability.Ffi>), guaranteeing handles and callback trampolines are never leaked and never use-after-free while an in-flighteffect fnworker holds a reference (refcounted pin until worker completion). - Cross-Compilation & Caching:
vibe buildcaches compiled.dylib/.so/.dllartifacts by(sourceHash, compilerVersion, targetTriple)under.vibe/ffi-cache/and supports multi-target packaging (vibe build --target darwin-arm64,linux-x64,linux-arm64) usingzig ccas an optional zero-config cross-compiler.
5. Static Rules
| Mistake | Code |
|---|---|
Non-ABI-safe type (e.g., JS function, Map, unboxed union) in a foreign signature or @repr("C") schema | EK8101 |
@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 build | EK8103 |
pure fn foreign call attempts to declare typed Effect error (! E) without effect fn | EK8104 |
Passing immutable Readonly<Uint8Array> to mut slice<u8> / mut ptr<T> parameter | EK8105 |
Calling native FFI inside a capability-restricted task/workflow lacking Capability.Ffi | EK5801 |
Testing & Verification Plan
- ABI Layout Verification (Z3 + Differential C/Zig/Rust/Go Harness): Compile the same
@repr("C") schemastructs across C (clang), Zig, Rust, and Go and assert byte-for-byte identicalsizeof,alignof, andoffsetofagainst 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") schemastruct passing & mutationeffect fnoff-thread execution + fiber interruption cancellation (VibeCancelToken)FFI.callbacknative-to-Vibe callbacks +Scopecleanup (AddressSanitizer / Valgrind leak-free verification)Capability.Ffidenial in sandboxed tasks (EK5801)
- Scalar math (
- Fuzzing:
FuzzFfiParserAndLayout(arbitraryforeignblocks and@repr("C") schemalayouts) + differential fuzzing ofvibe:ffidispatch acrossvibe run, Bun, and Node.
Open Questions for Will
- Keyword choice: Do you prefer
foreign "c" from "libfoo" { ... }orextern "c" from "libfoo" { ... }(closer to Rust/Zig/C)? - Async/off-thread default: Should functions in
foreigndefault toeffect fn(safe off-thread dispatch) with explicitpure fnopt-in for inline hot-path calls, or the reverse? (Recommendation:effect fnsafe default,pure fnexplicit opt-in for nanosecond math!) - Node/Deno bridge strategy: Should
vibelang-runtimebundle the ~25 KB prebuilt zero-dep Vibe ABI bridge binaries per platform (published as optional platform packages like@vibelang/ffi-darwin-arm64, zeronode-gyp), AND automatically use Bun's native FFI when running under Bun and Go's native trampoline when running undervibe run?