The Bridge: How To one contract, five carriers

Two programs that talk to each other cannot hand each other an object: a C host has no script dictionary, the engine cannot see a C struct, a Python host has no COM pointer, and a COM client has no UTF-8 buffer of its own. What crosses every one of those boundaries is UTF-8 text. The Bridge is therefore one request document in and one response document out, in both directions, and the object graph stays where it lives.

This page covers the whole contract and the five carriers that were driven through it end to end: C, C#, Python, PowerShell and COM. Each section carries a complete sample and the one or two details that decide whether it works.

What it is The envelope The seven rules The refusals Two kinds of failure The script side The five carriers No re-entry, and threads What travels Checking a carrier Troubleshooting Where the code is

What it is

Two doors, one dispatch, so a host and a script cannot disagree about what a request means:

DoorWhat it does
Bridge.Serve(handler)The script registers the function that answers the host. The host drives it.
Bridge.Handle(request)The host to script door, as text in and text out. This is what every carrier calls underneath, and it is also what a test drives, so a stub host is a script.
Bridge.Call(request)The script to host door. Answers the host's response document already parsed, so a script reads answer["r"]["n"].

The carrier only decides how the document travels. A C host installs a callback with slc_set_bridge and drives the script with slc_invoke; a COM client reaches the script with one Invoke member; a .NET host that owns the interpreter sets one field. Swapping the carrier changes no script, which is the reason the contract exists as a contract rather than as four protocols that resemble each other.

The envelope

A request is a JSON object with four members. Two are required.

MemberTypeMeaning
vwhole numberRequired. The contract version. This build speaks 1, and another value is refused by name rather than mis-read.
idany JSON valueOptional. The caller's correlation id. It is echoed verbatim, including an explicit null, and a request with no id member gets no id in the answer. The dispatcher writes it, so a handler cannot forget it or substitute somebody else's. It is how a host matches an answer to its request in a log: no carrier allows two requests outstanding at once, so pipelining would need a batch, which this version does not define.
mtextRequired. The verb, a dotted name such as invoice.post. It is the only thing a handler dispatches on.
pJSON objectOptional. The parameters. An explicit null is the same as leaving it out, which is stated rather than left to a handler to guess. Anything large is paged inside it, because a contract that allows one huge value invites a payload no reader can bound.

A response is also one object, and exactly one of r or e is present:

MemberTypeMeaning
vnumberThe contract version the answer was built for. Always 1, written by the dispatcher.
idanyThe request's id, echoed by construction, including null. No id member in the request, no id in the answer.
okbooleanRequired. The verdict of the request.
rany JSON valueThe result, when ok is true.
eobjectThe error, when ok is false.

The error object's four base members are always present. at and frames appear when the engine caught the failure, and retryAfter and details when the handler has something more to say:

MemberMeaning
codeA short, non-empty, stable name a host branches on: BadRequest, UnsupportedVersion, NoSuchVerb (the handler's own), or one of the engine's error codes.
messageOne non-empty sentence, in the engine's or the handler's voice, naming what to fix. Never a CLR resource key.
retryA boolean. true means the same request may succeed later (a busy resource), which is what a host needs to decide between an error dialog and a backoff. retryAfter says how long to wait.
origin"engine" when the dispatcher or the engine built the failure (a refusal, or a handler that threw), "handler" when the handler answered it with Bridge.Fail or Bridge.FromError. The dispatcher forces it, so a handler cannot claim the engine's voice.
retryAfterA whole number of milliseconds. Meaningful when retry is true, and what a host uses as its backoff.
detailsA JSON object the APPLICATION owns, such as { "field": "total" }. The engine never interprets it; it is where a validation failure names the parameter that was wrong.
at{ "file": "...", "line": 12, "col": 5 }, when the ENGINE caught the failure: the script that registered the handler and the position inside it.
framesThe engine's call frames, innermost first, as "Post [L10:C9]". Present when there are any.

A request and its answer

{"v":1,"id":"h1","m":"echo","p":{"n":21}}

{"v":1,"id":"h1","ok":true,"r":{"n":42}}

{"v":1,"id":"h2","m":"nope","p":{}}

{"v":1,"id":"h2","ok":false,"e":{"code":"NoSuchVerb","message":"no nope","retry":false,"origin":"handler"}}

{"v":1,"id":"h3","m":"boom"}

{"v":1,"id":"h3","ok":false,"e":{"code":"Unspecified","message":"boom","retry":false,"origin":"engine",
  "at":{"file":"worker.slc","line":7,"col":9},"frames":["Post [L10:C9]"]}}

The third pair is a handler's own refusal, built with Bridge.Fail. The fourth is a handler that THREW: the engine turns it into the same error object, with the position and the frames a host would otherwise have to correlate by hand.

The seven rules

  1. One verb shape. Both directions use the same document, so a log or a fixture is readable without knowing which side produced it.
  2. No re-entry on the same session. A session serves one host request at a time. A handler MAY call the host with Bridge.Call; what is refused is Bridge.Handle on its own session, a verb issued from inside a host callback (a run posted there would wait on itself), and a host that answers Bridge.Call by calling back into the same session. Each of those is a loop, which is why the rule is about re-entry rather than about depth.
  3. Nothing throws across. A handler that throws becomes ok:false with the engine's code, message, position and frames. A host that throws, or that answers a negative length, is a refusal the script can catch at the Bridge.Call that reached it.
  4. m is additive only. A verb may be added at any time. Removing one, or changing what one means, is a contract version bump, which is what v is for. A reader tolerates members it does not know, so a newer side does not break an older one.
  5. p is an object, absent, or explicitly null. A null means the same as absent. Arrays and scalars travel inside it.
  6. id is echoed by construction. The dispatcher rewrites it from the request, null included, so a handler cannot forget it. It is how a host matches an answer to its request in a log; no carrier allows two requests outstanding, so pipelining would need a batch, which version 1 does not define.
  7. A response is validated. The whole shape, not only ok: text that is not an object, a missing or non-boolean ok, an ok:true answer carrying e, an e that is not an object, or an error whose code or message is missing or not a non-empty string is HandlerReturnedNonEnvelope, never forwarded to a host that would have to guess. An ok:false answer carrying r has the r dropped, because exactly one of the two shapes is present.

The refusals

Every one of these arrives as a normal answer, so a host parses one shape and reads e.code.

CodeWhen
BadRequestThe request is not a JSON object at all.
UnsupportedVersionv is missing, is not a whole number, or names another contract version. The message says which one it read.
MissingMethodm is missing or empty.
BadParamsp is present and is not a JSON object. An explicit null is treated as absent.
NoHandlerThe script has not called Bridge.Serve, or a later run unregistered it.
HandlerReturnedNothingThe handler answered null, or something that is not text. A verb must end with Bridge.Ok or Bridge.Fail.
HandlerReturnedNonEnvelopeThe handler's text is not a JSON object, has no boolean ok, carries e beside ok:true, has an e that is not an object, or has an error whose code or message is missing or not a non-empty string.
FailedA handler reported a failure without a reason, and the dispatcher filled one in.
the engine's own codeA handler that threw answers its own code (Unspecified for a plain failure, DivisionByZero, UndefinedVariable, Cancelled, and so on) with its message, at and frames.
A verb the host does not know is the handler's decision, not the dispatcher's. The dispatcher only checks the envelope. A handler that receives an unknown m and answers Bridge.Fail(req["id"], "NoSuchVerb", ...) is what makes the refusal app-specific; a handler that ignores the verb and answers Ok is equally legal, and that is the contract being silent about verbs rather than vague.

Two kinds of failure

A contract failure is an answer. An unknown verb, another version, a handler that threw: all of them travel INSIDE the document as ok:false, so the transport succeeded and the code is a value a host branches on.

A transport failure is not an answer. No such session, a session already running, a freed handle, a callback that could not be called: there is no document to parse, so the carrier says so in ITS OWN vocabulary and the reason goes to the carrier's error channel.

CarrierContract failureTransport failure
C, C#, Python, PowerShellThe document's own ok:false, a non-negative lengthslc_invoke answers a NEGATIVE status; the sentence is in slc_last_error
the host half (C, C#, Python, PowerShell)the host's own ok:false documentthe callback answers a NEGATIVE length; the script catches the refusal at Bridge.Call
COMthe document's own ok:false, and the HRESULT stays 0the sentence in LastError (a freed object, a session already running), because a member has no status to answer

Putting a sentence in a buffer the host parses as JSON is how a binding ends up reporting a parse error instead of the real problem. That is why a transport failure is never a document.

The script side: the Bridge namespace

MemberWhat it does
Bridge.VersionThe contract version this build speaks, as a number (1).
Bridge.ServedWhether a handler is registered, so a script can decide before it advertises anything.
Bridge.HostedWhether a host installed its side, which is what Bridge.Call needs.
Bridge.Serve(handler)Registers the function that answers the host's requests. It takes ONE parameter, the request as a script dictionary (req["m"], req["p"]), and answers the text Bridge.Ok or Bridge.Fail builds. Bridge.Serve(null) stops serving, and one handler per session means a second call replaces the first.
Bridge.Handle(request)The host to script door as text. Every carrier calls it underneath.
Bridge.Call(request)The script to host door. Answers the parsed response document, and refuses by name when no host installed its side.
Bridge.Ok(id, result)Builds a successful response document.
Bridge.Fail(id, code, message [, retry | options])Builds a failed one. id may be null when the request had none, and code and message must be non-empty. The fourth argument is either the retry boolean or an options object: { retry: true, retryAfter: 250, details: { field: "total" } }. An unknown option, or one of the wrong type, is refused by name.
Bridge.FromError(id, error)Turns a CAUGHT value into the contract's error object: an ErrorInfo, or a { code: ..., message: ... } dictionary, so a failure the script handled answers in the same shape as one the engine caught. A dictionary is read member by member: retry, retryAfter and details travel when present, and a malformed member is refused by name.

A handler that serves two verbs

Bridge.Serve(fun (req) {
    var verb = "" + req["m"];
    var id = req.ContainsKey("id") ? req["id"] : null;      // echoed by the dispatcher, but read here to answer
    if (verb == "invoice.post") {
        if (req["p"]["total"] < 0) { return Bridge.Fail(id, "BadTotal", "a total cannot be negative"); }
        return Bridge.Ok(id, { posted: true, invoice: 4171 });
    }
    if (verb == "invoice.get") {
        return Bridge.Ok(id, { invoice: 4171, total: 120.50 });
    }
    return Bridge.Fail(id, "NoSuchVerb", "this script serves invoice.post and invoice.get, not " + verb);
});

Answering a failure the script handled

Bridge.Serve(fun (req) {
    var id = req.ContainsKey("id") ? req["id"] : null;
    try {
        return Bridge.Ok(id, { rows: Database.Rows(req["p"]) });
    } catch (var e) {
        return Bridge.FromError(id, e);        // ErrorInfo: code, message and the frames travel as they are
    }
});

Calling the host

if (Bridge.Hosted) {
    var answer = Bridge.Call('{"v":1,"id":"s1","m":"customer.lookup","p":{"id":42}}');   // the request document, as text
    if (answer["ok"]) { print("customer: " + answer["r"]["name"]); }
    else { print("the host refused: " + answer["e"]["code"] + " " + answer["e"]["message"]); }
}
A stub host is just a script. Bridge.Handle answers the same document every carrier receives, so the contract can be tested with no host technology at all. That is what assets/language/repl/interop/bridge_contract_test.slc does: it decides the version, the verb, the parameters object (including an explicit null), a handler being served, a re-entrant call and a handler calling the host while serving, a handler's own failure, a non-envelope answer, the answer's whole shape (exactly one of r or e, and the error's code, message, origin, retryAfter and details), a response that names somebody else's id and version, and the id echoed four ways (string, numeric, absent, null). It runs on both engines.

The five carriers

Both directions are carried by the C ABI. COM carries the host to script direction. The table is the whole difference between them.

CarrierThe host half (a script calls back)The script half (the host asks)The one thing to get right
Cslc_set_bridge(handle, callback, user)slc_invoke(handle, request, buffer, capacity)the two-pass length, and a NEGATIVE answer is your own refusal
C#the same, with a [UnmanagedFunctionPointer(Cdecl)] delegatethe samekeep the delegate alive for the session's lifetime
Pythonthe same, with a ctypes.CFUNCTYPEthe samethe buffer parameter is c_void_p, and write with memmove
PowerShellthe same, with COMPILED callbacks (Add-Type)the samea script block cannot be a callback, and a property read goes through InvokeMember
COMnot over COM (LastError explains why a call could not be made, but no member installs a callback)Invoke(requestJson), DISPID 8the document IS the answer; Invoke does not write LastResult
The published library is x64 (PE32+). Every carrier needs a 64-bit host process: a 32-bit Python, PowerShell or Office gets "the specified module could not be found" or "class not registered", which reads like a missing install rather than a bitness mismatch.

C

A C host links nothing from the engine: it resolves the exports by name at run time, which is what a host without an import library does. The generated header bindings/ScriptLangCore.h declares all of them; the sample below spells only the six it uses and is shipped as bindings/bridge_host.c, so it can be built and run against an installed engine instead of retyped.

/* bridge_host.c: the Bridge contract from a C host, both directions, with no import library and NO C RUNTIME.
 *
 * THIS IS THE SHIPPED C CARRIER, beside `BridgeTest.py` (the Python one) in `bindings\`, the folder the installer copies
 * to `{app}\bindings`: a host builds and runs this proof against an installed engine instead of retyping it, which is
 * what the Bridge page's own block is (`docs\bridge\howto.html`, the C section), so the two cannot drift.
 *
 * BUILD, with an x86_64 MinGW-w64 GCC (see the three rules below), from this folder:
 *   set PATH=C:\msys64\mingw64\bin;%PATH%
 *   gcc -std=c11 -Oz -fno-stack-protector -mno-stack-arg-probe -falign-functions=1 -falign-jumps=1 ^
 *       -falign-loops=1 -falign-labels=1 -fno-plt -s -Wall -Wextra -Werror -mconsole -ffunction-sections ^
 *       -fno-asynchronous-unwind-tables -fno-unwind-tables -fdata-sections -fno-ident -fno-builtin ^
 *       -Wl,--gc-sections -Wl,--build-id=none -Wl,--no-insert-timestamp -nostartfiles -nostdlib ^
 *       -e wmainCRTStartup -o bridge_host.exe bridge_host.c -lkernel32
 *
 * RUN it with the engine DLL's path:
 *   bridge_host.exe "C:\Program Files\ScriptLangCore\bin\ScriptLangCore.dll"
 *
 * THREE RULES THIS FILE OBEYS, because -nostartfiles -nostdlib changes what "a C program" is:
 *   1. IT MUST BE AN x64 COMPILER, because the engine image is x64: a 32-bit host answers LoadLibrary = 193
 *      (ERROR_BAD_EXE_FORMAT) before a single export is looked up. `gcc -dumpmachine` must say x86_64-w64-mingw32.
 *   2. -fno-builtin, because GCC recognises the byte loops below as strlen/memcpy and would emit CALLS to them, which
 *      nothing provides here (without it the link fails on an undefined `strlen`).
 *   3. -lkernel32, because -nostdlib names every library explicitly: the entry point, the output and every Win32 call
 *      come from there, and WITHOUT it the link stops on `LoadLibraryW`.
 *
 * WHAT IS GONE, and why: no stdio, no string.h, no main(). This program writes with WriteFile on the inherited handle
 * and takes its one argument off GetCommandLineW, so the image is a few kilobytes instead of 250 KB of CRT.
 */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdint.h>

/* The engine's six exports this host uses, each as its OWN prototype: the names are resolved at run time, so these
 * typedefs are what the compiler checks the host's call sites against instead of an import library. */
typedef int64_t (*create_fn)(const char *options);
typedef int     (*free_fn)(int64_t handle);
typedef int     (*last_error_fn)(int64_t handle, char *buffer, int capacity);
typedef int     (*run_text_fn)(int64_t handle, const char *source, const char *name);
typedef int     (*set_bridge_fn)(int64_t handle, void *callback, void *user);
typedef int     (*invoke_fn)(int64_t handle, const char *request, char *buffer, int capacity);
typedef int32_t (*bridge_fn)(int64_t handle, void *user, const char *request, char *buffer, int32_t capacity);

/* A FARPROC is a function pointer of UNKNOWN signature, so casting it to one of the types above is a cast between
 * incompatible function types: -Wcast-function-type refuses it, correctly, because calling through such a cast is
 * undefined. Storing its REPRESENTATION into a correctly typed pointer is the idiom that IS well defined, and these
 * asserts are what make the copy exact rather than hopeful (every pointer is one machine word, in both image kinds). */
_Static_assert(sizeof(FARPROC) == sizeof(void *), "a FARPROC is one machine word");
_Static_assert(sizeof(create_fn) == sizeof(void *), "an export pointer is one machine word");
_Static_assert(sizeof(free_fn) == sizeof(void *), "an export pointer is one machine word");
_Static_assert(sizeof(last_error_fn) == sizeof(void *), "an export pointer is one machine word");
_Static_assert(sizeof(run_text_fn) == sizeof(void *), "an export pointer is one machine word");
_Static_assert(sizeof(set_bridge_fn) == sizeof(void *), "an export pointer is one machine word");
_Static_assert(sizeof(invoke_fn) == sizeof(void *), "an export pointer is one machine word");
_Static_assert(sizeof(bridge_fn) == sizeof(void *), "an export pointer is one machine word");

static HANDLE g_out;                       /* stdout, taken once: with no CRT there is no stdout of its own */
static int64_t g_session;
static invoke_fn g_invoke;
static last_error_fn g_last_error;
static char g_answer[8192];                /* the host's answer buffer, static so no stack probe is needed */
static char g_narrow[4096];

/* ---- the two primitives a CRT would have given: a length and a byte copy -------------------------------------- */
static unsigned long long text_length(const char *text)
{
    unsigned long long n = 0;
    if (text != NULL) { while (text[n] != '\0') n++; }
    return n;
}

static void copy_bytes(void *destination, const void *source, unsigned long long count)
{
    unsigned char *to = (unsigned char *)destination;
    const unsigned char *from = (const unsigned char *)source;
    while (count > 0) { *to++ = *from++; count--; }
}

/* ---- output: WriteFile on the inherited handle, so a redirected stream keeps working --------------------------- */
static void say(const char *text)
{
    DWORD written = 0;
    unsigned long long n = text_length(text);
    if (g_out == NULL || g_out == INVALID_HANDLE_VALUE || n == 0) return;
    WriteFile(g_out, text, (DWORD)n, &written, NULL);
}

static void say_uint(unsigned long value)
{
    char digits[21];
    int at = 20;
    if (value == 0) { say("0"); return; }
    digits[at] = '\0';
    while (value > 0) { digits[--at] = (char)('0' + (int)(value % 10)); value /= 10; }
    say(digits + at);
}

static void say_wide(const wchar_t *wide)
{
    int n = WideCharToMultiByte(CP_UTF8, 0, wide, -1, g_narrow, (int)sizeof(g_narrow), NULL, NULL);
    if (n > 0) say(g_narrow);
}

static void end_line(void)
{
    say("\r\n");
}

/* ---- loading an export by name: a representation copy, never a cast between function types -------------------- */
static int load_export(HMODULE dll, const char *name, void *slot, unsigned long long size)
{
    FARPROC raw = GetProcAddress(dll, name);
    if (raw == NULL) return 0;
    copy_bytes(slot, &raw, size);
    return 1;
}

static const char *last_error_text(void)
{
    static char buffer[1024];
    if (g_last_error == NULL) return "";
    return g_last_error(g_session, buffer, (int)sizeof(buffer)) > 0 ? buffer : "";
}

/* THE HOST HALF: one request document in, one response document out. Answer the length the document NEEDS, write at
 * most capacity - 1 bytes plus a terminator, and a NEGATIVE answer means this host refuses the request. */
static int32_t host_bridge(int64_t handle, void *user, const char *request, char *buffer, int32_t capacity)
{
    static const char response[] = "{\"v\":1,\"ok\":true,\"r\":{\"name\":\"Ada\"}}";
    int32_t length = (int32_t)text_length(response);
    (void)handle;
    (void)user;
    say("  the script asked: ");
    if (request != NULL) say(request);
    end_line();
    if (buffer != NULL && capacity > 0) {
        int32_t copy = length < capacity - 1 ? length : capacity - 1;
        copy_bytes(buffer, response, (unsigned long long)copy);
        buffer[copy] = '\0';
    }
    return length;
}

/* One slc_invoke, the way a host does it: capacity 0 asks for the length, then a buffer of that size. */
static int ask(const char *request)
{
    int needed = g_invoke(g_session, request, NULL, 0);
    if (needed < 0) {
        say("  transport failure: ");
        say(last_error_text());
        end_line();
        return -1;
    }
    if (needed + 1 > (int)sizeof(g_answer)) {
        say("  the answer needs ");
        say_uint((unsigned long)needed);
        say(" bytes");
        end_line();
        return -1;
    }
    if (g_invoke(g_session, request, g_answer, needed + 1) < 0) {
        say("  transport failure: ");
        say(last_error_text());
        end_line();
        return -1;
    }
    return needed;
}

/* ---- the command line: with no CRT nobody hands us argv, so one token is read from GetCommandLineW ------------- */
/* Takes the token at `at` into `into` (quoted tokens keep their spaces, and the quotes are dropped). A NULL `into`
 * skips the token, which is how the program's own path is stepped over. Returns where the next token starts. */
static const wchar_t *take_token(const wchar_t *at, wchar_t *into, unsigned long long capacity)
{
    unsigned long long n = 0;
    while (*at == L' ' || *at == L'\t') at++;
    if (*at == L'\0') return NULL;
    if (*at == L'"') {
        at++;
        while (*at != L'\0' && *at != L'"') {
            if (into != NULL && n + 1 < capacity) into[n++] = *at;
            at++;
        }
        if (*at == L'"') at++;
    } else {
        while (*at != L'\0' && *at != L' ' && *at != L'\t') {
            if (into != NULL && n + 1 < capacity) into[n++] = *at;
            at++;
        }
    }
    if (into != NULL && capacity > 0) into[n < capacity ? n : capacity - 1] = L'\0';
    return at;
}

static unsigned run(void)
{
    static wchar_t dll_path[1024];
    create_fn p_create;
    free_fn p_free;
    run_text_fn p_run_text;
    set_bridge_fn p_set_bridge;
    HMODULE dll;
    int loaded;

    const wchar_t *after_exe;

    g_out = GetStdHandle(STD_OUTPUT_HANDLE);

    /* argv[0] is this program's own path; argv[1] is the engine's. A missing one is a usage refusal, exit 2. */
    after_exe = take_token(GetCommandLineW(), NULL, 0);
    if (after_exe == NULL || take_token(after_exe, dll_path, 1024) == NULL) {
        say("usage: bridge_host.exe <ScriptLangCore.dll>");
        end_line();
        return 2;
    }

    dll = LoadLibraryW(dll_path);
    if (dll == NULL) {
        say("LoadLibrary(");
        say_wide(dll_path);
        say(") = ");
        say_uint((unsigned long)GetLastError());
        end_line();
        return 2;
    }

    loaded  = load_export(dll, "slc_create", &p_create, sizeof p_create);
    loaded &= load_export(dll, "slc_free", &p_free, sizeof p_free);
    loaded &= load_export(dll, "slc_last_error", &g_last_error, sizeof g_last_error);
    loaded &= load_export(dll, "slc_run_text", &p_run_text, sizeof p_run_text);
    loaded &= load_export(dll, "slc_set_bridge", &p_set_bridge, sizeof p_set_bridge);
    loaded &= load_export(dll, "slc_invoke", &g_invoke, sizeof g_invoke);
    if (!loaded) {
        say("this engine has no bridge: ask for capability 0x200 (slc_capabilities)");
        end_line();
        return 2;
    }

    g_session = p_create("{\"thread\":\"own\"}");
    if (g_session <= 0) {
        say("slc_create: ");
        say(last_error_text());
        end_line();
        return 2;
    }

    /* The host half, installed once. NULL removes it. */
    if (p_set_bridge(g_session, (void *)host_bridge, NULL) != 0) {
        say("slc_set_bridge: ");
        say(last_error_text());
        end_line();
        return 1;
    }

    /* script -> host */
    p_run_text(g_session,
        "var who = Bridge.Call('{\"v\":1,\"id\":\"s1\",\"m\":\"customer.lookup\",\"p\":{\"id\":42}}');\n"
        "print(\"  customer: \" + who[\"r\"][\"name\"]);", NULL);

    /* host -> script: the script serves a verb, then the host invokes it */
    p_run_text(g_session,
        "Bridge.Serve(fun (req) {\n"
        "    var verb = \"\" + req[\"m\"];\n"
        "    if (verb == \"echo\") { return Bridge.Ok(req[\"id\"], { n: req[\"p\"][\"n\"] * 2 }); }\n"
        "    return Bridge.Fail(req[\"id\"], \"NoSuchVerb\", \"no \" + verb);\n"
        "});", NULL);

    if (ask("{\"v\":1,\"id\":\"h1\",\"m\":\"echo\",\"p\":{\"n\":21}}") >= 0) {
        say("  the script answered: ");
        say(g_answer);
        end_line();
    }
    if (ask("{\"v\":1,\"id\":\"h2\",\"m\":\"nope\"}") >= 0) {
        say("  an unknown verb answered: ");
        say(g_answer);
        end_line();
    }

    p_free(g_session);
    FreeLibrary(dll);
    return 0;
}

/* The entry point the build line names (-e wmainCRTStartup). With no CRT there is no main(), no argv and nobody to
 * return to, so the verdict is ExitProcess'd here rather than returned. */
void wmainCRTStartup(void)
{
    ExitProcess((UINT)run());
}

Details that decide whether it works

C#

A managed host uses the same two exports. The signatures are already written down: include the GENERATED bindings file (bindings/ScriptLangCore.cs, produced from docs/embed/abi.json) instead of retyping them, which is what the embedding harness itself does.

// bridge_host.cs: both directions over the C ABI. Build as an x64 project that includes the generated bindings:
//   <Compile Include="bindings/ScriptLangCore.cs" />
using System.Runtime.InteropServices;
using ScriptLangCore.Abi;

if (args.Length < 1) { Console.WriteLine("usage: bridge_host <ScriptLangCore.dll>"); return 2; }
var lib = NativeLibrary.Load(Path.GetFullPath(args[0]));

T Export<T>(string name) where T : Delegate
    => Marshal.GetDelegateForFunctionPointer<T>(NativeLibrary.GetExport(lib, name));

var create = Export<CreateFn>(AbiExports.Create);
var free = Export<FreeFn>(AbiExports.Free);
var capabilities = Export<CapabilitiesFn>(AbiExports.Capabilities);
var runText = Export<RunTextFn>(AbiExports.RunText);
var lastError = Export<LastErrorFn>(AbiExports.LastError);
var setBridge = Export<SetBridgeFn>(AbiExports.SetBridge);
var invoke = Export<InvokeFn>(AbiExports.Invoke);

if ((capabilities() & AbiCapabilities.Bridge) == 0) { Console.WriteLine("this build has no bridge"); return 2; }

var handle = create(Utf8("{\"thread\":\"own\"}"));

// THE HOST HALF. Keep the delegate in a variable that outlives every call: the engine holds this pointer, and a
// collected callback is a crash rather than an error.
var requests = new List<string>();
BridgeCb bridgeHost = (long session, nint user, nint request, nint buffer, int capacity) =>
{
    var text = Marshal.PtrToStringUTF8(request) ?? "";
    requests.Add(text);
    const string response = "{\"v\":1,\"ok\":true,\"r\":{\"name\":\"Ada\"}}";
    var bytes = System.Text.Encoding.UTF8.GetBytes(response);
    if (capacity > 0 && buffer != nint.Zero)
    {
        var copy = Math.Min(bytes.Length, capacity - 1);
        Marshal.Copy(bytes, 0, buffer, copy);
        Marshal.WriteByte(buffer, copy, 0);
    }
    return bytes.Length;                       // negative would be THIS host refusing
};
var bridgePointer = Marshal.GetFunctionPointerForDelegate(bridgeHost);
if (setBridge(handle, bridgePointer, nint.Zero) != 0) { Console.WriteLine(Error(handle)); return 1; }

// script -> host
runText(handle, Utf8(
    "var who = Bridge.Call('{\"v\":1,\"id\":\"s1\",\"m\":\"customer.lookup\",\"p\":{\"id\":42}}');\n" +
    "print(\"customer: \" + who[\"r\"][\"name\"]);"), nint.Zero);

// host -> script
runText(handle, Utf8(
    "Bridge.Serve(fun (req) {\n" +
    "    if (req[\"m\"] == \"echo\") { return Bridge.Ok(req[\"id\"], { n: req[\"p\"][\"n\"] * 2 }); }\n" +
    "    return Bridge.Fail(req[\"id\"], \"NoSuchVerb\", \"no \" + req[\"m\"]);\n" +
    "});"), nint.Zero);

Console.WriteLine(InvokeText("{\"v\":1,\"id\":\"h1\",\"m\":\"echo\",\"p\":{\"n\":21}}"));

free(handle);
GC.KeepAlive(bridgeHost);                       // belt and braces: the delegate outlives the session
return 0;

string InvokeText(string request)
{
    var requestPointer = Utf8(request);
    try
    {
        var needed = invoke(handle, requestPointer, nint.Zero, 0);
        if (needed < 0) return "<status " + needed + "> " + Error(handle);   // TRANSPORT failure
        var buffer = Marshal.AllocCoTaskMem(needed + 1);
        try
        {
            var written = invoke(handle, requestPointer, buffer, needed + 1);
            return written < 0 ? "<status " + written + "> " + Error(handle)
                              : Marshal.PtrToStringUTF8(buffer) ?? "";
        }
        finally { Marshal.FreeCoTaskMem(buffer); }
    }
    finally { Marshal.FreeCoTaskMem(requestPointer); }
}

string Error(long session)
{
    var needed = lastError(session, nint.Zero, 0);
    if (needed <= 0) return "";
    var buffer = Marshal.AllocCoTaskMem(needed + 1);
    try { lastError(session, buffer, needed + 1); return Marshal.PtrToStringUTF8(buffer) ?? ""; }
    finally { Marshal.FreeCoTaskMem(buffer); }
}

nint Utf8(string text)
{
    var bytes = System.Text.Encoding.UTF8.GetBytes(text + "\0");
    var memory = Marshal.AllocCoTaskMem(bytes.Length);
    Marshal.Copy(bytes, 0, memory, bytes.Length);
    return memory;
}

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int BridgeCb(long handle, nint user, nint request, nint buffer, int capacity);

Details that decide whether it works

Python

ctypes is in the standard library, so this carrier needs nothing installed. The declarations are also generated: bindings/scriptlangcore.py holds the signatures and the capability names. The sample below is shipped as bindings/BridgeTest.py, so it can be run rather than retyped: it checks both directions and every refusal in this section's list, and it ends with PYTHON BRIDGE OK, which is its exit code.

"""bridge_host.py: both directions over the C ABI, with the standard library only.
    python bridge_host.py C:\\Program Files\\ScriptLangCore\\bin\\ScriptLangCore.dll
"""
import ctypes
import sys

engine = ctypes.WinDLL(sys.argv[1])          # x64 CPython, because the library is x64

engine.slc_create.restype = ctypes.c_longlong
engine.slc_create.argtypes = [ctypes.c_char_p]
engine.slc_free.restype = ctypes.c_int
engine.slc_free.argtypes = [ctypes.c_longlong]
engine.slc_capabilities.restype = ctypes.c_int
engine.slc_capabilities.argtypes = []
engine.slc_last_error.restype = ctypes.c_int
engine.slc_last_error.argtypes = [ctypes.c_longlong, ctypes.c_char_p, ctypes.c_int]
engine.slc_set_output.restype = ctypes.c_int
engine.slc_set_output.argtypes = [ctypes.c_longlong, ctypes.c_void_p, ctypes.c_void_p]
engine.slc_run_text.restype = ctypes.c_int
engine.slc_run_text.argtypes = [ctypes.c_longlong, ctypes.c_char_p, ctypes.c_char_p]
engine.slc_set_bridge.restype = ctypes.c_int
engine.slc_set_bridge.argtypes = [ctypes.c_longlong, ctypes.c_void_p, ctypes.c_void_p]
engine.slc_invoke.restype = ctypes.c_int
engine.slc_invoke.argtypes = [ctypes.c_longlong, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int]

CAP_BRIDGE = 1 << 9
if (engine.slc_capabilities() & CAP_BRIDGE) == 0:
    raise SystemExit("this build has no bridge")

LINE_CB = ctypes.CFUNCTYPE(None, ctypes.c_longlong, ctypes.c_int, ctypes.c_char_p, ctypes.c_void_p)
# THE BUFFER IS c_void_p, NOT c_char_p. A c_char_p parameter arrives as an immutable Python bytes object, so a
# write into it is lost and this host would answer a length for a document it never wrote.
BRIDGE_CB = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_longlong, ctypes.c_void_p,
                             ctypes.c_char_p, ctypes.c_void_p, ctypes.c_int)

lines = []
requests = []

def on_line(handle, channel, utf8, user):
    lines.append(str(channel) + "|" + (utf8 or b"").decode("utf-8"))

def on_request(handle, user, request, buffer, capacity):
    """The host half: the length the response needs, at most capacity - 1 bytes plus a terminator."""
    requests.append((request or b"").decode("utf-8"))
    response = b'{"v":1,"ok":true,"r":{"name":"Ada"}}'
    if capacity > 0 and buffer:
        count = min(len(response), capacity - 1)
        ctypes.memmove(buffer, response, count)
        ctypes.memset(buffer + count, 0, 1)
    return len(response)                      # a negative return would be THIS host refusing

sink = LINE_CB(on_line)                      # keep BOTH callback objects alive: ctypes frees them with the object
bridge = BRIDGE_CB(on_request)

handle = engine.slc_create(b'{"thread":"own"}')

def last_error():
    needed = engine.slc_last_error(handle, None, 0)
    if needed <= 0:
        return ""
    buffer = ctypes.create_string_buffer(needed + 1)
    engine.slc_last_error(handle, buffer, needed + 1)
    return buffer.value.decode("utf-8")

engine.slc_set_output(handle, ctypes.cast(sink, ctypes.c_void_p), None)
if engine.slc_set_bridge(handle, ctypes.cast(bridge, ctypes.c_void_p), None) != 0:
    raise SystemExit(last_error())

# script -> host
engine.slc_run_text(handle,
    b'var who = Bridge.Call(\'{"v":1,"id":"s1","m":"customer.lookup","p":{"id":42}}\');\n'
    b'print("customer: " + who["r"]["name"]);', None)

# host -> script
engine.slc_run_text(handle,
    b'Bridge.Serve(fun (req) {\n'
    b'    if (req["m"] == "echo") { return Bridge.Ok(req["id"], { n: req["p"]["n"] * 2 }); }\n'
    b'    return Bridge.Fail(req["id"], "NoSuchVerb", "no " + req["m"]);\n'
    b'});', None)

def ask(document):
    data = document.encode("utf-8")
    needed = engine.slc_invoke(handle, data, None, 0)
    if needed < 0:
        return "<status {}> {}".format(needed, last_error())
    buffer = ctypes.create_string_buffer(needed + 1)
    if engine.slc_invoke(handle, data, buffer, needed + 1) < 0:
        return "<status {}> {}".format(needed, last_error())
    return buffer.value.decode("utf-8")

print(ask('{"v":1,"id":"h1","m":"echo","p":{"n":21}}'))
print(ask('{"v":1,"id":"h2","m":"nope"}'))
engine.slc_free(handle)

Details that decide whether it works

PowerShell

Add-Type compiles the declarations and the callbacks in one step, which is PowerShell's native door to a C ABI: a script block cannot be a callback, and the reason is a real limitation rather than a style choice (see below).

# bridge_host.ps1, run with: pwsh -File bridge_host.ps1 -EngineDll "C:\Program Files\ScriptLangCore\bin\ScriptLangCore.dll"
param([Parameter(Mandatory = $true)][string] $EngineDll)
$ErrorActionPreference = 'Stop'

Add-Type -TypeDefinition @'
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public static class Engine
{
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate void LineCb(long handle, int channel, IntPtr utf8, IntPtr user);

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate int BridgeCb(long handle, IntPtr user, IntPtr request, IntPtr buffer, int capacity);

    [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
    public static extern IntPtr LoadLibraryW(string path);

    [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    public static extern IntPtr GetProcAddress(IntPtr module, string name);

    public delegate long CreateFn(IntPtr options);
    public delegate int FreeFn(long handle);
    public delegate int CapabilitiesFn();
    public delegate int LastErrorFn(long handle, IntPtr buffer, int capacity);
    public delegate int RunTextFn(long handle, IntPtr source, IntPtr name);
    public delegate int SetBridgeFn(long handle, IntPtr callback, IntPtr user);
    public delegate int InvokeFn(long handle, IntPtr request, IntPtr buffer, int capacity);

    // THE CALLBACKS RUN ON THE ENGINE'S THREAD, so they hand their answers over through static state.
    public static readonly List<string> Lines = new List<string>();
    public static readonly List<string> Requests = new List<string>();

    // KEPT ALIVE FOR THE SESSION'S LIFETIME: the engine holds these pointers.
    public static readonly LineCb LineHandler = OnLine;
    public static readonly BridgeCb BridgeHandler = OnBridge;

    private static void OnLine(long handle, int channel, IntPtr utf8, IntPtr user)
        => Lines.Add(channel.ToString() + "|" + Read(utf8));

    private static int OnBridge(long handle, IntPtr user, IntPtr request, IntPtr buffer, int capacity)
    {
        Requests.Add(Read(request));
        var response = "{\"v\":1,\"ok\":true,\"r\":{\"name\":\"Ada\"}}";
        var bytes = System.Text.Encoding.UTF8.GetBytes(response);
        if (capacity > 0 && buffer != IntPtr.Zero)
        {
            var count = Math.Min(bytes.Length, capacity - 1);
            Marshal.Copy(bytes, 0, buffer, count);
            Marshal.WriteByte(buffer, count, 0);
        }
        return bytes.Length;
    }

    public static T Export<T>(IntPtr module, string name) where T : Delegate
        => Marshal.GetDelegateForFunctionPointer<T>(GetProcAddress(module, name));

    public static IntPtr Utf8(string text)
    {
        var bytes = System.Text.Encoding.UTF8.GetBytes(text + "\0");
        var memory = Marshal.AllocCoTaskMem(bytes.Length);
        Marshal.Copy(bytes, 0, memory, bytes.Length);
        return memory;
    }

    public static string Read(IntPtr memory) => memory == IntPtr.Zero ? "" : Marshal.PtrToStringUTF8(memory) ?? "";
}
'@

$module = [Engine]::LoadLibraryW((Resolve-Path -LiteralPath $EngineDll).Path)
$capabilities = [Engine]::Export[Engine+CapabilitiesFn]($module, 'slc_capabilities')
if (($capabilities.Invoke() -band (1 -shl 9)) -eq 0) { throw 'this build has no bridge' }

$create     = [Engine]::Export[Engine+CreateFn]($module, 'slc_create')
$free       = [Engine]::Export[Engine+FreeFn]($module, 'slc_free')
$lastError  = [Engine]::Export[Engine+LastErrorFn]($module, 'slc_last_error')
$setOutput  = [Engine]::Export[Engine+SetOutputFn]($module, 'slc_set_output')
$runText    = [Engine]::Export[Engine+RunTextFn]($module, 'slc_run_text')
$setBridge  = [Engine]::Export[Engine+SetBridgeFn]($module, 'slc_set_bridge')
$invoke     = [Engine]::Export[Engine+InvokeFn]($module, 'slc_invoke')

$options = [Engine]::Utf8('{"thread":"own"}')
try { $session = $create.Invoke($options) } finally { [Runtime.InteropServices.Marshal]::FreeCoTaskMem($options) }

$null = $setOutput.Invoke($session, [Runtime.InteropServices.Marshal]::GetFunctionPointerForDelegate([Engine]::LineHandler), [IntPtr]::Zero)
$null = $setBridge.Invoke($session, [Runtime.InteropServices.Marshal]::GetFunctionPointerForDelegate([Engine]::BridgeHandler), [IntPtr]::Zero)

# script -> host
$text = [Engine]::Utf8("var who = Bridge.Call('{`"v`":1,`"id`":`"s1`",`"m`":`"customer.lookup`",`"p`":{`"id`":42}}');`nprint(`"customer: `" + who[`"r`"][`"name`"]);")
try { $null = $runText.Invoke($session, $text, [IntPtr]::Zero) } finally { [Runtime.InteropServices.Marshal]::FreeCoTaskMem($text) }

# host -> script
$text = [Engine]::Utf8("Bridge.Serve(fun (req) {`n    if (req[`"m`"] == `"echo`") { return Bridge.Ok(req[`"id`"], { n: req[`"p`"][`"n`"] * 2 }); }`n    return Bridge.Fail(req[`"id`"], `"NoSuchVerb`", `"no `" + req[`"m`"]);`n});")
try { $null = $runText.Invoke($session, $text, [IntPtr]::Zero) } finally { [Runtime.InteropServices.Marshal]::FreeCoTaskMem($text) }

function Ask([string] $document) {
    $request = [Engine]::Utf8($document)
    try {
        $needed = $invoke.Invoke($session, $request, [IntPtr]::Zero, 0)
        if ($needed -lt 0) { return "<status $needed> " + (Get-LastError) }
        $buffer = [Runtime.InteropServices.Marshal]::AllocCoTaskMem($needed + 1)
        try {
            if ($invoke.Invoke($session, $request, $buffer, $needed + 1) -lt 0) { return "<status> " + (Get-LastError) }
            return [Engine]::Read($buffer)
        } finally { [Runtime.InteropServices.Marshal]::FreeCoTaskMem($buffer) }
    } finally { [Runtime.InteropServices.Marshal]::FreeCoTaskMem($request) }
}

function Get-LastError {
    $needed = $lastError.Invoke($session, [IntPtr]::Zero, 0)
    if ($needed -le 0) { return '' }
    $buffer = [Runtime.InteropServices.Marshal]::AllocCoTaskMem($needed + 1)
    try { $null = $lastError.Invoke($session, $buffer, $needed + 1); return [Engine]::Read($buffer) }
    finally { [Runtime.InteropServices.Marshal]::FreeCoTaskMem($buffer) }
}

Write-Output (Ask '{"v":1,"id":"h1","m":"echo","p":{"n":21}}')
Write-Output (Ask '{"v":1,"id":"h2","m":"nope"}')
$null = $free.Invoke($session)

Details that decide whether it works

COM

A COM client needs no declarations, no buffer and no handle: one ProgID, one member. CreateObject("ScriptLangCore.Session") loads this same ScriptLangCore.dll (the Embed configuration) into the client's own process, and since the server publishes no type library every call arrives as IDispatch: the member's name resolves to a DISPID, then one Invoke runs it, RunText being DISPID 2 and Invoke DISPID 8. The object holds ONE session, created on its first use on a thread the engine starts, and every member is a single job marshalled onto that thread. That is what ties the two verbs together: RunText runs a script in the session's interpreter, so the Bridge.Serve handler it installs is still there when Invoke posts one request document to the same interpreter, where the engine's dispatcher checks the envelope, calls the handler and rebuilds the answer with the caller's id echoed, so what returns is a document rather than whatever the handler happened to write. How one call travels is that path step by step, with the eight members and the three kinds of failure.

# PowerShell as a COM client: nothing to install in this process.
$engine = New-Object -ComObject ScriptLangCore.Session
$null = $engine.RunText(@'
Bridge.Serve(fun (req) {
    var verb = "" + req["m"];
    if (verb == "echo") { return Bridge.Ok(req["id"], { n: req["p"]["n"] * 2 }); }
    if (verb == "boom") { throw "com boom"; }
    return Bridge.Fail(req["id"], "NoSuchVerb", "no " + verb);
});
'@)

$echo = $engine.Invoke('{"v":1,"id":"p1","m":"echo","p":{"n":21}}')
# {"v":1,"id":"p1","ok":true,"r":{"n":42}}

$unknown = $engine.Invoke('{"v":1,"id":"p2","m":"nope"}')
# {"v":1,"id":"p2","ok":false,"e":{"code":"NoSuchVerb",...}}

$engine.Free()
Option Explicit
' VBA: the same door through late binding. The module assets\language\stdcall\ComEngine.bas wraps these members.
' The handler answers a CLASS INSTANCE, so the response carries its PUBLIC FIELDS; VBA has no JSON
' parser, so one local reader pulls a top-level field out of the document.
Private Function Field(ByVal document As String, ByVal name As String) As String
    Dim at As Long, piece As String, cut As Long
    at = InStr(1, document, """" & name & """:")
    If at = 0 Then Exit Function
    piece = Mid$(document, at + Len(name) + 3)
    cut = InStr(1, piece, ",")
    If cut = 0 Then cut = InStr(1, piece, "}")
    piece = Left$(piece, cut - 1)
    If Left$(piece, 1) = """" Then piece = Mid$(piece, 2, Len(piece) - 2)
    Field = piece
End Function

Sub ComBridgeDemo()
    Dim engine As Object, verdict As String, answer As String, code As Long
    Set engine = CreateObject("ScriptLangCore.Session")

    ' One class the session declares, and one verb that shows a YES/NO box and answers an instance of it.
    verdict = engine.RunText( _
        "class Reply { public string Id; public string Name; public int Code; }" & vbLf & _
        "Bridge.Serve(fun (req) {" & vbLf & _
        "    var code = MessageBox(""Proceed with the export?"", ""ScriptLangCore"", 4);" & vbLf & _
        "    var reply = new Reply();" & vbLf & _
        "    reply.Id = ""req-"" + req[""id""];" & vbLf & _
        "    reply.Name = ""factice"";" & vbLf & _
        "    reply.Code = code;" & vbLf & _
        "    return Bridge.Ok(req[""id""], reply);" & vbLf & _
        "});")

    ' RunText never raises: a snippet that did not parse leaves nothing served, and the Invoke below
    ' would answer NoHandler, which names the wrong thing.
    If InStr(verdict, """Ok"":true") = 0 Then
        MsgBox verdict
        Exit Sub
    End If

    ' The box appears in THIS process, because the server is in-process, and the call waits until it
    ' is answered: nothing here repaints while it is up.
    answer = engine.Invoke("{""v"":1,""id"":""v1"",""m"":""confirm""}")
    ' {"v":1,"id":"v1","ok":true,"r":{"Id":"req-v1","Name":"factice","Code":6}}

    code = CLng(Field(answer, "Code"))     ' the button's own id: 6 for Yes, 7 for No, 1 for OK
    MsgBox Field(answer, "Id") & " / " & Field(answer, "Name") & " / " & code
    Set engine = Nothing
End Sub

That is the whole round trip, and three things in it decide whether the answer is usable. The handler answers a CLASS INSTANCE, so the response's r is a document of its PUBLIC FIELDS (Id, Name, Code) and nothing else: a field is data, while a method or a computed member is behaviour and does not travel. The box belongs to the client, because the server runs in the client's own process, so the dialog appears on the client's screen while the client's thread waits inside Invoke. And Code is Win32's own button id (6 for Yes, 7 for No, 1 for OK), so the script branches on it and the client reads what the script decided rather than re-deriving anything.

How one call travels

Every step below is the same code the C ABI drives, reached through IDispatch instead of an export, so a COM client and a C host cannot disagree about what a document means.

  1. The object is late-bound, and that decides what a client may write. CreateObject resolves the ProgID to the CLSID above, loads ScriptLangCore.dll in-process and asks its DllGetClassObject for a class factory, which answers an IDispatch and nothing else. There is no type library, so VBA declares the variable As Object, GetTypeInfoCount answers 0, and each call resolves its member name with GetIDsOfNames (case-insensitively) and arrives as one Invoke carrying a DISPID.
  2. The object is one session, created on first use, on a thread the engine starts. CreateObject only makes the object; the first member creates the session with {"thread":"own"}, which is an STA thread with 32 MB of stack. That is not a detail: a caller's own thread (Excel's is 1 MB) would trip the engine's depth guard, so the work runs where the interpreter lives. Two objects are two sessions, and each keeps its own handler.
  3. Every member is one marshalled job. The calling thread posts the work to the session's thread and waits for it. A disposed session, a call from a thread that does not own it, and a second call while one is in flight are each refused by name. The host object a script may reach through Com.Host() is registered for that one run and released after it, which is what lets the host application quit.
  4. RunText is a real run of the session's interpreter. Lex, parse, precompile the declarations, interpret: what a snippet declares, and what it serves, stays in that session. The answer is the run's verdict (status, Ok, code, message, line, column, result), or what the snippet printed when it printed anything. A failing snippet is a verdict, never an exception.
  5. Bridge.Serve stores the handler on the running interpreter, together with the file it came from, which becomes the at.file of a failure the engine reports later. Bridge.Serve(null) removes it, Bridge.Served answers whether one is installed, and a session that never served answers NoHandler.
  6. Invoke posts the document to that same interpreter, and the dispatcher decides the contract in a fixed order. Text that is not a JSON object is BadRequest; a v that is not this build's contract version is UnsupportedVersion; a missing or empty m is MissingMethod; a p that is present and is not an object is BadParams; no handler is NoHandler. Then the handler is called with the request as a script dictionary, so req["m"] and req["p"] are the caller's own values, and a handler that throws answers its own error object, with the position and the frames the engine caught.
  7. The answer is rebuilt rather than forwarded. A handler answers the text Bridge.Ok or Bridge.Fail builds; an answer that is not text is HandlerReturnedNothing, and one that is not an envelope with a boolean ok is HandlerReturnedNonEnvelope. The dispatcher then forces v to the contract version, echoes id from the REQUEST (and removes it when the request carried none), and supplies a default e for a failure that forgot its reason. A client therefore correlates on the id it sent, whatever the handler wrote.
  8. It comes back as a BSTR with HRESULT 0, and the document is the whole answer. Invoke does not write LastResult, because the document IS the answer. Free(), or releasing the last reference, ends the session on its own thread, and the handler goes with the interpreter.
MemberDISPIDWhat it does
Version1the engine's version line, which carries the runtime and the ABI revision a client can compare
RunText(source [, name])2runs a snippet in the session: what it printed, else its verdict JSON
RunFile(path)3the same for a file on disk, run in the same session
LastResult4the last run's verdict JSON
LastError5the last transport sentence, and empty after a call that worked
Eval(name, args...)6calls a function the session already holds, answering its value as text
Free()7ends the session now; a later member says so instead of crashing
Invoke(requestDocument)8the Bridge document in, the Bridge document out

Three kinds of failure, and a client can tell them apart.

What failedWhat the caller gets
the contract: a malformed request, another version, no verb, no handler, a handler that threw or answered the wrong shapea document with ok:false and HRESULT 0, so nothing has to catch anything
the transport: a freed object, a session already running, a call from the wrong thread, a call from inside the session's own runthe sentence, both as the member's answer and in LastError
the snippet itself: a parse error, a runtime error, exita verdict from RunText: status, Ok, Code, Message, Line, Column

Only the first kind travels inside a document. A transport sentence and a snippet's verdict never do, so a client that parses Invoke's answer as JSON can rely on it being a document, and one that wants to know why a run failed reads the verdict RunText answered or LastResult afterwards.

Details that decide whether it works

No re-entry, and threads

The contract refuses re-entry on the same session: a session serves one host request at a time. A handler MAY call the host with Bridge.Call, which is how it asks the host a question while serving.

What travels, and what stays home

Checking a carrier

Every one of the five carriers was driven through the SAME ten checks, so a difference between them is a difference in the carrier and not in what was asked of it:

  1. the capability bit 0x200 says this build has the bridge, and slc_abi_revision is at least 6;
  2. a session is created;
  3. the host callback is installed;
  4. Bridge.Call reaches the host and answers its document;
  5. the host callback received the request document, verb and all;
  6. a script serves a verb, and slc_invoke (or Invoke) doubles 21 and echoes the id;
  7. an unknown verb is a CONTRACT failure inside the document;
  8. a request that is not JSON, or names another version, is a contract answer rather than a transport failure;
  9. the host half can be removed (slc_set_bridge(NULL)), and then Bridge.Call says so by name;
  10. the session frees, and a freed object or handle says so instead of crashing.

The in-tree instruments are these:

InstrumentWhat it proves
src/embed/Program.cs (the embedding harness)The C ABI over a REAL function pointer: both directions, the two-pass length, a re-entrant verb refused, a negative answer as a refusal, and the COM server's Invoke over IDispatch.
assets/language/repl/interop/bridge_contract_test.slcThe contract itself, with a stub host that is just a script: the envelope, the version, the verb, the parameters object including an explicit null, the handler's own failure, a non-envelope answer, the answer's whole shape (exactly one of r or e, and the error's members), a handler calling the host while serving, and the id echoed four ways. Runs on both engines.
bindings/BridgeTest.pyThe Python carrier, shipped: the host half and the script half in one run, plus every refusal, and PYTHON BRIDGE OK as the answer a driver asserts.
assets/language/com/VbaBench.bas, VbaBench.xlsmThe VBA carrier as a workbook: RunBridgeSelfTest drives Invoke in nine named checks and returns BRIDGE OK; bindings/vba-bench-check.ps1 rebuilds the workbook from the module and asserts both the verdict and that the text it carries is that file, line for line.
src/build/embed-check.shThe published DLL end to end, including the COM registration chain and the process-level legs.
src/build/check-abi-manifest.shdocs/embed/abi.json, the exports marked [UnmanagedCallersOnly], the capability bits and the generated bindings agree.
src/build/check-doc-bridge-c.shThe C block on THIS page is bindings/bridge_host.c verbatim, so the sample a reader copies and the file a host compiles cannot drift apart.
bash src/build/embed-check.sh                       # HARNESS OK, and the process legs
bash src/build/run-repl-tests.sh --filter bridge_contract_test --build aot
bash src/build/check-abi-manifest.sh
bash src/build/check-doc-bridge-c.sh

Troubleshooting

SymptomCause and fix
Bridge.Call says it needs a host bridgeNothing installed the host side on THIS session. Call slc_set_bridge with the callback (C, C#, Python, PowerShell), or set HostBridge in-process. A separately installed bridge on another session does not count.
Bridge.Call says the host refused the requestYour callback answered a NEGATIVE length. That is the host refusing on purpose; the script catches it, and the engine's sentence is the one to read.
slc_invoke answers a negative numberA transport failure: an unknown or freed handle, a session already running, or a re-entrant call. The sentence is in slc_last_error, never in the buffer.
The callback was never called, or the process died in itThe delegate or CFUNCTYPE object was collected, or a PowerShell script block was used. Hold the delegate in a field, or compile it.
Python: a length is answered but the document is missingThe buffer parameter was declared c_char_p. Declare c_void_p and write with ctypes.memmove.
PowerShell: PSInvalidOperationException from GetContextFromTLSA script block was passed as a callback. Compile the callback with Add-Type.
PowerShell: $engine.Version is emptyThe PSObject adapter, not the server. Read through InvokeMember(name, GetProperty, ...).
COM: "class not registered", or "the specified module could not be found"Not registered (run the installer, or setup/com-register.reg), or a 32-bit client against the x64 server.
UnsupportedVersionv is missing or names another contract version. The message says which one was read; write "v": 1.
NoHandlerThe script has not called Bridge.Serve, or Bridge.Serve(null) stopped it.
HandlerReturnedNonEnvelope / HandlerReturnedNothingThe handler returned a raw value instead of Bridge.Ok or Bridge.Fail, or returned a non-object text. The same code covers a missing or non-boolean ok, an ok:true answer carrying e, an e that is not an object, and an error whose code or message is missing or not a non-empty string. A verb must answer with one of the two builders.
"the contract is no re-entry on the same session"A handler called Bridge.Handle on its own session, or a host called back into the session it was answering. Bridge.Call from a handler is legal; post the host's question to another thread if it needs to ask one while answering.
An empty id in the answerThe request had no id member. Absent stays absent by rule 6, so a handler that echoes req["id"] must tolerate a missing one. A request that sent "id": null gets "id": null back.

Where the code is

FileWhat it holds
src/Interpreter/Registration/Bridge.csThe whole script side: the envelope, the one dispatcher (BridgeHandle), the validation and every refusal code.
src/Host/EmbedApi.csslc_invoke and slc_set_bridge: the two carriers over the C ABI, including the length convention and the negative status.
src/Host/ComServer.csThe COM member Invoke (DISPID 8), forwarding to the same dispatcher.
src/Host/EmbedCapabilities.csThe capability bit 0x200 (bridge) and the revision this build answers.
docs/embed/abi.jsonThe manifest both exports and the bit are generated from.
bindings/ScriptLangCore.h, .cs, scriptlangcore.pyThe generated declarations, one set per carrier, so a sample does not retype a signature.
assets/language/repl/interop/bridge_contract_test.slcThe contract's own suite, driven by a stub host that is a script.
src/embed/Program.csThe C ABI harness: a real function pointer in both directions, and the COM server's Invoke.

The language reference's Bridge entry states the script-facing rules. The embedding page's #bridge section places this contract beside the rest of the C ABI, and its #comserver section covers the COM server's registration and its eight members.